organizr.class.php 249 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786
  1. <?php
  2. use Dibi\Connection;
  3. class Organizr
  4. {
  5. // Use Custom Functions From Traits;
  6. use TwoFAFunctions;
  7. use ApiFunctions;
  8. use AuthFunctions;
  9. use BackupFunctions;
  10. use ConfigFunctions;
  11. use DemoFunctions;
  12. use HomepageConnectFunctions;
  13. use HomepageFunctions;
  14. use LogFunctions;
  15. use NetDataFunctions;
  16. use NormalFunctions;
  17. use OAuthFunctions;
  18. use OptionsFunction;
  19. use OrganizrFunctions;
  20. use PluginFunctions;
  21. use StaticFunctions;
  22. use SSOFunctions;
  23. use TokenFunctions;
  24. use UpdateFunctions;
  25. use UpgradeFunctions;
  26. // Use homepage item functions
  27. use BookmarksHomepageItem;
  28. use CalendarHomepageItem;
  29. use CouchPotatoHomepageItem;
  30. use DelugeHomepageItem;
  31. use DonateHomepageItem;
  32. use EmbyHomepageItem;
  33. use HealthChecksHomepageItem;
  34. use HTMLHomepageItem;
  35. use ICalHomepageItem;
  36. use JackettHomepageItem;
  37. use JDownloaderHomepageItem;
  38. use JellyfinHomepageItem;
  39. use LidarrHomepageItem;
  40. use MiscHomepageItem;
  41. use MonitorrHomepageItem;
  42. use NetDataHomepageItem;
  43. use NZBGetHomepageItem;
  44. use OctoPrintHomepageItem;
  45. use OmbiHomepageItem;
  46. use OverseerrHomepageItem;
  47. use PiHoleHomepageItem;
  48. use PlexHomepageItem;
  49. use QBitTorrentHomepageItem;
  50. use RadarrHomepageItem;
  51. use RTorrentHomepageItem;
  52. use SabNZBdHomepageItem;
  53. use SickRageHomepageItem;
  54. use SonarrHomepageItem;
  55. use SpeedTestHomepageItem;
  56. use TautulliHomepageItem;
  57. use TraktHomepageItem;
  58. use TransmissionHomepageItem;
  59. use UnifiHomepageItem;
  60. use WeatherHomepageItem;
  61. use uTorrentHomepageItem;
  62. // ===================================
  63. // Organizr Version
  64. public $version = '2.1.2200';
  65. // ===================================
  66. // Quick php Version check
  67. public $minimumPHP = '7.4';
  68. // ===================================
  69. protected $db;
  70. protected $otherDb;
  71. public $config;
  72. public $user;
  73. public $userConfigPath;
  74. public $defaultConfigPath;
  75. public $currentTime;
  76. public $docker;
  77. public $dev;
  78. public $demo;
  79. public $commit;
  80. public $fileHash;
  81. public $cookieName;
  82. public $logFile;
  83. public $timeExecution;
  84. public $root;
  85. public $paths;
  86. public $updating;
  87. public $groupOptions;
  88. public $warnings;
  89. public $errors;
  90. public bool $loggerSetup = false;
  91. public \Nekonomokochan\PhpJsonLogger\Logger $logger;
  92. public function __construct($updating = false)
  93. {
  94. // Constructed from Updater?
  95. $this->updating = $updating;
  96. // Set Project Root directory and paths
  97. $this->root = dirname(__DIR__, 2);
  98. $this->paths = [
  99. 'Root Folder' => $this->root . DIRECTORY_SEPARATOR,
  100. 'Cache Folder' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR,
  101. 'Tab Folder' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR,
  102. 'API Folder' => dirname(__DIR__, 1) . DIRECTORY_SEPARATOR
  103. ];
  104. // Temp Set Errors
  105. $this->errors = E_ALL;//E_ALL & ~E_NOTICE
  106. // Set current time
  107. $this->currentTime = gmdate('Y-m-d\TH:i:s\Z');
  108. // Set variable if install is for official docker
  109. $this->docker = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Docker.txt'));
  110. // Set variable if install is for develop and set php Error levels
  111. $this->dev = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Dev.txt'));
  112. // Set variable if install is for demo
  113. $this->demo = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Demo.txt'));
  114. // Set variable if install has commit hash and variable to be used as hash for files
  115. $this->commit = ($this->docker && !$this->dev) ? file_get_contents(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Github.txt') : null;
  116. $this->fileHash = ($this->commit) ?? $this->version;
  117. $this->fileHash = trim($this->fileHash);
  118. // Set location path to user config path
  119. $this->chooseConfigFile();
  120. // Set location path to default config path
  121. $this->defaultConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'default.php';
  122. // Load Config file
  123. $this->config = $this->config();
  124. // Set cookie name for Organizr Instance
  125. $this->cookieName = ($this->hasConfig()) ? $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp' : 'organizr_token_temp';
  126. // Set custom Error handler
  127. set_error_handler([$this, 'setAPIErrorResponse'], $this->errors);
  128. // Next Check PHP Version
  129. $this->checkPHP();
  130. // Check Disk Space
  131. $this->checkDiskSpace();
  132. // Set UUID for device
  133. $this->setDeviceUUID();
  134. // Add Plugin prefix to plugin global
  135. $this->setPluginListNameFromConfigPrefix();
  136. // Add database path to paths
  137. $this->addDatabaseToPaths();
  138. // Set Start Execution Time
  139. $this->timeExecution = $this->timeExecution();
  140. $this->phpErrors();
  141. // Set organizr Logs and logger
  142. $this->logFile = $this->setOrganizrLog();
  143. $this->setLoggerChannel();
  144. // Connect to DB
  145. $this->connectDB();
  146. // Check DB Writable
  147. $this->checkWritableDB();
  148. // Get token form cookie and validate
  149. $this->setCurrentUser();
  150. // might just run this at index
  151. $this->upgradeCheck();
  152. // Is Page load Organizr OAuth?
  153. $this->checkForOrganizrOAuth();
  154. // Is user Blacklisted?
  155. $this->checkIfUserIsBlacklisted();
  156. }
  157. public function __destruct()
  158. {
  159. $this->disconnectDB();
  160. }
  161. public function addDatabaseToPaths()
  162. {
  163. if ($this->hasConfig()) {
  164. $this->paths = array_merge($this->paths, ['DB Folder' => $this->config['dbLocation']]);
  165. }
  166. }
  167. public function chooseConfigFile()
  168. {
  169. $oldUserConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
  170. $userConfigPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
  171. if (file_exists($userConfigPath) && file_exists($oldUserConfigPath)) {
  172. $this->userConfigPath = $userConfigPath;
  173. } elseif (file_exists($oldUserConfigPath)) {
  174. $this->makeDir(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR);
  175. if ($this->rcopy($oldUserConfigPath, $userConfigPath)) {
  176. $this->userConfigPath = $userConfigPath;
  177. @unlink($oldUserConfigPath);
  178. } else {
  179. $this->userConfigPath = $oldUserConfigPath;
  180. }
  181. } else {
  182. $this->userConfigPath = $userConfigPath;
  183. }
  184. }
  185. public function hasConfig()
  186. {
  187. return (file_exists($this->userConfigPath)) ?? false;
  188. }
  189. public function hasDatabase($file = null)
  190. {
  191. $databaseType = $this->config['driver'];
  192. if (!$this->hasConfig()) {
  193. return false;
  194. }
  195. switch (strtolower($databaseType)) {
  196. case 'sqlite3':
  197. $file = $file ? $this->config['dbLocation'] . $file : $this->config['dbLocation'] . $this->config['dbName'];
  198. return [
  199. 'driver' => 'sqlite3',
  200. 'database' => $file
  201. ];
  202. case 'mysql':
  203. case 'mysqli':
  204. $db = $file ? 'tempMigration' : $this->config['dbName'];
  205. return [
  206. 'driver' => 'mysqli',
  207. 'host' => $this->config['dbHost'],
  208. 'username' => $this->config['dbUsername'],
  209. 'password' => $this->decrypt($this->config['dbPassword']),
  210. 'database' => $db,
  211. 'options' => [
  212. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  213. ],
  214. 'flags' => MYSQLI_CLIENT_COMPRESS,
  215. ];
  216. case 'postgre':
  217. $config = [
  218. 'driver' => 'postgre',
  219. 'username' => $this->config['dbUsername'],
  220. 'password' => $this->decrypt($this->config['dbPassword']),
  221. 'persistent' => true,
  222. ];
  223. $host = $this->qualifyURL($this->config['dbHost'], true);
  224. if ($host['port']) {
  225. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  226. }
  227. if ($host['host']) {
  228. $config = array_merge($config, ['host' => $host['host']]);
  229. }
  230. if (!$host['host'] && $host['path']) {
  231. $config = array_merge($config, ['host' => $host['path']]);
  232. }
  233. return $config;
  234. default:
  235. return false;
  236. }
  237. }
  238. protected function connectDB()
  239. {
  240. $databaseConnection = $this->hasDatabase();
  241. //$this->prettyPrint($databaseConnection);
  242. if ($databaseConnection) {
  243. try {
  244. $this->db = new Connection($databaseConnection);
  245. } catch (Dibi\Exception $e) {
  246. $this->db = null;
  247. }
  248. } else {
  249. $this->db = null;
  250. }
  251. }
  252. public function disconnectDB()
  253. {
  254. if ($this->db) {
  255. $this->db->disconnect();
  256. $this->db = null;
  257. unset($this->db);
  258. }
  259. }
  260. public function connectOtherDB($file = null)
  261. {
  262. $databaseConnection = $this->hasDatabase('tempMigration.db');
  263. if ($databaseConnection) {
  264. try {
  265. $this->otherDb = new Connection($databaseConnection);
  266. } catch (Dibi\Exception $e) {
  267. $this->prettyPrint($e->getMessage());
  268. $this->otherDb = null;
  269. }
  270. } else {
  271. $this->otherDb = null;
  272. }
  273. }
  274. public function setDeviceUUID()
  275. {
  276. if (!isset($_COOKIE['organizr_user_uuid'])) {
  277. $this->coookie('set', 'organizr_user_uuid', $this->gen_uuid(), 7);
  278. }
  279. }
  280. public function refreshDeviceUUID()
  281. {
  282. if (isset($_COOKIE['organizr_user_uuid'])) {
  283. $this->coookie('delete', 'organizr_user_uuid');
  284. }
  285. $this->coookie('set', 'organizr_user_uuid', $this->gen_uuid(), 7);
  286. }
  287. public function setCurrentUser($validate = true)
  288. {
  289. $user = false;
  290. if ($this->hasDatabase()) {
  291. if ($this->hasCookie()) {
  292. $user = $this->getUserFromToken($_COOKIE[$this->cookieName]);
  293. }
  294. }
  295. $this->user = ($user) ?: $this->guestUser();
  296. $this->setLoggerChannel(null, $this->user['username']);
  297. if ($validate) {
  298. $this->checkUserTokenForValidation();
  299. }
  300. }
  301. public function checkUserTokenForValidation()
  302. {
  303. if ($this->hasDB()) {
  304. if ($this->hasCookie()) {
  305. $this->validateToken($_COOKIE[$this->cookieName]);
  306. }
  307. }
  308. }
  309. public function phpErrors()
  310. {
  311. $errorTypes = $this->dev ? E_ERROR | E_WARNING | E_PARSE | E_NOTICE : 0;
  312. // Temp overwrite for now
  313. $displayErrors = $this->dev ? 1 : 0;
  314. error_reporting($this->errors);
  315. ini_set('display_errors', $displayErrors);
  316. }
  317. public function checkForOrganizrOAuth()
  318. {
  319. // Oauth?
  320. if ($this->hasDB() && $this->user) {
  321. if ($this->user['groupID'] == '999') {
  322. $this->setLoggerChannel('OAuth')->debug('Starting OAuth login check');
  323. $data = [
  324. 'enabled' => $this->config['authProxyEnabled'],
  325. 'header_name' => $this->config['authProxyHeaderName'],
  326. 'header_name_email' => $this->config['authProxyHeaderNameEmail'],
  327. 'whitelist' => $this->config['authProxyWhitelist'],
  328. ];
  329. if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
  330. if (isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])]) || isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])])) {
  331. $this->coookieSeconds('set', 'organizrOAuth', 'true', 20000, false);
  332. $this->setLoggerChannel('OAuth')->info('OAuth pre-check passed - adding organizrOAuth cookie', $data);
  333. } else {
  334. $data = array_merge($data, ['headers' => $this->getallheadersi()]);
  335. $this->setLoggerChannel('OAuth')->debug('Headers not set', $data);
  336. }
  337. } else {
  338. $this->setLoggerChannel('OAuth')->debug('OAuth not triggered', $data);
  339. }
  340. }
  341. }
  342. }
  343. public function checkIfUserIsBlacklisted()
  344. {
  345. if ($this->hasConfig()) {
  346. $currentIP = $this->userIP();
  347. if ($this->config['blacklisted'] !== '') {
  348. if (in_array($currentIP, $this->arrayIP($this->config['blacklisted']))) {
  349. $this->setLoggerChannel('Authentication');
  350. $this->logger->debug('User was sent to black hole', ['blacklist' => $this->config['blacklisted']]);
  351. die($this->showHTML('Blacklisted', $this->config['blacklistedMessage']));
  352. }
  353. }
  354. }
  355. }
  356. public function checkDiskSpace($directory = './')
  357. {
  358. $readable = @is_readable($directory);
  359. if ($readable) {
  360. $disk = $this->checkDisk($directory);
  361. $diskLevels = [
  362. 'warn' => 1000000000,
  363. 'warn_human_readable' => $this->human_filesize(1000000000, 0),
  364. 'error' => 100000000,
  365. 'error_human_readable' => $this->human_filesize(100000000, 0),
  366. ];
  367. if ($disk['free']['raw'] <= $diskLevels['error']) {
  368. die($this->showHTML('Low Disk Space', 'You are dangerously low on disk space.<br/>There is only ' . $disk['free']['human_readable'] . ' remaining.<br/><b>Percent Used = ' . $disk['used']['percent_used'] . '%</b>'));
  369. } elseif ($disk['free']['raw'] <= $diskLevels['warn']) {
  370. $this->warnings[] = 'You are low on disk space. There is only ' . $disk['free']['human_readable'] . ' remaining. This warning shows up because you are past the warning threshold of ' . $diskLevels['warn_human_readable'];
  371. }
  372. }
  373. return true;
  374. }
  375. public function getFreeSpace($directory = './')
  376. {
  377. $disk = disk_free_space($directory);
  378. return [
  379. 'raw' => $disk,
  380. 'human_readable' => $this->human_filesize($disk, 0)
  381. ];
  382. }
  383. public function getDiskSpace($directory = './')
  384. {
  385. $disk = disk_total_space($directory);
  386. return [
  387. 'raw' => $disk,
  388. 'human_readable' => $this->human_filesize($disk, 0)
  389. ];
  390. }
  391. public function getUsedSpace($directory = './')
  392. {
  393. $diskFree = $this->getFreeSpace($directory);
  394. $diskTotal = $this->getDiskSpace($directory);
  395. $diskUsed = $diskTotal['raw'] - $diskFree['raw'];
  396. $percentUsed = ($diskUsed / $diskTotal['raw']) * 100;
  397. $percentFree = 100 - $percentUsed;
  398. return [
  399. 'raw' => $diskUsed,
  400. 'human_readable' => $this->human_filesize($diskUsed, 0),
  401. 'percent_used' => round($percentUsed),
  402. 'percent_free' => round($percentFree)
  403. ];
  404. }
  405. public function checkDisk($directory = './')
  406. {
  407. $readable = @is_readable($directory);
  408. if ($readable) {
  409. return [
  410. 'free' => $this->getFreeSpace($directory),
  411. 'used' => $this->getUsedSpace($directory),
  412. 'total' => $this->getDiskSpace($directory),
  413. ];
  414. } else {
  415. return [
  416. 'free' => 'error accessing path',
  417. 'used' => 'error accessing path',
  418. 'total' => 'error accessing path',
  419. ];
  420. }
  421. }
  422. public function errorCodes($error = 000)
  423. {
  424. $errorCodes = [
  425. 400 => [
  426. 'type' => 'Bad Request',
  427. 'description' => 'The request was incorrect'
  428. ],
  429. 401 => [
  430. 'type' => 'Unauthorized ',
  431. 'description' => 'You are not authorized to view this page'
  432. ],
  433. 402 => [
  434. 'type' => 'Payment Required',
  435. 'description' => 'Payment required before you can view this page'
  436. ],
  437. 403 => [
  438. 'type' => 'Forbidden',
  439. 'description' => 'You are forbidden to view this page'
  440. ],
  441. 404 => [
  442. 'type' => 'Not Found',
  443. 'description' => 'The requested resource was not found'
  444. ],
  445. 405 => [
  446. 'type' => 'Method Not Allowed',
  447. 'description' => 'The requested method is not allowed'
  448. ],
  449. 406 => [
  450. 'type' => 'Not Acceptable',
  451. 'description' => 'There was an issue with the requests Headers'
  452. ],
  453. 407 => [
  454. 'type' => 'Proxy Authentication Required',
  455. 'description' => 'Authentication is required and was not passed'
  456. ],
  457. 408 => [
  458. 'type' => 'Request Time-out',
  459. 'description' => 'The request has timed out'
  460. ],
  461. 409 => [
  462. 'type' => 'Conflict',
  463. 'description' => 'An error has occurred'
  464. ],
  465. 410 => [
  466. 'type' => 'Gone',
  467. 'description' => 'The requested resource is no longer available and has been permanently removed'
  468. ],
  469. 411 => [
  470. 'type' => 'Length Required',
  471. 'description' => 'The request can not be processed without a "Content-Length" header field'
  472. ],
  473. 412 => [
  474. 'type' => 'Precondition Failed',
  475. 'description' => ' A header needed was not found'
  476. ],
  477. 413 => [
  478. 'type' => 'Request Entity Too Large',
  479. 'description' => 'The query was too large to be processed by the server'
  480. ],
  481. 414 => [
  482. 'type' => 'Request-URI Too Long',
  483. 'description' => 'The URI of the request was too long'
  484. ],
  485. 415 => [
  486. 'type' => 'Unsupported Media Type',
  487. 'description' => 'The contents of the request has been submitted with invalid or out of defined media type'
  488. ],
  489. 416 => [
  490. 'type' => 'Requested range not satisfiable',
  491. 'description' => 'The requested resource was part of an invalid or is not on the server'
  492. ],
  493. 417 => [
  494. 'type' => 'Expectation Failed',
  495. 'description' => 'Expected Header was not found'
  496. ],
  497. 444 => [
  498. 'type' => 'No Response',
  499. 'description' => 'Nothing was returned from server'
  500. ],
  501. 500 => [
  502. 'type' => 'Internal Server Error',
  503. 'description' => 'An unexpected server error'
  504. ],
  505. 501 => [
  506. 'type' => 'Not Implemented',
  507. 'description' => 'The functionality to process the request is not available from this server'
  508. ],
  509. 502 => [
  510. 'type' => 'Bad Gateway',
  511. 'description' => 'The server could not fulfill its function as a gateway or proxy'
  512. ],
  513. 503 => [
  514. 'type' => 'Service Unavailable',
  515. 'description' => 'The server is temporarily unavailable, due to overloading or maintenance'
  516. ],
  517. 504 => [
  518. 'type' => 'Gateway Time-out',
  519. 'description' => 'The server could not fulfill its function as a gateway or proxy'
  520. ],
  521. 505 => [
  522. 'type' => 'HTTP version not supported',
  523. 'description' => 'The used version of HTTP is not supported by the server or rejected'
  524. ],
  525. 507 => [
  526. 'type' => 'Insufficient Storage',
  527. 'description' => 'The request could not be processed because the server disk space it currently is not sufficient'
  528. ],
  529. 509 => [
  530. 'type' => 'Bandwidth Limit Exceeded',
  531. 'description' => 'The request was rejected, because otherwise the bandwidth would be exceeded'
  532. ],
  533. 510 => [
  534. 'type' => 'Not Extended',
  535. 'description' => 'The request does not contain all information that is waiting for the requested server extension imperative'
  536. ],
  537. 000 => [
  538. 'type' => 'Unexpected Error',
  539. 'description' => 'An unexpected error occurred'
  540. ],
  541. ];
  542. return (isset($errorCodes[$error])) ? $errorCodes[$error] : $errorCodes[000];
  543. }
  544. public function showTopBarHamburger()
  545. {
  546. if ($this->config['allowCollapsableSideMenu']) {
  547. if ($this->config['sideMenuCollapsed']) {
  548. return '<a class="toggle-side-menu" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
  549. } else {
  550. return '<a class="toggle-side-menu hidden" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
  551. }
  552. }
  553. return '';
  554. }
  555. public function showSideBarHamburger()
  556. {
  557. if ($this->config['allowCollapsableSideMenu']) {
  558. if (!$this->config['sideMenuCollapsed']) {
  559. return '<i class="hidden-xs ti-shift-left mouse"></i>';
  560. }
  561. }
  562. return '<i class="ti-menu hidden-xs"></i>';
  563. }
  564. public function showSideBarText()
  565. {
  566. if ($this->config['allowCollapsableSideMenu']) {
  567. if (!$this->config['sideMenuCollapsed']) {
  568. return '<span class="hide-menu hidden-xs" lang="en">Hide Menu</span>';
  569. }
  570. }
  571. return '<span class="hide-menu hidden-xs" lang="en">Navigation</span>';
  572. }
  573. public function auth()
  574. {
  575. if ($this->hasDB()) {
  576. $this->setLoggerChannel('Auth');
  577. if (isset($_GET['type'])) {
  578. switch (strtolower($_GET['type'])) {
  579. case 'whitelist':
  580. case 'white':
  581. case 'w':
  582. case 'wl':
  583. case 'allow':
  584. $_GET['whitelist'] = $_GET['ips'] ?? false;
  585. break;
  586. case 'blacklist':
  587. case 'black':
  588. case 'b':
  589. case 'bl':
  590. case 'deny':
  591. $_GET['blacklist'] = $_GET['ips'] ?? false;
  592. break;
  593. default:
  594. $this->setAPIResponse('error', $_GET['type'] . ' is not a valid type', 401);
  595. return true;
  596. }
  597. }
  598. $whitelist = $_GET['whitelist'] ?? false;
  599. $blacklist = $_GET['blacklist'] ?? false;
  600. $group = 0;
  601. $groupParam = ($_GET['group']) ?? 0;
  602. $redirect = false;
  603. if (isset($groupParam)) {
  604. if (is_numeric($groupParam)) {
  605. $group = (int)$groupParam;
  606. } else {
  607. $group = $this->getTabGroupByTabName($groupParam);
  608. }
  609. }
  610. $currentIP = $this->userIP();
  611. $unlocked = !($this->user['locked'] == '1');
  612. if (isset($this->user)) {
  613. $currentUser = $this->user['username'];
  614. $currentGroup = $this->user['groupID'];
  615. $currentEmail = $this->user['email'];
  616. } else {
  617. $currentUser = 'Guest';
  618. $currentGroup = $this->getUserLevel();
  619. $currentEmail = 'guest@guest.com';
  620. }
  621. $userInfo = [
  622. "user" => $currentUser,
  623. "group" => $currentGroup,
  624. "email" => $currentEmail,
  625. "user_ip" => $currentIP,
  626. "requested_group" => $group,
  627. "uuid" => $_COOKIE['organizr_user_uuid'] ?? 'n/a'
  628. ];
  629. $this->logger->debug('Starting check', $userInfo);
  630. $responseMessage = 'User is not Authorized or User is locked';
  631. if ($whitelist) {
  632. if (in_array($currentIP, $this->arrayIP($whitelist))) {
  633. $responseMessage = 'User is whitelisted';
  634. $this->setAPIResponse('success', $responseMessage, 200, $userInfo);
  635. $this->logger->debug($responseMessage, $userInfo);
  636. return true;
  637. }
  638. }
  639. if ($blacklist) {
  640. if (in_array($currentIP, $this->arrayIP($blacklist))) {
  641. $responseMessage = 'User is blacklisted';
  642. $this->setAPIResponse('error', $responseMessage, 401, $userInfo);
  643. $this->logger->debug($responseMessage, $userInfo);
  644. return true;
  645. }
  646. }
  647. if ($group !== null) {
  648. if ((isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER'] == 'traefik') || $this->config['traefikAuthEnable']) {
  649. $return = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && isset($_SERVER['HTTP_X_FORWARDED_URI']) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) ? '?return=' . $_SERVER['HTTP_X_FORWARDED_PROTO'] . '://' . $_SERVER['HTTP_X_FORWARDED_HOST'] . $_SERVER['HTTP_X_FORWARDED_URI'] : '';
  650. $redirectDomain = ($this->config['traefikDomainOverride'] !== '') ? $this->config['traefikDomainOverride'] : $this->getServerPath();
  651. $redirect = 'Location: ' . $redirectDomain . $return;
  652. }
  653. if ($this->qualifyRequest($group) && $unlocked) {
  654. header("X-Organizr-User: $currentUser");
  655. header("X-Organizr-Email: $currentEmail");
  656. header("X-Organizr-Group: $currentGroup");
  657. $responseMessage = 'User is authorized';
  658. $this->setAPIResponse('success', $responseMessage, 200, $userInfo);
  659. $this->logger->debug($responseMessage, $userInfo);
  660. } else {
  661. if (!$redirect) {
  662. $this->setAPIResponse('error', $responseMessage, 401, $userInfo);
  663. $this->logger->debug($responseMessage, $userInfo);
  664. } else {
  665. exit(http_response_code(401) . header($redirect));
  666. }
  667. }
  668. } else {
  669. $this->setAPIResponse('error', 'Missing info', 401);
  670. $this->logger->debug('Missing info', $userInfo);
  671. }
  672. return true;
  673. } else {
  674. $this->setAPIResponse('error', 'Organizr is not setup or an error occurred', 401);
  675. return false;
  676. }
  677. }
  678. public function getIpInfo($ip = null)
  679. {
  680. if (!$ip) {
  681. $this->setResponse(422, 'No IP Address supplied');
  682. return false;
  683. }
  684. try {
  685. $options = array('verify' => false);
  686. $response = Requests::get('https://ipinfo.io/' . $ip . '/?token=ddd0c072ad5021', array(), $options);
  687. if ($response->success) {
  688. $api = json_decode($response->body, true);
  689. $this->setResponse(200, null, $api);
  690. return true;
  691. } else {
  692. $this->setResponse(500, 'An error occurred', null);
  693. }
  694. } catch (Requests_Exception $e) {
  695. $this->setResponse(500, 'An error occurred', $e->getMessage());
  696. }
  697. return false;
  698. }
  699. public function setAPIResponse($result = null, $message = null, $responseCode = null, $data = null)
  700. {
  701. if ($result) {
  702. $GLOBALS['api']['response']['result'] = $result;
  703. }
  704. if ($message) {
  705. $GLOBALS['api']['response']['message'] = $message;
  706. }
  707. if ($responseCode) {
  708. $GLOBALS['responseCode'] = $responseCode;
  709. }
  710. if ($data) {
  711. $GLOBALS['api']['response']['data'] = $data;
  712. }
  713. }
  714. public function setResponse(int $responseCode = 200, string $message = null, $data = null)
  715. {
  716. switch ($responseCode) {
  717. case 200:
  718. case 201:
  719. case 204:
  720. $result = 'success';
  721. break;
  722. default:
  723. $result = 'error';
  724. break;
  725. }
  726. $GLOBALS['api']['response']['result'] = $result;
  727. if ($message) {
  728. $GLOBALS['api']['response']['message'] = $message;
  729. }
  730. if ($responseCode) {
  731. $GLOBALS['responseCode'] = $responseCode;
  732. }
  733. if ($data) {
  734. $GLOBALS['api']['response']['data'] = $data;
  735. }
  736. }
  737. public function printWarningsAndErrors()
  738. {
  739. if (isset($GLOBALS['api']['response']['exceptions'])) {
  740. $this->prettyPrint($GLOBALS['api']['response']['exceptions'], true);
  741. } else {
  742. $this->prettyPrint('No Errors');
  743. }
  744. }
  745. public function setAPIErrorResponse($number, $message, $file, $line)
  746. {
  747. if (!(error_reporting() & $number)) {
  748. return;
  749. }
  750. $exceptions = [
  751. E_ERROR => 'E_ERROR',
  752. E_WARNING => 'E_WARNING',
  753. E_PARSE => 'E_PARSE',
  754. E_NOTICE => 'E_NOTICE',
  755. E_CORE_ERROR => 'E_CORE_ERROR',
  756. E_CORE_WARNING => 'E_CORE_WARNING',
  757. E_COMPILE_ERROR => 'E_COMPILE_ERROR',
  758. E_COMPILE_WARNING => 'E_COMPILE_WARNING',
  759. E_USER_ERROR => 'E_USER_ERROR',
  760. E_USER_WARNING => 'E_USER_WARNING',
  761. E_USER_NOTICE => 'E_USER_NOTICE',
  762. E_STRICT => 'E_STRICT',
  763. E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
  764. E_DEPRECATED => 'E_DEPRECATED',
  765. E_USER_DEPRECATED => 'E_USER_DEPRECATED',
  766. E_ALL => 'E_ALL'
  767. ];
  768. switch ($number) {
  769. case E_USER_ERROR:
  770. case E_ERROR:
  771. case E_CORE_ERROR:
  772. case E_COMPILE_ERROR:
  773. case E_RECOVERABLE_ERROR:
  774. $type = 'errors';
  775. break;
  776. case E_USER_WARNING:
  777. case E_WARNING:
  778. case E_CORE_WARNING:
  779. case E_COMPILE_WARNING:
  780. $type = 'warnings';
  781. break;
  782. case E_USER_NOTICE:
  783. case E_PARSE:
  784. case E_DEPRECATED:
  785. case E_USER_DEPRECATED:
  786. case E_NOTICE:
  787. $type = 'notice';
  788. break;
  789. default:
  790. $type = 'other';
  791. break;
  792. }
  793. if ($this->qualifyRequest(1)) {
  794. $count = isset($GLOBALS['api']['response']['exceptions'][$type]) ? count($GLOBALS['api']['response']['exceptions'][$type]) : 0;
  795. if ($count <= 10) {
  796. $GLOBALS['api']['response']['exceptions'][$type][] = [
  797. 'error' => $exceptions[$number],
  798. 'message' => $message,
  799. 'file' => $file,
  800. 'line' => $line
  801. ];
  802. }
  803. }
  804. $this->handleError($exceptions[$number], $message, $file, $line, $type);
  805. }
  806. public function setErrorResponse($number, $message, $file, $line)
  807. {
  808. $error = [
  809. 'error' => $number,
  810. 'message' => $message,
  811. 'file' => $file,
  812. 'line' => $line
  813. ];
  814. $this->handleError($number, $message, $file, $line);
  815. //$this->prettyPrint($error, true);
  816. }
  817. public function handleError($number, $message, $file, $line, $type)
  818. {
  819. $log = false;
  820. $error = sprintf('Organizr %s: %s in %s on line %d', $number, $message, $file, $line);
  821. error_log($error);
  822. if ($this->dev) {
  823. $log = true;
  824. } else {
  825. if ($type == 'errors') {
  826. $log = true;
  827. }
  828. }
  829. if ($log && $this->hasDB()) {
  830. $this->setLoggerChannel('Server Error')->warning('PHP Error', $error);
  831. }
  832. }
  833. public function checkRoute($request)
  834. {
  835. $route = '/api/v2/' . explode('api/v2/', $request->getUri()->getPath())[1];
  836. $method = $request->getMethod();
  837. $data = $this->apiData($request);
  838. if (!in_array($route, $GLOBALS['bypass'])) {
  839. if ($this->isApprovedRequest($method, $data) === false) {
  840. $this->setAPIResponse('error', 'Not authorized for current Route: ' . $route, 401);
  841. $this->setLoggerChannel('API Security');
  842. $this->logger->notice('Killed Attack From [' . ($_SERVER['HTTP_REFERER'] ?? 'No Referer') . ']');
  843. return false;
  844. }
  845. }
  846. return true;
  847. }
  848. public function apiData($request, $decode = true)
  849. {
  850. switch ($request->getMethod()) {
  851. case 'POST':
  852. if (stripos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
  853. return $decode ? json_decode(file_get_contents('php://input', 'r'), true) : file_get_contents('php://input', 'r');
  854. } else {
  855. return $request->getParsedBody();
  856. }
  857. default:
  858. if (stripos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
  859. return $decode ? json_decode(file_get_contents('php://input', 'r'), true) : file_get_contents('php://input', 'r');
  860. } else {
  861. return null;
  862. }
  863. }
  864. }
  865. public function getPlugins($returnType = 'all')
  866. {
  867. if ($this->hasDB()) {
  868. switch ($returnType) {
  869. case 'enabled':
  870. $returnType = 'enabled';
  871. break;
  872. case 'disabled':
  873. $returnType = 'disabled';
  874. break;
  875. default:
  876. $returnType = 'all';
  877. }
  878. $pluginList = [];
  879. foreach ($GLOBALS['plugins'] as $key => $value) {
  880. if (strpos($value['license'], $this->config['license']) !== false) {
  881. $GLOBALS['plugins'][$key]['enabled'] = $this->config[$value['configPrefix'] . '-enabled'] ?? false;
  882. if ($returnType == 'all') {
  883. $pluginList[$key] = $GLOBALS['plugins'][$key];
  884. } elseif ($returnType == 'enabled' && $GLOBALS['plugins'][$key]['enabled'] == true) {
  885. $pluginList[$key] = $GLOBALS['plugins'][$key];
  886. } elseif ($returnType == 'disabled' && $GLOBALS['plugins'][$key]['enabled'] == false) {
  887. $pluginList[$key] = $GLOBALS['plugins'][$key];
  888. }
  889. }
  890. }
  891. asort($pluginList);
  892. return $pluginList;
  893. }
  894. return false;
  895. }
  896. public function refreshCookieName()
  897. {
  898. $this->cookieName = $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp';
  899. }
  900. public function favIcons($rootPath = '')
  901. {
  902. $favicon = '
  903. <link rel="apple-touch-icon" sizes="180x180" href="' . $rootPath . 'plugins/images/favicon/apple-touch-icon.png">
  904. <link rel="icon" type="image/png" sizes="32x32" href="' . $rootPath . 'plugins/images/favicon/favicon-32x32.png">
  905. <link rel="icon" type="image/png" sizes="16x16" href="' . $rootPath . 'plugins/images/favicon/favicon-16x16.png">
  906. <link rel="manifest" href="' . $rootPath . 'plugins/images/favicon/site.webmanifest" crossorigin="use-credentials">
  907. <link rel="mask-icon" href="' . $rootPath . 'plugins/images/favicon/safari-pinned-tab.svg" color="#5bbad5">
  908. <link rel="shortcut icon" href="' . $rootPath . 'plugins/images/favicon/favicon.ico">
  909. <meta name="msapplication-TileColor" content="#da532c">
  910. <meta name="msapplication-TileImage" content="' . $rootPath . 'plugins/images/favicon/mstile-144x144.png">
  911. <meta name="msapplication-config" content="' . $rootPath . 'plugins/images/favicon/browserconfig.xml">
  912. <meta name="theme-color" content="#ffffff">
  913. ';
  914. if ($this->config['favIcon'] !== '' && $rootPath !== '') {
  915. $this->config['favIcon'] = str_replace('data/favicon', $rootPath . 'data/favicon', $this->config['favIcon']);
  916. }
  917. return ($this->config['favIcon'] == '') ? $favicon : $this->config['favIcon'];
  918. }
  919. public function pluginGlobalList()
  920. {
  921. $pluginSearch = '-enabled';
  922. $pluginInclude = '-include';
  923. $plugins = array_filter($this->config, function ($k) use ($pluginSearch) {
  924. return stripos($k, $pluginSearch) !== false;
  925. }, ARRAY_FILTER_USE_KEY);
  926. $plugins['includes'] = array_filter($this->config, function ($k) use ($pluginInclude) {
  927. return stripos($k, $pluginInclude) !== false;
  928. }, ARRAY_FILTER_USE_KEY);
  929. return $plugins;
  930. }
  931. public function googleTracking()
  932. {
  933. if ($this->config['gaTrackingID'] !== '') {
  934. return '
  935. <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
  936. <script async src="https://www.googletagmanager.com/gtag/js?id=' . $this->config['gaTrackingID'] . '"></script>
  937. <script>
  938. window.dataLayer = window.dataLayer || [];
  939. function gtag(){dataLayer.push(arguments);}
  940. gtag("js", new Date());
  941. gtag("config","' . $this->config['gaTrackingID'] . '");
  942. </script>
  943. ';
  944. }
  945. return null;
  946. }
  947. public function matchBrackets($text, $brackets = 's')
  948. {
  949. switch ($brackets) {
  950. case 's':
  951. case 'square':
  952. $pattern = '#\[(.*?)\]#';
  953. break;
  954. case 'c':
  955. case 'curly':
  956. $pattern = '#\((.*?)\)#';
  957. break;
  958. default:
  959. return null;
  960. }
  961. preg_match($pattern, $text, $match);
  962. return $match[1];
  963. }
  964. public function languagePacks($encode = false)
  965. {
  966. $files = array();
  967. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'langpack' . DIRECTORY_SEPARATOR . "*.json") as $filename) {
  968. if (strpos(basename($filename), '[') !== false) {
  969. $explode = explode('[', basename($filename));
  970. $files[] = array(
  971. 'filename' => basename($filename),
  972. 'code' => $explode[0],
  973. 'language' => $this->matchBrackets(basename($filename))
  974. );
  975. }
  976. }
  977. usort($files, function ($a, $b) {
  978. return $a['language'] <=> $b['language'];
  979. });
  980. return ($encode) ? json_encode($files) : $files;
  981. }
  982. public function getRootPath()
  983. {
  984. $count = (count(explode('/', $_SERVER['REQUEST_URI']))) - 2;
  985. $rootPath = '';
  986. $rootPath .= str_repeat('../', $count);
  987. return $rootPath;
  988. }
  989. public function setTheme($theme = null, $rootPath = '')
  990. {
  991. $theme = $theme ?? $this->config['theme'];
  992. $themeInformation = $this->validateTheme($theme);
  993. if (!$themeInformation) {
  994. $themeInformation = $this->defaultThemeInformation()['information']['Organizr'];
  995. }
  996. return '<link id="theme" href="' . $rootPath . $themeInformation['path'] . '/' . $themeInformation['name'] . '.css?v=' . $this->fileHash . '" rel="stylesheet">';
  997. }
  998. public function validateTheme($theme = null)
  999. {
  1000. $theme = $theme ?? $this->config['theme'];
  1001. $information = $this->getAllThemesInformation();
  1002. if (isset($information[$theme])) {
  1003. return $information[$theme];
  1004. } else {
  1005. return null;
  1006. }
  1007. }
  1008. public function getAllThemesInformation()
  1009. {
  1010. $organizrThemes = $this->defaultThemeInformation();
  1011. $userThemes = $this->userThemeInformation();
  1012. if ($userThemes) {
  1013. return array_merge($organizrThemes['information'], $userThemes);
  1014. }
  1015. return $organizrThemes['information'];
  1016. }
  1017. public function userThemeInformation()
  1018. {
  1019. $themes = $this->config['installedThemes'];
  1020. if (is_array($themes)) {
  1021. return $themes;
  1022. } else {
  1023. return [];
  1024. }
  1025. }
  1026. public function defaultThemeInformation()
  1027. {
  1028. return [
  1029. 'files' => ['Blue', 'Organizr'],
  1030. 'information' => [
  1031. 'Blue' => [
  1032. 'name' => 'Blue',
  1033. 'repo' => null,
  1034. 'version' => '1.0.0',
  1035. 'path' => 'css/themes'
  1036. ],
  1037. 'Organizr' => [
  1038. 'name' => 'Organizr',
  1039. 'repo' => null,
  1040. 'version' => '1.0.0',
  1041. 'path' => 'css/themes'
  1042. ]
  1043. ]
  1044. ];
  1045. }
  1046. public function getAllThemes()
  1047. {
  1048. $organizrThemes = $this->getOrganizrThemes();
  1049. $userThemes = $this->getUserThemes();
  1050. if ($userThemes) {
  1051. return array_merge($organizrThemes, $userThemes);
  1052. }
  1053. return $organizrThemes;
  1054. }
  1055. public function getOrganizrThemes()
  1056. {
  1057. $themes = [];
  1058. $themeFolder = $this->root . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'themes';
  1059. $originalThemes = $this->defaultThemeInformation();
  1060. foreach (glob($themeFolder . DIRECTORY_SEPARATOR . '*.css') as $filename) {
  1061. $file = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename));
  1062. if (in_array($file, $originalThemes['files'])) {
  1063. $themes[] = array(
  1064. 'name' => $file,
  1065. 'value' => $file,
  1066. );
  1067. }
  1068. }
  1069. return $themes;
  1070. }
  1071. public function getUserThemes()
  1072. {
  1073. $themes = [];
  1074. $themeFolder = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes';
  1075. $userThemesInformation = $this->userThemeInformation();
  1076. if (file_exists($themeFolder)) {
  1077. $directoryIterator = new RecursiveDirectoryIterator($themeFolder, FilesystemIterator::SKIP_DOTS);
  1078. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1079. foreach ($iteratorIterator as $info) {
  1080. if (stripos($info->getFilename(), '.css') !== false) {
  1081. $file = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($info->getFilename()));
  1082. if (key_exists($file, $userThemesInformation)) {
  1083. $themes[] = [
  1084. 'name' => ucwords(str_replace('_', ' ', $file)),
  1085. 'value' => $file,
  1086. ];
  1087. }
  1088. }
  1089. }
  1090. }
  1091. return $themes;
  1092. }
  1093. public function setPluginListNameFromConfigPrefix()
  1094. {
  1095. foreach ($GLOBALS['plugins'] as $pluginName => $pluginInfo) {
  1096. $GLOBALS['pluginInfo'][strtolower($pluginInfo['configPrefix'])] = $pluginInfo;
  1097. $GLOBALS['pluginInfo'][strtolower($pluginName)] = $pluginInfo;
  1098. }
  1099. }
  1100. public function pluginFilesFromDirectory($directory, $webDirectory, $type, $settings = false, $rootPath = '')
  1101. {
  1102. $files = '';
  1103. if (file_exists($directory)) {
  1104. $directoryIterator = new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS);
  1105. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1106. switch ($type) {
  1107. case 'js':
  1108. foreach ($iteratorIterator as $info) {
  1109. if (pathinfo($info->getPathname(), PATHINFO_EXTENSION) == 'js') {
  1110. $pluginEnabled = false;
  1111. $keyOriginal = strtoupper(basename(dirname($info->getPathname())));
  1112. $key = str_replace('-SETTINGS', '', $keyOriginal);
  1113. $continue = false;
  1114. if ($settings) {
  1115. if ($info->getFilename() == 'settings.js') {
  1116. $continue = true;
  1117. }
  1118. } else {
  1119. if ($info->getFilename() !== 'settings.js') {
  1120. $continue = true;
  1121. }
  1122. }
  1123. switch ($key) {
  1124. case 'PHP-MAILER':
  1125. $key = 'PHPMAILER';
  1126. break;
  1127. case 'NGXC':
  1128. $key = 'ngxc';
  1129. break;
  1130. default:
  1131. $key = $key;
  1132. }
  1133. if (isset($this->config[$key . '-enabled'])) {
  1134. if ($this->config[$key . '-enabled']) {
  1135. $pluginEnabled = true;
  1136. }
  1137. }
  1138. if ($pluginEnabled || $settings) {
  1139. if ($continue) {
  1140. $version = $GLOBALS['pluginInfo'][strtolower($key)]['version'] ?? $this->fileHash;
  1141. $files .= '<script src="' . $rootPath . $webDirectory . basename(dirname($info->getPathname())) . '/' . basename($info->getFilename()) . '?v=' . $version . '" defer="true"></script>';
  1142. }
  1143. }
  1144. }
  1145. }
  1146. break;
  1147. case 'css':
  1148. foreach ($iteratorIterator as $info) {
  1149. if (pathinfo($info->getPathname(), PATHINFO_EXTENSION) == 'css') {
  1150. $key = basename(dirname($info->getPathname()));
  1151. $version = $GLOBALS['pluginInfo'][strtolower($key)]['version'] ?? $this->fileHash;
  1152. $files .= '<link href="' . $rootPath . $webDirectory . basename(dirname($info->getPathname())) . '/' . basename($info->getFilename()) . '?v=' . $version . '" rel="stylesheet">';
  1153. }
  1154. }
  1155. break;
  1156. default:
  1157. break;
  1158. }
  1159. }
  1160. return $files;
  1161. }
  1162. public function pluginFiles($type, $settings = false, $rootPath = '')
  1163. {
  1164. $files = '';
  1165. $organizrPlugins = $this->root . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'plugins';
  1166. $files .= $this->pluginFilesFromDirectory($organizrPlugins, 'api/plugins/', $type, $settings);
  1167. $userPlugins = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins';
  1168. $files .= $this->pluginFilesFromDirectory($userPlugins, 'data/plugins/', $type, $settings);
  1169. return $files;
  1170. }
  1171. public function formKey($script = true)
  1172. {
  1173. if (isset($this->config['organizrHash'])) {
  1174. if ($this->config['organizrHash'] !== '') {
  1175. $hash = password_hash(substr($this->config['organizrHash'], 2, 10), PASSWORD_BCRYPT);
  1176. return ($script) ? '<script>local("s","formKey","' . $hash . '");</script>' : $hash;
  1177. }
  1178. }
  1179. }
  1180. private function checkPHP()
  1181. {
  1182. if (!(version_compare(PHP_VERSION, $this->minimumPHP) >= 0)) {
  1183. die($this->showHTML('PHP Version', 'Organizr needs PHP Version: ' . $this->minimumPHP . '<br/> You have PHP Version: ' . PHP_VERSION));
  1184. }
  1185. }
  1186. private function checkWritableDB()
  1187. {
  1188. if ($this->hasDB()) {
  1189. if (isset($this->config['dbLocation']) && isset($this->config['dbName'])) {
  1190. $db = is_writable($this->config['dbLocation'] . $this->config['dbName']);
  1191. if (!$db) {
  1192. //die($this->showHTML('Organizr DB is not writable!', 'Please check permissions and/or disk space'));
  1193. }
  1194. } else {
  1195. die($this->showHTML('Config File Malformed', 'dbLocation and/or dbName is not listed in config.php'));
  1196. }
  1197. }
  1198. }
  1199. // Create config file in the return syntax
  1200. public function createConfig($array, $path = null, $nest = 0)
  1201. {
  1202. $path = ($path) ? $path : $this->userConfigPath;
  1203. // Define Initial Value
  1204. $output = array();
  1205. // Sort Items
  1206. ksort($array);
  1207. // Update the current config version
  1208. if (!$nest) {
  1209. // Inject Current Version
  1210. $output[] = "\t'configVersion' => '" . (isset($array['apply_CONFIG_VERSION']) ? $array['apply_CONFIG_VERSION'] : $this->version) . "'";
  1211. }
  1212. unset($array['configVersion']);
  1213. unset($array['apply_CONFIG_VERSION']);
  1214. // Process Settings
  1215. foreach ($array as $k => $v) {
  1216. $allowCommit = true;
  1217. $item = '';
  1218. switch (gettype($v)) {
  1219. case 'boolean':
  1220. $item = ($v ? 'true' : 'false');
  1221. break;
  1222. case 'integer':
  1223. case 'double':
  1224. case 'NULL':
  1225. $item = $v;
  1226. break;
  1227. case 'string':
  1228. $item = "'" . str_replace(array('\\', "'"), array('\\\\', "\'"), $v) . "'";
  1229. break;
  1230. case 'array':
  1231. $item = $this->createConfig($v, false, $nest + 1);
  1232. break;
  1233. default:
  1234. $allowCommit = false;
  1235. }
  1236. if ($allowCommit) {
  1237. $output[] = str_repeat("\t", $nest + 1) . "'$k' => $item";
  1238. }
  1239. }
  1240. // Build output
  1241. $output = (!$nest ? "<?php\nreturn " : '') . "[\n" . implode(",\n", $output) . "\n" . str_repeat("\t", $nest) . ']' . (!$nest ? ';' : '');
  1242. if (!$nest && $path) {
  1243. $pathDigest = pathinfo($path);
  1244. @mkdir($pathDigest['dirname'], 0770, true);
  1245. if (file_exists($path)) {
  1246. rename($path, $pathDigest['dirname'] . '/' . $pathDigest['filename'] . '.bak.php');
  1247. }
  1248. $file = fopen($path, 'w');
  1249. fwrite($file, $output);
  1250. fclose($file);
  1251. if (file_exists($path)) {
  1252. return true;
  1253. }
  1254. return false;
  1255. } else {
  1256. return $output;
  1257. }
  1258. }
  1259. // Commit new values to the configuration
  1260. public function updateConfig($new, $current = false)
  1261. {
  1262. // Get config if not supplied
  1263. if ($current === false) {
  1264. //$current = $this->loadConfig();
  1265. $current = $this->config;
  1266. } elseif (is_string($current) && is_file($current)) {
  1267. $current = $this->loadConfig($current);
  1268. }
  1269. // Inject Parts
  1270. foreach ($new as $k => $v) {
  1271. $current[$k] = $v;
  1272. $this->config[$k] = $v;
  1273. }
  1274. // Return Create
  1275. return $this->createConfig($current);
  1276. }
  1277. public function removeConfigItem($new, $current = false)
  1278. {
  1279. // Get config if not supplied
  1280. if ($current === false) {
  1281. $current = $this->config;
  1282. } elseif (is_string($current) && is_file($current)) {
  1283. $current = $this->loadConfig($current);
  1284. }
  1285. // Inject Parts
  1286. foreach ($new as $k) {
  1287. if (isset($current[$k])) {
  1288. $current['deletedConfigItems'][$k] = $current[$k];
  1289. $this->config['deletedConfigItems'][$k] = $current[$k];
  1290. }
  1291. unset($current[$k]);
  1292. unset($this->config[$k]);
  1293. }
  1294. // Return Create
  1295. return $this->createConfig($current);
  1296. }
  1297. public function loadConfig($path = null)
  1298. {
  1299. $path = ($path) ? $path : $this->userConfigPath;
  1300. if (!is_file($path)) {
  1301. return null;
  1302. } else {
  1303. return (array)call_user_func(function () use ($path) {
  1304. return include($path);
  1305. });
  1306. }
  1307. }
  1308. public function fillDefaultConfig($array)
  1309. {
  1310. $path = $this->defaultConfigPath;
  1311. if (is_string($path)) {
  1312. $loadedDefaults = $this->loadConfig($path);
  1313. } else {
  1314. $loadedDefaults = $path;
  1315. }
  1316. // Include all plugin config files
  1317. $folder = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'plugins';
  1318. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  1319. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1320. foreach ($iteratorIterator as $info) {
  1321. if ($info->getFilename() == 'config.php') {
  1322. $loadedDefaults = array_merge($loadedDefaults, $this->loadConfig($info->getPathname()));
  1323. }
  1324. }
  1325. /*
  1326. * Include all custom Plugin routes
  1327. */
  1328. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins')) {
  1329. $folder = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins';
  1330. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  1331. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  1332. foreach ($iteratorIterator as $info) {
  1333. if ($info->getFilename() == 'config.php') {
  1334. $loadedDefaults = array_merge($loadedDefaults, $this->loadConfig($info->getPathname()));
  1335. }
  1336. }
  1337. }
  1338. return (is_array($loadedDefaults) ? $this->fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  1339. }
  1340. public function fillDefaultConfig_recurse($current, $defaults)
  1341. {
  1342. foreach ($defaults as $k => $v) {
  1343. if (!isset($current[$k])) {
  1344. $current[$k] = $v;
  1345. } elseif (is_array($current[$k]) && is_array($v)) {
  1346. $current[$k] = $this->fillDefaultConfig_recurse($current[$k], $v);
  1347. }
  1348. }
  1349. return $current;
  1350. }
  1351. public function config($tries = 1)
  1352. {
  1353. // Load config or default
  1354. if (file_exists($this->userConfigPath)) {
  1355. $config = $this->fillDefaultConfig($this->loadConfig($this->userConfigPath));
  1356. } else {
  1357. $config = $this->fillDefaultConfig($this->loadConfig($this->defaultConfigPath));
  1358. }
  1359. if ((!is_array($config) || !file_exists($this->userConfigPath)) && $tries < 5) {
  1360. $tries++;
  1361. return $this->config($tries);
  1362. }
  1363. return $config;
  1364. }
  1365. public function combineConfig($array)
  1366. {
  1367. $this->config = array_merge($this->config, $array);
  1368. return $this->config;
  1369. }
  1370. public function status($action = false)
  1371. {
  1372. $status = [];
  1373. $dependenciesActive = [];
  1374. $dependenciesInactive = [];
  1375. $extensions = ['PDO_SQLITE', 'PDO', 'SQLITE3', 'zip', 'cURL', 'openssl', 'simplexml', 'json', 'session', 'filter'];
  1376. $functions = ['hash', 'fopen', 'fsockopen', 'fwrite', 'fclose', 'readfile'];
  1377. foreach ($extensions as $check) {
  1378. if (extension_loaded($check)) {
  1379. array_push($dependenciesActive, $check);
  1380. } else {
  1381. array_push($dependenciesInactive, $check);
  1382. }
  1383. }
  1384. foreach ($functions as $check) {
  1385. if (function_exists($check)) {
  1386. array_push($dependenciesActive, $check);
  1387. } else {
  1388. array_push($dependenciesInactive, $check);
  1389. }
  1390. }
  1391. $status['writable'] = is_writable(dirname(__DIR__, 2));
  1392. $status['minVersion'] = (version_compare(PHP_VERSION, $this->minimumPHP) >= 0);
  1393. $status['os'] = $this->getOS();
  1394. $status['php'] = phpversion();
  1395. $status['userConfigPathExists'] = file_exists($this->userConfigPath);
  1396. if (!($status['minVersion'])) {
  1397. $status['action'] = 'php';
  1398. if ($action) {
  1399. header($this->getServerPath() . 'api/v2/organizr/error');
  1400. exit;
  1401. }
  1402. } elseif (count($dependenciesInactive) > 0) {
  1403. $status['action'] = 'dependencies';
  1404. } elseif (!$status['writable']) {
  1405. $status['action'] = 'permission';
  1406. } elseif (!$status['userConfigPathExists']) {
  1407. $status['action'] = 'wizard';
  1408. } else {
  1409. $status['action'] = 'launch';
  1410. if ($action) {
  1411. echo '<script type="text/javascript"> window.location.href="' . $this->getServerPath() . 'api/v2/organizr/error/409' . '";</script>';
  1412. exit;
  1413. }
  1414. }
  1415. return $status;
  1416. }
  1417. public function launch()
  1418. {
  1419. $status = array();
  1420. $dependenciesActive = array();
  1421. $dependenciesInactive = array();
  1422. $extensions = array('PDO_SQLITE', 'PDO', 'SQLITE3', 'zip', 'cURL', 'openssl', 'simplexml', 'json', 'session', 'filter');
  1423. $functions = array('hash', 'fopen', 'fsockopen', 'fwrite', 'fclose', 'readfile');
  1424. foreach ($extensions as $check) {
  1425. if (extension_loaded($check)) {
  1426. array_push($dependenciesActive, $check);
  1427. } else {
  1428. array_push($dependenciesInactive, $check);
  1429. }
  1430. }
  1431. foreach ($functions as $check) {
  1432. if (function_exists($check)) {
  1433. array_push($dependenciesActive, $check);
  1434. } else {
  1435. array_push($dependenciesInactive, $check);
  1436. }
  1437. }
  1438. if (!file_exists($this->userConfigPath)) {
  1439. $status['status'] = 'wizard';//wizard - ok for test
  1440. }
  1441. if (count($dependenciesInactive) > 0 || !is_writable(dirname(__DIR__, 2)) || !(version_compare(PHP_VERSION, $this->minimumPHP) >= 0)) {
  1442. $status['status'] = 'dependencies';
  1443. }
  1444. $status['status'] = ($status['status']) ?? 'ok';
  1445. $status['writable'] = is_writable(dirname(__DIR__, 2)) ? 'yes' : 'no';
  1446. $status['minVersion'] = (version_compare(PHP_VERSION, $this->minimumPHP) >= 0) ? 'yes' : 'no';
  1447. $status['dependenciesActive'] = $dependenciesActive;
  1448. $status['dependenciesInactive'] = $dependenciesInactive;
  1449. $status['version'] = $this->version;
  1450. $status['os'] = $this->getOS();
  1451. $status['php'] = phpversion();
  1452. $status['php_user'] = get_current_user();
  1453. $status['userConfigPath'] = $this->userConfigPath;
  1454. return $status;
  1455. }
  1456. public function hasDB()
  1457. {
  1458. return (file_exists($this->userConfigPath)) ?? false;
  1459. }
  1460. public function hasCookie()
  1461. {
  1462. return ($_COOKIE[$this->cookieName]) ?? false;
  1463. }
  1464. public function getGuest()
  1465. {
  1466. $guest = array(
  1467. 'group' => 'Guest',
  1468. 'group_id' => 999,
  1469. 'image' => 'plugins/images/groups/guest.png'
  1470. );
  1471. $response = [
  1472. array(
  1473. 'function' => 'fetch',
  1474. 'query' => 'SELECT * FROM groups WHERE `group_id` = 999'
  1475. ),
  1476. ];
  1477. return $this->hasDB() ? $this->processQueries($response) : $guest;
  1478. }
  1479. public function getSchema()
  1480. {
  1481. if ($this->config['driver'] == 'sqlite3') {
  1482. $response = [
  1483. array(
  1484. 'function' => 'fetchAll',
  1485. 'query' => 'SELECT name, sql FROM sqlite_master WHERE type=\'table\' ORDER BY name'
  1486. ),
  1487. ];
  1488. return $this->hasDB() ? $this->processQueries($response) : 'Database not setup yet';
  1489. } else {
  1490. return false;
  1491. }
  1492. }
  1493. public function guestUser()
  1494. {
  1495. if ($this->hasDB()) {
  1496. if ($this->getUserLevel() !== 999) {
  1497. $guest = array(
  1498. "token" => null,
  1499. "tokenDate" => null,
  1500. "tokenExpire" => null,
  1501. "username" => "Organizr API",
  1502. "uid" => $this->guestHash(0, 5),
  1503. "group" => 'Admin',
  1504. "groupID" => 0,
  1505. "email" => null,
  1506. //"groupImage"=>getGuest()['image'],
  1507. "image" => $this->getGuest()['image'],
  1508. "userID" => null,
  1509. "loggedin" => false,
  1510. "locked" => false,
  1511. "tokenList" => null,
  1512. "authService" => null
  1513. );
  1514. }
  1515. }
  1516. $guest = $guest ?? array(
  1517. "token" => null,
  1518. "tokenDate" => null,
  1519. "tokenExpire" => null,
  1520. "username" => "Guest",
  1521. "uid" => $this->guestHash(0, 5),
  1522. "group" => $this->getGuest()['group'],
  1523. "groupID" => $this->getGuest()['group_id'],
  1524. "email" => null,
  1525. //"groupImage"=>getGuest()['image'],
  1526. "image" => $this->getGuest()['image'],
  1527. "userID" => null,
  1528. "loggedin" => false,
  1529. "locked" => false,
  1530. "tokenList" => null,
  1531. "authService" => null
  1532. );
  1533. return $guest;
  1534. }
  1535. public function getAllUserTokens($id, $includeAllFields = true)
  1536. {
  1537. $select = $includeAllFields ? '*' : 'token, ip, id, expires, created';
  1538. $response = [
  1539. array(
  1540. 'function' => 'fetchAll',
  1541. 'query' => array(
  1542. 'SELECT ' . $select . ' FROM `tokens` WHERE user_id = ? AND expires > ?',
  1543. [$id],
  1544. [$this->currentTime]
  1545. )
  1546. ),
  1547. ];
  1548. return $this->processQueries($response);
  1549. }
  1550. public function getUserById($id)
  1551. {
  1552. $response = [
  1553. array(
  1554. 'function' => 'fetch',
  1555. 'query' => array(
  1556. 'SELECT * FROM users WHERE id = ?',
  1557. $id
  1558. )
  1559. )
  1560. ];
  1561. return $this->processQueries($response);
  1562. }
  1563. public function getUserByEmail($email)
  1564. {
  1565. $response = [
  1566. array(
  1567. 'function' => 'fetch',
  1568. 'query' => array(
  1569. 'SELECT * FROM users WHERE email = ? COLLATE NOCASE',
  1570. $email
  1571. )
  1572. )
  1573. ];
  1574. return $this->processQueries($response);
  1575. }
  1576. protected function invalidToken($token)
  1577. {
  1578. if (isset($_COOKIE[$this->cookieName])) {
  1579. if ($token == $_COOKIE[$this->cookieName]) {
  1580. $this->setLoggerChannel('Authentication');
  1581. $this->logger->debug('Token was invalid - deleting cookie and user session');
  1582. $this->coookie('delete', $this->cookieName);
  1583. $this->user = null;
  1584. }
  1585. }
  1586. }
  1587. public function validateToken($token, $api = false)
  1588. {
  1589. // Validate script
  1590. $userInfo = $this->jwtParse($token);
  1591. $validated = (bool)$userInfo;
  1592. if ($validated == true) {
  1593. $allTokens = $this->getAllUserTokens($userInfo['userID']);
  1594. $user = $this->getUserById($userInfo['userID']);
  1595. $tokenKey = $this->searchArray($allTokens, 'token', $token);
  1596. $tokenCheck = ($tokenKey !== false);
  1597. if (!$tokenCheck) {
  1598. $this->setLoggerChannel('Authentication');
  1599. $this->logger->debug('Token failed check against all token listings', $allTokens);
  1600. $this->invalidToken($token);
  1601. if ($api) {
  1602. $this->setResponse(403, 'Token was not in approved list');
  1603. }
  1604. return false;
  1605. } else {
  1606. // Check if user is on same browser as token
  1607. if ($allTokens[$tokenKey]['browser'] !== $_SERVER ['HTTP_USER_AGENT']) {
  1608. if ($this->config['matchUserAgents']) {
  1609. $this->setLoggerChannel('Authentication')->warning('Mismatch of useragent', ['token' => $allTokens[$tokenKey]['browser'], 'browser' => $_SERVER ['HTTP_USER_AGENT']]);
  1610. $this->invalidToken($token);
  1611. return false;
  1612. }
  1613. }
  1614. if (($allTokens[$tokenKey]['ip'] !== $this->userIP()) && (!$this->isLocalOrServer())) {
  1615. if ($this->config['matchUserIP']) {
  1616. $this->setLoggerChannel('Authentication')->warning('Mismatch of user IP', ['token' => $allTokens[$tokenKey]['ip'], 'user' => $this->userIP()]);
  1617. $this->invalidToken($token);
  1618. return false;
  1619. }
  1620. }
  1621. if ($api) {
  1622. $this->setResponse(200, 'Token is valid');
  1623. }
  1624. return array(
  1625. 'token' => $token,
  1626. 'tokenDate' => $userInfo['tokenDate'],
  1627. 'tokenExpire' => $userInfo['tokenExpire'],
  1628. 'username' => $user['username'] ?? $userInfo['username'],
  1629. 'uid' => $this->guestHash(0, 5),
  1630. 'group' => $user['group'] ?? $userInfo['group'],
  1631. 'groupID' => $user['group_id'] ?? $userInfo['groupID'],
  1632. 'email' => $user['email'] ?? $userInfo['email'],
  1633. 'image' => $user['image'] ?? $userInfo['image'],
  1634. 'userID' => $user['id'] ?? $userInfo['userID'],
  1635. 'loggedin' => true,
  1636. 'locked' => $user['locked'] ?? 0,
  1637. 'tokenList' => $allTokens,
  1638. 'authService' => (isset($user['auth_service'])) ? explode('::', $user['auth_service'])[0] : 'internal'
  1639. );
  1640. }
  1641. } else {
  1642. if ($api) {
  1643. $this->setResponse(403, 'Token was invalid');
  1644. }
  1645. $this->setLoggerChannel('Authentication');
  1646. $this->logger->debug('User token was invalid', ['token' => $token]);
  1647. $this->invalidToken($token);
  1648. }
  1649. if ($api) {
  1650. $this->setResponse(403, 'Token was invalid');
  1651. }
  1652. return false;
  1653. }
  1654. public function getUserFromToken($token)
  1655. {
  1656. // Validate script
  1657. $userInfo = $this->jwtParse($token);
  1658. $validated = (bool)$userInfo;
  1659. if ($validated == true) {
  1660. $user = $this->getUserById($userInfo['userID']);
  1661. $allTokens = $this->getAllUserTokens($userInfo['userID'], false);
  1662. return array(
  1663. 'token' => $token,
  1664. 'tokenDate' => $userInfo['tokenDate'],
  1665. 'tokenExpire' => $userInfo['tokenExpire'],
  1666. 'username' => $user['username'] ?? $userInfo['username'],
  1667. 'uid' => $this->guestHash(0, 5),
  1668. 'group' => $user['group'] ?? $userInfo['group'],
  1669. 'groupID' => $user['group_id'] ?? $userInfo['groupID'],
  1670. 'email' => $user['email'] ?? $userInfo['email'],
  1671. 'image' => $user['image'] ?? $userInfo['image'],
  1672. 'userID' => $user['id'] ?? $userInfo['userID'],
  1673. 'loggedin' => true,
  1674. 'locked' => $user['locked'] ?? 0,
  1675. 'tokenList' => $allTokens,
  1676. 'authService' => (isset($user['auth_service'])) ? explode('::', $user['auth_service'])[0] : 'internal'
  1677. );
  1678. }
  1679. return false;
  1680. }
  1681. public function defaultUserGroup()
  1682. {
  1683. $response = [
  1684. array(
  1685. 'function' => 'fetch',
  1686. 'query' => 'SELECT * FROM groups WHERE `default` = 1'
  1687. )
  1688. ];
  1689. return $this->processQueries($response);
  1690. }
  1691. public function getAllTabs()
  1692. {
  1693. $response = [
  1694. array(
  1695. 'function' => 'fetchAll',
  1696. 'query' => 'SELECT * FROM tabs ORDER BY `order` ASC',
  1697. 'key' => 'tabs'
  1698. ),
  1699. array(
  1700. 'function' => 'fetchAll',
  1701. 'query' => 'SELECT * FROM categories ORDER BY `order` ASC',
  1702. 'key' => 'categories'
  1703. ),
  1704. array(
  1705. 'function' => 'fetchAll',
  1706. 'query' => 'SELECT * FROM groups ORDER BY `group_id` ASC',
  1707. 'key' => 'groups'
  1708. ),
  1709. ];
  1710. $query = $this->processQueries($response);
  1711. $this->applyTabVariables($query['tabs']);
  1712. return $query;
  1713. }
  1714. public function applyTabVariables($tabs)
  1715. {
  1716. $variables = [
  1717. '{domain}' => $this->getServer(),
  1718. '{username}' => $this->user['username'],
  1719. '{username_lower}' => $this->user['username'],
  1720. '{email}' => $this->user['email'],
  1721. '{group}' => $this->user['group'],
  1722. '{group_id}' => $this->user['groupID'],
  1723. '{komga}' => $_COOKIE['komga_token'] ?? ''
  1724. ];
  1725. if (empty($tabs)) {
  1726. return $tabs;
  1727. }
  1728. foreach ($tabs as $id => $tab) {
  1729. $tabs[$id]['url'] = $this->userDefinedIdReplacementLink($tab['url'], $variables);
  1730. $tabs[$id]['url_local'] = $this->userDefinedIdReplacementLink($tab['url_local'], $variables);
  1731. }
  1732. return $tabs;
  1733. }
  1734. public function getUsers()
  1735. {
  1736. $response = [
  1737. array(
  1738. 'function' => 'fetchAll',
  1739. 'query' => 'SELECT * FROM users'
  1740. ),
  1741. array(
  1742. 'function' => 'fetchAll',
  1743. 'query' => 'SELECT * FROM groups ORDER BY group_id ASC'
  1744. ),
  1745. ];
  1746. return $this->processQueries($response);
  1747. }
  1748. public function usernameTaken($username, $email, $id = null)
  1749. {
  1750. if ($id) {
  1751. $response = [
  1752. array(
  1753. 'function' => 'fetch',
  1754. 'query' => array(
  1755. 'SELECT * FROM users WHERE `id` != ? AND (username = ? COLLATE NOCASE or email = ? COLLATE NOCASE)',
  1756. $id,
  1757. $username,
  1758. $email
  1759. )
  1760. ),
  1761. ];
  1762. } else {
  1763. $response = [
  1764. array(
  1765. 'function' => 'fetch',
  1766. 'query' => array(
  1767. 'SELECT * FROM users WHERE username = ? COLLATE NOCASE or email = ? COLLATE NOCASE',
  1768. [$username],
  1769. [$email]
  1770. )
  1771. ),
  1772. ];
  1773. }
  1774. return $this->processQueries($response);
  1775. }
  1776. public function cleanPageName($page)
  1777. {
  1778. return ($page) ? strtolower(str_replace(array('%20', ' ', '-', '_'), '_', $page)) : '';
  1779. }
  1780. public function cleanClassName($name, $char = '-')
  1781. {
  1782. return ($name) ? (str_replace(array('%20', ' ', '-', '_'), $char, strtolower($name))) : '';
  1783. }
  1784. public function reverseCleanClassName($name)
  1785. {
  1786. return ($name) ? (str_replace(array('%20', '-', '_'), ' ', strtolower($name))) : '';
  1787. }
  1788. public function getPageList()
  1789. {
  1790. return $GLOBALS['organizrPages'];
  1791. }
  1792. public function getPage($page)
  1793. {
  1794. if (!$page) {
  1795. $this->setAPIResponse('error', 'Page not setup', 409);
  1796. return null;
  1797. }
  1798. $pageFunction = 'get_page_' . $this->cleanPageName($page);
  1799. if (function_exists($pageFunction)) {
  1800. return $pageFunction($this);
  1801. } else {
  1802. $this->setAPIResponse('error', 'Page not setup', 409);
  1803. return null;
  1804. }
  1805. }
  1806. public function getUserLevel()
  1807. {
  1808. // Grab token
  1809. $requesterToken = $this->getallheadersi()['token'] ?? ($_GET['apikey'] ?? false);
  1810. $apiKey = ($this->config['organizrAPI']) ?? null;
  1811. // Check token or API key
  1812. // If API key, return 0 for admin
  1813. if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
  1814. //DO API CHECK
  1815. return 0;
  1816. } elseif (isset($this->user)) {
  1817. return $this->user['groupID'];
  1818. }
  1819. // All else fails? return guest id
  1820. return 999;
  1821. }
  1822. public function qualifyRequest($accessLevelNeeded, $api = false)
  1823. {
  1824. if ($this->getUserLevel() <= $accessLevelNeeded && $this->getUserLevel() !== null) {
  1825. return true;
  1826. } else {
  1827. if ($api) {
  1828. $this->setAPIResponse('error', 'Not Authorized', 401);
  1829. }
  1830. return false;
  1831. }
  1832. }
  1833. public function qualifyLength($string, $length = 100, $api = false)
  1834. {
  1835. if (strlen($string) <= $length) {
  1836. return true;
  1837. } else {
  1838. if ($api) {
  1839. $this->setResponse(409, 'String is over limit of: ' . $length);
  1840. }
  1841. return false;
  1842. }
  1843. }
  1844. public function getImages()
  1845. {
  1846. $allIconsPrep = array();
  1847. $allIcons = array();
  1848. $ignore = array(".", "..", "._.DS_Store", ".DS_Store", ".pydio_id", "index.html");
  1849. $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'tabs' . DIRECTORY_SEPARATOR;
  1850. $path = 'plugins/images/tabs/';
  1851. $images = scandir($dirname);
  1852. foreach ($images as $image) {
  1853. if (!in_array($image, $ignore)) {
  1854. $allIconsPrep[$image] = array(
  1855. 'path' => $path,
  1856. 'name' => $image
  1857. );
  1858. }
  1859. }
  1860. $dirname = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1861. $path = 'data/userTabs/';
  1862. if (file_exists($dirname)) {
  1863. $images = scandir($dirname);
  1864. foreach ($images as $image) {
  1865. if (!in_array($image, $ignore)) {
  1866. $allIconsPrep[$image] = array(
  1867. 'path' => $path,
  1868. 'name' => $image
  1869. );
  1870. }
  1871. }
  1872. }
  1873. uksort($allIconsPrep, 'strcasecmp');
  1874. foreach ($allIconsPrep as $item) {
  1875. $allIcons[] = $item['path'] . $item['name'];
  1876. }
  1877. return $allIcons;
  1878. }
  1879. public function getImagesSelect()
  1880. {
  1881. $term = $_GET['search'] ?? null;
  1882. $page = $_GET['page'] ?? 1;
  1883. $limit = $_GET['limit'] ?? 20;
  1884. $offset = ($page * $limit) - $limit;
  1885. $goodIcons['results'] = [];
  1886. $goodIcons['limit'] = $limit;
  1887. $goodIcons['page'] = $page;
  1888. $goodIcons['term'] = $term;
  1889. $imageListing = $this->getImages();
  1890. $newImageListing = [];
  1891. foreach ($imageListing as $image) {
  1892. $newImageListing[] = [
  1893. 'id' => $image,
  1894. 'text' => basename($image)
  1895. ];
  1896. }
  1897. foreach ($newImageListing as $k => $v) {
  1898. if ($term) {
  1899. if (stripos($v['text'], $term) !== false) {
  1900. $goodIcons['results'][] = $v;
  1901. }
  1902. } else {
  1903. $goodIcons['results'][] = $v;
  1904. }
  1905. }
  1906. $total = count($goodIcons['results']);
  1907. $goodIcons['total'] = $total;
  1908. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  1909. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  1910. return $goodIcons;
  1911. }
  1912. public function removeImage($image = null)
  1913. {
  1914. if (!$image) {
  1915. $this->setAPIResponse('error', 'No image supplied', 422);
  1916. return false;
  1917. }
  1918. $approvedPath = 'data/userTabs/';
  1919. $removeImage = $approvedPath . pathinfo($image, PATHINFO_BASENAME);
  1920. if ($this->approvedFileExtension($removeImage, 'image')) {
  1921. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage)) {
  1922. $this->setLoggerChannel('Image Manager');
  1923. $this->logger->info('Image Manager Function - Deleted Image [' . pathinfo($image, PATHINFO_BASENAME) . ']');
  1924. $this->setAPIResponse(null, pathinfo($image, PATHINFO_BASENAME) . ' has been deleted', null);
  1925. return (unlink(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage));
  1926. } else {
  1927. $this->setAPIResponse('error', $removeImage . ' does not exist', 404);
  1928. return false;
  1929. }
  1930. } else {
  1931. $this->setAPIResponse('error', $removeImage . ' is not approved to be deleted', 409);
  1932. return false;
  1933. }
  1934. }
  1935. public function uploadImage()
  1936. {
  1937. $filesCheck = array_filter($_FILES);
  1938. if (!empty($filesCheck)) {
  1939. if (strpos($_FILES['file']['type'], 'image/') === false) {
  1940. $this->setResponse(403, 'File Type not approved', $_FILES['file']['type']);
  1941. return false;
  1942. }
  1943. if (!$this->approvedFileType($_FILES['file']['tmp_name'])) {
  1944. $this->setResponse(403, 'File Type not approved', $_FILES['file']['tmp_name']);
  1945. return false;
  1946. }
  1947. if ($this->approvedFileExtension($_FILES['file']['name'])) {
  1948. ini_set('upload_max_filesize', '10M');
  1949. ini_set('post_max_size', '10M');
  1950. $tempFile = $_FILES['file']['tmp_name'];
  1951. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1952. $this->makeDir($targetPath);
  1953. $targetFile = $targetPath . $this->sanitizeUserString($_FILES['file']['name']);
  1954. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  1955. return move_uploaded_file($tempFile, $targetFile);
  1956. } else {
  1957. $this->setResponse(403, 'File Extension not approved');
  1958. return false;
  1959. }
  1960. } else {
  1961. $this->setResponse(500, 'No File was uploaded');
  1962. return false;
  1963. }
  1964. }
  1965. public function formatPingHost($host)
  1966. {
  1967. $host = $this->qualifyURL($host, true);
  1968. if ($host['port'] !== '') {
  1969. $host['port'] = str_replace(':', '', $host['port']);
  1970. }
  1971. if ($host['host'] == '' && $host['path'] !== '') {
  1972. $host['host'] = $host['path'];
  1973. $host['path'] = '';
  1974. if (strpos($host['host'], '/') !== false) {
  1975. $host['host'] = explode('/', $host['host'])[0];
  1976. }
  1977. }
  1978. return $host;
  1979. }
  1980. public function ping($pings)
  1981. {
  1982. if ($this->qualifyRequest($this->config['pingAuth'], true)) {
  1983. if (!$pings['list']) {
  1984. $this->setAPIResponse('error', 'No ping hostname/IP\'s entered', 409);
  1985. return null;
  1986. }
  1987. $pings = $pings['list'];
  1988. $type = gettype($pings);
  1989. $ping = new Ping("");
  1990. $ping->setTtl(128);
  1991. $ping->setTimeout(2);
  1992. switch ($type) {
  1993. case "array":
  1994. $results = [];
  1995. foreach ($pings as $k => $v) {
  1996. $pingFormatted = $this->formatPingHost($v);
  1997. $ping->setHost($pingFormatted['host']);
  1998. if ($pingFormatted['port'] !== '') {
  1999. $ping->setPort($pingFormatted['port']);
  2000. $latency = $ping->ping('fsockopen');
  2001. } else {
  2002. $latency = $ping->ping();
  2003. }
  2004. if ($latency || $latency === 0) {
  2005. $results[$v] = $latency;
  2006. } else {
  2007. $results[$v] = false;
  2008. }
  2009. }
  2010. break;
  2011. case "string":
  2012. $pingFormatted = $this->formatPingHost($pings);
  2013. $ping->setHost($pingFormatted['host']);
  2014. if ($pingFormatted['port'] !== '') {
  2015. $ping->setPort($pingFormatted['port']);
  2016. $latency = $ping->ping('fsockopen');
  2017. } else {
  2018. $latency = $ping->ping();
  2019. }
  2020. if ($latency || $latency === 0) {
  2021. $results = $latency;
  2022. } else {
  2023. $results = null;
  2024. }
  2025. break;
  2026. }
  2027. return ($results) ?? null;
  2028. }
  2029. return null;
  2030. }
  2031. public function getPluginSettings()
  2032. {
  2033. return [
  2034. 'Marketplace' => [
  2035. $this->settingsOption('notice', null, ['notice' => 'danger', 'body' => '3rd Party Repositories are not affiliated with Organizr and therefore the code on these repositories are not inspected. Use at your own risk.']),
  2036. $this->settingsOption('multiple-url', 'externalPluginMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  2037. $this->settingsOption('token', 'githubAccessToken', ['label' => 'Github Person Access Token', 'help' => 'The Github Person Access Token will help with API rate limiting as well as let you access your own Private Repos']),
  2038. $this->settingsOption('switch', 'checkForPluginUpdate', ['label' => 'Check for Plugin Updates', ['help' => 'Check for updates on page load']])
  2039. ]
  2040. ];
  2041. }
  2042. public function getThemeSettings()
  2043. {
  2044. return [
  2045. 'Marketplace' => [
  2046. $this->settingsOption('notice', null, ['notice' => 'danger', 'body' => '3rd Party Repositories are not affiliated with Organizr and therefore the themes on these repositories are not inspected. Use at your own risk.']),
  2047. $this->settingsOption('multiple-url', 'externalThemeMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  2048. $this->settingsOption('token', 'githubAccessToken', ['label' => 'Github Person Access Token', 'help' => 'The Github Person Access Token will help with API rate limiting as well as let you access your own Private Repos']),
  2049. $this->settingsOption('switch', 'checkForThemeUpdate', ['label' => 'Check for Theme Updates', ['help' => 'Check for updates on page load']])
  2050. ]
  2051. ];
  2052. }
  2053. public function getCustomizeAppearance()
  2054. {
  2055. return [
  2056. 'Top Bar' => [
  2057. $this->settingsOption('input', 'logo', ['label' => 'Logo URL']),
  2058. $this->settingsOption('input', 'title', ['label' => 'Organizr Title']),
  2059. $this->settingsOption('switch', 'useLogo', ['label' => 'Use Logo instead of Title', 'help' => 'Also sets the title of your site']),
  2060. $this->settingsOption('input', 'description', ['label' => 'Meta Description', 'help' => 'Used to set the description for SEO meta tags']),
  2061. ],
  2062. 'Side Menu' => [
  2063. $this->settingsOption('switch', 'allowCollapsableSideMenu', ['label' => 'Allow Side Menu to be Collapsable']),
  2064. $this->settingsOption('switch', 'sideMenuCollapsed', ['label' => 'Side Menu Collapsed at Launch']),
  2065. $this->settingsOption('switch', 'collapseSideMenuOnClick', ['label' => 'Collapse Side Menu after clicking Tab']),
  2066. $this->settingsOption('switch', 'githubMenuLink', ['label' => 'Show GitHub Repo Link']),
  2067. $this->settingsOption('switch', 'organizrFeatureRequestLink', ['label' => 'Show Organizr Feature Request Link']),
  2068. $this->settingsOption('switch', 'organizrSupportMenuLink', ['label' => 'Show Organizr Support Link']),
  2069. $this->settingsOption('switch', 'organizrDocsMenuLink', ['label' => 'Show Organizr Docs Link']),
  2070. $this->settingsOption('switch', 'organizrSignoutMenuLink', ['label' => 'Show Organizr Sign out & in Button on Sidebar']),
  2071. $this->settingsOption('switch', 'expandCategoriesByDefault', ['label' => 'Expand All Categories']),
  2072. $this->settingsOption('switch', 'autoCollapseCategories', ['label' => 'Auto-Collapse Categories']),
  2073. $this->settingsOption('switch', 'autoExpandNavBar', ['label' => 'Auto-Expand Nav Bar']),
  2074. $this->settingsOption('select', 'unsortedTabs', ['label' => 'Unsorted Tab Placement', 'options' => [['name' => 'Top', 'value' => 'top'], ['name' => 'Bottom', 'value' => 'bottom']]]),
  2075. ],
  2076. 'Login Page' => [
  2077. $this->settingsOption('input', 'loginLogo', ['label' => 'Login Logo URL']),
  2078. $this->settingsOption('multiple-url', 'loginWallpaper', ['label' => 'Login Wallpaper URL', 'help' => 'You may enter multiple URL\'s']),
  2079. $this->settingsOption('switch', 'useLogoLogin', ['label' => 'Use Logo instead of Title on Login Page']),
  2080. $this->settingsOption('switch', 'minimalLoginScreen', ['label' => 'Minimal Login Screen']),
  2081. $this->settingsOption('switch', 'useRandomMediaImage', ['label' => 'Use Random Media Wallpaper From Media Server']),
  2082. ],
  2083. 'Options' => [
  2084. $this->settingsOption('switch', 'alternateHomepageHeaders', ['label' => 'Alternate Homepage Titles']),
  2085. $this->settingsOption('switch', 'debugErrors', ['label' => 'Show Debug Errors']),
  2086. $this->settingsOption('switch', 'easterEggs', ['label' => 'Show Easter Eggs']),
  2087. $this->settingsOption('input', 'gaTrackingID', ['label' => 'Google Analytics Tracking ID', 'placeholder' => 'e.g. UA-XXXXXXXXX-X']),
  2088. ],
  2089. 'Colors & Themes' => [
  2090. $this->settingsOption('notice', null, ['notice' => 'info', 'title' => 'Attention', 'bodyHTML' => '<span lang="en">The value of #987654 is just a placeholder, you can change to any value you like.</span><span lang="en">To revert back to default, save with no value defined in the relevant field.</span>']),
  2091. $this->settingsOption('blank'),
  2092. $this->settingsOption('button', '', ['label' => 'Reset Colors', 'icon' => 'fa fa-ticket', 'text' => 'Reset', 'attr' => 'onclick="resetCustomColors()"']),
  2093. $this->settingsOption('blank'),
  2094. $this->settingsOption('color', 'headerColor', ['label' => 'Nav Bar Color']),
  2095. $this->settingsOption('color', 'headerTextColor', ['label' => 'Nav Bar Text Color']),
  2096. $this->settingsOption('color', 'sidebarColor', ['label' => 'Side Bar Color']),
  2097. $this->settingsOption('color', 'sidebarTextColor', ['label' => 'Side Bar Text Color']),
  2098. $this->settingsOption('color', 'accentColor', ['label' => 'Accent Color']),
  2099. $this->settingsOption('color', 'accentTextColor', ['label' => 'Accent Text Color']),
  2100. $this->settingsOption('color', 'buttonColor', ['label' => 'Button Color']),
  2101. $this->settingsOption('color', 'buttonTextColor', ['label' => 'Button Text Color']),
  2102. $this->settingsOption('select', 'theme', ['label' => 'Theme', 'class' => 'themeChanger', 'options' => $this->getAllThemes()]),
  2103. $this->settingsOption('select', 'style', ['label' => 'Style', 'class' => 'styleChanger', 'options' => [['name' => 'Light', 'value' => 'light'], ['name' => 'Dark', 'value' => 'dark'], ['name' => 'Horizontal', 'value' => 'horizontal']]]),
  2104. ],
  2105. 'Notifications' => [
  2106. $this->settingsOption('select', 'notificationBackbone', ['label' => 'Type', 'class' => 'notifyChanger', 'options' => $this->notificationTypesOptions()]),
  2107. $this->settingsOption('select', 'notificationPosition', ['label' => 'Position', 'class' => 'notifyPositionChanger', 'options' => $this->notificationPositionsOptions()]),
  2108. $this->settingsOption('html', null, ['label' => 'Test Message', 'html' => '
  2109. <div class="btn-group m-r-10 dropup">
  2110. <button aria-expanded="false" data-toggle="dropdown" class="btn btn-info btn-outline dropdown-toggle waves-effect waves-light" type="button">
  2111. <i class="fa fa-comment m-r-5"></i>
  2112. <span>Test </span>
  2113. </button>
  2114. <ul role="menu" class="dropdown-menu">
  2115. <li><a onclick="message(\'Test Message\',\'This is a success Message\',activeInfo.settings.notifications.position,\'#FFF\',\'success\',\'5000\');">Success</a></li>
  2116. <li><a onclick="message(\'Test Message\',\'This is a info Message\',activeInfo.settings.notifications.position,\'#FFF\',\'info\',\'5000\');">Info</a></li>
  2117. <li><a onclick="message(\'Test Message\',\'This is a warning Message\',activeInfo.settings.notifications.position,\'#FFF\',\'warning\',\'5000\');">Warning</a></li>
  2118. <li><a onclick="message(\'Test Message\',\'This is a error Message\',activeInfo.settings.notifications.position,\'#FFF\',\'error\',\'5000\');">Error</a></li>
  2119. </ul>
  2120. </div>
  2121. ']
  2122. ),
  2123. ],
  2124. 'FavIcon' => [
  2125. $this->settingsOption('html', null, ['label' => 'Instructions', 'override' => 12, 'html' => '
  2126. <div class="panel panel-default">
  2127. <div class="panel-heading">
  2128. <a href="https://realfavicongenerator.net/" target="_blank"><span class="label label-info m-l-5">Visit FavIcon Site</span></a>
  2129. </div>
  2130. <div class="panel-wrapper collapse in">
  2131. <div class="panel-body">
  2132. <ul class="list-icons">
  2133. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Select your Favicon picture]</li>
  2134. <li lang="en"><i class="fa fa-caret-right text-info"></i> Choose your image to use</li>
  2135. <li lang="en"><i class="fa fa-caret-right text-info"></i> Edit settings to your liking</li>
  2136. <li lang="en"><i class="fa fa-caret-right text-info"></i> At bottom of page on [Favicon Generator Options] under [Path] choose [I cannot or I do not want to place favicon files at the root of my web site.]</li>
  2137. <li lang="en"><i class="fa fa-caret-right text-info"></i> Enter this path <code>data/favicon</code></li>
  2138. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Generate your Favicons and HTML code]</li>
  2139. <li lang="en"><i class="fa fa-caret-right text-info"></i> Download and unzip file and place in <code>data/favicon</code></li>
  2140. <li lang="en"><i class="fa fa-caret-right text-info"></i> Copy code and paste inside left box</li>
  2141. </ul>
  2142. </div>
  2143. </div>
  2144. </div>
  2145. ']
  2146. ),
  2147. $this->settingsOption('code-editor', 'favIcon', ['label' => 'Fav Icon Code', 'mode' => 'html']),
  2148. ],
  2149. 'Custom CSS' => [
  2150. $this->settingsOption('code-editor', 'customCss', ['label' => 'Custom CSS', 'mode' => 'css']),
  2151. ],
  2152. 'Theme CSS' => [
  2153. $this->settingsOption('code-editor', 'customThemeCss', ['label' => 'Theme CSS', 'mode' => 'css']),
  2154. ],
  2155. 'Custom Javascript' => [
  2156. $this->settingsOption('code-editor', 'customJava', ['label' => 'Custom Javascript', 'mode' => 'javascript']),
  2157. ],
  2158. 'Theme Javascript' => [
  2159. $this->settingsOption('code-editor', 'customThemeJava', ['label' => 'Theme Javascript', 'mode' => 'javascript']),
  2160. ],
  2161. ];
  2162. }
  2163. public function loadAppearance()
  2164. {
  2165. $appearance['logo'] = $this->config['logo'];
  2166. $appearance['title'] = $this->config['title'];
  2167. $appearance['useLogo'] = $this->config['useLogo'];
  2168. $appearance['useLogoLogin'] = $this->config['useLogoLogin'];
  2169. $appearance['headerColor'] = $this->config['headerColor'];
  2170. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2171. $appearance['sidebarColor'] = $this->config['sidebarColor'];
  2172. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2173. $appearance['sidebarTextColor'] = $this->config['sidebarTextColor'];
  2174. $appearance['accentColor'] = $this->config['accentColor'];
  2175. $appearance['accentTextColor'] = $this->config['accentTextColor'];
  2176. $appearance['buttonColor'] = $this->config['buttonColor'];
  2177. $appearance['buttonTextColor'] = $this->config['buttonTextColor'];
  2178. $appearance['buttonTextHoverColor'] = $this->config['buttonTextHoverColor'];
  2179. $appearance['buttonHoverColor'] = $this->config['buttonHoverColor'];
  2180. $appearance['loginWallpaper'] = $this->config['loginWallpaper'];
  2181. $appearance['randomMediaImage'] = $this->getRandomMediaImage('np');
  2182. $appearance['loginLogo'] = $this->config['loginLogo'];
  2183. $appearance['customCss'] = $this->config['customCss'];
  2184. $appearance['customThemeCss'] = $this->config['customThemeCss'];
  2185. $appearance['customJava'] = $this->config['customJava'];
  2186. $appearance['customThemeJava'] = $this->config['customThemeJava'];
  2187. return $appearance;
  2188. }
  2189. public function getRandomMediaImage($type = null)
  2190. {
  2191. if (!$this->config['useRandomMediaImage']) {
  2192. return false;
  2193. }
  2194. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache')) {
  2195. $folder = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache';
  2196. try {
  2197. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  2198. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  2199. $image = null;
  2200. switch ($type) {
  2201. case 'np':
  2202. $i = 0;
  2203. $array = iterator_to_array($iteratorIterator);
  2204. if (count($array) > 0) {
  2205. shuffle($array);
  2206. $iteratorIterator = new ArrayIterator($array);
  2207. }
  2208. foreach ($iteratorIterator as $info) {
  2209. if (stripos($info->getFilename(), 'np') !== false) {
  2210. if ($i < 1) {
  2211. $imageInfo = getimagesize($folder . DIRECTORY_SEPARATOR . $info->getFilename());
  2212. if ($imageInfo[0] >= $this->getCacheImageSize('npw')) {
  2213. $image = 'data/cache/' . $info->getFilename();
  2214. $i++;
  2215. }
  2216. } else {
  2217. break;
  2218. }
  2219. }
  2220. }
  2221. return $image;
  2222. default:
  2223. return false;
  2224. }
  2225. } catch (Exception $e) {
  2226. return false;
  2227. }
  2228. } else {
  2229. return false;
  2230. }
  2231. }
  2232. public function getSettingsMain()
  2233. {
  2234. $certificateStatus = $this->hasCustomCert() ? '<span lang="en">Custom Certificate Loaded</span><br />Located at <span>' . $this->getCustomCert() . '</span>' : '<span lang="en">Custom Certificate not found - please upload below</span>';
  2235. $settings = [
  2236. 'Settings Page' => [
  2237. $this->settingsOption('select', 'defaultSettingsTab', ['label' => 'Default Settings Tab', 'options' => $this->getSettingsTabs(), 'help' => 'Choose which Settings Tab to be default when opening settings page']),
  2238. ],
  2239. 'Github' => [
  2240. $this->settingsOption('select', 'branch', ['label' => 'Branch', 'value' => $this->config['branch'], 'options' => $this->getBranches(), 'disabled' => $this->docker, 'help' => ($this->docker) ? 'Since you are using the Official Docker image, Change the image to change the branch' : 'Choose which branch to download from']),
  2241. $this->settingsOption('button', 'force-install-branch', ['label' => 'Force Install Branch', 'class' => 'updateNow', 'icon' => 'fa fa-download', 'text' => 'Retrieve', 'attr' => ($this->docker) ? 'title="You can just restart your docker to update"' : '', 'help' => ($this->docker) ? 'Since you are using the official Docker image, you can just restart your Docker container to update Organizr' : 'This will re-download all of the source files for Organizr']),
  2242. ],
  2243. 'API' => [
  2244. $this->settingsOption('password-alt-copy', 'organizrAPI', ['label' => 'Organizr API']),
  2245. $this->settingsOption('button', null, ['label' => 'Generate New API Key', 'class' => 'newAPIKey', 'icon' => 'fa fa-refresh', 'text' => 'Generate']),
  2246. $this->settingsOption('notice', null, ['title' => 'API Documentation', 'body' => 'The documentation for Organizr\'s API is included with this installation. To access the docs, use the button below.', 'bodyHTML' => '<br/><br/><div class="row"><div class="col-lg-2 col-sm-4 col-xs-12"><a href="' . $this->getServerPath() . 'docs/" target="_blank" class="btn btn-block btn-primary text-white" lang="en">Organizr Docs</a></div></div>'])
  2247. ],
  2248. 'Authentication' => [
  2249. $this->settingsOption('select', 'authType', ['id' => 'authSelect', 'label' => 'Authentication Type', 'value' => $this->config['authType'], 'options' => $this->getAuthTypes()]),
  2250. $this->settingsOption('select', 'authBackend', ['id' => 'authBackendSelect', 'label' => 'Authentication Backend', 'class' => 'backendAuth switchAuth', 'value' => $this->config['authBackend'], 'options' => $this->getAuthBackends()]),
  2251. $this->settingsOption('token', 'plexToken', ['class' => 'plexAuth switchAuth']),
  2252. $this->settingsOption('button', '', ['class' => 'getPlexTokenAuth plexAuth switchAuth', 'label' => 'Get Plex Token', 'icon' => 'fa fa-ticket', 'text' => 'Retrieve', 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#settings-main-form [name=plexToken]\')"']),
  2253. $this->settingsOption('password-alt', 'plexID', ['class' => 'plexAuth switchAuth', 'label' => 'Plex Machine', 'placeholder' => 'Use Get Plex Machine Button']),
  2254. $this->settingsOption('button', '', ['class' => 'getPlexMachineAuth plexAuth switchAuth', 'label' => 'Get Plex Machine', 'icon' => 'fa fa-id-badge', 'text' => 'Retrieve', 'attr' => 'onclick="showPlexMachineForm(\'#settings-main-form [name=plexID]\')"']),
  2255. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email', 'class' => 'plexAuth switchAuth', 'placeholder' => 'Admin username for Plex']),
  2256. $this->settingsOption('switch', 'plexoAuth', ['label' => 'Enable Plex oAuth', 'class' => 'plexAuth switchAuth']),
  2257. $this->settingsOption('switch', 'ignoreTFAIfPlexOAuth', ['label' => 'Ignore 2FA if Plex OAuth ', 'class' => 'plexAuth switchAuth', 'help' => 'Enabling this will disable Organizr 2FA (If applicable) if User uses Plex OAuth to login']),
  2258. $this->settingsOption('switch', 'plexStrictFriends', ['label' => 'Strict Plex Friends ', 'class' => 'plexAuth switchAuth', 'help' => 'Enabling this will only allow Friends that have shares to the Machine ID entered above to login, Having this disabled will allow all Friends on your Friends list to login']),
  2259. $this->settingsOption('switch', 'ignoreTFALocal', ['label' => 'Ignore External 2FA on Local Subnet', 'help' => 'Enabling this will bypass external 2FA security if user is on local Subnet']),
  2260. $this->settingsOption('url', 'authBackendHost', ['class' => 'ldapAuth ftpAuth switchAuth', 'label' => 'Host Address', 'placeholder' => 'http(s) | ftp(s) | ldap(s)://hostname:port']),
  2261. $this->settingsOption('input', 'authBaseDN', ['class' => 'ldapAuth switchAuth', 'label' => 'Host Base DN', 'placeholder' => 'cn=%s,dc=sub,dc=domain,dc=com']),
  2262. $this->settingsOption('input', 'authBackendHostPrefix', ['class' => 'ldapAuth switchAuth', 'label' => 'Account Prefix', 'id' => 'authBackendHostPrefix-input', 'placeholder' => 'Account prefix - i.e. Controller\ from Controller\Username for AD - uid= for OpenLDAP']),
  2263. $this->settingsOption('input', 'authBackendHostSuffix', ['class' => 'ldapAuth switchAuth', 'label' => 'Account Suffix', 'id' => 'authBackendHostSuffix-input', 'placeholder' => 'Account suffix - start with comma - ,ou=people,dc=domain,dc=tld']),
  2264. $this->settingsOption('input', 'ldapBindUsername', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Username']),
  2265. $this->settingsOption('password', 'ldapBindPassword', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Password']),
  2266. $this->settingsOption('select', 'ldapType', ['id' => 'ldapType', 'label' => 'LDAP Backend Type', 'class' => 'ldapAuth switchAuth', 'options' => $this->getLDAPOptions()]),
  2267. $this->settingsOption('html', null, ['class' => 'ldapAuth switchAuth', 'label' => 'Account DN', 'html' => '<span id="accountDN" class="ldapAuth switchAuth">' . $this->config['authBackendHostPrefix'] . 'TestAcct' . $this->config['authBackendHostSuffix'] . '</span>']),
  2268. $this->settingsOption('blank', null, ['class' => 'ldapAuth switchAuth']),
  2269. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP SSL', 'help' => 'This will enable the use of SSL for LDAP connections']),
  2270. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP TLS', 'help' => 'This will enable the use of TLS for LDAP connections']),
  2271. $this->settingsOption('test', 'ldap', ['class' => 'ldapAuth switchAuth']),
  2272. $this->settingsOption('test', '', ['label' => 'Test Login', 'class' => 'ldapAuth switchAuth', 'text' => 'Test Login', 'attr' => 'onclick="showLDAPLoginTest()"']),
  2273. $this->settingsOption('url', 'embyURL', ['class' => 'embyAuth switchAuth', 'label' => 'Emby URL', 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.']),
  2274. $this->settingsOption('token', 'embyToken', ['class' => 'embyAuth switchAuth', 'label' => 'Emby Token']),
  2275. $this->settingsOption('url', 'jellyfinURL', ['class' => 'jellyfinAuth switchAuth', 'label' => 'Jellyfin URL', 'help' => 'Please make sure to use local IP address and port - You also may use local dns name too.']),
  2276. $this->settingsOption('token', 'jellyfinToken', ['class' => 'jellyfinAuth switchAuth', 'label' => 'Jellyfin Token']),
  2277. ],
  2278. 'Security' => [
  2279. $this->settingsOption('number', 'loginAttempts', ['label' => 'Max Login Attempts']),
  2280. $this->settingsOption('select', 'loginLockout', ['label' => 'Login Lockout Seconds', 'options' => $this->timeOptions()]),
  2281. $this->settingsOption('number', 'lockoutTimeout', ['label' => 'Inactivity Timer [Minutes]']),
  2282. $this->settingsOption('switch', 'lockoutSystem', ['label' => 'Inactivity Lock']),
  2283. $this->settingsOption('select', 'lockoutMinAuth', ['label' => 'Lockout Groups From', 'options' => $this->groupSelect()]),
  2284. $this->settingsOption('select', 'lockoutMaxAuth', ['label' => 'Lockout Groups To', 'options' => $this->groupSelect()]),
  2285. $this->settingsOption('switch', 'matchUserAgents', ['label' => 'Match UserAgent', 'help' => 'Match Browser UserAgent to Token UserAgent - Can be very aggressive on matching']),
  2286. $this->settingsOption('switch', 'matchUserIP', ['label' => 'Match User IP', 'help' => 'Match User IP to Token IP - Also allows approval if user token is valid and is local to server']),
  2287. $this->settingsOption('switch', 'traefikAuthEnable', ['label' => 'Enable Traefik Auth Redirect', 'help' => 'This will enable the webserver to forward errors so traefik will accept them']),
  2288. $this->settingsOption('input', 'traefikDomainOverride', ['label' => 'Traefik Domain for Return Override', 'help' => 'Please use a FQDN on this URL Override', 'placeholder' => 'http(s)://domain']),
  2289. $this->settingsOption('select', 'debugAreaAuth', ['label' => 'Minimum Authentication for Debug Area', 'options' => $this->groupSelect(), 'settings' => '{}']),
  2290. $this->settingsOption('multiple', 'sandbox', ['override' => 12, 'label' => 'iFrame Sandbox', 'help' => 'WARNING! This can potentially mess up your iFrames', 'options' => $this->sandboxOptions()]),
  2291. $this->settingsOption('multiple', 'blacklisted', ['override' => 12, 'label' => 'Blacklisted IP\'s', 'help' => 'WARNING! This will block anyone with these IP\'s', 'options' => $this->makeOptionsFromValues($this->config['blacklisted']), 'settings' => '{tags: true}']),
  2292. $this->settingsOption('code-editor', 'blacklistedMessage', ['mode' => 'html']),
  2293. ],
  2294. 'Logs' => [
  2295. $this->settingsOption('folder', 'logLocation', ['label' => 'Log Save Path', 'help' => 'Folder path to save Organizr Logs - Please test before saving', 'value' => $this->logLocation()]),
  2296. $this->settingsOption('select', 'logLevel', ['label' => 'Log Level', 'options' => $this->logLevels()]),
  2297. $this->settingsOption('switch', 'includeDatabaseQueriesInDebug', ['label' => 'Include Database Queries', 'help' => 'Include Database queries in debug logs']),
  2298. $this->settingsOption('number', 'maxLogFiles', ['label' => 'Maximum Log Files', 'help' => 'Number of log files to preserve', 'attr' => 'min="1"']),
  2299. $this->settingsOption('select', 'logLiveUpdateRefresh', ['label' => 'Live Update Refresh', 'options' => $this->timeOptions()]),
  2300. $this->settingsOption('select', 'logPageSize', ['label' => 'Log Page Size', 'options' => [['name' => '10 Items', 'value' => '10'], ['name' => '25 Items', 'value' => '25'], ['name' => '50 Items', 'value' => '50'], ['name' => '100 Items', 'value' => '100']]]),
  2301. $this->settingsOption('switch', 'sendLogsToSlack', ['label' => 'Send Logs to Slack', 'help' => 'Send Logs to Slack as well']),
  2302. $this->settingsOption('select', 'slackLogLevel', ['label' => 'Slack Log Level', 'options' => $this->logLevels()]),
  2303. $this->settingsOption('url', 'slackLogWebhook', ['label' => 'Slack Webhook URL', 'help' => 'If using Discord make sure to end the URL with /slack']),
  2304. $this->settingsOption('input', 'slackLogWebHookChannel', ['label' => 'Slack Channel for Webhook', 'help' => 'Channel ID for webhook - Not needed for Discord']),
  2305. $this->settingsOption('blank'),
  2306. $this->settingsOption('test', 'slack-logs', ['label' => 'Test Slack', 'text' => 'Test Slack', 'help' => 'Test only sends a warning message so make sure Slack Log Level is Warning when testing']),
  2307. ],
  2308. 'Cron' => [
  2309. $this->settingsOption('cron-file'),
  2310. $this->settingsOption('blank'),
  2311. $this->settingsOption('enable', 'autoUpdateCronEnabled', ['label' => 'Auto-Update Organizr']),
  2312. $this->settingsOption('cron', 'autoUpdateCronSchedule'),
  2313. $this->settingsOption('enable', 'autoBackupCronEnabled', ['label' => 'Auto-Backup Organizr']),
  2314. $this->settingsOption('cron', 'autoBackupCronSchedule'),
  2315. $this->settingsOption('number', 'keepBackupsCountCron', ['label' => '# Backups Keep', 'help' => 'Number of backups to keep', 'attr' => 'min="1"']),
  2316. $this->settingsOption('blank'),
  2317. ],
  2318. 'Login' => [
  2319. $this->settingsOption('password', 'registrationPassword', ['label' => 'Registration Password', 'help' => 'Sets the password for the Registration form on the login screen']),
  2320. $this->settingsOption('switch', 'hideRegistration', ['label' => 'Hide Registration', 'help' => 'Enable this to hide the Registration button on the login screen']),
  2321. $this->settingsOption('number', 'rememberMeDays', ['label' => 'Remember Me Length', 'help' => 'Number of days cookies and tokens will be valid for', 'attr' => 'min="1"']),
  2322. $this->settingsOption('switch', 'rememberMe', ['label' => 'Remember Me', 'help' => 'Default status of Remember Me button on login screen']),
  2323. $this->settingsOption('multiple-url', 'localIPList', ['label' => 'Override Local IP or Subnet', 'help' => 'IPv4 only at the moment - This will set your login as local if your IP falls within the From and To']),
  2324. $this->settingsOption('input', 'wanDomain', ['label' => 'WAN Domain', 'placeholder' => 'only domain and tld - i.e. domain.com', 'help' => 'Enter domain if you wish to be forwarded to a local address - Local Address filled out on next item']),
  2325. $this->settingsOption('url', 'localAddress', ['label' => 'Local Address', 'placeholder' => 'http://home.local', 'help' => 'Full local address of organizr install - i.e. http://home.local or http://192.168.0.100']),
  2326. $this->settingsOption('switch', 'enableLocalAddressForward', ['label' => 'Enable Local Address Forward', 'help' => 'Enables the local address forward if on local address and accessed from WAN Domain']),
  2327. $this->settingsOption('switch', 'disableRecoverPass', ['label' => 'Disable Recover Password', 'help' => 'Disables recover password area']),
  2328. $this->settingsOption('input', 'customForgotPassText', ['label' => 'Custom Recover Password Text', 'help' => 'Text or HTML for recovery password section']),
  2329. ],
  2330. 'Auth Proxy' => [
  2331. $this->settingsOption('switch', 'authProxyEnabled', ['label' => 'Auth Proxy', 'help' => 'Enable option to set Auth Proxy Header Login']),
  2332. $this->settingsOption('input', 'authProxyWhitelist', ['label' => 'Auth Proxy Whitelist', 'placeholder' => 'i.e. 10.0.0.0/24 or 10.0.0.20', 'help' => 'IPv4 only at the moment - This must be set to work, will accept subnet or IP address']),
  2333. $this->settingsOption('input', 'authProxyHeaderName', ['label' => 'Auth Proxy Header Name', 'placeholder' => 'i.e. X-Forwarded-User', 'help' => 'Please choose a unique value for added security']),
  2334. $this->settingsOption('input', 'authProxyHeaderNameEmail', ['label' => 'Auth Proxy Header Name for Email', 'placeholder' => 'i.e. X-Forwarded-Email', 'help' => 'Please choose a unique value for added security']),
  2335. $this->settingsOption('switch', 'authProxyOverrideLogout', ['label' => 'Override Logout', 'help' => 'Enable option to set custom Logout URL for Auth Proxy']),
  2336. $this->settingsOption('input', 'authProxyLogoutURL', ['label' => 'Logout URL', 'help' => 'Logout URL to redirect user for Auth Proxy']),
  2337. ],
  2338. 'Ping' => [
  2339. $this->settingsOption('auth', 'pingAuth'),
  2340. $this->settingsOption('auth', 'pingAuthMessage', ['label' => 'Minimum Authentication for Message and Sound']),
  2341. $this->settingsOption('select', 'pingOnlineSound', ['label' => 'Online Sound', 'options' => $this->getSounds()]),
  2342. $this->settingsOption('select', 'pingOfflineSound', ['label' => 'Offline Sound', 'options' => $this->getSounds()]),
  2343. $this->settingsOption('switch', 'pingMs', ['label' => 'Show Ping Time']),
  2344. $this->settingsOption('switch', 'statusSounds', ['label' => 'Enable Notify Sounds', 'help' => 'Will play a sound if the server goes down and will play sound if comes back up.']),
  2345. $this->settingsOption('auth', 'pingAuthMs', ['label' => 'Minimum Authentication for Time Display']),
  2346. $this->settingsOption('refresh', 'adminPingRefresh', ['label' => 'Admin Refresh Seconds']),
  2347. $this->settingsOption('refresh', 'otherPingRefresh', ['label' => 'Everyone Refresh Seconds']),
  2348. ],
  2349. 'Certificate' => [
  2350. $this->settingsOption('html', '', ['override' => 12,
  2351. 'html' => '
  2352. <script>
  2353. let myDropzone = new Dropzone("#upload-custom-certificate", {
  2354. url: "api/v2/certificate/custom",
  2355. headers:{ "formKey": local("g","formKey") },
  2356. init: function() {
  2357. this.on("complete", function(file) {
  2358. if(file["status"] === "success"){
  2359. $(".custom-certificate-status").html("<span lang=\"en\">Custom Certificate Loaded</span>");
  2360. }else{
  2361. $(".custom-certificate-status").html("<span lang=\"en\">Error Saving file...</span>");
  2362. }
  2363. });
  2364. }
  2365. });
  2366. </script>
  2367. <div class="row">
  2368. <div class="col-lg-12">
  2369. <div class="panel panel-info">
  2370. <div class="panel-heading"><span lang="en">Notice</span></div>
  2371. <div class="panel-wrapper collapse in" aria-expanded="true">
  2372. <div class="panel-body">
  2373. <span lang="en">By default, Organizr uses certificates from https://curl.se/docs/caextract.html<br/>If you would like to use your own certificate, please upload it below. You will then need to enable each homepage item to use it.</span>
  2374. </div>
  2375. </div>
  2376. </div>
  2377. </div>
  2378. </div>
  2379. <div class="row">
  2380. <div class="col-md-12">
  2381. <div class="white-box">
  2382. <h3 class="box-title m-b-0" lang="en">Custom Certificate Status</h3>
  2383. <p class="text-muted m-b-30 custom-certificate-status">' . $certificateStatus . '</p>
  2384. <form action="#" class="dropzone dz-clickable" id="upload-custom-certificate">
  2385. <div class="dz-default dz-message"><span lang="en">Drop Certificate file here to upload</span></div>
  2386. </form>
  2387. </div>
  2388. </div>
  2389. </div>
  2390. ']
  2391. )
  2392. ],
  2393. ];
  2394. if ($this->config['driver'] == 'sqlite3') {
  2395. $database = [
  2396. 'Database' => [
  2397. $this->settingsOption('notice', '', ['notice' => 'danger', 'title' => 'Warning', 'body' => 'This feature is experimental - You may face unexpected database is locked errors in logs']),
  2398. $this->settingsOption('html', '', ['label' => 'Journal Mode Status', 'html' => '<script>getJournalMode();</script><h4 class="journal-mode font-bold text-uppercase"><i class="fa fa-spin fa-circle-o-notch"></i></h4>']),
  2399. $this->settingsOption('button', '', ['label' => 'Set DELETE Mode (Default)', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'DELETE\')"']),
  2400. $this->settingsOption('button', '', ['label' => 'Set WAL Mode', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'WAL\')"']),
  2401. ]
  2402. ];
  2403. $settings = array_merge($settings, $database);
  2404. }
  2405. ksort($settings);
  2406. return $settings;
  2407. }
  2408. public function getSettingsSSO()
  2409. {
  2410. return [
  2411. 'FYI' => [
  2412. $this->settingsOption('html', '', ['override' => 12,
  2413. 'html' => '
  2414. <div class="row">
  2415. <div class="col-lg-12">
  2416. <div class="panel panel-primary">
  2417. <div class="panel-heading"><span lang="en">Please Read First</span></div>
  2418. <div class="panel-wrapper collapse in" aria-expanded="true">
  2419. <div class="panel-body">
  2420. <span lang="en">Using multiple SSO application will cause your Cookie Header item to increase. If you haven\'t increased it by now, please follow this guide</span>
  2421. <br/><br/>
  2422. <div class="row">
  2423. <div class="col-lg-2 col-sm-4 col-xs-12">
  2424. <a href="https://docs.organizr.app/help/faq/organizr-login-error" target="_blank" class="btn btn-block btn-primary text-white" lang="en">Cookie Header Guide</a>
  2425. </div>
  2426. </div>
  2427. <br/>
  2428. <span lang="en">This is not the same as database authentication - i.e. Plex Authentication | Emby Authentication | FTP Authentication<br/>Click Main on the sub-menu above.</span>
  2429. </div>
  2430. </div>
  2431. </div>
  2432. </div>
  2433. </div>'
  2434. ]
  2435. ),
  2436. ],
  2437. 'Plex' => [
  2438. $this->settingsOption('token', 'plexToken'),
  2439. $this->settingsOption('button', '', ['label' => 'Get Plex Token', 'icon' => 'fa fa-ticket', 'text' => 'Retrieve', 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#sso-form [name=plexToken]\')"']),
  2440. $this->settingsOption('password-alt', 'plexID', ['label' => 'Plex Machine']),
  2441. $this->settingsOption('button', '', ['label' => 'Get Plex Machine', 'icon' => 'fa fa-id-badge', 'text' => 'Retrieve', 'attr' => 'onclick="showPlexMachineForm(\'#sso-form [name=plexID]\')"']),
  2442. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email']),
  2443. $this->settingsOption('blank'),
  2444. $this->settingsOption('html', 'Plex Note', ['html' => '<span lang="en">Please make sure both Token and Machine are filled in</span>']),
  2445. $this->settingsOption('enable', 'ssoPlex'),
  2446. ],
  2447. 'Tautulli' => [
  2448. $this->settingsOption('multiple-url', 'tautulliURL'),
  2449. $this->settingsOption('auth', 'ssoTautulliAuth'),
  2450. $this->settingsOption('enable', 'ssoTautulli'),
  2451. ],
  2452. 'Overseerr' => [
  2453. $this->settingsOption('url', 'overseerrURL'),
  2454. $this->settingsOption('token', 'overseerrToken'),
  2455. $this->settingsOption('username', 'overseerrFallbackUser', ['label' => 'Overseerr Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2456. $this->settingsOption('password', 'overseerrFallbackPassword', ['label' => 'Overseerr Fallback Password']),
  2457. $this->settingsOption('enable', 'ssoOverseerr'),
  2458. ],
  2459. 'Petio' => [
  2460. $this->settingsOption('url', 'petioURL'),
  2461. $this->settingsOption('token', 'petioToken'),
  2462. $this->settingsOption('username', 'petioFallbackUser', ['label' => 'Petio Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2463. $this->settingsOption('password', 'petioFallbackPassword', ['label' => 'Petio Fallback Password']),
  2464. $this->settingsOption('enable', 'ssoPetio'),
  2465. ],
  2466. 'Ombi' => [
  2467. $this->settingsOption('url', 'ombiURL'),
  2468. $this->settingsOption('token', 'ombiToken'),
  2469. $this->settingsOption('username', 'ombiFallbackUser', ['label' => 'Ombi Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2470. $this->settingsOption('password', 'ombiFallbackPassword', ['label' => 'Ombi Fallback Password']),
  2471. $this->settingsOption('enable', 'ssoOmbi'),
  2472. ],
  2473. 'Jellyfin' => [
  2474. $this->settingsOption('url', 'jellyfinURL', ['label' => 'Jellyfin API URL', 'help' => 'Please make sure to use the local address to the API']),
  2475. $this->settingsOption('url', 'jellyfinSSOURL', ['label' => 'Jellyfin SSO URL', 'help' => 'Please make sure to use the same (sub)domain to access Jellyfin as Organizr\'s']),
  2476. $this->settingsOption('enable', 'ssoJellyfin'),
  2477. ],
  2478. 'Komga' => [
  2479. $this->settingsOption('url', 'komgaURL'),
  2480. $this->settingsOption('auth', 'ssoKomgaAuth'),
  2481. $this->settingsOption('enable', 'ssoKomga'),
  2482. $this->settingsOption('blank'),
  2483. $this->settingsOption('username', 'komgaFallbackUser', ['label' => 'Komga Fallback Email', 'help' => 'DO NOT SET THIS TO YOUR ADMIN ACCOUNT. We recommend you create a local account as a "catch all" for when Organizr is unable to perform SSO. Organizr will request a User Token based off of this user credentials']),
  2484. $this->settingsOption('password', 'komgaFallbackPassword', ['label' => 'Komga Fallback Password']),
  2485. ],
  2486. ];
  2487. }
  2488. public function systemMenuLists()
  2489. {
  2490. $pluginsMenu = [
  2491. [
  2492. 'active' => false,
  2493. 'api' => 'api/v2/page/settings_plugins_enabled',
  2494. 'anchor' => 'settings-plugins-enabled-anchor',
  2495. 'name' => 'Active',
  2496. ],
  2497. [
  2498. 'active' => false,
  2499. 'api' => 'api/v2/page/settings_plugins_disabled',
  2500. 'anchor' => 'settings-plugins-disabled-anchor',
  2501. 'name' => 'Inactive',
  2502. ],
  2503. [
  2504. 'active' => false,
  2505. 'api' => 'api/v2/page/settings_plugins_settings',
  2506. 'anchor' => 'settings-plugins-settings-anchor',
  2507. 'name' => 'Settings',
  2508. ],
  2509. [
  2510. 'active' => false,
  2511. 'api' => false,
  2512. 'anchor' => 'settings-plugins-marketplace-anchor',
  2513. 'name' => 'Marketplace',
  2514. 'onclick' => 'loadPluginMarketplace();'
  2515. ],
  2516. ];
  2517. $userManagementMenu = [
  2518. [
  2519. 'active' => false,
  2520. 'api' => 'api/v2/page/settings_user_manage_users',
  2521. 'anchor' => 'settings-user-manage-users-anchor',
  2522. 'name' => 'Manage Users'
  2523. ],
  2524. [
  2525. 'active' => false,
  2526. 'api' => 'api/v2/page/settings_user_manage_groups',
  2527. 'anchor' => 'settings-user-manage-groups-anchor',
  2528. 'name' => 'Manage Groups'
  2529. ],
  2530. [
  2531. 'active' => false,
  2532. 'api' => false,
  2533. 'anchor' => 'settings-user-import-users-anchor',
  2534. 'name' => 'Import Users'
  2535. ],
  2536. ];
  2537. $customizeMenu = [
  2538. [
  2539. 'active' => false,
  2540. 'api' => 'api/v2/page/settings_customize_appearance',
  2541. 'anchor' => 'settings-customize-appearance-anchor',
  2542. 'name' => 'Appearance',
  2543. ],
  2544. [
  2545. 'active' => false,
  2546. 'api' => 'api/v2/page/settings_customize_settings',
  2547. 'anchor' => 'settings-customize-settings-anchor',
  2548. 'name' => 'Marketplace Settings',
  2549. ],
  2550. [
  2551. 'active' => false,
  2552. 'api' => false,
  2553. 'anchor' => 'settings-customize-marketplace-anchor',
  2554. 'name' => 'Marketplace',
  2555. 'onclick' => 'loadThemeMarketplace();'
  2556. ],
  2557. ];
  2558. $tabEditorMenu = [
  2559. [
  2560. 'active' => false,
  2561. 'api' => 'api/v2/page/settings_tab_editor_tabs',
  2562. 'anchor' => 'settings-tab-editor-tabs-anchor',
  2563. 'name' => 'Tabs'
  2564. ],
  2565. [
  2566. 'active' => false,
  2567. 'api' => 'api/v2/page/settings_tab_editor_categories',
  2568. 'anchor' => 'settings-tab-editor-categories-anchor',
  2569. 'name' => 'Categories'
  2570. ],
  2571. [
  2572. 'active' => false,
  2573. 'api' => 'api/v2/page/settings_tab_editor_homepage',
  2574. 'anchor' => 'settings-tab-editor-homepage-anchor',
  2575. 'name' => 'Homepage Items'
  2576. ],
  2577. [
  2578. 'active' => false,
  2579. 'api' => 'api/v2/page/settings_tab_editor_homepage_order',
  2580. 'anchor' => 'settings-tab-editor-homepage-order-anchor',
  2581. 'name' => 'Homepage Order'
  2582. ],
  2583. ];
  2584. $systemSettingsMenu = [
  2585. [
  2586. 'active' => true,
  2587. 'api' => false,
  2588. 'anchor' => 'settings-settings-about-anchor',
  2589. 'name' => 'About'
  2590. ],
  2591. [
  2592. 'active' => false,
  2593. 'api' => 'api/v2/page/settings_settings_main',
  2594. 'anchor' => 'settings-settings-main-anchor',
  2595. 'name' => 'Main'
  2596. ],
  2597. [
  2598. 'active' => false,
  2599. 'api' => 'api/v2/page/settings_settings_sso',
  2600. 'anchor' => 'settings-settings-sso-anchor',
  2601. 'name' => 'SSO'
  2602. ],
  2603. [
  2604. 'active' => false,
  2605. 'api' => 'api/v2/page/settings_settings_logs',
  2606. 'anchor' => 'settings-settings-logs-anchor',
  2607. 'name' => 'Logs'
  2608. ],
  2609. [
  2610. 'active' => false,
  2611. 'api' => false,
  2612. 'anchor' => 'settings-settings-updates-anchor',
  2613. 'name' => 'Updates'
  2614. ],
  2615. [
  2616. 'active' => false,
  2617. 'api' => 'api/v2/page/settings_settings_backup',
  2618. 'anchor' => 'settings-settings-backup-anchor',
  2619. 'name' => 'Backup'
  2620. ],
  2621. [
  2622. 'active' => false,
  2623. 'api' => false,
  2624. 'anchor' => 'settings-settings-donate-anchor',
  2625. 'name' => 'Donate'
  2626. ],
  2627. ];
  2628. $systemMenus['system_settings'] = $this->buildSettingsMenus($systemSettingsMenu, 'System Settings');
  2629. $systemMenus['tab_editor'] = $this->buildSettingsMenus($tabEditorMenu, 'Tab Editor');
  2630. $systemMenus['customize'] = $this->buildSettingsMenus($customizeMenu, 'Customize');
  2631. $systemMenus['user_management'] = $this->buildSettingsMenus($userManagementMenu, 'User Management');
  2632. $systemMenus['plugins'] = $this->buildSettingsMenus($pluginsMenu, 'Plugins');
  2633. return $systemMenus;
  2634. }
  2635. public function updateConfigMultiple($array)
  2636. {
  2637. return (bool)$this->updateConfig($array);
  2638. }
  2639. public function updateConfigItems($array)
  2640. {
  2641. if (!count($array)) {
  2642. $this->setAPIResponse('error', 'No data submitted', 409);
  2643. return false;
  2644. }
  2645. $newItems = [];
  2646. $updatedItems = [];
  2647. foreach ($array as $k => $v) {
  2648. $v = $v ?? '';
  2649. switch ($v) {
  2650. case 'true':
  2651. $v = (bool)true;
  2652. break;
  2653. case 'false':
  2654. $v = (bool)false;
  2655. break;
  2656. }
  2657. // Hash
  2658. if ((stripos($k, 'password') !== false)) {
  2659. if (!$this->isEncrypted($v)) {
  2660. if ($v !== '') {
  2661. $v = $this->encrypt($v);
  2662. }
  2663. }
  2664. }
  2665. switch ($k) {
  2666. case 'logLocation':
  2667. case 'dbLocation':
  2668. if (!empty($v)) {
  2669. $v = $this->cleanDirectory($v);
  2670. }
  2671. break;
  2672. default:
  2673. break;
  2674. }
  2675. if (strtolower($k) !== 'formkey') {
  2676. if ($this->config[$k] !== $v) {
  2677. $updatedItems[$k] = $v;
  2678. }
  2679. $newItems[$k] = $v;
  2680. $this->config[$k] = $v;
  2681. }
  2682. }
  2683. $this->setAPIResponse('success', 'Config items updated', 200);
  2684. $this->setLoggerChannel('Config')->notice('Config items updated', ['items' => array_keys($updatedItems)]);
  2685. return (bool)$this->updateConfig($newItems);
  2686. }
  2687. public function updateConfigItem($array)
  2688. {
  2689. $array['value'] = $array['value'] ?? '';
  2690. switch ($array['value']) {
  2691. case 'true':
  2692. $array['value'] = (bool)true;
  2693. break;
  2694. case 'false':
  2695. $array['value'] = (bool)false;
  2696. break;
  2697. }
  2698. // Hash
  2699. if ($array['type'] == 'password') {
  2700. $array['value'] = $this->encrypt($array['value']);
  2701. }
  2702. $newItem = array(
  2703. $array['name'] => $array['value']
  2704. );
  2705. $this->config[$array['name']] = $array['value'];
  2706. return (bool)$this->updateConfig($newItem);
  2707. }
  2708. public function ignoreNewsId($id)
  2709. {
  2710. if (!$id) {
  2711. $this->setAPIResponse('error', 'News id was not supplied', 409);
  2712. return false;
  2713. }
  2714. $id = array(intval($id));
  2715. $newsIds = $this->config['ignoredNewsIds'];
  2716. $newsIds = array_merge($newsIds, $id);
  2717. $newsIds = array_unique($newsIds);
  2718. $this->updateConfig(['ignoredNewsIds' => $newsIds]);
  2719. $this->setAPIResponse('success', 'News id is now ignored', 200, null);
  2720. }
  2721. public function getNewsIds()
  2722. {
  2723. $newsIds = $this->config['ignoredNewsIds'];
  2724. $this->setAPIResponse('success', null, 200, $newsIds);
  2725. return $newsIds;
  2726. }
  2727. public function testWizardPath($array)
  2728. {
  2729. if ($this->hasDB()) {
  2730. $this->setAPIResponse('error', 'Endpoint disabled as database already exists', 401);
  2731. return false;
  2732. }
  2733. $path = $array['path'] ?? null;
  2734. if (file_exists($path)) {
  2735. if (is_writable($path)) {
  2736. $this->setAPIResponse('success', 'Path exists and is writable', 200);
  2737. return true;
  2738. } else {
  2739. $this->setAPIResponse('error', 'Path exists but is not writable', 403);
  2740. return false;
  2741. }
  2742. } else {
  2743. if (mkdir($path, 0760, true)) {
  2744. $this->setAPIResponse('success', 'Path is writable - Creating now', 200);
  2745. return true;
  2746. } else {
  2747. $this->setAPIResponse('error', 'Failed making directory - Check permissions', 403);
  2748. return false;
  2749. }
  2750. }
  2751. }
  2752. public function formatDatabaseDriver($driver)
  2753. {
  2754. $driver = strtolower($driver);
  2755. switch ($driver) {
  2756. case 'sqlite':
  2757. case 'sqlite3':
  2758. return 'sqlite3';
  2759. case 'mysql':
  2760. case 'mysqli':
  2761. return 'mysqli';
  2762. case 'postgre':
  2763. case 'postgres':
  2764. case 'postgresql':
  2765. return 'postgre';
  2766. default:
  2767. return $driver;
  2768. }
  2769. }
  2770. public function wizardConfig($array)
  2771. {
  2772. $array['driver'] = $array['driver'] ?? 'sqlite3';
  2773. $driver = $this->formatDatabaseDriver($array['driver']);
  2774. $dbName = $array['dbName'] ?? null;
  2775. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2776. $license = $array['license'] ?? null;
  2777. $hashKey = $array['hashKey'] ?? null;
  2778. $api = $array['api'] ?? null;
  2779. $registrationPassword = $array['registrationPassword'] ?? null;
  2780. $username = $array['username'] ?? null;
  2781. $password = $array['password'] ?? null;
  2782. $email = $array['email'] ?? null;
  2783. $dbHost = $array['dbHost'] ?? null;
  2784. $dbUsername = $array['dbUsername'] ?? null;
  2785. $dbPassword = $array['dbPassword'] ?? null;
  2786. $validation = [
  2787. 'dbPath' => $path,
  2788. 'dbName' => $dbName,
  2789. 'license' => $license,
  2790. 'hashKey' => $hashKey,
  2791. 'api' => $api,
  2792. 'registrationPassword' => $registrationPassword,
  2793. 'username' => $username,
  2794. 'password' => $password,
  2795. 'email' => $email,
  2796. 'driver' => $driver
  2797. ];
  2798. $dbName = $this->dbExtension($dbName);
  2799. if ($driver == 'mysqli' || $driver == 'postgre') {
  2800. $dbName = $this->removeDbExtension($dbName);
  2801. $validation = array_merge($validation, [
  2802. 'dbHost' => $dbHost,
  2803. 'dbUsername' => $dbUsername,
  2804. 'dbPassword' => $dbPassword,
  2805. ]);
  2806. }
  2807. foreach ($validation as $k => $v) {
  2808. if ($v == null) {
  2809. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2810. return false;
  2811. }
  2812. }
  2813. if ($path) {
  2814. $path = $this->cleanDirectory($path);
  2815. if (file_exists($path)) {
  2816. if (!is_writable($path)) {
  2817. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2818. return false;
  2819. }
  2820. } else {
  2821. if (!mkdir($path, 0760, true)) {
  2822. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2823. return false;
  2824. }
  2825. }
  2826. }
  2827. $configVersion = $this->version;
  2828. $configArray = array(
  2829. 'dbLocation' => $path,
  2830. 'driver' => $driver,
  2831. 'dbName' => $dbName,
  2832. 'license' => $license,
  2833. 'organizrHash' => $hashKey,
  2834. 'organizrAPI' => $api,
  2835. 'registrationPassword' => $registrationPassword,
  2836. 'uuid' => $this->gen_uuid()
  2837. );
  2838. if ($driver == 'mysqli' || $driver == 'postgre') {
  2839. $configArray = array_merge($configArray, [
  2840. 'dbHost' => $dbHost,
  2841. 'dbUsername' => $dbUsername,
  2842. 'dbPassword' => $this->encrypt($dbPassword, $hashKey),
  2843. ]);
  2844. }
  2845. //Test Database Connection before saving config
  2846. $testDatabaseConnection = $this->testDatabaseConnection($array);
  2847. if (!$testDatabaseConnection) {
  2848. // setResponse already defined
  2849. return false;
  2850. }
  2851. // Create Config
  2852. if ($this->createConfig($configArray)) {
  2853. $this->config = $this->config();
  2854. $this->refreshCookieName();
  2855. $this->connectDB();
  2856. // Call DB Create
  2857. if (!$this->createNewDB($dbName, false)) {
  2858. $this->setAPIResponse('error', 'error creating database using driver: ' . $driver, 500);
  2859. return false;
  2860. }
  2861. if ($this->createDB($path)) {
  2862. // Add in first user
  2863. if ($this->createFirstAdmin($username, $password, $email)) {
  2864. if ($this->createToken($username, $email, 1)) {
  2865. return true;
  2866. } else {
  2867. $this->setAPIResponse('error', 'error creating token', 500);
  2868. }
  2869. } else {
  2870. $this->setAPIResponse('error', 'error creating admin', 500);
  2871. }
  2872. } else {
  2873. $this->setAPIResponse('error', 'error creating database', 500);
  2874. }
  2875. } else {
  2876. $this->setAPIResponse('error', 'error creating config', 500);
  2877. }
  2878. return false;
  2879. }
  2880. public function testDatabaseConnection($array)
  2881. {
  2882. $driver = $array['driver'] ?? 'sqlite3';
  2883. $driver = $this->formatDatabaseDriver($driver);
  2884. $dbName = $array['dbName'] ?? null;
  2885. $dbHost = $array['dbHost'] ?? null;
  2886. $dbUsername = $array['dbUsername'] ?? null;
  2887. $dbPassword = $array['dbPassword'] ?? null;
  2888. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2889. switch ($driver) {
  2890. case 'mysqli':
  2891. if (!extension_loaded('mysqli')) {
  2892. $this->setResponse(500, 'PHP Extension `mysqli` is not loaded');
  2893. return false;
  2894. }
  2895. $config = [
  2896. 'driver' => 'mysqli',
  2897. 'host' => $dbHost,
  2898. 'username' => $dbUsername,
  2899. 'password' => $dbPassword,
  2900. 'options' => [
  2901. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2902. ],
  2903. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2904. ];
  2905. $validation = [
  2906. 'dbHost' => $dbHost,
  2907. 'dbUsername' => $dbUsername,
  2908. 'dbPassword' => $dbPassword,
  2909. ];
  2910. break;
  2911. case 'postgre':
  2912. // DISABLE FOR NOW
  2913. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2914. return false;
  2915. $config = [
  2916. //host, hostaddr, port, dbname, user, password, connect_timeout, options, sslmode, service => see PostgreSQL API
  2917. 'driver' => 'postgre',
  2918. 'username' => $dbUsername,
  2919. 'password' => $dbPassword,
  2920. 'persistent' => true,
  2921. ];
  2922. $host = $this->qualifyURL($dbHost, true);
  2923. if ($host['port']) {
  2924. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  2925. }
  2926. if (($host['host'])) {
  2927. $config = array_merge($config, ['host' => $host['host']]);
  2928. }
  2929. if (!$host['host'] && $host['path']) {
  2930. $config = array_merge($config, ['host' => $host['path']]);
  2931. }
  2932. $validation = [
  2933. 'dbHost' => $dbHost,
  2934. 'dbUsername' => $dbUsername,
  2935. 'dbPassword' => $dbPassword,
  2936. ];
  2937. break;
  2938. case 'sqlite3':
  2939. $path = $this->cleanDirectory($path);
  2940. if (file_exists($path)) {
  2941. if (!is_writable($path)) {
  2942. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2943. return false;
  2944. }
  2945. } else {
  2946. if (is_writable(dirname($path, 1))) {
  2947. if (!mkdir($path, 0760, true)) {
  2948. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2949. return false;
  2950. }
  2951. } else {
  2952. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2953. return false;
  2954. }
  2955. }
  2956. return true;
  2957. default:
  2958. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2959. return false;
  2960. }
  2961. foreach ($validation as $k => $v) {
  2962. if ($v == null) {
  2963. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2964. return false;
  2965. }
  2966. }
  2967. try {
  2968. $connection = new Connection($config);
  2969. $testConnection = $connection->isConnected();
  2970. if ($testConnection) {
  2971. $this->setResponse(200, 'Database connection successful');
  2972. return true;
  2973. } else {
  2974. $this->setResponse(409, 'Database connection unsuccessful');
  2975. return false;
  2976. }
  2977. } catch (Dibi\Exception $e) {
  2978. $this->setResponse(500, $e->getMessage());
  2979. return false;
  2980. }
  2981. }
  2982. public function createNewDB($dbName, $migration = false)
  2983. {
  2984. if ($this->config['driver'] == 'mysqli') {
  2985. $config = [
  2986. 'driver' => 'mysqli',
  2987. 'host' => $this->config['dbHost'],
  2988. 'username' => $this->config['dbUsername'],
  2989. 'password' => $this->decrypt($this->config['dbPassword']),
  2990. 'options' => [
  2991. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2992. ],
  2993. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2994. ];
  2995. if ($migration) {
  2996. try {
  2997. $this->otherDb = new Connection($config);
  2998. } catch (Dibi\Exception $e) {
  2999. $this->otherDb = null;
  3000. }
  3001. } else {
  3002. try {
  3003. $this->db = new Connection($config);
  3004. } catch (Dibi\Exception $e) {
  3005. $this->db = null;
  3006. }
  3007. }
  3008. if ($dbName == 'tempMigration') {
  3009. $response = [
  3010. array(
  3011. 'function' => 'query',
  3012. 'query' => [
  3013. 'DROP DATABASE IF EXISTS tempMigration'
  3014. ]
  3015. ),
  3016. ];
  3017. $drop = $this->processQueries($response, $migration);
  3018. }
  3019. $response = [
  3020. array(
  3021. 'function' => 'query',
  3022. 'query' => ['CREATE DATABASE IF NOT EXISTS %n',
  3023. $dbName
  3024. ]
  3025. )
  3026. ];
  3027. $results = $this->processQueries($response, $migration);
  3028. if ($results) {
  3029. if ($migration) {
  3030. $this->connectOtherDB();
  3031. } else {
  3032. $this->connectDB();
  3033. }
  3034. return true;
  3035. } else {
  3036. return false;
  3037. }
  3038. } elseif ($this->config['driver'] == 'postgre') {
  3039. $config = [
  3040. 'driver' => 'postgre',
  3041. 'username' => $this->config['dbUsername'],
  3042. 'password' => $this->decrypt($this->config['dbPassword']),
  3043. 'persistent' => true,
  3044. ];
  3045. $host = $this->qualifyURL($this->config['dbHost'], true);
  3046. if ($host['port']) {
  3047. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  3048. }
  3049. if ($host['host']) {
  3050. $config = array_merge($config, ['host' => $host['host']]);
  3051. }
  3052. if (!$host['host'] && $host['path']) {
  3053. $config = array_merge($config, ['host' => $host['path']]);
  3054. }
  3055. try {
  3056. $this->db = new Connection($config);
  3057. } catch (Dibi\Exception $e) {
  3058. $this->db = null;
  3059. }
  3060. $response = [
  3061. array(
  3062. 'function' => 'query',
  3063. 'query' => ['CREATE DATABASE %n',
  3064. $dbName
  3065. ]
  3066. )
  3067. ];
  3068. $results = $this->processQueries($response, $migration);
  3069. if ($results) {
  3070. $this->connectDB();
  3071. return true;
  3072. } else {
  3073. return false;
  3074. }
  3075. } else {
  3076. return true;
  3077. }
  3078. }
  3079. public function getDefaultTablesFormatted()
  3080. {
  3081. $list = [];
  3082. $tables = $this->defaultTables();
  3083. foreach ($tables as $table) {
  3084. $string = trim($table['query']);
  3085. preg_match('/CREATE TABLE `(.*?)`/', $string, $output_array);
  3086. if (count($output_array) > 1) {
  3087. $list[] = $output_array[1];
  3088. }
  3089. }
  3090. return $list;
  3091. }
  3092. public function defaultTables()
  3093. {
  3094. return [
  3095. array(
  3096. 'function' => 'query',
  3097. 'query' => '
  3098. CREATE TABLE `users` (
  3099. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3100. `username` TEXT UNIQUE,
  3101. `password` TEXT,
  3102. `email` TEXT,
  3103. `plex_token` TEXT,
  3104. `group` TEXT,
  3105. `group_id` INTEGER,
  3106. `locked` INTEGER,
  3107. `image` TEXT,
  3108. `register_date` DATETIME,
  3109. `auth_service` TEXT DEFAULT \'internal\'
  3110. );
  3111. '
  3112. ),
  3113. array(
  3114. 'function' => 'query',
  3115. 'query' => 'CREATE TABLE `chatroom` (
  3116. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3117. `username` TEXT,
  3118. `gravatar` TEXT,
  3119. `uid` TEXT,
  3120. `date` DATETIME,
  3121. `ip` TEXT,
  3122. `message` TEXT
  3123. );'
  3124. ),
  3125. array(
  3126. 'function' => 'query',
  3127. 'query' => 'CREATE TABLE `tokens` (
  3128. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3129. `token` TEXT UNIQUE,
  3130. `user_id` INTEGER,
  3131. `browser` TEXT,
  3132. `ip` TEXT,
  3133. `created` DATETIME,
  3134. `expires` DATETIME
  3135. );'
  3136. ),
  3137. array(
  3138. 'function' => 'query',
  3139. 'query' => 'CREATE TABLE `groups` (
  3140. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3141. `group` TEXT UNIQUE,
  3142. `group_id` INTEGER,
  3143. `image` TEXT,
  3144. `default` INTEGER
  3145. );'
  3146. ),
  3147. array(
  3148. 'function' => 'query',
  3149. 'query' => 'CREATE TABLE `categories` (
  3150. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3151. `order` INTEGER,
  3152. `category` TEXT UNIQUE,
  3153. `category_id` INTEGER,
  3154. `image` TEXT,
  3155. `default` INTEGER
  3156. );'
  3157. ),
  3158. array(
  3159. 'function' => 'query',
  3160. 'query' => 'CREATE TABLE `tabs` (
  3161. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3162. `order` INTEGER,
  3163. `category_id` INTEGER,
  3164. `name` TEXT,
  3165. `url` TEXT,
  3166. `url_local` TEXT,
  3167. `default` INTEGER,
  3168. `enabled` INTEGER,
  3169. `group_id` INTEGER,
  3170. `group_id_max` INTEGER DEFAULT \'0\',
  3171. `add_to_admin` INTEGER DEFAULT \'0\',
  3172. `image` TEXT,
  3173. `type` INTEGER,
  3174. `splash` INTEGER,
  3175. `ping` INTEGER,
  3176. `ping_url` TEXT,
  3177. `timeout` INTEGER,
  3178. `timeout_ms` INTEGER,
  3179. `preload` INTEGER
  3180. );'
  3181. ),
  3182. array(
  3183. 'function' => 'query',
  3184. 'query' => 'CREATE TABLE `options` (
  3185. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3186. `name` TEXT UNIQUE,
  3187. `value` TEXT
  3188. );'
  3189. ),
  3190. array(
  3191. 'function' => 'query',
  3192. 'query' => 'CREATE TABLE `invites` (
  3193. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3194. `code` TEXT UNIQUE,
  3195. `date` DATETIME,
  3196. `email` TEXT,
  3197. `username` TEXT,
  3198. `dateused` TIMESTAMP,
  3199. `usedby` TEXT,
  3200. `ip` TEXT,
  3201. `valid` TEXT,
  3202. `type` TEXT,
  3203. `invitedby` TEXT
  3204. );'
  3205. ),
  3206. array(
  3207. 'function' => 'query',
  3208. 'query' => 'CREATE TABLE `BOOKMARK-categories` (
  3209. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3210. `order` INTEGER,
  3211. `category` TEXT UNIQUE,
  3212. `category_id` INTEGER,
  3213. `default` INTEGER
  3214. );'
  3215. ),
  3216. array(
  3217. 'function' => 'query',
  3218. 'query' => 'CREATE TABLE `BOOKMARK-tabs` (
  3219. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3220. `order` INTEGER,
  3221. `category_id` INTEGER,
  3222. `name` TEXT,
  3223. `url` TEXT,
  3224. `enabled` INTEGER,
  3225. `group_id` INTEGER,
  3226. `image` TEXT,
  3227. `background_color` TEXT,
  3228. `text_color` TEXT
  3229. );'
  3230. )
  3231. ];
  3232. }
  3233. public function createDB($path, $migration = false)
  3234. {
  3235. if (!file_exists($path)) {
  3236. mkdir($path, 0777, true);
  3237. }
  3238. $tables = $this->defaultTables();
  3239. return $this->processQueries($tables, $migration);
  3240. }
  3241. public function createFirstAdmin($username, $password, $email)
  3242. {
  3243. $userInfo = [
  3244. 'username' => $username,
  3245. 'password' => password_hash($password, PASSWORD_BCRYPT),
  3246. 'email' => $email,
  3247. 'group' => 'Admin',
  3248. 'group_id' => 0,
  3249. 'image' => $this->gravatar($email),
  3250. 'register_date' => gmdate('Y-m-d H:i:s'),
  3251. ];
  3252. $groupInfo0 = [
  3253. 'group' => 'Admin',
  3254. 'group_id' => 0,
  3255. 'default' => 0,
  3256. 'image' => 'plugins/images/groups/admin.png',
  3257. ];
  3258. $groupInfo1 = [
  3259. 'group' => 'Co-Admin',
  3260. 'group_id' => 1,
  3261. 'default' => 0,
  3262. 'image' => 'plugins/images/groups/coadmin.png',
  3263. ];
  3264. $groupInfo2 = [
  3265. 'group' => 'Super User',
  3266. 'group_id' => 2,
  3267. 'default' => 0,
  3268. 'image' => 'plugins/images/groups/superuser.png',
  3269. ];
  3270. $groupInfo3 = [
  3271. 'group' => 'Power User',
  3272. 'group_id' => 3,
  3273. 'default' => 0,
  3274. 'image' => 'plugins/images/groups/poweruser.png',
  3275. ];
  3276. $groupInfo4 = [
  3277. 'group' => 'User',
  3278. 'group_id' => 4,
  3279. 'default' => 1,
  3280. 'image' => 'plugins/images/groups/user.png',
  3281. ];
  3282. $groupInfoGuest = [
  3283. 'group' => 'Guest',
  3284. 'group_id' => 999,
  3285. 'default' => 0,
  3286. 'image' => 'plugins/images/groups/guest.png',
  3287. ];
  3288. $settingsInfo = [
  3289. 'order' => 1,
  3290. 'category_id' => 0,
  3291. 'name' => 'Settings',
  3292. 'url' => 'api/v2/page/settings',
  3293. 'default' => 0,
  3294. 'enabled' => 1,
  3295. 'group_id' => 1,
  3296. 'image' => 'fontawesome::cog',
  3297. 'type' => 0
  3298. ];
  3299. $homepageInfo = [
  3300. 'order' => 2,
  3301. 'category_id' => 0,
  3302. 'name' => 'Homepage',
  3303. 'url' => 'api/v2/page/homepage',
  3304. 'default' => 0,
  3305. 'enabled' => 0,
  3306. 'group_id' => 4,
  3307. 'image' => 'fontawesome::home',
  3308. 'type' => 0
  3309. ];
  3310. $unsortedInfo = [
  3311. 'order' => 1,
  3312. 'category' => 'Unsorted',
  3313. 'category_id' => 0,
  3314. 'image' => 'fontawesome::question',
  3315. 'default' => 1
  3316. ];
  3317. $response = [
  3318. array(
  3319. 'function' => 'query',
  3320. 'query' => array(
  3321. 'INSERT INTO [users]',
  3322. $userInfo
  3323. )
  3324. ),
  3325. array(
  3326. 'function' => 'query',
  3327. 'query' => array(
  3328. 'INSERT INTO [groups]',
  3329. $groupInfo0
  3330. )
  3331. ),
  3332. array(
  3333. 'function' => 'query',
  3334. 'query' => array(
  3335. 'INSERT INTO [groups]',
  3336. $groupInfo1
  3337. )
  3338. ),
  3339. array(
  3340. 'function' => 'query',
  3341. 'query' => array(
  3342. 'INSERT INTO [groups]',
  3343. $groupInfo2
  3344. )
  3345. ),
  3346. array(
  3347. 'function' => 'query',
  3348. 'query' => array(
  3349. 'INSERT INTO [groups]',
  3350. $groupInfo3
  3351. )
  3352. ),
  3353. array(
  3354. 'function' => 'query',
  3355. 'query' => array(
  3356. 'INSERT INTO [groups]',
  3357. $groupInfo4
  3358. )
  3359. ),
  3360. array(
  3361. 'function' => 'query',
  3362. 'query' => array(
  3363. 'INSERT INTO [groups]',
  3364. $groupInfoGuest
  3365. )
  3366. ),
  3367. array(
  3368. 'function' => 'query',
  3369. 'query' => array(
  3370. 'INSERT INTO [tabs]',
  3371. $settingsInfo
  3372. )
  3373. ),
  3374. array(
  3375. 'function' => 'query',
  3376. 'query' => array(
  3377. 'INSERT INTO [tabs]',
  3378. $homepageInfo
  3379. )
  3380. ),
  3381. array(
  3382. 'function' => 'query',
  3383. 'query' => array(
  3384. 'INSERT INTO [categories]',
  3385. $unsortedInfo
  3386. )
  3387. ),
  3388. ];
  3389. return $this->processQueries($response);
  3390. }
  3391. public function getUserByUsernameAndEmail($username, $email)
  3392. {
  3393. $response = [
  3394. array(
  3395. 'function' => 'fetch',
  3396. 'query' => array(
  3397. 'SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',
  3398. [$username],
  3399. [$email]
  3400. )
  3401. ),
  3402. ];
  3403. return $this->processQueries($response);
  3404. }
  3405. public function createToken($username, $email, $days = 1)
  3406. {
  3407. $this->setLoggerChannel('Authentication', $username);
  3408. $this->logger->debug('Starting token creation function');
  3409. $days = ($days > 365) ? 365 : $days;
  3410. //Quick get user ID
  3411. $result = $this->getUserByUsernameAndEmail($username, $email);
  3412. $config = $this->configToken();
  3413. assert($config instanceof Lcobucci\JWT\Configuration);
  3414. $now = new DateTimeImmutable();
  3415. $token = $config->builder()
  3416. // Configures the issuer (iss claim)
  3417. ->issuedBy('Organizr')
  3418. // Configures the audience (aud claim)
  3419. ->permittedFor('Organizr')
  3420. // Configures the id (jti claim)
  3421. ->identifiedBy('4f1g23a12aa')
  3422. // Configures the time that the token was issue (iat claim)
  3423. ->issuedAt($now)
  3424. // Configures the time that the token can be used (nbf claim)
  3425. ->canOnlyBeUsedAfter($now)
  3426. // Configures the expiration time of the token (exp claim)
  3427. ->expiresAt($now->modify('+' . $days . ' days'))
  3428. // Configures a new claim, called "uid"
  3429. ->withClaim('name', $result['username'])// Configures a new claim, called "name"
  3430. ->withClaim('group', $result['group'])// Configures a new claim, called "group"
  3431. ->withClaim('groupID', $result['group_id'])// Configures a new claim, called "groupID"
  3432. ->withClaim('email', $result['email'])// Configures a new claim, called "email"
  3433. ->withClaim('image', $result['image'])// Configures a new claim, called "image"
  3434. ->withClaim('userID', $result['id'])// Configures a new claim, called "image"
  3435. // Configures a new header, called "foo"
  3436. //->withHeader('foo', 'bar')
  3437. // Builds a new token
  3438. ->getToken($config->signer(), $config->signingKey());
  3439. //$token->headers(); // Retrieves the token headers
  3440. //$token->claims(); // Retrieves the token claims
  3441. $this->coookie('set', $this->cookieName, $token->toString(), $days);
  3442. // Add token to DB
  3443. $addToken = [
  3444. 'token' => $token->toString(),
  3445. 'user_id' => $result['id'],
  3446. 'created' => gmdate('Y-m-d H:i:s'),
  3447. 'browser' => $_SERVER ['HTTP_USER_AGENT'] ?? null,
  3448. 'ip' => $this->userIP(),
  3449. 'expires' => gmdate('Y-m-d H:i:s', time() + (86400 * $days))
  3450. ];
  3451. $response = [
  3452. array(
  3453. 'function' => 'query',
  3454. 'query' => array(
  3455. 'INSERT INTO [tokens]',
  3456. $addToken
  3457. )
  3458. ),
  3459. ];
  3460. $this->processQueries($response);
  3461. if ($token) {
  3462. $this->logger->debug('Token has been created');
  3463. } else {
  3464. $this->logger->warning('Token creation error');
  3465. }
  3466. $this->logger->debug('Token creation function has finished');
  3467. return $token->toString();
  3468. }
  3469. public function login($array)
  3470. {
  3471. // Grab username, Password & other optional items from api call
  3472. $username = $array['username'] ?? null;
  3473. $password = $array['password'] ?? null;
  3474. $oAuth = $array['oAuth'] ?? null;
  3475. $oAuthType = $array['oAuthType'] ?? null;
  3476. $remember = $array['remember'] ?? null;
  3477. $tfaCode = $array['tfaCode'] ?? null;
  3478. $loginAttempts = $array['loginAttempts'] ?? null;
  3479. $output = $array['output'] ?? null;
  3480. $username = (strpos($this->config['authBackend'], 'emby') !== false) ? $username : strtolower($username);
  3481. $days = (isset($remember)) ? $this->config['rememberMeDays'] : 1;
  3482. // Set logger channel
  3483. $this->setLoggerChannel('Authentication', $username);
  3484. $this->logger->debug('Starting login function');
  3485. // Set other variables
  3486. $function = 'plugin_auth_' . $this->config['authBackend'];
  3487. $authSuccess = false;
  3488. $authProxy = false;
  3489. $addEmailToAuthProxy = true;
  3490. // Check Login attempts and kill if over limit
  3491. if ($loginAttempts > $this->config['loginAttempts'] || isset($_COOKIE['lockout'])) {
  3492. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3493. $this->logger->warning('User is locked out');
  3494. $this->setAPIResponse('error', 'User is locked out', 403);
  3495. return false;
  3496. }
  3497. // Check if Auth Proxy is enabled
  3498. if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
  3499. if (isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])]) || isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])])) {
  3500. $usernameHeader = $this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])] ?? null;
  3501. $emailHeader = $this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])] ?? null;
  3502. $headerForLogin = $usernameHeader ?: ($emailHeader ?: null);
  3503. $this->setLoggerChannel('Authentication', $headerForLogin);
  3504. $this->logger->debug('Starting Auth Proxy verification');
  3505. $whitelistRange = $this->analyzeIP($this->config['authProxyWhitelist']);
  3506. $authProxy = $this->authProxyRangeCheck($whitelistRange['from'], $whitelistRange['to']);
  3507. $username = ($authProxy) ? $headerForLogin : $username;
  3508. $password = ($password == null) ? $this->random_ascii_string(10) : $password;
  3509. $addEmailToAuthProxy = ($authProxy && $emailHeader) ? ['email' => $emailHeader] : true;
  3510. if ($authProxy) {
  3511. $this->logger->info('User has been verified using Auth Proxy');
  3512. } else {
  3513. $this->logger->warning('User has failed verification using Auth Proxy');
  3514. }
  3515. }
  3516. }
  3517. // Check if Login method was an oAuth login
  3518. if (!$oAuth) {
  3519. $result = $this->getUserByUsernameAndEmail($username, $username);
  3520. $result['password'] = $result['password'] ?? '';
  3521. // Switch AuthType - internal - external - both
  3522. switch ($this->config['authType']) {
  3523. case 'external':
  3524. if (method_exists($this, $function)) {
  3525. $authSuccess = $this->$function($username, $password);
  3526. }
  3527. break;
  3528. /** @noinspection PhpMissingBreakStatementInspection */
  3529. case 'both':
  3530. if (method_exists($this, $function)) {
  3531. $authSuccess = $this->$function($username, $password);
  3532. }
  3533. // no break
  3534. default: // Internal
  3535. if (!$authSuccess) {
  3536. // perform the internal authentication step
  3537. if (password_verify($password, $result['password'])) {
  3538. $this->logger->debug('User password has been verified');
  3539. $authSuccess = true;
  3540. }
  3541. }
  3542. }
  3543. $authSuccess = ($authProxy) ? $addEmailToAuthProxy : $authSuccess;
  3544. } else {
  3545. // Has oAuth Token!
  3546. switch ($oAuthType) {
  3547. case 'plex':
  3548. if ($this->config['plexoAuth']) {
  3549. $this->logger->debug('Starting Plex oAuth verification');
  3550. $tokenInfo = $this->checkPlexToken($oAuth);
  3551. if ($tokenInfo) {
  3552. $authSuccess = [
  3553. 'username' => $tokenInfo['user']['username'],
  3554. 'email' => $tokenInfo['user']['email'],
  3555. 'image' => $tokenInfo['user']['thumb'],
  3556. 'token' => $tokenInfo['user']['authToken'],
  3557. 'oauth' => 'plex'
  3558. ];
  3559. $this->logger->debug('User\'s Plex Token has been verified');
  3560. $this->coookie('set', 'oAuth', 'true', $this->config['rememberMeDays']);
  3561. $authSuccess = ((!empty($this->config['plexAdmin']) && strtolower($this->config['plexAdmin']) == strtolower($tokenInfo['user']['username'])) || (!empty($this->config['plexAdmin']) && strtolower($this->config['plexAdmin']) == strtolower($tokenInfo['user']['email'])) || $this->checkPlexUser($tokenInfo['user']['username'])) ? $authSuccess : false;
  3562. } else {
  3563. $this->logger->warning('User\'s Plex Token has failed verification');
  3564. }
  3565. } else {
  3566. $this->logger->debug('Plex oAuth is not setup');
  3567. $this->setAPIResponse('error', 'Plex oAuth is not setup', 422);
  3568. return false;
  3569. }
  3570. break;
  3571. default:
  3572. return ($output) ? 'No oAuthType defined' : 'error';
  3573. }
  3574. $result = ($authSuccess) ? $this->getUserByUsernameAndEmail($authSuccess['username'], $authSuccess['email']) : '';
  3575. }
  3576. if ($authSuccess) {
  3577. // Make sure user exists in database
  3578. $userExists = false;
  3579. $passwordMatches = $oAuth || $authProxy;
  3580. $token = (is_array($authSuccess) && isset($authSuccess['token']) ? $authSuccess['token'] : '');
  3581. if (isset($result['username'])) {
  3582. $userExists = true;
  3583. $username = $result['username'];
  3584. if ($passwordMatches == false) {
  3585. $passwordMatches = password_verify($password, $result['password']);
  3586. }
  3587. }
  3588. if ($userExists) {
  3589. //does org password need to be updated
  3590. if (!$passwordMatches) {
  3591. $this->updateUserPassword($password, $result['id']);
  3592. $this->setLoggerChannel('Authentication', $username);
  3593. $this->logger->info('User Password updated from backend');
  3594. }
  3595. if ($token !== '') {
  3596. if ($token !== $result['plex_token']) {
  3597. $this->updateUserPlexToken($token, $result['id']);
  3598. $this->setLoggerChannel('Authentication', $username);
  3599. $this->logger->info('User Plex Token updated from backend');
  3600. }
  3601. }
  3602. // 2FA might go here
  3603. if ($result['auth_service'] !== 'internal' && strpos($result['auth_service'], '::') !== false) {
  3604. $tfaProceed = true;
  3605. // Add check for local or not
  3606. if ($this->config['ignoreTFALocal'] !== false) {
  3607. $tfaProceed = !$this->isLocal();
  3608. }
  3609. // Is Plex Oauth?
  3610. if ($this->config['ignoreTFAIfPlexOAuth'] !== false) {
  3611. if (isset($authSuccess['oauth'])) {
  3612. if ($authSuccess['oauth'] == 'plex') {
  3613. $tfaProceed = false;
  3614. }
  3615. }
  3616. }
  3617. if ($tfaProceed) {
  3618. $this->setLoggerChannel('Authentication', $username);
  3619. $this->logger->debug('Starting 2FA verification');
  3620. $TFA = explode('::', $result['auth_service']);
  3621. // Is code with login info?
  3622. if ($tfaCode == '') {
  3623. $this->logger->debug('Sending 2FA response to login UI');
  3624. $this->setAPIResponse('warning', '2FA Code Needed', 422);
  3625. return false;
  3626. } else {
  3627. if (!$this->verify2FA($TFA[1], $tfaCode, $TFA[0])) {
  3628. $this->logger->warning('Incorrect 2FA');
  3629. $this->setAPIResponse('error', 'Wrong 2FA', 422);
  3630. return false;
  3631. } else {
  3632. $this->logger->info('2FA verification passed');
  3633. }
  3634. }
  3635. }
  3636. }
  3637. // End 2FA
  3638. // authentication passed - 1) mark active and update token
  3639. $createToken = $this->createToken($result['username'], $result['email'], $days);
  3640. if ($createToken) {
  3641. $this->logger->info('User has logged in');
  3642. $ssoUserObject = ($token !== '') ? $authSuccess : $result;
  3643. $this->ssoCheck($ssoUserObject, $password, $token); //need to work on this
  3644. return ($output) ? array('name' => $this->cookieName, 'token' => (string)$createToken) : true;
  3645. } else {
  3646. $this->setAPIResponse('error', 'Token creation error', 500);
  3647. return false;
  3648. }
  3649. } else {
  3650. // Create User
  3651. $this->setLoggerChannel('Authentication', (is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username));
  3652. $this->logger->debug('Starting Registration function');
  3653. return $this->authRegister((is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username), $password, (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $token);
  3654. }
  3655. } else {
  3656. // authentication failed
  3657. $this->setLoggerChannel('Authentication', $username);
  3658. $this->logger->warning('Wrong Password');
  3659. if ($loginAttempts >= $this->config['loginAttempts']) {
  3660. $this->logger->warning('User exceeded maximum login attempts');
  3661. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3662. $this->setAPIResponse('error', 'User is locked out', 403);
  3663. return false;
  3664. } else {
  3665. $this->logger->debug('User has not exceeded maximum login attempts');
  3666. $this->setAPIResponse('error', 'User credentials incorrect', 401);
  3667. return false;
  3668. }
  3669. }
  3670. }
  3671. public function logout()
  3672. {
  3673. $this->setLoggerChannel('Authentication');
  3674. $this->logger->debug('Starting log out process');
  3675. $this->logger->info('User has logged out');
  3676. $this->coookie('delete', $this->cookieName);
  3677. $this->coookie('delete', 'mpt');
  3678. $this->coookie('delete', 'Auth');
  3679. $this->coookie('delete', 'oAuth');
  3680. $this->coookie('delete', 'connect.sid');
  3681. $this->coookie('delete', 'petio_jwt');
  3682. $this->clearTautulliTokens();
  3683. $this->clearJellyfinTokens();
  3684. $this->revokeTokenCurrentUser($this->user['token']);
  3685. $this->clearKomgaToken();
  3686. $this->refreshDeviceUUID();
  3687. $this->logger->debug('Log out process has finished');
  3688. $this->user = null;
  3689. return true;
  3690. }
  3691. public function recover($array)
  3692. {
  3693. $email = $array['email'] ?? null;
  3694. if (!$email) {
  3695. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3696. return false;
  3697. }
  3698. $newPassword = $this->randString(10);
  3699. $isUser = $this->getUserByEmail($email);
  3700. if ($isUser) {
  3701. $this->updateUserPassword($newPassword, $isUser['id']);
  3702. $this->setAPIResponse('success', 'User password has been reset', 200);
  3703. $this->setLoggerChannel('User Management');
  3704. $this->logger->info('User Management Function - User: ' . $isUser['username'] . '\'s password was reset');
  3705. if ($this->config['PHPMAILER-enabled']) {
  3706. $PhpMailer = new PhpMailer();
  3707. $emailTemplate = array(
  3708. 'type' => 'reset',
  3709. 'body' => $this->config['PHPMAILER-emailTemplateReset'],
  3710. 'subject' => $this->config['PHPMAILER-emailTemplateResetSubject'],
  3711. 'user' => $isUser['username'],
  3712. 'password' => $newPassword,
  3713. 'inviteCode' => null,
  3714. );
  3715. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3716. $sendEmail = array(
  3717. 'to' => $email,
  3718. 'user' => $isUser['username'],
  3719. 'subject' => $emailTemplate['subject'],
  3720. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3721. );
  3722. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3723. $this->setAPIResponse('success', 'User password has been reset and email has been sent', 200);
  3724. }
  3725. return true;
  3726. } else {
  3727. $this->setAPIResponse('error', 'User not found', 404);
  3728. return false;
  3729. }
  3730. }
  3731. public function register($array)
  3732. {
  3733. $email = $array['email'] ?? null;
  3734. $username = $array['username'] ?? null;
  3735. $password = $array['password'] ?? null;
  3736. $registrationPassword = $array['registrationPassword'] ?? null;
  3737. if (!$email) {
  3738. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3739. return false;
  3740. }
  3741. if (!$username) {
  3742. $this->setAPIResponse('error', 'Username was not supplied', 422);
  3743. return false;
  3744. }
  3745. if (!$password) {
  3746. $this->setAPIResponse('error', 'Password was not supplied', 422);
  3747. return false;
  3748. }
  3749. if (!$registrationPassword) {
  3750. $this->setAPIResponse('error', 'Registration Password was not supplied', 422);
  3751. return false;
  3752. }
  3753. $this->setLoggerChannel('User Registration');
  3754. if ($registrationPassword == $this->decrypt($this->config['registrationPassword'])) {
  3755. $this->logger->debug('Registration Password Verified');
  3756. if ($this->createUser($username, $password, $email)) {
  3757. $this->logger->info('A User has registered');
  3758. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3759. $this->setLoggerChannel('Authentication', $username);
  3760. $this->logger->info('User has logged in');
  3761. return true;
  3762. }
  3763. } else {
  3764. return false;
  3765. }
  3766. } else {
  3767. $this->logger->warning('Wrong Password');
  3768. $this->setAPIResponse('error', 'Registration Password was incorrect', 401);
  3769. return false;
  3770. }
  3771. }
  3772. public function authRegister($username, $password, $email, $token = null)
  3773. {
  3774. $this->setLoggerChannel('Authentication', $username);
  3775. if ($this->config['authBackend'] !== '') {
  3776. $this->ombiImport($this->config['authBackend']);
  3777. }
  3778. $this->ssoCheck($username, $password, $token);
  3779. if ($token && (!$password || $password == '')) {
  3780. $password = $this->random_ascii_string(10);
  3781. }
  3782. if ($this->createUser($username, $password, $email)) {
  3783. $this->logger->info('A User has registered');
  3784. if ($this->config['PHPMAILER-enabled'] && $email !== '') {
  3785. $PhpMailer = new PhpMailer();
  3786. $emailTemplate = array(
  3787. 'type' => 'registration',
  3788. 'body' => $this->config['PHPMAILER-emailTemplateRegisterUser'],
  3789. 'subject' => $this->config['PHPMAILER-emailTemplateRegisterUserSubject'],
  3790. 'user' => $username,
  3791. 'password' => null,
  3792. 'inviteCode' => null,
  3793. );
  3794. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3795. $sendEmail = array(
  3796. 'to' => $email,
  3797. 'user' => $username,
  3798. 'subject' => $emailTemplate['subject'],
  3799. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3800. );
  3801. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3802. }
  3803. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3804. $this->logger->info('User has logged in');
  3805. return true;
  3806. } else {
  3807. return false;
  3808. }
  3809. } else {
  3810. $this->logger->warning('Registration error occurred');
  3811. return false;
  3812. }
  3813. }
  3814. public function revokeTokenCurrentUser($token = null)
  3815. {
  3816. if ($token) {
  3817. $response = [
  3818. array(
  3819. 'function' => 'query',
  3820. 'query' => array(
  3821. 'DELETE FROM tokens WHERE token = ?',
  3822. [$token]
  3823. )
  3824. ),
  3825. ];
  3826. } else {
  3827. $response = [
  3828. array(
  3829. 'function' => 'query',
  3830. 'query' => array(
  3831. 'DELETE FROM tokens WHERE user_id = ?',
  3832. [$this->user['userID']]
  3833. )
  3834. ),
  3835. ];
  3836. }
  3837. return $this->processQueries($response);
  3838. }
  3839. public function revokeToken($token = null)
  3840. {
  3841. if (!$token) {
  3842. $this->setAPIResponse('error', 'Token was not supplied', 422);
  3843. return false;
  3844. }
  3845. $response = [
  3846. array(
  3847. 'function' => 'query',
  3848. 'query' => array(
  3849. 'DELETE FROM tokens WHERE token = ?',
  3850. [$token]
  3851. )
  3852. ),
  3853. ];
  3854. $this->setAPIResponse('success', 'Token revoked', 204);
  3855. return $this->processQueries($response);
  3856. }
  3857. public function revokeTokenByIdCurrentUser($id = null)
  3858. {
  3859. if (!$id) {
  3860. $this->setAPIResponse('error', 'Id was not supplied', 422);
  3861. return false;
  3862. }
  3863. $response = [
  3864. array(
  3865. 'function' => 'query',
  3866. 'query' => array(
  3867. 'DELETE FROM tokens WHERE id = ? AND user_id = ?',
  3868. $id,
  3869. $this->user['userID']
  3870. )
  3871. ),
  3872. ];
  3873. $this->setAPIResponse('success', 'Token revoked', 204);
  3874. return $this->processQueries($response);
  3875. }
  3876. public function updateUserPassword($password, $id)
  3877. {
  3878. $response = [
  3879. array(
  3880. 'function' => 'query',
  3881. 'query' => array(
  3882. 'UPDATE users SET',
  3883. ['password' => password_hash($password, PASSWORD_BCRYPT)],
  3884. 'WHERE id = ?',
  3885. $id
  3886. )
  3887. ),
  3888. ];
  3889. return $this->processQueries($response);
  3890. }
  3891. public function updateUserPlexToken($token, $id)
  3892. {
  3893. $response = [
  3894. array(
  3895. 'function' => 'query',
  3896. 'query' => array(
  3897. 'UPDATE users SET',
  3898. ['plex_token' => $token],
  3899. 'WHERE id = ?',
  3900. $id
  3901. )
  3902. ),
  3903. ];
  3904. return $this->processQueries($response);
  3905. }
  3906. public function getUserTabsAndCategories($type = null)
  3907. {
  3908. if (!$this->hasDB()) {
  3909. return false;
  3910. }
  3911. $sort = ($this->config['unsortedTabs'] == 'top') ? 'DESC' : 'ASC';
  3912. $response = [
  3913. array(
  3914. 'function' => 'fetchAll',
  3915. 'query' => array(
  3916. 'SELECT * FROM tabs WHERE `group_id` >= ? AND `group_id_max` <= ? AND `enabled` = 1 ORDER BY `order` ' . $sort,
  3917. $this->user['groupID'],
  3918. $this->user['groupID'],
  3919. ),
  3920. 'key' => 'tabs'
  3921. ),
  3922. array(
  3923. 'function' => 'fetchAll',
  3924. 'query' => array(
  3925. 'SELECT * FROM tabs WHERE `add_to_admin` = 1 AND `enabled` = 1 ORDER BY `order` ' . $sort
  3926. ),
  3927. 'key' => 'tabs-admin'
  3928. ),
  3929. array(
  3930. 'function' => 'fetchAll',
  3931. 'query' => array(
  3932. 'SELECT * FROM categories ORDER BY `order` ASC',
  3933. ),
  3934. 'key' => 'categories'
  3935. ),
  3936. ];
  3937. $queries = $this->processQueries($response);
  3938. $this->applyTabVariables($queries['tabs']);
  3939. if ($this->qualifyRequest(1)) {
  3940. $this->applyTabVariables($queries['tabs-admin']);
  3941. $all['tabs'] = array_merge($queries['tabs'], $queries['tabs-admin']);
  3942. $newArray = [];
  3943. $ids = [];
  3944. foreach ($all['tabs'] as $key => $line) {
  3945. if (!in_array($line['id'], $ids)) {
  3946. $ids[] = $line['id'];
  3947. $newArray[$key] = $line;
  3948. }
  3949. }
  3950. $all['tabs'] = $newArray;
  3951. if (count($all['tabs']) > 0) {
  3952. usort($all['tabs'], function ($a, $b) {
  3953. if ($this->config['unsortedTabs'] == 'top') {
  3954. return $b['order'] <=> $a['order'];
  3955. } else {
  3956. return $a['order'] <=> $b['order'];
  3957. }
  3958. });
  3959. }
  3960. $newArray = NULL;
  3961. $ids = NULL;
  3962. } else {
  3963. $all['tabs'] = $queries['tabs'];
  3964. }
  3965. foreach ($all['tabs'] as $k => $v) {
  3966. $v['url_local'] = $v['type'] !== 0 ? $this->checkTabURL($v['url_local']) : $v['url_local'];
  3967. $v['url'] = $v['type'] !== 0 ? $this->checkTabURL($v['url']) : $v['url'];
  3968. $v['access_url'] = (!empty($v['url_local']) && ($v['url_local'] !== null) && ($v['url_local'] !== 'null') && $this->isLocal() && $v['type'] !== 0) ? $v['url_local'] : $v['url'];
  3969. }
  3970. $count = array_map(function ($element) {
  3971. return $element['category_id'];
  3972. }, $all['tabs']);
  3973. $count = (array_count_values($count));
  3974. foreach ($queries['categories'] as $k => $v) {
  3975. $v['count'] = $count[$v['category_id']] ?? 0;
  3976. }
  3977. $all['categories'] = $queries['categories'];
  3978. switch ($type) {
  3979. case 'categories':
  3980. return $all['categories'];
  3981. case 'tabs':
  3982. return $all['tabs'];
  3983. default:
  3984. return $all;
  3985. }
  3986. }
  3987. public function checkTabURL($url = null)
  3988. {
  3989. return $url !== '' && $url !== null & $url !== 'null' ? $this->qualifyURL($url, false, true) : '';
  3990. }
  3991. public function refreshList()
  3992. {
  3993. $searchTerm = "Refresh";
  3994. $list = array_filter($this->config, function ($k) use ($searchTerm) {
  3995. return stripos($k, $searchTerm) !== false;
  3996. }, ARRAY_FILTER_USE_KEY);
  3997. foreach ($list as $item => $value) {
  3998. if (!is_numeric($value)) {
  3999. unset($list[$item]);
  4000. }
  4001. }
  4002. return $list;
  4003. }
  4004. public function homepageOrderList()
  4005. {
  4006. $searchTerm = "homepageOrder";
  4007. $order = array_filter($this->config, function ($k) use ($searchTerm) {
  4008. return stripos($k, $searchTerm) !== false;
  4009. }, ARRAY_FILTER_USE_KEY);
  4010. asort($order);
  4011. return $order;
  4012. }
  4013. public function tautulliList()
  4014. {
  4015. $searchTerm = "tautulli_token";
  4016. return array_filter($this->config, function ($k) use ($searchTerm) {
  4017. return stripos($k, $searchTerm) !== false;
  4018. }, ARRAY_FILTER_USE_KEY);
  4019. }
  4020. public function checkPlexAdminFilled()
  4021. {
  4022. if ($this->config['plexAdmin'] == '') {
  4023. return false;
  4024. } else {
  4025. if ((strpos($this->config['plexAdmin'], '@') !== false)) {
  4026. return 'email';
  4027. } else {
  4028. return 'username';
  4029. }
  4030. }
  4031. }
  4032. public function organizrSpecialSettings()
  4033. {
  4034. // js activeInfo
  4035. return [
  4036. 'homepage' => [
  4037. 'refresh' => $this->refreshList(),
  4038. 'order' => $this->homepageOrderList(),
  4039. 'search' => [
  4040. 'enabled' => $this->qualifyRequest($this->config['mediaSearchAuth']) && $this->config['mediaSearch'] == true && $this->config['plexToken'],
  4041. 'type' => $this->config['mediaSearchType'],
  4042. ],
  4043. 'requests' => [
  4044. 'service' => $this->config['defaultRequestService'],
  4045. ],
  4046. 'ombi' => [
  4047. 'enabled' => $this->qualifyRequest($this->config['homepageOmbiAuth']) && $this->qualifyRequest($this->config['homepageOmbiRequestAuth']) && $this->config['homepageOmbiEnabled'] == true && $this->config['ssoOmbi'] && isset($_COOKIE['Auth']),
  4048. 'authView' => $this->qualifyRequest($this->config['homepageOmbiAuth']),
  4049. 'authRequest' => $this->qualifyRequest($this->config['homepageOmbiRequestAuth']),
  4050. 'sso' => (bool)$this->config['ssoOmbi'],
  4051. 'cookie' => isset($_COOKIE['Auth']),
  4052. 'alias' => (bool)$this->config['ombiAlias'],
  4053. 'ombiDefaultFilterAvailable' => (bool)$this->config['ombiDefaultFilterAvailable'],
  4054. 'ombiDefaultFilterUnavailable' => (bool)$this->config['ombiDefaultFilterUnavailable'],
  4055. 'ombiDefaultFilterApproved' => (bool)$this->config['ombiDefaultFilterApproved'],
  4056. 'ombiDefaultFilterUnapproved' => (bool)$this->config['ombiDefaultFilterUnapproved'],
  4057. 'ombiDefaultFilterDenied' => (bool)$this->config['ombiDefaultFilterDenied']
  4058. ],
  4059. 'overseerr' => [
  4060. 'enabled' => $this->qualifyRequest($this->config['homepageOverseerrAuth']) && $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']) && $this->config['homepageOverseerrEnabled'] == true && $this->config['ssoOverseerr'] && isset($_COOKIE['connect_sid']),
  4061. 'authView' => $this->qualifyRequest($this->config['homepageOverseerrAuth']),
  4062. 'authRequest' => $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']),
  4063. 'sso' => (bool)$this->config['ssoOverseerr'],
  4064. 'cookie' => isset($_COOKIE['connect_sid']),
  4065. 'userSelectTv' => (bool)$this->config['homepageOverseerrRequestAuth'] == 'user',
  4066. 'overseerrDefaultFilterAvailable' => (bool)$this->config['overseerrDefaultFilterAvailable'],
  4067. 'overseerrDefaultFilterUnavailable' => (bool)$this->config['overseerrDefaultFilterUnavailable'],
  4068. 'overseerrDefaultFilterApproved' => (bool)$this->config['overseerrDefaultFilterApproved'],
  4069. 'overseerrDefaultFilterUnapproved' => (bool)$this->config['overseerrDefaultFilterUnapproved'],
  4070. 'overseerrDefaultFilterDenied' => (bool)$this->config['overseerrDefaultFilterDenied']
  4071. ],
  4072. 'jackett' => [
  4073. 'homepageJackettBackholeDownload' => $this->config['homepageJackettBackholeDownload'] ? true : false
  4074. ],
  4075. 'options' => [
  4076. 'alternateHomepageHeaders' => $this->config['alternateHomepageHeaders'],
  4077. 'healthChecksTags' => $this->config['healthChecksTags'],
  4078. 'titles' => [
  4079. 'tautulli' => $this->config['tautulliHeader']
  4080. ]
  4081. ],
  4082. 'media' => [
  4083. 'jellyfin' => $this->config['homepageJellyfinInstead']
  4084. ]
  4085. ],
  4086. 'sso' => [
  4087. 'misc' => [
  4088. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4089. 'rememberMe' => $this->config['rememberMe'],
  4090. 'rememberMeDays' => $this->config['rememberMeDays']
  4091. ],
  4092. 'plex' => [
  4093. 'enabled' => (bool)$this->config['ssoPlex'],
  4094. 'cookie' => isset($_COOKIE['mpt']),
  4095. 'machineID' => strlen($this->config['plexID']) == 40,
  4096. 'token' => $this->config['plexToken'] !== '',
  4097. 'plexAdmin' => $this->checkPlexAdminFilled(),
  4098. 'strict' => (bool)$this->config['plexStrictFriends'],
  4099. 'oAuthEnabled' => (bool)$this->config['plexoAuth'],
  4100. 'backend' => $this->config['authBackend'] == 'plex',
  4101. ],
  4102. 'tautulli' => [
  4103. 'enabled' => (bool)$this->config['ssoTautulli'],
  4104. 'cookie' => !empty($this->tautulliList()),
  4105. 'url' => ($this->config['tautulliURL'] !== '') ? $this->config['tautulliURL'] : false,
  4106. ],
  4107. 'overseerr' => [
  4108. 'enabled' => (bool)$this->config['ssoOverseerr'],
  4109. 'cookie' => isset($_COOKIE['connect.sid']),
  4110. 'url' => ($this->config['overseerrURL'] !== '') ? $this->config['overseerrURL'] : false,
  4111. 'api' => $this->config['overseerrToken'] !== '',
  4112. ],
  4113. 'petio' => [
  4114. 'enabled' => (bool)$this->config['ssoPetio'],
  4115. 'cookie' => isset($_COOKIE['petio_jwt']),
  4116. 'url' => ($this->config['petioURL'] !== '') ? $this->config['petioURL'] : false,
  4117. 'api' => $this->config['petioToken'] !== '',
  4118. ],
  4119. 'ombi' => [
  4120. 'enabled' => (bool)$this->config['ssoOmbi'],
  4121. 'cookie' => isset($_COOKIE['Auth']),
  4122. 'url' => ($this->config['ombiURL'] !== '') ? $this->config['ombiURL'] : false,
  4123. 'api' => $this->config['ombiToken'] !== '',
  4124. ],
  4125. 'jellyfin' => [
  4126. 'enabled' => (bool)$this->config['ssoJellyfin'],
  4127. 'url' => ($this->config['jellyfinURL'] !== '') ? $this->config['jellyfinURL'] : false,
  4128. 'ssoUrl' => ($this->config['jellyfinSSOURL'] !== '') ? $this->config['jellyfinSSOURL'] : false,
  4129. ],
  4130. 'komga' => [
  4131. 'enabled' => (bool)$this->config['ssoKomga'],
  4132. 'cookie' => isset($_COOKIE['komga_token']),
  4133. 'url' => ($this->config['komgaURL'] !== '') ? $this->config['komgaURL'] : false,
  4134. ]
  4135. ],
  4136. 'ping' => [
  4137. 'onlineSound' => $this->config['pingOnlineSound'],
  4138. 'offlineSound' => $this->config['pingOfflineSound'],
  4139. 'statusSounds' => $this->config['statusSounds'],
  4140. 'auth' => $this->config['pingAuth'],
  4141. 'authMessage' => $this->config['pingAuthMessage'],
  4142. 'authMs' => $this->config['pingAuthMs'],
  4143. 'ms' => $this->config['pingMs'],
  4144. 'adminRefresh' => $this->config['adminPingRefresh'],
  4145. 'everyoneRefresh' => $this->config['otherPingRefresh'],
  4146. ],
  4147. 'notifications' => [
  4148. 'backbone' => $this->config['notificationBackbone'],
  4149. 'position' => $this->config['notificationPosition']
  4150. ],
  4151. 'lockout' => [
  4152. 'enabled' => $this->config['lockoutSystem'],
  4153. 'timer' => $this->config['lockoutTimeout'],
  4154. 'minGroup' => $this->config['lockoutMinAuth'],
  4155. 'maxGroup' => $this->config['lockoutMaxAuth']
  4156. ],
  4157. 'user' => [
  4158. 'agent' => isset($_SERVER ['HTTP_USER_AGENT']) ? $_SERVER ['HTTP_USER_AGENT'] : null,
  4159. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4160. 'local' => $this->isLocal(),
  4161. 'ip' => $this->userIP()
  4162. ],
  4163. 'login' => [
  4164. 'rememberMe' => $this->config['rememberMe'],
  4165. 'rememberMeDays' => $this->config['rememberMeDays'],
  4166. 'wanDomain' => $this->config['wanDomain'],
  4167. 'localAddress' => $this->config['localAddress'],
  4168. 'enableLocalAddressForward' => $this->config['enableLocalAddressForward'],
  4169. ],
  4170. 'misc' => [
  4171. 'installedPlugins' => $this->qualifyRequest(1) ? $this->config['installedPlugins'] : '',
  4172. 'installedThemes' => $this->qualifyRequest(1) ? $this->config['installedThemes'] : '',
  4173. 'return' => $_SERVER['HTTP_REFERER'] ?? false,
  4174. 'authDebug' => $this->config['authDebug'],
  4175. 'minimalLoginScreen' => $this->config['minimalLoginScreen'],
  4176. 'unsortedTabs' => $this->config['unsortedTabs'],
  4177. 'authType' => $this->config['authType'],
  4178. 'authBackend' => $this->config['authBackend'],
  4179. 'newMessageSound' => (isset($this->config['CHAT-newMessageSound-include'])) ? $this->config['CHAT-newMessageSound-include'] : '',
  4180. 'uuid' => ($this->config['uuid']) ?? null,
  4181. 'docker' => $this->qualifyRequest(1) ? $this->docker : '',
  4182. 'githubCommit' => $this->qualifyRequest(1) ? $this->commit : '',
  4183. 'schema' => $this->qualifyRequest(1) ? $this->getSchema() : '',
  4184. 'debugArea' => $this->qualifyRequest($this->config['debugAreaAuth']),
  4185. 'debugErrors' => $this->config['debugErrors'],
  4186. 'sandbox' => $this->config['sandbox'],
  4187. 'expandCategoriesByDefault' => $this->config['expandCategoriesByDefault'],
  4188. 'autoCollapseCategories' => $this->config['autoCollapseCategories'],
  4189. 'autoExpandNavBar' => $this->config['autoExpandNavBar'],
  4190. 'sideMenuCollapsed' => $this->config['allowCollapsableSideMenu'] && $this->config['sideMenuCollapsed'],
  4191. 'collapseSideMenuOnClick' => $this->config['allowCollapsableSideMenu'] && $this->config['collapseSideMenuOnClick'],
  4192. 'authProxyOverrideLogout' => $this->config['authProxyOverrideLogout'],
  4193. 'authProxyLogoutURL' => $this->config['authProxyLogoutURL'],
  4194. ],
  4195. 'menuLink' => [
  4196. 'githubMenuLink' => $this->config['githubMenuLink'],
  4197. 'organizrSupportMenuLink' => $this->config['organizrSupportMenuLink'],
  4198. 'organizrDocsMenuLink' => $this->config['organizrDocsMenuLink'],
  4199. 'organizrSignoutMenuLink' => $this->config['organizrSignoutMenuLink'],
  4200. 'organizrFeatureRequestLink' => $this->config['organizrFeatureRequestLink']
  4201. ]
  4202. ];
  4203. }
  4204. public function checkLog($path)
  4205. {
  4206. if (file_exists($path)) {
  4207. if (filesize($path) > 500000) {
  4208. rename($path, $path . '[' . date('Y-m-d') . '].json');
  4209. return false;
  4210. }
  4211. return true;
  4212. } else {
  4213. return false;
  4214. }
  4215. }
  4216. public function isApprovedRequest($method, $data)
  4217. {
  4218. $requesterToken = $this->getallheadersi()['token'] ?? ($_GET['apikey'] ?? false);
  4219. $apiKey = ($this->config['organizrAPI']) ?? null;
  4220. if (isset($data['formKey'])) {
  4221. $formKey = $data['formKey'];
  4222. } elseif (isset($this->getallheadersi()['formkey'])) {
  4223. $formKey = $this->getallheadersi()['formkey'];
  4224. } else {
  4225. $formKey = false;
  4226. }
  4227. // Check token or API key
  4228. // If API key, return 0 for admin
  4229. if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
  4230. //DO API CHECK
  4231. return true;
  4232. } elseif ($method == 'POST') {
  4233. if ($this->checkFormKey($formKey)) {
  4234. return true;
  4235. } else {
  4236. $this->setLoggerChannel('Authentication');
  4237. $this->logger->warning('Unable to authenticate Form Key: ' . $formKey);
  4238. return false;
  4239. }
  4240. } else {
  4241. return true;
  4242. }
  4243. return false;
  4244. }
  4245. public function checkFormKey($formKey = '')
  4246. {
  4247. return password_verify(substr($this->config['organizrHash'], 2, 10), $formKey);
  4248. }
  4249. public function buildHomepage()
  4250. {
  4251. $homepageOrder = $this->homepageOrderList();
  4252. $homepageBuilt = '';
  4253. foreach ($homepageOrder as $key => $value) {
  4254. //new way
  4255. if (method_exists($this, $key)) {
  4256. $homepageBuilt .= $this->$key();
  4257. } elseif (strpos($key, 'homepageOrdercustomhtml') !== false) {
  4258. $iteration = substr($key, -2);
  4259. $homepageBuilt .= $this->homepageOrdercustomhtml($iteration);
  4260. } else {
  4261. $homepageBuilt .= '<div id="' . $key . '"></div>';
  4262. }
  4263. //old way
  4264. //$homepageBuilt .= $this->buildHomepageItem($key);
  4265. }
  4266. return $homepageBuilt;
  4267. }
  4268. public function buildHomepageSettings()
  4269. {
  4270. $homepageOrder = $this->homepageOrderList();
  4271. $homepageList = '<div class="col-lg-12"><h4 lang="en">Drag Homepage Items to Order Them</h4></div><div id="homepage-items-sort" class="external-events">';
  4272. $inputList = '<form id="homepage-values" class="row">';
  4273. foreach ($homepageOrder as $key => $val) {
  4274. switch ($key) {
  4275. case 'homepageOrdercustomhtml01':
  4276. case 'homepageOrdercustomhtml02':
  4277. case 'homepageOrdercustomhtml03':
  4278. case 'homepageOrdercustomhtml04':
  4279. case 'homepageOrdercustomhtml05':
  4280. case 'homepageOrdercustomhtml06':
  4281. case 'homepageOrdercustomhtml07':
  4282. case 'homepageOrdercustomhtml08':
  4283. $iteration = substr($key, -2);
  4284. $class = 'bg-info';
  4285. $image = 'plugins/images/tabs/HTML5.png';
  4286. if (!$this->config['homepageCustomHTML' . $iteration . 'Enabled']) {
  4287. $class .= ' faded';
  4288. }
  4289. break;
  4290. case 'homepageOrdertransmission':
  4291. $class = 'bg-transmission';
  4292. $image = 'plugins/images/tabs/transmission.png';
  4293. if (!$this->config['homepageTransmissionEnabled']) {
  4294. $class .= ' faded';
  4295. }
  4296. break;
  4297. case 'homepageOrdernzbget':
  4298. $class = 'bg-nzbget';
  4299. $image = 'plugins/images/tabs/nzbget.png';
  4300. if (!$this->config['homepageNzbgetEnabled']) {
  4301. $class .= ' faded';
  4302. }
  4303. break;
  4304. case 'homepageOrderjdownloader':
  4305. $class = 'bg-sab';
  4306. $image = 'plugins/images/tabs/jdownloader.png';
  4307. if (!$this->config['homepageJdownloaderEnabled']) {
  4308. $class .= ' faded';
  4309. }
  4310. break;
  4311. case 'homepageOrdersabnzbd':
  4312. $class = 'bg-sab';
  4313. $image = 'plugins/images/tabs/sabnzbd.png';
  4314. if (!$this->config['homepageSabnzbdEnabled']) {
  4315. $class .= ' faded';
  4316. }
  4317. break;
  4318. case 'homepageOrderdeluge':
  4319. $class = 'bg-deluge';
  4320. $image = 'plugins/images/tabs/deluge.png';
  4321. if (!$this->config['homepageDelugeEnabled']) {
  4322. $class .= ' faded';
  4323. }
  4324. break;
  4325. case 'homepageOrderqBittorrent':
  4326. $class = 'bg-qbit';
  4327. $image = 'plugins/images/tabs/qBittorrent.png';
  4328. if (!$this->config['homepageqBittorrentEnabled']) {
  4329. $class .= ' faded';
  4330. }
  4331. break;
  4332. case 'homepageOrderuTorrent':
  4333. $class = 'bg-qbit';
  4334. $image = 'plugins/images/tabs/utorrent.png';
  4335. if (!$this->config['homepageuTorrentEnabled']) {
  4336. $class .= ' faded';
  4337. }
  4338. break;
  4339. case 'homepageOrderrTorrent':
  4340. $class = 'bg-qbit';
  4341. $image = 'plugins/images/tabs/rTorrent.png';
  4342. if (!$this->config['homepagerTorrentEnabled']) {
  4343. $class .= ' faded';
  4344. }
  4345. break;
  4346. case 'homepageOrderplexnowplaying':
  4347. case 'homepageOrderplexrecent':
  4348. case 'homepageOrderplexplaylist':
  4349. $class = 'bg-plex';
  4350. $image = 'plugins/images/tabs/plex.png';
  4351. if (!$this->config['homepagePlexEnabled']) {
  4352. $class .= ' faded';
  4353. }
  4354. break;
  4355. case 'homepageOrderembynowplaying':
  4356. case 'homepageOrderembyrecent':
  4357. $class = 'bg-emby';
  4358. $image = 'plugins/images/tabs/emby.png';
  4359. if (!$this->config['homepageEmbyEnabled']) {
  4360. $class .= ' faded';
  4361. }
  4362. break;
  4363. case 'homepageOrderjellyfinnowplaying':
  4364. case 'homepageOrderjellyfinrecent':
  4365. $class = 'bg-jellyfin';
  4366. $image = 'plugins/images/tabs/jellyfin.png';
  4367. if (!$this->config['homepageJellyfinEnabled']) {
  4368. $class .= ' faded';
  4369. }
  4370. break;
  4371. case 'homepageOrderombi':
  4372. $class = 'bg-inverse';
  4373. $image = 'plugins/images/tabs/ombi.png';
  4374. if (!$this->config['homepageOmbiEnabled']) {
  4375. $class .= ' faded';
  4376. }
  4377. break;
  4378. case 'homepageOrderoverseerr':
  4379. $class = 'bg-inverse';
  4380. $image = 'plugins/images/tabs/overseerr.png';
  4381. if (!$this->config['homepageOverseerrEnabled']) {
  4382. $class .= ' faded';
  4383. }
  4384. break;
  4385. case 'homepageOrderDonate':
  4386. $class = 'bg-primary';
  4387. $image = 'plugins/images/tabs/donate.png';
  4388. if (!$this->config['homepageDonateEnabled']) {
  4389. $class .= ' faded';
  4390. }
  4391. break;
  4392. case 'homepageOrdercalendar':
  4393. $class = 'bg-primary';
  4394. $image = 'plugins/images/tabs/calendar.png';
  4395. if (!$this->config['homepageCalendarEnabled'] && !$this->config['homepageSonarrEnabled'] && !$this->config['homepageRadarrEnabled'] && !$this->config['homepageSickrageEnabled'] && !$this->config['homepageCouchpotatoEnabled']) {
  4396. $class .= ' faded';
  4397. }
  4398. break;
  4399. case 'homepageOrderdownloader':
  4400. $class = 'bg-inverse';
  4401. $image = 'plugins/images/tabs/downloader.png';
  4402. if (!$this->config['jdownloaderCombine'] && !$this->config['sabnzbdCombine'] && !$this->config['nzbgetCombine'] && !$this->config['rTorrentCombine'] && !$this->config['delugeCombine'] && !$this->config['transmissionCombine'] && !$this->config['qBittorrentCombine'] && !$this->config['uTorrentCombine']) {
  4403. $class .= ' faded';
  4404. }
  4405. break;
  4406. case 'homepageOrderhealthchecks':
  4407. $class = 'bg-healthchecks';
  4408. $image = 'plugins/images/tabs/healthchecks.png';
  4409. if (!$this->config['homepageHealthChecksEnabled']) {
  4410. $class .= ' faded';
  4411. }
  4412. break;
  4413. case 'homepageOrderunifi':
  4414. $class = 'bg-info';
  4415. $image = 'plugins/images/tabs/ubnt.png';
  4416. if (!$this->config['homepageUnifiEnabled']) {
  4417. $class .= ' faded';
  4418. }
  4419. break;
  4420. case 'homepageOrdertautulli':
  4421. $class = 'bg-info';
  4422. $image = 'plugins/images/tabs/tautulli.png';
  4423. if (!$this->config['homepageTautulliEnabled']) {
  4424. $class .= ' faded';
  4425. }
  4426. break;
  4427. case 'homepageOrderPihole':
  4428. $class = 'bg-info';
  4429. $image = 'plugins/images/tabs/pihole.png';
  4430. if (!$this->config['homepagePiholeEnabled']) {
  4431. $class .= ' faded';
  4432. }
  4433. break;
  4434. case 'homepageOrderMonitorr':
  4435. $class = 'bg-info';
  4436. $image = 'plugins/images/tabs/monitorr.png';
  4437. if (!$this->config['homepageMonitorrEnabled']) {
  4438. $class .= ' faded';
  4439. }
  4440. break;
  4441. case 'homepageOrderWeatherAndAir':
  4442. $class = 'bg-success';
  4443. $image = 'plugins/images/tabs/wind.png';
  4444. if (!$this->config['homepageWeatherAndAirEnabled']) {
  4445. $class .= ' faded';
  4446. }
  4447. break;
  4448. case 'homepageOrderSpeedtest':
  4449. $class = 'bg-success';
  4450. $image = 'plugins/images/tabs/speedtest-icon.png';
  4451. if (!$this->config['homepageSpeedtestEnabled']) {
  4452. $class .= ' faded';
  4453. }
  4454. break;
  4455. case 'homepageOrderNetdata':
  4456. $class = 'bg-success';
  4457. $image = 'plugins/images/tabs/netdata.png';
  4458. if (!$this->config['homepageNetdataEnabled']) {
  4459. $class .= ' faded';
  4460. }
  4461. break;
  4462. case 'homepageOrderOctoprint':
  4463. $class = 'bg-success';
  4464. $image = 'plugins/images/tabs/octoprint.png';
  4465. if (!$this->config['homepageOctoprintEnabled']) {
  4466. $class .= ' faded';
  4467. }
  4468. break;
  4469. case 'homepageOrderSonarrQueue':
  4470. $class = 'bg-sonarr';
  4471. $image = 'plugins/images/tabs/sonarr.png';
  4472. if (!$this->config['homepageSonarrQueueEnabled']) {
  4473. $class .= ' faded';
  4474. }
  4475. break;
  4476. case 'homepageOrderRadarrQueue':
  4477. $class = 'bg-radarr';
  4478. $image = 'plugins/images/tabs/radarr.png';
  4479. if (!$this->config['homepageRadarrQueueEnabled']) {
  4480. $class .= ' faded';
  4481. }
  4482. break;
  4483. case 'homepageOrderJackett':
  4484. $class = 'bg-inverse';
  4485. $image = 'plugins/images/tabs/jackett.png';
  4486. if (!$this->config['homepageJackettEnabled']) {
  4487. $class .= ' faded';
  4488. }
  4489. break;
  4490. case 'homepageOrderBookmarks':
  4491. $class = 'bg-bookmarks';
  4492. $image = 'plugins/images/bookmark.png';
  4493. if (!$this->config['homepageBookmarksEnabled']) {
  4494. $class .= ' faded';
  4495. }
  4496. break;
  4497. default:
  4498. $class = 'blue-bg';
  4499. $image = '';
  4500. break;
  4501. }
  4502. $homepageList .= '
  4503. <div class="col-md-3 col-xs-12 sort-homepage m-t-10 hvr-grow clearfix">
  4504. <div class="homepage-drag fc-event ' . $class . ' lazyload" data-src="' . $image . '">
  4505. <span class="ordinal-position text-uppercase badge bg-org homepage-number" data-link="' . $key . '" style="float:left;width: 30px;">' . $val . '</span>
  4506. <span class="homepage-text">&nbsp; ' . strtoupper(substr($key, 13)) . '</span>
  4507. </div>
  4508. </div>
  4509. ';
  4510. $inputList .= '<input type="hidden" name="' . $key . '">';
  4511. }
  4512. $homepageList .= '</div>';
  4513. $inputList .= '</form>';
  4514. return $homepageList . $inputList;
  4515. }
  4516. public function setGroupOptionsVariable()
  4517. {
  4518. $this->groupOptions = $this->groupSelect();
  4519. }
  4520. public function getSettingsHomepageItem($item)
  4521. {
  4522. $items = $this->getSettingsHomepage();
  4523. foreach ($items as $k => $v) {
  4524. if (strtolower($v['name']) === strtolower($item)) {
  4525. $functionName = $v['settingsArray'];
  4526. return $this->$functionName();
  4527. }
  4528. }
  4529. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4530. return null;
  4531. }
  4532. public function getSettingsHomepageItemDebug($service)
  4533. {
  4534. $service = $this->getSettingsHomepageItem($service);
  4535. if ($service) {
  4536. $debug = [];
  4537. foreach ($service['settings'] as $category => $items) {
  4538. if ($category !== 'About' && $category !== 'Test Connection') {
  4539. foreach ($items as $item) {
  4540. if ($item['type'] !== 'html' && $item['type'] !== 'blank' && $item['type'] !== 'button') {
  4541. if ((stripos($item['name'], 'token') !== false) || (stripos($item['name'], 'key') !== false) || (stripos($item['name'], 'password'))) {
  4542. if ($item['value'] !== '') {
  4543. $item['value'] = '***redacted***';
  4544. }
  4545. }
  4546. $debug[$category][$item['name']] = $item['value'];
  4547. }
  4548. }
  4549. }
  4550. }
  4551. return $debug;
  4552. }
  4553. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4554. return null;
  4555. }
  4556. public function getSettingsHomepage()
  4557. {
  4558. $this->setGroupOptionsVariable();
  4559. return $this->getHomepageSettingsCombined();
  4560. }
  4561. public function isTabNameTaken($name, $id = null)
  4562. {
  4563. if ($id) {
  4564. $response = [
  4565. array(
  4566. 'function' => 'fetchAll',
  4567. 'query' => array(
  4568. 'SELECT * FROM tabs WHERE `name` LIKE ? AND `id` != ?',
  4569. $name,
  4570. $id
  4571. )
  4572. ),
  4573. ];
  4574. } else {
  4575. $response = [
  4576. array(
  4577. 'function' => 'fetchAll',
  4578. 'query' => array(
  4579. 'SELECT * FROM tabs WHERE `name` LIKE ?',
  4580. $name
  4581. )
  4582. ),
  4583. ];
  4584. }
  4585. return $this->processQueries($response);
  4586. }
  4587. public function isCategoryNameTaken($name, $id = null)
  4588. {
  4589. if ($id) {
  4590. $response = [
  4591. array(
  4592. 'function' => 'fetchAll',
  4593. 'query' => array(
  4594. 'SELECT * FROM categories WHERE `category` LIKE ? AND `id` != ?',
  4595. $name,
  4596. $id
  4597. )
  4598. ),
  4599. ];
  4600. } else {
  4601. $response = [
  4602. array(
  4603. 'function' => 'fetchAll',
  4604. 'query' => array(
  4605. 'SELECT * FROM categories WHERE `category` LIKE ?',
  4606. $name
  4607. )
  4608. ),
  4609. ];
  4610. }
  4611. return $this->processQueries($response);
  4612. }
  4613. public function isGroupNameTaken($name, $id = null)
  4614. {
  4615. if ($id) {
  4616. $response = [
  4617. array(
  4618. 'function' => 'fetchAll',
  4619. 'query' => array(
  4620. 'SELECT * FROM groups WHERE `group` LIKE ? AND `id` != ?',
  4621. $name,
  4622. $id
  4623. )
  4624. ),
  4625. ];
  4626. } else {
  4627. $response = [
  4628. array(
  4629. 'function' => 'fetchAll',
  4630. 'query' => array(
  4631. 'SELECT * FROM groups WHERE `group` LIKE ?',
  4632. $name
  4633. )
  4634. ),
  4635. ];
  4636. }
  4637. return $this->processQueries($response);
  4638. }
  4639. public function getTableColumns($table)
  4640. {
  4641. if ($this->config['driver'] == 'sqlite3') {
  4642. $query = 'PRAGMA table_info(?)';
  4643. } else {
  4644. $query = 'DESCRIBE %n';
  4645. }
  4646. $response = [
  4647. array(
  4648. 'function' => 'fetchAll',
  4649. 'query' => [
  4650. $query, $table
  4651. ]
  4652. ),
  4653. ];
  4654. return $this->processQueries($response);
  4655. }
  4656. public function getTableColumnsFormatted($table)
  4657. {
  4658. if ($this->config['driver'] == 'sqlite3') {
  4659. $name = 'name';
  4660. } else {
  4661. $name = 'Field';
  4662. }
  4663. $columns = $this->getTableColumns($table);
  4664. if ($columns) {
  4665. $columnsFormatted = [];
  4666. foreach ($columns as $k => $v) {
  4667. $columnsFormatted[$v[$name]] = $v;
  4668. }
  4669. return $columnsFormatted;
  4670. } else {
  4671. return false;
  4672. }
  4673. }
  4674. public function getTabById($id)
  4675. {
  4676. $response = [
  4677. array(
  4678. 'function' => 'fetch',
  4679. 'query' => array(
  4680. 'SELECT * FROM tabs WHERE `id` = ?',
  4681. $id
  4682. )
  4683. ),
  4684. ];
  4685. return $this->processQueries($response);
  4686. }
  4687. public function getTabGroupByTabName($tab)
  4688. {
  4689. $response = [
  4690. array(
  4691. 'function' => 'fetch',
  4692. 'query' => array(
  4693. 'SELECT group_id FROM tabs WHERE name LIKE %~like~',
  4694. $tab
  4695. )
  4696. ),
  4697. ];
  4698. $query = $this->processQueries($response);
  4699. return $query ? $query['group_id'] : 0;
  4700. }
  4701. public function getCategoryById($id)
  4702. {
  4703. $response = [
  4704. array(
  4705. 'function' => 'fetch',
  4706. 'query' => array(
  4707. 'SELECT * FROM categories WHERE `id` = ?',
  4708. $id
  4709. )
  4710. ),
  4711. ];
  4712. return $this->processQueries($response);
  4713. }
  4714. public function getGroupUserCountById($id)
  4715. {
  4716. $response = [
  4717. array(
  4718. 'function' => 'fetchSingle',
  4719. 'query' => array(
  4720. 'SELECT count(username) AS count FROM groups INNER JOIN users ON users.group_id = groups.group_id AND groups.id = ?',
  4721. $id
  4722. )
  4723. ),
  4724. ];
  4725. return $this->processQueries($response);
  4726. }
  4727. public function getGroupById($id)
  4728. {
  4729. $response = [
  4730. array(
  4731. 'function' => 'fetch',
  4732. 'query' => array(
  4733. 'SELECT * FROM groups WHERE `id` = ?',
  4734. $id
  4735. )
  4736. ),
  4737. ];
  4738. return $this->processQueries($response);
  4739. }
  4740. public function getGroupByGroupId($id)
  4741. {
  4742. $response = [
  4743. array(
  4744. 'function' => 'fetch',
  4745. 'query' => array(
  4746. 'SELECT * FROM groups WHERE `group_id` = ?',
  4747. $id
  4748. )
  4749. ),
  4750. ];
  4751. return $this->processQueries($response);
  4752. }
  4753. public function getDefaultGroup()
  4754. {
  4755. $response = [
  4756. array(
  4757. 'function' => 'fetch',
  4758. 'query' => array(
  4759. 'SELECT * FROM groups WHERE `default` = 1'
  4760. )
  4761. ),
  4762. ];
  4763. return $this->processQueries($response);
  4764. }
  4765. public function getDefaultGroupId()
  4766. {
  4767. $response = [
  4768. array(
  4769. 'function' => 'fetchSingle',
  4770. 'query' => array(
  4771. 'SELECT `group_id` FROM groups WHERE `default` = 1'
  4772. )
  4773. ),
  4774. ];
  4775. return $this->processQueries($response);
  4776. }
  4777. public function getDefaultCategory()
  4778. {
  4779. $response = [
  4780. array(
  4781. 'function' => 'fetch',
  4782. 'query' => array(
  4783. 'SELECT * FROM categories WHERE `default` = 1'
  4784. )
  4785. ),
  4786. ];
  4787. return $this->processQueries($response);
  4788. }
  4789. public function getDefaultCategoryId()
  4790. {
  4791. $response = [
  4792. array(
  4793. 'function' => 'fetchSingle',
  4794. 'query' => array(
  4795. 'SELECT `category_id` FROM categories WHERE `default` = 1'
  4796. )
  4797. ),
  4798. ];
  4799. return $this->processQueries($response);
  4800. }
  4801. public function getNextTabOrder()
  4802. {
  4803. $response = [
  4804. array(
  4805. 'function' => 'fetchSingle',
  4806. 'query' => array(
  4807. 'SELECT `order` from tabs ORDER BY `order` DESC'
  4808. )
  4809. ),
  4810. ];
  4811. return $this->processQueries($response);
  4812. }
  4813. public function getNextCategoryOrder()
  4814. {
  4815. $response = [
  4816. array(
  4817. 'function' => 'fetchSingle',
  4818. 'query' => array(
  4819. 'SELECT `order` from categories ORDER BY `order` DESC'
  4820. )
  4821. ),
  4822. ];
  4823. return $this->processQueries($response);
  4824. }
  4825. public function getNextGroupOrder()
  4826. {
  4827. $response = [
  4828. array(
  4829. 'function' => 'fetchSingle',
  4830. 'query' => array(
  4831. 'SELECT `group_id` from groups WHERE `group_id` != "999" ORDER BY `group_id` DESC'
  4832. )
  4833. ),
  4834. ];
  4835. return $this->processQueries($response);
  4836. }
  4837. public function getNextCategoryId()
  4838. {
  4839. $response = [
  4840. array(
  4841. 'function' => 'fetchSingle',
  4842. 'query' => array(
  4843. 'SELECT `category_id` from categories ORDER BY `category_id` DESC'
  4844. )
  4845. ),
  4846. ];
  4847. return $this->processQueries($response);
  4848. }
  4849. public function clearTabDefault()
  4850. {
  4851. $response = [
  4852. array(
  4853. 'function' => 'query',
  4854. 'query' => array(
  4855. 'UPDATE tabs SET `default` = 0'
  4856. )
  4857. ),
  4858. ];
  4859. return $this->processQueries($response);
  4860. }
  4861. public function clearCategoryDefault()
  4862. {
  4863. $response = [
  4864. array(
  4865. 'function' => 'query',
  4866. 'query' => array(
  4867. 'UPDATE categories SET `default` = 0'
  4868. )
  4869. ),
  4870. ];
  4871. return $this->processQueries($response);
  4872. }
  4873. public function clearGroupDefault()
  4874. {
  4875. $response = [
  4876. array(
  4877. 'function' => 'query',
  4878. 'query' => array(
  4879. 'UPDATE groups SET `default` = 0'
  4880. )
  4881. ),
  4882. ];
  4883. return $this->processQueries($response);
  4884. }
  4885. public function checkKeys($tabInfo, $newData)
  4886. {
  4887. foreach ($newData as $k => $v) {
  4888. if (!array_key_exists($k, $tabInfo)) {
  4889. unset($newData[$k]);
  4890. }
  4891. }
  4892. return $newData;
  4893. }
  4894. public function getTabByIdCheckUser($id)
  4895. {
  4896. $tabInfo = $this->getTabById($id);
  4897. if ($tabInfo) {
  4898. if ($this->qualifyRequest($tabInfo['group_id'], true)) {
  4899. return $tabInfo;
  4900. }
  4901. } else {
  4902. $this->setAPIResponse('error', 'id not found', 404);
  4903. return false;
  4904. }
  4905. }
  4906. public function deleteTab($id)
  4907. {
  4908. $response = [
  4909. array(
  4910. 'function' => 'query',
  4911. 'query' => array(
  4912. 'DELETE FROM tabs WHERE id = ?',
  4913. $id
  4914. )
  4915. ),
  4916. ];
  4917. $tabInfo = $this->getTabById($id);
  4918. if ($tabInfo) {
  4919. $this->setLoggerChannel('Tab Management');
  4920. $this->logger->debug('Deleted Tab [' . $tabInfo['name'] . ']');
  4921. $this->setAPIResponse('success', 'Tab deleted', 204);
  4922. return $this->processQueries($response);
  4923. } else {
  4924. $this->setAPIResponse('error', 'id not found', 404);
  4925. return false;
  4926. }
  4927. }
  4928. public function addTab($array)
  4929. {
  4930. if (!$array) {
  4931. $this->setAPIResponse('error', 'no data was sent', 422);
  4932. return null;
  4933. }
  4934. $array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
  4935. $array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
  4936. $array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
  4937. $array['enabled'] = ($array['enabled']) ?? 0;
  4938. $array['default'] = ($array['default']) ?? 0;
  4939. $array['type'] = ($array['type']) ?? 1;
  4940. $array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
  4941. if (array_key_exists('name', $array)) {
  4942. $array['name'] = $this->sanitizeUserString($array['name']);
  4943. if ($this->isTabNameTaken($array['name'])) {
  4944. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  4945. return false;
  4946. }
  4947. if (!$this->qualifyLength($array['name'], 50, true)) {
  4948. return false;
  4949. }
  4950. } else {
  4951. $this->setAPIResponse('error', 'Tab name was not supplied', 422);
  4952. return false;
  4953. }
  4954. if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
  4955. $this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
  4956. return false;
  4957. }
  4958. if (!array_key_exists('image', $array)) {
  4959. $this->setAPIResponse('error', 'Tab image was not supplied', 422);
  4960. return false;
  4961. }
  4962. $response = [
  4963. array(
  4964. 'function' => 'query',
  4965. 'query' => array(
  4966. 'INSERT INTO [tabs]',
  4967. $array
  4968. )
  4969. ),
  4970. ];
  4971. $this->setAPIResponse(null, 'Tab added');
  4972. $this->setLoggerChannel('Tab Management');
  4973. $this->logger->debug('Added Tab for [' . $array['name'] . ']');
  4974. return $this->processQueries($response);
  4975. }
  4976. public function updateTab($id, $array)
  4977. {
  4978. if (!$id || $id == '') {
  4979. $this->setAPIResponse('error', 'id was not set', 422);
  4980. return null;
  4981. }
  4982. if (!$array) {
  4983. $this->setAPIResponse('error', 'no data was sent', 422);
  4984. return null;
  4985. }
  4986. $tabInfo = $this->getTabById($id);
  4987. if ($tabInfo) {
  4988. $array = $this->checkKeys($tabInfo, $array);
  4989. } else {
  4990. $this->setAPIResponse('error', 'No tab info found', 404);
  4991. return false;
  4992. }
  4993. if (array_key_exists('name', $array)) {
  4994. $array['name'] = $this->sanitizeUserString($array['name']);
  4995. if ($this->isTabNameTaken($array['name'], $id)) {
  4996. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  4997. return false;
  4998. }
  4999. if (!$this->qualifyLength($array['name'], 50, true)) {
  5000. return false;
  5001. }
  5002. }
  5003. if (array_key_exists('default', $array)) {
  5004. if ($array['default']) {
  5005. $this->clearTabDefault();
  5006. }
  5007. }
  5008. if (array_key_exists('group_id', $array)) {
  5009. $groupCheck = (array_key_exists('group_id_max', $array)) ? $array['group_id_max'] : $tabInfo['group_id_max'];
  5010. if ($array['group_id'] < $groupCheck) {
  5011. $this->setAPIResponse('error', 'Tab name: ' . $tabInfo['name'] . ' cannot have a lower Group Id Max than Group Id Min', 409);
  5012. return false;
  5013. }
  5014. }
  5015. if (array_key_exists('group_id_max', $array)) {
  5016. $groupCheck = (array_key_exists('group_id', $array)) ? $array['group_id'] : $tabInfo['group_id'];
  5017. if ($array['group_id_max'] > $groupCheck) {
  5018. $this->setAPIResponse('error', 'Tab name: ' . $tabInfo['name'] . ' cannot have a higher Group Id Min than Group Id Max', 409);
  5019. return false;
  5020. }
  5021. }
  5022. $response = [
  5023. array(
  5024. 'function' => 'query',
  5025. 'query' => array(
  5026. 'UPDATE tabs SET',
  5027. $array,
  5028. 'WHERE id = ?',
  5029. $id
  5030. )
  5031. ),
  5032. ];
  5033. $this->setAPIResponse(null, 'Tab info updated');
  5034. $this->setLoggerChannel('Tab Management');
  5035. $this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
  5036. return $this->processQueries($response);
  5037. }
  5038. public function updateTabOrder($array)
  5039. {
  5040. if (count($array) >= 1) {
  5041. foreach ($array as $tab) {
  5042. if (count($tab) !== 2) {
  5043. $this->setAPIResponse('error', 'data is malformed', 422);
  5044. break;
  5045. }
  5046. $id = $tab['id'] ?? null;
  5047. $order = $tab['order'] ?? null;
  5048. if ($id && $order) {
  5049. $response = [
  5050. array(
  5051. 'function' => 'query',
  5052. 'query' => array(
  5053. 'UPDATE tabs set `order` = ? WHERE `id` = ?',
  5054. $order,
  5055. $id
  5056. )
  5057. ),
  5058. ];
  5059. $this->processQueries($response);
  5060. $this->setAPIResponse(null, 'Tab Order updated');
  5061. } else {
  5062. $this->setAPIResponse('error', 'data is malformed', 422);
  5063. }
  5064. }
  5065. } else {
  5066. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5067. return false;
  5068. }
  5069. }
  5070. public function addCategory($array)
  5071. {
  5072. if (!$array) {
  5073. $this->setAPIResponse('error', 'no data was sent', 422);
  5074. return null;
  5075. }
  5076. $array = $this->checkKeys($this->getTableColumnsFormatted('categories'), $array);
  5077. $array['default'] = ($array['default']) ?? 0;
  5078. $array['order'] = ($array['order']) ?? $this->getNextCategoryOrder() + 1;
  5079. $array['category_id'] = ($array['category_id']) ?? $this->getNextCategoryId() + 1;
  5080. if (array_key_exists('category', $array)) {
  5081. $array['category'] = $this->sanitizeUserString($array['category']);
  5082. if ($this->isCategoryNameTaken($array['category'])) {
  5083. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  5084. return false;
  5085. }
  5086. if (!$this->qualifyLength($array['category'], 50, true)) {
  5087. return false;
  5088. }
  5089. } else {
  5090. $this->setAPIResponse('error', 'Category name was not supplied', 422);
  5091. return false;
  5092. }
  5093. if (!array_key_exists('image', $array)) {
  5094. $this->setAPIResponse('error', 'Category image was not supplied', 422);
  5095. return false;
  5096. } else {
  5097. $array['image'] = $this->sanitizeUserString($array['image']);
  5098. }
  5099. $response = [
  5100. array(
  5101. 'function' => 'query',
  5102. 'query' => array(
  5103. 'INSERT INTO [categories]',
  5104. $array
  5105. )
  5106. ),
  5107. ];
  5108. $this->setAPIResponse(null, 'Category added');
  5109. $this->setLoggerChannel('Category Management');
  5110. $this->logger->debug('Added Category for [' . $array['category'] . ']');
  5111. return $this->processQueries($response);
  5112. }
  5113. public function updateCategory($id, $array)
  5114. {
  5115. if (!$id || $id == '') {
  5116. $this->setAPIResponse('error', 'id was not set', 422);
  5117. return null;
  5118. }
  5119. if (!$array) {
  5120. $this->setAPIResponse('error', 'no data was sent', 422);
  5121. return null;
  5122. }
  5123. $categoryInfo = $this->getCategoryById($id);
  5124. if ($categoryInfo) {
  5125. $array = $this->checkKeys($categoryInfo, $array);
  5126. } else {
  5127. $this->setAPIResponse('error', 'No category info found', 404);
  5128. return false;
  5129. }
  5130. if (array_key_exists('category', $array)) {
  5131. $array['category'] = $this->sanitizeUserString($array['category']);
  5132. if ($this->isCategoryNameTaken($array['category'], $id)) {
  5133. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  5134. return false;
  5135. }
  5136. if (!$this->qualifyLength($array['category'], 50, true)) {
  5137. return false;
  5138. }
  5139. }
  5140. if (array_key_exists('image', $array)) {
  5141. $array['image'] = $this->sanitizeUserString($array['image']);
  5142. }
  5143. if (array_key_exists('default', $array)) {
  5144. if ($array['default']) {
  5145. $this->clearCategoryDefault();
  5146. }
  5147. }
  5148. $response = [
  5149. array(
  5150. 'function' => 'query',
  5151. 'query' => array(
  5152. 'UPDATE categories SET',
  5153. $array,
  5154. 'WHERE id = ?',
  5155. $id
  5156. )
  5157. ),
  5158. ];
  5159. $this->setAPIResponse(null, 'Category info updated');
  5160. $this->setLoggerChannel('Category Management');
  5161. $this->logger->debug('Edited Category [' . $categoryInfo['category'] . ']');
  5162. return $this->processQueries($response);
  5163. }
  5164. public function updateCategoryOrder($array)
  5165. {
  5166. if (count($array) >= 1) {
  5167. foreach ($array as $category) {
  5168. if (count($category) !== 2) {
  5169. $this->setAPIResponse('error', 'data is malformed', 422);
  5170. break;
  5171. }
  5172. $id = $category['id'] ?? null;
  5173. $order = $category['order'] ?? null;
  5174. if ($id && $order) {
  5175. $response = [
  5176. array(
  5177. 'function' => 'query',
  5178. 'query' => array(
  5179. 'UPDATE categories set `order` = ? WHERE `id` = ?',
  5180. $order,
  5181. $id
  5182. )
  5183. ),
  5184. ];
  5185. $this->processQueries($response);
  5186. $this->setAPIResponse(null, 'Category Order updated');
  5187. } else {
  5188. $this->setAPIResponse('error', 'data is malformed', 422);
  5189. }
  5190. }
  5191. } else {
  5192. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5193. return false;
  5194. }
  5195. }
  5196. public function deleteCategory($id)
  5197. {
  5198. $response = [
  5199. array(
  5200. 'function' => 'query',
  5201. 'query' => array(
  5202. 'DELETE FROM categories WHERE id = ?',
  5203. $id
  5204. )
  5205. ),
  5206. ];
  5207. $categoryInfo = $this->getCategoryById($id);
  5208. if ($categoryInfo) {
  5209. $this->setLoggerChannel('Category Management');
  5210. $this->logger->debug('Deleted Category [' . $categoryInfo['category'] . ']');
  5211. $this->setAPIResponse('success', 'Category deleted', 204);
  5212. return $this->processQueries($response);
  5213. } else {
  5214. $this->setAPIResponse('error', 'id not found', 404);
  5215. return false;
  5216. }
  5217. }
  5218. public function inconspicuous(): string
  5219. {
  5220. if ($this->hasDB()) {
  5221. if ($this->config['easterEggs']) {
  5222. return '
  5223. <div class="org-rox-trigger">
  5224. <div class="org-rox">
  5225. <div class="hair"></div>
  5226. <div class="head">
  5227. <div class="ear left"></div>
  5228. <div class="ear right"></div>
  5229. <div class="face">
  5230. <div class="eye left"></div>
  5231. <div class="eye right"></div>
  5232. <div class="nose"></div>
  5233. <div class="mouth"></div>
  5234. </div>
  5235. </div>
  5236. </div>
  5237. </div>';
  5238. }
  5239. }
  5240. return '';
  5241. }
  5242. public function marketplaceFileListFormat($files, $folder, $type)
  5243. {
  5244. foreach ($files as $k => $v) {
  5245. $splitFiles = explode('|', $v);
  5246. $prePath = (strlen($k) !== 1) ? $k . '/' : $k;
  5247. foreach ($splitFiles as $file) {
  5248. $filesList[] = array(
  5249. 'fileName' => $file,
  5250. 'path' => $prePath,
  5251. 'githubPath' => 'https://raw.githubusercontent.com/causefx/Organizr/v2-' . $type . '/' . $folder . $prePath . $file
  5252. );
  5253. }
  5254. }
  5255. return $filesList;
  5256. }
  5257. public function removeTheme($theme)
  5258. {
  5259. $this->setLoggerChannel('Theme Marketplace');
  5260. $theme = $this->cleanClassName($theme, '_');
  5261. $array = $this->getThemesMarketplace();
  5262. $arrayLower = array_change_key_case($array);
  5263. if (!$array) {
  5264. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5265. return false;
  5266. }
  5267. if (!isset($arrayLower[$theme])) {
  5268. $this->setAPIResponse('error', 'Theme does not exist in marketplace', 404);
  5269. return false;
  5270. } else {
  5271. $key = array_search($theme, array_keys($arrayLower));
  5272. $theme = array_keys($array)[$key];
  5273. }
  5274. $array = $array[$theme];
  5275. $themeDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5276. $dirExists = file_exists($themeDir);
  5277. if ($dirExists) {
  5278. if (!$this->rrmdir($themeDir)) {
  5279. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5280. return false;
  5281. }
  5282. } else {
  5283. $this->setAPIResponse('error', 'Theme is not installed', 404);
  5284. return false;
  5285. }
  5286. $this->updateInstalledThemes('uninstall', $theme, $array);
  5287. $this->setAPIResponse('success', 'Theme removed', 200, $array);
  5288. return true;
  5289. }
  5290. public function installTheme($theme)
  5291. {
  5292. $this->setLoggerChannel('Theme Marketplace');
  5293. $theme = $this->cleanClassName($theme, '_');
  5294. $array = $this->getThemesMarketplace();
  5295. $arrayLower = array_change_key_case($array);
  5296. if (!$array) {
  5297. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5298. return false;
  5299. }
  5300. if (!isset($arrayLower[$theme])) {
  5301. $this->setAPIResponse('error', 'Theme [' . $theme . '] does not exist in marketplace', 404, $arrayLower);
  5302. return false;
  5303. } else {
  5304. $key = array_search($theme, array_keys($arrayLower));
  5305. $theme = array_keys($array)[$key];
  5306. }
  5307. $array = $array[$theme];
  5308. // Check Version of Organizr against minimum version needed
  5309. $compare = new Composer\Semver\Comparator;
  5310. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5311. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5312. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5313. return true;
  5314. }
  5315. // It is okay to user Plugin function - we should rename it so it is universal
  5316. $files = $this->getPluginFilesFromRepo($theme, $array);
  5317. if ($files) {
  5318. $downloadList = $this->themeFileListFormat($files, $array['project_folder']);
  5319. } else {
  5320. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5321. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5322. return false;
  5323. }
  5324. if (!$downloadList) {
  5325. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5326. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5327. return false;
  5328. }
  5329. foreach ($downloadList as $k => $v) {
  5330. $file = array(
  5331. 'from' => $v['githubPath'],
  5332. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5333. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5334. );
  5335. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes');
  5336. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5337. $this->setLoggerChannel('Theme Marketplace');
  5338. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5339. $this->setAPIResponse('error', 'Theme download failed', 500);
  5340. return false;
  5341. }
  5342. }
  5343. $this->updateInstalledThemes('install', $theme, $array);
  5344. $this->setAPIResponse('success', 'Theme installed', 200, $array);
  5345. return true;
  5346. }
  5347. public function themeFileListFormat($files, $folder)
  5348. {
  5349. $filesList = false;
  5350. foreach ($files as $k => $v) {
  5351. if ($v['type'] !== 'dir') {
  5352. $filesList[] = array(
  5353. 'fileName' => $v['name'],
  5354. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5355. 'githubPath' => $v['download_url']
  5356. );
  5357. }
  5358. }
  5359. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder);
  5360. return $filesList;
  5361. }
  5362. public function pluginFileListFormat($files, $folder)
  5363. {
  5364. $filesList = false;
  5365. foreach ($files as $k => $v) {
  5366. if ($v['type'] !== 'dir') {
  5367. $filesList[] = array(
  5368. 'fileName' => $v['name'],
  5369. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5370. 'githubPath' => $v['download_url']
  5371. );
  5372. }
  5373. }
  5374. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder);
  5375. return $filesList;
  5376. }
  5377. public function getPluginFilesFromGithub($plugin = 'test')
  5378. {
  5379. $url = 'https://api.github.com/repos/causefx/organizr/contents/' . $plugin . '?ref=v2-plugins';
  5380. $options = array('verify' => false);
  5381. $response = Requests::get($url, array(), $options);
  5382. if ($response->success) {
  5383. return json_decode($response->body, true);
  5384. }
  5385. return false;
  5386. }
  5387. public function getBranchFromGithub($repo)
  5388. {
  5389. $url = 'https://api.github.com/repos/' . $repo;
  5390. $options = array('verify' => false);
  5391. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5392. try {
  5393. if ($response->success) {
  5394. $github = json_decode($response->body, true);
  5395. return $github['default_branch'] ?? null;
  5396. } else {
  5397. $this->setLoggerChannel('Plugins');
  5398. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5399. return false;
  5400. }
  5401. } catch (Requests_Exception $e) {
  5402. $this->logger->error($e);
  5403. $this->setAPIResponse('error', $e->getMessage(), 401);
  5404. return false;
  5405. }
  5406. }
  5407. public function getFilesFromGithub($repo, $branch)
  5408. {
  5409. if (!$repo || !$branch) {
  5410. return false;
  5411. }
  5412. $url = 'https://api.github.com/repos/' . $repo . '/git/trees/' . $branch . '?recursive=1';
  5413. $options = array('verify' => false);
  5414. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5415. try {
  5416. if ($response->success) {
  5417. $github = json_decode($response->body, true);
  5418. return is_array($github) ? $github : null;
  5419. } else {
  5420. $this->setLoggerChannel('Plugins');
  5421. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5422. return false;
  5423. }
  5424. } catch (Requests_Exception $e) {
  5425. $this->logger->error($e);
  5426. $this->setAPIResponse('error', $e->getMessage(), 401);
  5427. return false;
  5428. }
  5429. }
  5430. public function formatFilesFromGithub($files, $repo, $branch, $folder)
  5431. {
  5432. if (!$files || !$repo || !$branch || !$folder) {
  5433. return false;
  5434. }
  5435. if (isset($files['tree'])) {
  5436. $fileList = [];
  5437. foreach ($files['tree'] as $k => $v) {
  5438. if ($v['type'] !== 'tree') {
  5439. $fileInfo = pathinfo($v['path']);
  5440. $v['name'] = $fileInfo['basename'];
  5441. $v['download_url'] = 'https://raw.githubusercontent.com/' . $repo . '/' . $branch . '/' . $v['path'];
  5442. if ($folder == 'root') {
  5443. $fileList[] = $v;
  5444. } else {
  5445. if (stripos($v['path'], $folder) !== false) {
  5446. $v['path'] = (substr($v['path'], 0, strlen($folder)) == $folder) ? substr($v['path'], (strlen($folder) + 1)) : $v['path'];
  5447. $fileList[] = $v;
  5448. }
  5449. }
  5450. }
  5451. }
  5452. return $fileList;
  5453. }
  5454. return false;
  5455. }
  5456. public function getPluginFilesFromRepo($plugin, $pluginDetails)
  5457. {
  5458. if (stripos($pluginDetails['repo'], 'github.com') !== false) {
  5459. $repo = explode('https://github.com/', $pluginDetails['repo']);
  5460. } else {
  5461. return false;
  5462. }
  5463. $branch = $this->getBranchFromGithub($repo[1]);
  5464. if ($branch) {
  5465. return $this->formatFilesFromGithub($this->getFilesFromGithub($repo[1], $branch), $repo[1], $branch, $pluginDetails['github_folder']);
  5466. }
  5467. return false;
  5468. }
  5469. public function installPlugin($plugin)
  5470. {
  5471. $this->setLoggerChannel('Plugin Marketplace');
  5472. $plugin = $this->reverseCleanClassName($plugin);
  5473. $array = $this->getPluginsMarketplace();
  5474. $arrayLower = array_change_key_case($array);
  5475. if (!$array) {
  5476. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5477. return false;
  5478. }
  5479. if (!$arrayLower[$plugin]) {
  5480. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5481. return false;
  5482. } else {
  5483. $key = array_search($plugin, array_keys($arrayLower));
  5484. $plugin = array_keys($array)[$key];
  5485. }
  5486. $array = $array[$plugin];
  5487. // Check Version of Organizr against minimum version needed
  5488. $compare = new Composer\Semver\Comparator;
  5489. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5490. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5491. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5492. return true;
  5493. }
  5494. $files = $this->getPluginFilesFromRepo($plugin, $array);
  5495. if ($files) {
  5496. $downloadList = $this->pluginFileListFormat($files, $array['project_folder']);
  5497. } else {
  5498. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5499. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5500. return false;
  5501. }
  5502. if (!$downloadList) {
  5503. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5504. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5505. return false;
  5506. }
  5507. foreach ($downloadList as $k => $v) {
  5508. $file = array(
  5509. 'from' => $v['githubPath'],
  5510. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5511. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5512. );
  5513. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins');
  5514. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5515. $this->setLoggerChannel('Plugin Marketplace');
  5516. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5517. $this->setAPIResponse('error', 'Plugin download failed', 500);
  5518. return false;
  5519. }
  5520. }
  5521. $this->updateInstalledPlugins('install', $plugin, $array);
  5522. $this->setAPIResponse('success', 'Plugin installed', 200, $array);
  5523. return true;
  5524. }
  5525. public function removePlugin($plugin)
  5526. {
  5527. $this->setLoggerChannel('Plugin Marketplace');
  5528. $plugin = $this->reverseCleanClassName($plugin);
  5529. $array = $this->getPluginsMarketplace();
  5530. $arrayLower = array_change_key_case($array);
  5531. if (!$array) {
  5532. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5533. return false;
  5534. }
  5535. if (!$arrayLower[$plugin]) {
  5536. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5537. return false;
  5538. } else {
  5539. $key = array_search($plugin, array_keys($arrayLower));
  5540. $plugin = array_keys($array)[$key];
  5541. }
  5542. $array = $array[$plugin];
  5543. $pluginDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5544. $dirExists = file_exists($pluginDir);
  5545. if ($dirExists) {
  5546. if (!$this->rrmdir($pluginDir)) {
  5547. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5548. return false;
  5549. }
  5550. } else {
  5551. $this->setAPIResponse('error', 'Plugin is not installed', 404);
  5552. return false;
  5553. }
  5554. $this->updateInstalledPlugins('uninstall', $plugin, $array);
  5555. $this->setAPIResponse('success', 'Plugin removed', 200, $array);
  5556. return true;
  5557. }
  5558. public function updateInstalledPlugins($action, $plugin, $pluginDetails)
  5559. {
  5560. if (!$action || !$plugin || !$pluginDetails) {
  5561. return false;
  5562. }
  5563. $config = $this->config['installedPlugins'];
  5564. $config = is_array($config) ? $config : [];
  5565. switch ($action) {
  5566. case 'install':
  5567. case 'update':
  5568. $update[$plugin] = [
  5569. 'name' => $plugin,
  5570. 'version' => $pluginDetails['version'],
  5571. 'repo' => $pluginDetails['repo']
  5572. ];
  5573. $config = array_merge($config, $update);
  5574. break;
  5575. default:
  5576. unset($config[$plugin]);
  5577. break;
  5578. }
  5579. $this->updateConfig(['installedPlugins' => $config]);
  5580. }
  5581. public function updateInstalledThemes($action, $theme, $themeDetails)
  5582. {
  5583. if (!$action || !$theme || !$themeDetails) {
  5584. return false;
  5585. }
  5586. $config = $this->config['installedThemes'];
  5587. $config = is_array($config) ? $config : [];
  5588. switch ($action) {
  5589. case 'install':
  5590. case 'update':
  5591. $update[$theme] = [
  5592. 'name' => $theme,
  5593. 'version' => $themeDetails['version'],
  5594. 'repo' => $themeDetails['repo'],
  5595. 'path' => 'data/themes/' . $themeDetails['project_folder']
  5596. ];
  5597. $config = array_merge($config, $update);
  5598. break;
  5599. default:
  5600. unset($config[$theme]);
  5601. break;
  5602. }
  5603. $this->updateConfig(['installedThemes' => $config]);
  5604. }
  5605. public function getThemesGithub()
  5606. {
  5607. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-themes/themes.json';
  5608. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5609. $response = Requests::get($url, array(), $options);
  5610. if ($response->success) {
  5611. return json_decode($response->body, true);
  5612. }
  5613. return false;
  5614. }
  5615. public function getPluginsGithub()
  5616. {
  5617. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-plugins/plugins.json';
  5618. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5619. try {
  5620. $response = Requests::get($url, array(), $options);
  5621. if ($response->success) {
  5622. return json_decode($response->body, true);
  5623. }
  5624. } catch (Requests_Exception $e) {
  5625. return false;
  5626. }
  5627. return false;
  5628. }
  5629. public function getPluginsMarketplace()
  5630. {
  5631. $plugins = $this->getPluginsGithubCombined();
  5632. foreach ($plugins as $pluginName => $pluginDetails) {
  5633. $plugins[$pluginName]['installed'] = (isset($this->config['installedPlugins'][$pluginName]));
  5634. $plugins[$pluginName]['installed_version'] = $this->config['installedPlugins'][$pluginName]['version'] ?? null;
  5635. $plugins[$pluginName]['needs_update'] = ($plugins[$pluginName]['installed'] && ($plugins[$pluginName]['installed_version'] !== $plugins[$pluginName]['version']));
  5636. $plugins[$pluginName]['status'] = $this->getPluginStatus($plugins[$pluginName]);
  5637. }
  5638. return $plugins;
  5639. }
  5640. public function getThemesMarketplace()
  5641. {
  5642. $themes = $this->getThemesGithubCombined();
  5643. foreach ($themes as $themeName => $themeDetails) {
  5644. $themes[$themeName]['installed'] = (isset($this->config['installedThemes'][$themeName]));
  5645. $themes[$themeName]['installed_version'] = $this->config['installedThemes'][$themeName]['version'] ?? null;
  5646. $themes[$themeName]['needs_update'] = ($themes[$themeName]['installed'] && ($themes[$themeName]['installed_version'] !== $themes[$themeName]['version']));
  5647. $themes[$themeName]['status'] = $this->getPluginStatus($themes[$themeName]);
  5648. }
  5649. return $themes;
  5650. }
  5651. public function getThemesGithubCombined()
  5652. {
  5653. // Organizr Repo
  5654. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Themes')];
  5655. foreach (explode(',', $this->config['externalThemeMarketplaceRepos']) as $repo) {
  5656. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5657. }
  5658. $themes = [];
  5659. foreach ($urls as $repo) {
  5660. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5661. try {
  5662. $response = Requests::get($repo, array(), $options);
  5663. if ($response->success) {
  5664. $themes = array_merge($themes, json_decode($response->body, true));
  5665. } else {
  5666. $this->setLoggerChannel('Themes');
  5667. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5668. return false;
  5669. }
  5670. } catch (Requests_Exception $e) {
  5671. //return false;
  5672. }
  5673. }
  5674. return $themes;
  5675. }
  5676. public function getPluginStatus($pluginDetails)
  5677. {
  5678. if ($pluginDetails['needs_update']) {
  5679. return 'Update Available';
  5680. } elseif ($pluginDetails['installed']) {
  5681. return 'Up to date';
  5682. } else {
  5683. return 'Not Installed';
  5684. }
  5685. }
  5686. public function getPluginsGithubCombined()
  5687. {
  5688. // Organizr Repo
  5689. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Plugins')];
  5690. foreach (explode(',', $this->config['externalPluginMarketplaceRepos']) as $repo) {
  5691. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5692. }
  5693. $plugins = [];
  5694. foreach ($urls as $repo) {
  5695. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5696. try {
  5697. $response = Requests::get($repo, array(), $options);
  5698. if ($response->success) {
  5699. $plugins = array_merge($plugins, json_decode($response->body, true));
  5700. } else {
  5701. $this->setLoggerChannel('Plugins');
  5702. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5703. return false;
  5704. }
  5705. } catch (Requests_Exception $e) {
  5706. //return false;
  5707. }
  5708. }
  5709. return $plugins;
  5710. }
  5711. public function getMarketplaceJSONFromRepo($url)
  5712. {
  5713. if (stripos($url, '.json') !== false) {
  5714. return $url;
  5715. } elseif (stripos($url, 'github.com') !== false) {
  5716. $repo = explode('https://github.com/', $url);
  5717. $newURL = 'https://api.github.com/repos/' . $repo[1] . '/contents';
  5718. $options = ($this->localURL($newURL)) ? array('verify' => false) : array();
  5719. try {
  5720. $response = Requests::get($newURL, $this->setGithubAccessToken(), $options);
  5721. if ($response->success) {
  5722. $jsonFiles = json_decode($response->body, true);
  5723. foreach ($jsonFiles as $file) {
  5724. if (stripos($file['name'], '.json') !== false) {
  5725. return $file['download_url'];
  5726. }
  5727. }
  5728. return false;
  5729. } else {
  5730. $this->setLoggerChannel('Plugins');
  5731. $this->logger->warning('Getting Marketplace JSON from Github', $this->apiResponseFormatter($response->body));
  5732. return false;
  5733. }
  5734. } catch (Requests_Exception $e) {
  5735. return false;
  5736. }
  5737. }
  5738. return false;
  5739. }
  5740. public function setGithubAccessToken()
  5741. {
  5742. return ($this->config['githubAccessToken'] !== '') ? ['Authorization' => 'token ' . $this->config['githubAccessToken']] : [];
  5743. }
  5744. public function formatGithubAccessToken()
  5745. {
  5746. $accessToken = $this->setGithubAccessToken();
  5747. if (count($accessToken) >= 1) {
  5748. return key($accessToken) . ': ' . $accessToken[key($accessToken)];
  5749. } else {
  5750. return '';
  5751. }
  5752. }
  5753. public function getOpenCollectiveBackers()
  5754. {
  5755. $url = 'https://opencollective.com/organizr/members/users.json?limit=100&offset=0';
  5756. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5757. try {
  5758. $response = Requests::get($url, array(), $options);
  5759. if ($response->success) {
  5760. $api = json_decode($response->body, true);
  5761. foreach ($api as $k => $backer) {
  5762. $api[$k] = array_merge($api[$k], ['sortName' => strtolower($backer['name'])]);
  5763. }
  5764. $this->setAPIResponse('success', '', 200, $api);
  5765. return $api;
  5766. }
  5767. } catch (Requests_Exception $e) {
  5768. $this->setResponse(500, $e->getMessage());
  5769. return false;
  5770. }
  5771. $this->setAPIResponse('error', 'Error connecting to Open Collective', 409);
  5772. return false;
  5773. }
  5774. public function getGithubSponsors()
  5775. {
  5776. $url = 'https://github.com/sponsors/causefx';
  5777. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5778. $response = Requests::get($url, array(), $options);
  5779. if ($response->success) {
  5780. $sponsors = [];
  5781. $dom = new PHPHtmlParser\Dom;
  5782. try {
  5783. $dom->loadStr($response->body);
  5784. $contents = $dom->find('#sponsors .clearfix div');
  5785. foreach ($contents as $content) {
  5786. $html = $content->innerHtml;
  5787. preg_match('/(@[a-zA-Z])\w+/', $html, $username);
  5788. preg_match('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»""\'\']))/', $html, $image);
  5789. if (isset($image[0]) && isset($username[0])) {
  5790. $sponsors[] = [
  5791. 'name' => str_replace('@', '', $username[0]),
  5792. 'sortName' => str_replace('@', '', strtolower($username[0])),
  5793. 'image' => str_replace('s=60', 's=200', $image[0]),
  5794. 'isActive' => true,
  5795. 'type' => 'USER',
  5796. 'role' => 'BACKER'
  5797. ];
  5798. }
  5799. }
  5800. $this->setAPIResponse('success', '', 200, $sponsors);
  5801. return $sponsors;
  5802. } catch (\PHPHtmlParser\Exceptions\ChildNotFoundException | \PHPHtmlParser\Exceptions\CircularException | \PHPHtmlParser\Exceptions\LogicalException | \PHPHtmlParser\Exceptions\StrictException | \PHPHtmlParser\Exceptions\ContentLengthException | \PHPHtmlParser\Exceptions\NotLoadedException $e) {
  5803. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5804. return false;
  5805. }
  5806. }
  5807. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5808. return false;
  5809. }
  5810. public function getAllSponsors()
  5811. {
  5812. $sponsors = [];
  5813. $list = [
  5814. 'openCollective' => $this->getOpenCollectiveBackers(),
  5815. 'github' => $this->getGithubSponsors()
  5816. ];
  5817. foreach ($list as $k => $sponsor) {
  5818. if ($sponsor) {
  5819. $sponsors = array_merge($sponsor, $sponsors);
  5820. }
  5821. }
  5822. if ($sponsors) {
  5823. usort($sponsors, function ($a, $b) {
  5824. return $a['sortName'] <=> $b['sortName'];
  5825. });
  5826. }
  5827. $this->setAPIResponse('success', '', 200, $sponsors);
  5828. return $sponsors;
  5829. }
  5830. public function getOrganizrSmtpFromAPI()
  5831. {
  5832. $url = 'https://api.organizr.app/?cmd=smtp';
  5833. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5834. try {
  5835. $response = Requests::get($url, array(), $options);
  5836. if ($response->success) {
  5837. return json_decode($response->body, true);
  5838. }
  5839. } catch (Requests_Exception $e) {
  5840. $this->setResponse(500, $e->getMessage());
  5841. return false;
  5842. }
  5843. return false;
  5844. }
  5845. public function saveOrganizrSmtpFromAPI()
  5846. {
  5847. $api = $this->getOrganizrSmtpFromAPI();
  5848. if ($api) {
  5849. $this->updateConfigItems($api['response']['data']);
  5850. $this->setAPIResponse(null, 'SMTP activated with Organizr SMTP account');
  5851. return true;
  5852. } else {
  5853. return false;
  5854. }
  5855. }
  5856. public function guestHash($start, $end)
  5857. {
  5858. $ip = $this->userIP();
  5859. $ip = md5($ip);
  5860. return substr($ip, $start, $end);
  5861. }
  5862. public function rrmdir($dir)
  5863. {
  5864. ini_set('max_execution_time', 0);
  5865. set_time_limit(0);
  5866. if (is_dir($dir)) {
  5867. $files = scandir($dir);
  5868. foreach ($files as $file) {
  5869. if ($file != "." && $file != "..") {
  5870. $this->rrmdir("$dir/$file");
  5871. }
  5872. }
  5873. rmdir($dir);
  5874. } elseif (file_exists($dir)) {
  5875. unlink($dir);
  5876. }
  5877. return true;
  5878. }
  5879. public function rcopy($src, $dst)
  5880. {
  5881. ini_set('max_execution_time', 0);
  5882. set_time_limit(0);
  5883. $src = $this->cleanPath($src);
  5884. $dst = $this->cleanPath($dst);
  5885. if (is_dir($src)) {
  5886. if (!file_exists($dst)) : mkdir($dst);
  5887. endif;
  5888. $files = scandir($src);
  5889. foreach ($files as $file) {
  5890. if ($file != "." && $file != "..") {
  5891. $this->rcopy("$src/$file", "$dst/$file");
  5892. }
  5893. }
  5894. } elseif (file_exists($src)) {
  5895. copy($src, $dst);
  5896. }
  5897. return true;
  5898. }
  5899. public function unzipFile($zipFile)
  5900. {
  5901. ini_set('max_execution_time', 0);
  5902. set_time_limit(0);
  5903. $zip = new ZipArchive;
  5904. $extractPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade/";
  5905. $this->setLoggerChannel('File Management');
  5906. if ($zip->open($extractPath . $zipFile) != "true") {
  5907. $this->logger->warning('organizr could not unzip upgrade.zip');
  5908. } else {
  5909. $this->logger->debug('organizr unzipped upgrade.zip');
  5910. }
  5911. /* Extract Zip File */
  5912. $zip->extractTo($extractPath);
  5913. $zip->close();
  5914. return true;
  5915. }
  5916. public function downloadFile($url, $path)
  5917. {
  5918. ini_set('max_execution_time', 0);
  5919. set_time_limit(0);
  5920. $folderPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade" . DIRECTORY_SEPARATOR;
  5921. $this->setLoggerChannel('File Management');
  5922. if (!file_exists($folderPath)) {
  5923. if (@!mkdir($folderPath)) {
  5924. $this->logger->warning('Folder Creation failed');
  5925. return false;
  5926. }
  5927. }
  5928. $newfname = $folderPath . $path;
  5929. $context = stream_context_create(
  5930. array(
  5931. 'ssl' => array(
  5932. 'verify_peer' => true,
  5933. 'cafile' => $this->getCert()
  5934. )
  5935. )
  5936. );
  5937. $file = fopen($url, 'rb', false, $context);
  5938. if ($file) {
  5939. $newf = fopen($newfname, 'wb');
  5940. if ($newf) {
  5941. while (!feof($file)) {
  5942. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  5943. }
  5944. }
  5945. } else {
  5946. $this->logger->warning('Organizr could not download ' . $url);
  5947. return false;
  5948. }
  5949. if ($file) {
  5950. fclose($file);
  5951. $this->logger->debug('Organizr finished downloading the github zip file');
  5952. } else {
  5953. $this->logger->warning('Organizr could not download the github zip file');
  5954. return false;
  5955. }
  5956. if ($newf) {
  5957. fclose($newf);
  5958. $this->logger->debug('Organizr created upgrade zip file from github zip file');
  5959. } else {
  5960. $this->logger->warning('Organizr could not create upgrade zip file from github zip file');
  5961. return false;
  5962. }
  5963. return true;
  5964. }
  5965. public function downloadFileToPath($from, $to, $path)
  5966. {
  5967. if (((stripos($from, 'api.github.com') !== false) || (stripos($from, 'raw.githubusercontent.com') !== false)) && $this->config['githubAccessToken'] !== '') {
  5968. $context = stream_context_create(
  5969. array(
  5970. 'ssl' => array(
  5971. 'verify_peer' => false,
  5972. 'cafile' => $this->getCert()
  5973. ),
  5974. 'http' => array(
  5975. 'method' => 'GET',
  5976. 'header' => $this->formatGithubAccessToken()
  5977. )
  5978. )
  5979. );
  5980. } else {
  5981. $context = stream_context_create([]);
  5982. }
  5983. ini_set('max_execution_time', 0);
  5984. set_time_limit(0);
  5985. $this->makeDir($path);
  5986. $file = fopen($from, 'rb', false, $context);
  5987. if ($file) {
  5988. $newf = fopen($to, 'wb', false, $context);
  5989. if ($newf) {
  5990. while (!feof($file)) {
  5991. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  5992. }
  5993. }
  5994. } else {
  5995. $this->logger->warning('Organizr could not download file');
  5996. }
  5997. if ($file) {
  5998. fclose($file);
  5999. $this->logger->debug('Organizr finished downloading the file');
  6000. } else {
  6001. $this->logger->warning('Organizr could not download file');
  6002. }
  6003. if ($newf) {
  6004. fclose($newf);
  6005. $this->logger->debug('Organizr saved and/or moved the file');
  6006. } else {
  6007. $this->logger->warning('Organizr could not save and/or move the file');
  6008. }
  6009. return true;
  6010. }
  6011. public function getAllUsers($includeGroups = false)
  6012. {
  6013. $response = [
  6014. array(
  6015. 'function' => 'fetchAll',
  6016. 'query' => array(
  6017. 'SELECT * FROM users'
  6018. ),
  6019. 'key' => 'users'
  6020. ),
  6021. ];
  6022. $groups = array(
  6023. 'function' => 'fetchAll',
  6024. 'query' => array(
  6025. 'SELECT * FROM groups ORDER BY group_id ASC'
  6026. ),
  6027. 'key' => 'groups'
  6028. );
  6029. $addGroups = (isset($_GET['includeGroups']) || $includeGroups) ?? false;
  6030. if ($addGroups) {
  6031. array_push($response, $groups);
  6032. }
  6033. return $this->processQueries($response);
  6034. }
  6035. public function getAllGroups()
  6036. {
  6037. $response = [
  6038. array(
  6039. 'function' => 'fetchAll',
  6040. 'query' => array(
  6041. 'SELECT * FROM groups ORDER BY group_id ASC'
  6042. ),
  6043. 'key' => 'groups'
  6044. ),
  6045. ];
  6046. $users = array(
  6047. 'function' => 'fetchAll',
  6048. 'query' => array(
  6049. 'SELECT * FROM users'
  6050. ),
  6051. 'key' => 'users'
  6052. );
  6053. $addUsers = (isset($_GET['includeUsers'])) ?? false;
  6054. if ($addUsers) {
  6055. array_push($response, $users);
  6056. }
  6057. return $this->processQueries($response);
  6058. }
  6059. public function importUsers($array)
  6060. {
  6061. $imported = 0;
  6062. if ($array) {
  6063. foreach ($array as $user) {
  6064. $password = $this->random_ascii_string(30);
  6065. if ($user['username'] !== '' && $user['email'] !== '' && $password !== '') {
  6066. $newUser = $this->createUser($user['username'], $password, $user['email']);
  6067. if (!$newUser) {
  6068. $this->setLoggerChannel('User Management');
  6069. $this->logger->warning('An error occurred during user import');
  6070. } else {
  6071. $imported++;
  6072. }
  6073. }
  6074. }
  6075. }
  6076. $this->setAPIResponse('success', 'Imported ' . $imported . ' users', 200);
  6077. return true;
  6078. }
  6079. public function importUsersType($type)
  6080. {
  6081. if ($type !== '') {
  6082. switch ($type) {
  6083. case 'plex':
  6084. return $this->importUsers($this->allPlexUsers(true));
  6085. case 'jellyfin':
  6086. return $this->importUsers($this->allJellyfinUsers(true));
  6087. case 'emby':
  6088. return $this->importUsers($this->allEmbyUsers(true));
  6089. default:
  6090. return false;
  6091. }
  6092. }
  6093. return false;
  6094. }
  6095. public function allPlexUsers($newOnly = false, $friendsOnly = false)
  6096. {
  6097. try {
  6098. if (!empty($this->config['plexToken'])) {
  6099. $url = 'https://plex.tv/api/users';
  6100. $headers = array(
  6101. 'X-Plex-Token' => $this->config['plexToken'],
  6102. );
  6103. $response = Requests::get($url, $headers);
  6104. if ($response->success) {
  6105. libxml_use_internal_errors(true);
  6106. $userXML = simplexml_load_string($response->body);
  6107. if (is_array($userXML) || is_object($userXML)) {
  6108. $results = array();
  6109. foreach ($userXML as $child) {
  6110. if (((string)$child['restricted'] == '0')) {
  6111. if ($newOnly) {
  6112. $taken = $this->usernameTaken((string)$child['username'], (string)$child['email']);
  6113. if (!$taken) {
  6114. $results[] = array(
  6115. 'username' => (string)$child['username'],
  6116. 'email' => (string)$child['email'],
  6117. 'id' => (string)$child['id'],
  6118. );
  6119. }
  6120. } elseif ($friendsOnly) {
  6121. $machineMatches = false;
  6122. foreach ($child->Server as $server) {
  6123. if ((string)$server['machineIdentifier'] == $this->config['plexID']) {
  6124. $machineMatches = true;
  6125. $shareId = $server['id'];
  6126. }
  6127. }
  6128. if ($machineMatches) {
  6129. $results[] = array(
  6130. 'username' => (string)$child['username'],
  6131. 'email' => (string)$child['email'],
  6132. 'id' => (string)$child['id'],
  6133. 'shareId' => (string)$shareId
  6134. );
  6135. }
  6136. } else {
  6137. $results[] = array(
  6138. 'username' => (string)$child['username'],
  6139. 'email' => (string)$child['email'],
  6140. 'id' => (string)$child['id'],
  6141. );
  6142. }
  6143. }
  6144. }
  6145. return $results;
  6146. }
  6147. }
  6148. }
  6149. return false;
  6150. } catch (Requests_Exception $e) {
  6151. $this->setLoggerChannel('User Management');
  6152. $this->logger->error($e);
  6153. }
  6154. return false;
  6155. }
  6156. public function allJellyfinUsers($newOnly = false)
  6157. {
  6158. try {
  6159. if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
  6160. $url = $this->qualifyURL($this->config['jellyfinURL']) . '/Users?api_key=' . $this->config['jellyfinToken'];
  6161. $headers = array();
  6162. $response = Requests::get($url, $headers);
  6163. if ($response->success) {
  6164. $users = json_decode($response->body, true);
  6165. if (is_array($users) || is_object($users)) {
  6166. $results = array();
  6167. foreach ($users as $child) {
  6168. // Jellyfin doesn't list emails for some reason
  6169. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6170. if ($newOnly) {
  6171. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6172. if (!$taken) {
  6173. $results[] = array(
  6174. 'username' => (string)$child['Name'],
  6175. 'email' => $email
  6176. );
  6177. }
  6178. } else {
  6179. $results[] = array(
  6180. 'username' => (string)$child['Name'],
  6181. 'email' => $email,
  6182. );
  6183. }
  6184. }
  6185. return $results;
  6186. }
  6187. }
  6188. }
  6189. return false;
  6190. } catch (Requests_Exception $e) {
  6191. $this->setLoggerChannel('User Management');
  6192. $this->logger->error($e);
  6193. }
  6194. return false;
  6195. }
  6196. public function allEmbyUsers($newOnly = false)
  6197. {
  6198. try {
  6199. if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
  6200. $url = $this->qualifyURL($this->config['embyURL']) . '/Users?api_key=' . $this->config['embyToken'];
  6201. $headers = array();
  6202. $response = Requests::get($url, $headers);
  6203. if ($response->success) {
  6204. $users = json_decode($response->body, true);
  6205. if (is_array($users) || is_object($users)) {
  6206. $results = array();
  6207. foreach ($users as $child) {
  6208. // Emby doesn't list emails for some reason
  6209. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6210. if ($newOnly) {
  6211. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6212. if (!$taken) {
  6213. $results[] = array(
  6214. 'username' => (string)$child['Name'],
  6215. 'email' => $email
  6216. );
  6217. }
  6218. } else {
  6219. $results[] = array(
  6220. 'username' => (string)$child['Name'],
  6221. 'email' => $email,
  6222. );
  6223. }
  6224. }
  6225. return $results;
  6226. }
  6227. }
  6228. }
  6229. return false;
  6230. } catch (Requests_Exception $e) {
  6231. $this->setLoggerChannel('User Management');
  6232. $this->logger->error($e);
  6233. }
  6234. return false;
  6235. }
  6236. public function validateEmail($email)
  6237. {
  6238. return filter_var(trim($email), FILTER_VALIDATE_EMAIL);
  6239. }
  6240. public function sanitizeEmail($email)
  6241. {
  6242. return filter_var(trim($email), FILTER_SANITIZE_EMAIL);
  6243. }
  6244. public function sanitizeUserString($string)
  6245. {
  6246. return htmlspecialchars(trim($string));
  6247. }
  6248. public function updateUser($id, $array)
  6249. {
  6250. if (!$id) {
  6251. $this->setAPIResponse('error', 'Id was not supplied', 422);
  6252. return false;
  6253. }
  6254. if ((int)$id !== $this->user['userID']) {
  6255. if (!$this->qualifyRequest('1', true)) {
  6256. return false;
  6257. }
  6258. }
  6259. $user = $this->getUserById($id);
  6260. if ($user) {
  6261. $array = $this->checkKeys($user, $array);
  6262. } else {
  6263. $this->setAPIResponse('error', 'User was not found', 404);
  6264. return false;
  6265. }
  6266. if ($user['group_id'] == 0 && $this->user['groupID'] !== 0) {
  6267. $this->setAPIResponse('error', 'Cannot update admin unless you are admin', 401);
  6268. return false;
  6269. }
  6270. if (array_key_exists('username', $array)) {
  6271. if ($array['username'] == '') {
  6272. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6273. return false;
  6274. }
  6275. $array['username'] = $this->sanitizeUserString($array['username']);
  6276. if ($this->usernameTaken($array['username'], $array['username'], $id)) {
  6277. $this->setAPIResponse('error', 'Username: ' . $array['username'] . ' is already taken', 409);
  6278. return false;
  6279. }
  6280. if (!$this->qualifyLength($array['username'], 50, true)) {
  6281. return false;
  6282. }
  6283. }
  6284. if (array_key_exists('email', $array)) {
  6285. if ($array['email'] == '') {
  6286. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6287. return false;
  6288. }
  6289. if ($this->validateEmail($array['email'])) {
  6290. $array['email'] = $this->sanitizeEmail($array['email']);
  6291. } else {
  6292. $this->setResponse(409, 'Email is not a valid email', ['email' => $array['email']]);
  6293. return false;
  6294. }
  6295. if ($this->usernameTaken($array['email'], $array['email'], $id)) {
  6296. $this->setAPIResponse('error', 'Email: ' . $array['email'] . ' is already taken', 409);
  6297. return false;
  6298. }
  6299. if (!$this->qualifyLength($array['email'], 50, true)) {
  6300. return false;
  6301. }
  6302. }
  6303. if (array_key_exists('group_id', $array)) {
  6304. if ($array['group_id'] == '') {
  6305. $array['group_id'] = 0;
  6306. //$this->setAPIResponse('error', 'group_id was set but empty', 409);
  6307. //return false;
  6308. }
  6309. if (!$this->qualifyRequest('1', false)) {
  6310. $this->setAPIResponse('error', 'Cannot change your own group_id', 401);
  6311. return false;
  6312. }
  6313. if (($id == $this->user['userID']) && $this->user['groupID'] == 0) {
  6314. $array['group_id'] = 0;
  6315. }
  6316. if (($id == $this->user['userID']) && ($array['group_id'] == 0 && $this->user['groupID'] !== 0)) {
  6317. $this->setAPIResponse('error', 'Only admins can make others admins', 401);
  6318. return false;
  6319. }
  6320. $array['group'] = $this->getGroupByGroupId($array['group_id'])['group'];
  6321. if (!$array['group']) {
  6322. $this->setAPIResponse('error', 'group_id does not exist', 404);
  6323. return false;
  6324. }
  6325. }
  6326. if (array_key_exists('locked', $array)) {
  6327. //$this->setAPIResponse('error', 'Cannot use endpoint to unlock or lock user - please use /users/{id}/lock', 409);
  6328. //return false;
  6329. }
  6330. if (array_key_exists('password', $array)) {
  6331. if ($array['password'] == '') {
  6332. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6333. return false;
  6334. }
  6335. $array['password'] = password_hash($array['password'], PASSWORD_BCRYPT);
  6336. }
  6337. if (array_key_exists('image', $array)) {
  6338. $array['image'] = $this->sanitizeUserString($array['image']);
  6339. }
  6340. if (array_key_exists('register_date', $array)) {
  6341. $this->setAPIResponse('error', 'Cannot update register date', 409);
  6342. return false;
  6343. }
  6344. $response = [
  6345. array(
  6346. 'function' => 'query',
  6347. 'query' => array(
  6348. 'UPDATE users SET',
  6349. $array,
  6350. 'WHERE id = ?',
  6351. $id
  6352. )
  6353. ),
  6354. ];
  6355. $this->setAPIResponse(null, 'User info updated');
  6356. $this->setLoggerChannel('User Management');
  6357. $this->logger->info('Updated User Info for [' . $user['username'] . ']');
  6358. return $this->processQueries($response);
  6359. }
  6360. public function deleteUser($id)
  6361. {
  6362. $response = [
  6363. array(
  6364. 'function' => 'query',
  6365. 'query' => array(
  6366. 'DELETE FROM users WHERE id = ?',
  6367. $id
  6368. )
  6369. ),
  6370. ];
  6371. $userInfo = $this->getUserById($id);
  6372. if ($id == $this->user['userID']) {
  6373. $this->setAPIResponse('error', 'Cannot delete your own user', 409);
  6374. return false;
  6375. }
  6376. if ($userInfo) {
  6377. $this->setLoggerChannel('User Management');
  6378. $this->logger->info('Deleted User [' . $userInfo['username'] . ']');
  6379. $this->setAPIResponse('success', 'User deleted', 204);
  6380. return $this->processQueries($response);
  6381. } else {
  6382. $this->setAPIResponse('error', 'id not found', 404);
  6383. return false;
  6384. }
  6385. }
  6386. public function addUser($array)
  6387. {
  6388. $username = $array['username'] ?? null;
  6389. $password = $array['password'] ?? null;
  6390. $email = $array['email'] ?? null;
  6391. if (!$username) {
  6392. $this->setAPIResponse('error', 'Username was not supplied', 409);
  6393. return false;
  6394. }
  6395. if ($username == '') {
  6396. $this->setResponse(409, 'Username was set but empty');
  6397. return false;
  6398. } else {
  6399. $username = $this->sanitizeUserString($username);
  6400. }
  6401. if (!$password) {
  6402. $this->setAPIResponse('error', 'Password was not supplied', 409);
  6403. return false;
  6404. }
  6405. if (!$email) {
  6406. $this->setAPIResponse('error', 'Email was set not supplied', 409);
  6407. return false;
  6408. }
  6409. if ($email == '') {
  6410. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6411. return false;
  6412. }
  6413. if ($this->validateEmail($email)) {
  6414. $email = $this->sanitizeEmail($email);
  6415. } else {
  6416. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6417. return false;
  6418. }
  6419. if (!$this->qualifyLength($username, 50, true)) {
  6420. return false;
  6421. }
  6422. if (!$this->qualifyLength($email, 50, true)) {
  6423. return false;
  6424. }
  6425. if (!$this->qualifyLength($password, 200, true)) {
  6426. return false;
  6427. }
  6428. $this->setLoggerChannel('User Management');
  6429. if ($this->createUser($username, $password, $email)) {
  6430. $this->logger->info('Account created for [' . $username . ']');
  6431. return true;
  6432. } else {
  6433. $this->logger->warning('An error occurred');
  6434. return false;
  6435. }
  6436. }
  6437. public function createUser($username, $password, $email = null)
  6438. {
  6439. $username = $username ?? null;
  6440. $password = $password ?? null;
  6441. $email = ($email) ? $email : $this->random_ascii_string(10) . '@placeholder.eml';
  6442. if (!$username) {
  6443. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6444. return false;
  6445. }
  6446. $username = $this->sanitizeUserString($username);
  6447. if (!$password) {
  6448. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6449. return false;
  6450. }
  6451. if ($email == '') {
  6452. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6453. return false;
  6454. }
  6455. if ($this->validateEmail($email)) {
  6456. $email = $this->sanitizeEmail($email);
  6457. } else {
  6458. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6459. return false;
  6460. }
  6461. if ($this->usernameTaken($username, $email)) {
  6462. $this->setAPIResponse('error', 'Username: ' . $username . ' or Email: ' . $email . ' is already taken', 409);
  6463. return false;
  6464. }
  6465. if (!$this->qualifyLength($username, 50, true)) {
  6466. return false;
  6467. }
  6468. if (!$this->qualifyLength($email, 50, true)) {
  6469. return false;
  6470. }
  6471. if (!$this->qualifyLength($password, 200, true)) {
  6472. return false;
  6473. }
  6474. $defaults = $this->getDefaultGroup();
  6475. $userInfo = [
  6476. 'username' => $username,
  6477. 'password' => password_hash($password, PASSWORD_BCRYPT),
  6478. 'email' => $email,
  6479. 'group' => $defaults['group'],
  6480. 'group_id' => $defaults['group_id'],
  6481. 'image' => $this->gravatar($email),
  6482. 'register_date' => gmdate('Y-m-d H:i:s'),
  6483. ];
  6484. $response = [
  6485. array(
  6486. 'function' => 'query',
  6487. 'query' => array(
  6488. 'INSERT INTO [users]',
  6489. $userInfo
  6490. )
  6491. ),
  6492. ];
  6493. $this->setAPIResponse('success', 'User created', 200);
  6494. return $this->processQueries($response);
  6495. }
  6496. public function updateGroup($id, $array)
  6497. {
  6498. if (!$id || $id == '') {
  6499. $this->setAPIResponse('error', 'id was not set', 422);
  6500. return null;
  6501. }
  6502. if (!$array) {
  6503. $this->setAPIResponse('error', 'no data was sent', 422);
  6504. return null;
  6505. }
  6506. $groupInfo = $this->getGroupById($id);
  6507. if ($groupInfo) {
  6508. $array = $this->checkKeys($groupInfo, $array);
  6509. } else {
  6510. $this->setAPIResponse('error', 'No category info found', 404);
  6511. return false;
  6512. }
  6513. if (array_key_exists('group_id', $array)) {
  6514. $this->setAPIResponse('error', 'Cannot change group_id', 409);
  6515. return false;
  6516. }
  6517. if (array_key_exists('group', $array)) {
  6518. if ($array['group'] == '') {
  6519. $this->setAPIResponse('error', 'Group was set but empty', 409);
  6520. return false;
  6521. }
  6522. $array['group'] = $this->sanitizeUserString($array['group']);
  6523. if ($this->isGroupNameTaken($array['group'], $id)) {
  6524. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6525. return false;
  6526. }
  6527. if (!$this->qualifyLength($array['group'], 50, true)) {
  6528. return false;
  6529. }
  6530. }
  6531. if (array_key_exists('image', $array)) {
  6532. if ($array['image'] == '') {
  6533. $this->setAPIResponse('error', 'Image was set but empty', 409);
  6534. return false;
  6535. }
  6536. }
  6537. if (array_key_exists('default', $array)) {
  6538. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6539. $this->setAPIResponse('error', 'Setting ' . $groupInfo['group'] . ' as default group is not allowed', 409);
  6540. return false;
  6541. }
  6542. if ($array['default']) {
  6543. $this->clearGroupDefault();
  6544. $array['default'] = 1;
  6545. }
  6546. }
  6547. $response = [
  6548. array(
  6549. 'function' => 'query',
  6550. 'query' => array(
  6551. 'UPDATE groups SET',
  6552. $array,
  6553. 'WHERE id = ?',
  6554. $id
  6555. )
  6556. ),
  6557. ];
  6558. $this->setAPIResponse(null, 'Group info updated');
  6559. $this->setLoggerChannel('Group Management');
  6560. $this->logger->info('Edited Group Info for [' . $groupInfo['group'] . ']');
  6561. return $this->processQueries($response);
  6562. }
  6563. public function deleteGroup($id)
  6564. {
  6565. $response = [
  6566. array(
  6567. 'function' => 'query',
  6568. 'query' => array(
  6569. 'DELETE FROM groups WHERE id = ?',
  6570. $id
  6571. )
  6572. ),
  6573. ];
  6574. $groupInfo = $this->getGroupById($id);
  6575. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6576. $this->setAPIResponse('error', 'Cannot delete group: ' . $groupInfo['group'] . ' as it is not allowed', 409);
  6577. return false;
  6578. }
  6579. if ($this->getGroupUserCountById($id) >= 1) {
  6580. $this->setAPIResponse('error', 'Cannot delete group as group still has users assigned to it', 409);
  6581. return false;
  6582. }
  6583. if ($groupInfo) {
  6584. $this->setLoggerChannel('Group Management');
  6585. $this->logger->info('Deleted Group [' . $groupInfo['group'] . ']');
  6586. $this->setAPIResponse('success', 'Group deleted', 204);
  6587. return $this->processQueries($response);
  6588. } else {
  6589. $this->setAPIResponse('error', 'id not found', 404);
  6590. return false;
  6591. }
  6592. }
  6593. public function addGroup($array)
  6594. {
  6595. if (!$array) {
  6596. $this->setAPIResponse('error', 'no data was sent', 422);
  6597. return null;
  6598. }
  6599. $array = $this->checkKeys($this->getTableColumnsFormatted('groups'), $array);
  6600. $array['default'] = ($array['default']) ?? 0;
  6601. $array['group_id'] = $this->getNextGroupOrder() + 1;
  6602. if (array_key_exists('group', $array)) {
  6603. $array['group'] = $this->sanitizeUserString($array['group']);
  6604. if ($this->isGroupNameTaken($array['group'])) {
  6605. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6606. return false;
  6607. }
  6608. if (!$this->qualifyLength($array['group'], 50, true)) {
  6609. return false;
  6610. }
  6611. } else {
  6612. $this->setAPIResponse('error', 'Group name was not supplied', 422);
  6613. return false;
  6614. }
  6615. if (array_key_exists('image', $array)) {
  6616. if ($array['image'] == '') {
  6617. $this->setAPIResponse('error', 'Group image cannot be empty', 422);
  6618. return false;
  6619. }
  6620. } else {
  6621. $this->setAPIResponse('error', 'Group image was not supplied', 422);
  6622. return false;
  6623. }
  6624. $response = [
  6625. array(
  6626. 'function' => 'query',
  6627. 'query' => array(
  6628. 'INSERT INTO [groups]',
  6629. $array
  6630. )
  6631. ),
  6632. ];
  6633. $this->setAPIResponse(null, 'Group added');
  6634. $this->setLoggerChannel('Group Management');
  6635. $this->logger->info('Added Group for [' . $array['group'] . ']');
  6636. return $this->processQueries($response);
  6637. }
  6638. public function userList($type = null)
  6639. {
  6640. switch ($type) {
  6641. case 'plex':
  6642. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  6643. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'] . '/shared_servers';
  6644. try {
  6645. $headers = array(
  6646. "Accept" => "application/json",
  6647. "X-Plex-Token" => $this->config['plexToken']
  6648. );
  6649. $response = Requests::get($url, $headers, array());
  6650. libxml_use_internal_errors(true);
  6651. if ($response->success) {
  6652. $libraryList = array();
  6653. $plex = simplexml_load_string($response->body);
  6654. foreach ($plex->SharedServer as $child) {
  6655. if (!empty($child['username'])) {
  6656. $username = (string)strtolower($child['username']);
  6657. $email = (string)strtolower($child['email']);
  6658. $libraryList['users'][$username] = (string)$child['id'];
  6659. $libraryList['emails'][$email] = (string)$child['id'];
  6660. $libraryList['both'][$username] = $email;
  6661. }
  6662. }
  6663. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  6664. return $libraryList;
  6665. }
  6666. } catch (Requests_Exception $e) {
  6667. $this->setLoggerChannel('User Management');
  6668. $this->logger->error($e);
  6669. }
  6670. }
  6671. break;
  6672. default:
  6673. # code...
  6674. break;
  6675. }
  6676. return false;
  6677. }
  6678. public function encrypt($password, $key = null)
  6679. {
  6680. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6681. return openssl_encrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6682. }
  6683. public function decrypt($password, $key = null)
  6684. {
  6685. if (empty($password)) {
  6686. return '';
  6687. }
  6688. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6689. return openssl_decrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6690. }
  6691. public function checkValidCert($file)
  6692. {
  6693. if (file_exists($file)) {
  6694. return filesize($file) > 0;
  6695. } else {
  6696. return false;
  6697. }
  6698. }
  6699. public function getCert()
  6700. {
  6701. $url = 'http://curl.haxx.se/ca/cacert.pem';
  6702. $file = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  6703. $file2 = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  6704. $useCert = ($this->checkValidCert($file)) ? $file : $file2;
  6705. if ($this->config['selfSignedCert'] !== '') {
  6706. if (file_exists($this->config['selfSignedCert'])) {
  6707. return $this->config['selfSignedCert'];
  6708. }
  6709. }
  6710. $context = stream_context_create(
  6711. array(
  6712. 'ssl' => array(
  6713. 'verify_peer' => true,
  6714. 'cafile' => $useCert
  6715. )
  6716. )
  6717. );
  6718. if (!$this->checkValidCert($file) || (file_exists($file) && time() - 2592000 > filemtime($file))) {
  6719. file_put_contents($file, fopen($url, 'r', false, $context));
  6720. }
  6721. return ($this->checkValidCert($file)) ? $file : $file2;
  6722. }
  6723. public function hasCustomCert()
  6724. {
  6725. return file_exists($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem');
  6726. }
  6727. public function getCustomCert()
  6728. {
  6729. return ($this->hasCustomCert()) ? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem' : false;
  6730. }
  6731. public function uploadCert()
  6732. {
  6733. $filesCheck = array_filter($_FILES);
  6734. if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'cert')) {
  6735. ini_set('upload_max_filesize', '10M');
  6736. ini_set('post_max_size', '10M');
  6737. $tempFile = $_FILES['file']['tmp_name'];
  6738. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR;
  6739. $targetFile = $targetPath . 'custom.pem';
  6740. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  6741. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert');
  6742. return move_uploaded_file($tempFile, $targetFile);
  6743. } else {
  6744. $this->setAPIResponse('error', pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' is not approved to be uploaded', 403);
  6745. return false;
  6746. }
  6747. }
  6748. public function createCronFile()
  6749. {
  6750. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6751. file_put_contents($file, time());
  6752. }
  6753. public function checkCronFile()
  6754. {
  6755. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6756. return file_exists($file) && time() - 120 < filemtime($file);
  6757. }
  6758. public function plexJoinAPI($array)
  6759. {
  6760. $username = ($array['username']) ?? null;
  6761. $email = ($array['email']) ?? null;
  6762. $password = ($array['password']) ?? null;
  6763. if (!$username) {
  6764. $this->setAPIResponse('error', 'Username not supplied', 409);
  6765. return false;
  6766. }
  6767. if (!$email) {
  6768. $this->setAPIResponse('error', 'Email not supplied', 409);
  6769. return false;
  6770. }
  6771. if (!$password) {
  6772. $this->setAPIResponse('error', 'Password not supplied', 409);
  6773. return false;
  6774. }
  6775. return $this->plexJoin($username, $email, $password);
  6776. }
  6777. public function plexJoin($username, $email, $password)
  6778. {
  6779. try {
  6780. $url = 'https://plex.tv/api/v2/users';
  6781. $headers = array(
  6782. 'Accept' => 'application/json',
  6783. 'Content-Type' => 'application/x-www-form-urlencoded',
  6784. 'X-Plex-Product' => 'Organizr',
  6785. 'X-Plex-Version' => '2.0',
  6786. 'X-Plex-Client-Identifier' => $this->config['uuid'],
  6787. );
  6788. $data = array(
  6789. 'email' => $email,
  6790. 'username' => $username,
  6791. 'password' => $password,
  6792. );
  6793. $response = Requests::post($url, $headers, $data, array());
  6794. $json = json_decode($response->body, true);
  6795. $errors = !empty($json['errors']);
  6796. $success = empty($json['errors']);
  6797. //Use This for later
  6798. $errorMessage = '';
  6799. if ($errors) {
  6800. foreach ($json['errors'] as $error) {
  6801. if (isset($error['message']) && isset($error['field'])) {
  6802. $errorMessage .= "[Plex.tv Error: " . $error['message'] . " for field: (" . $error['field'] . ")]";
  6803. }
  6804. }
  6805. }
  6806. $msg = (!empty($success) && empty($errors)) ? 'User has joined Plex' : $errorMessage;
  6807. $status = (!empty($success) && empty($errors)) ? 'success' : 'error';
  6808. $code = (!empty($success) && empty($errors)) ? 200 : 422;
  6809. $this->setAPIResponse($status, $msg, $code);
  6810. return (!empty($success) && empty($errors));
  6811. } catch (Requests_Exception $e) {
  6812. $this->setLoggerChannel('User Management');
  6813. $this->logger->error($e);
  6814. $this->setAPIResponse('error', 'An Error Occurred', 409);
  6815. return false;
  6816. }
  6817. return false;
  6818. }
  6819. public function lockCurrentUser()
  6820. {
  6821. if ($this->user['userID'] == '999') {
  6822. $this->setAPIResponse('error', 'Locking not allowed on Guest users', 409);
  6823. return false;
  6824. }
  6825. return $this->lockUser($this->user['userID']);
  6826. }
  6827. public function lockUser($id)
  6828. {
  6829. $user = $this->getUserById($id);
  6830. if (!$user) {
  6831. $this->setAPIResponse('error', 'User not found', 404);
  6832. return false;
  6833. }
  6834. $response = [
  6835. array(
  6836. 'function' => 'query',
  6837. 'query' => array(
  6838. 'UPDATE users SET',
  6839. ['locked' => '1'],
  6840. 'WHERE id = ?',
  6841. $id
  6842. )
  6843. ),
  6844. ];
  6845. $this->setLoggerChannel('User Management');
  6846. $this->logger->info('User: ' . $user['username'] . ' account locked');
  6847. $this->setAPIResponse('success', 'User account locked', 200);
  6848. return $this->processQueries($response);
  6849. }
  6850. public function unlockCurrentUser($array)
  6851. {
  6852. if ($array['password'] == '') {
  6853. $this->setAPIResponse('error', 'Password Not Set', 422);
  6854. return false;
  6855. }
  6856. $user = $this->getUserById($this->user['userID']);
  6857. if (!password_verify($array['password'], $user['password'])) {
  6858. $this->setAPIResponse('error', 'Password Incorrect', 401);
  6859. return false;
  6860. }
  6861. return $this->unlockUser($this->user['userID']);
  6862. }
  6863. public function unlockUser($id)
  6864. {
  6865. $user = $this->getUserById($id);
  6866. if (!$user) {
  6867. $this->setAPIResponse('error', 'User not found', 404);
  6868. return false;
  6869. }
  6870. $response = [
  6871. array(
  6872. 'function' => 'query',
  6873. 'query' => array(
  6874. 'UPDATE users SET',
  6875. ['locked' => '0'],
  6876. 'WHERE id = ?',
  6877. $id
  6878. )
  6879. ),
  6880. ];
  6881. $this->setLoggerChannel('User Management');
  6882. $this->logger->info('User: ' . $user['username'] . ' account unlocked');
  6883. $this->setAPIResponse('success', 'User account unlocked', 200);
  6884. return $this->processQueries($response);
  6885. }
  6886. public function youtubeSearch($query)
  6887. {
  6888. if (!$query) {
  6889. $this->setAPIResponse('error', 'No query supplied', 422);
  6890. return false;
  6891. }
  6892. $keys = array(
  6893. 'AIzaSyBsdt8nLJRMTwOq5PY5A5GLZ2q7scgn01w',
  6894. 'AIzaSyD-8SHutB60GCcSM8q_Fle38rJUV7ujd8k',
  6895. 'AIzaSyBzOpVBT6VII-b-8gWD0MOEosGg4hyhCsQ',
  6896. 'AIzaSyBKnRe1P8fpfBHgooJpmT0WOsrdUtZ4cpk'
  6897. );
  6898. $randomKeyIndex = array_rand($keys);
  6899. $key = $keys[$randomKeyIndex];
  6900. $apikey = ($this->config['youtubeAPI'] !== '') ? $this->config['youtubeAPI'] : $key;
  6901. $results = false;
  6902. $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=$query+official+trailer&part=snippet&maxResults=1&type=video&videoDuration=short&key=$apikey";
  6903. $response = Requests::get($url);
  6904. if ($response->success) {
  6905. $results = json_decode($response->body, true);
  6906. $this->setAPIResponse('success', null, 200, $results);
  6907. return $results;
  6908. } else {
  6909. $this->setAPIResponse('error', 'Bad response from YouTube', 500);
  6910. return false;
  6911. }
  6912. }
  6913. public function scrapePage($array)
  6914. {
  6915. try {
  6916. $url = $array['url'] ?? false;
  6917. $type = $array['type'] ?? false;
  6918. if (!$url) {
  6919. $this->setAPIResponse('error', 'URL was not supplied', 422);
  6920. return false;
  6921. }
  6922. $url = $this->qualifyURL($url);
  6923. $data = array(
  6924. 'full_url' => $url,
  6925. 'drill_url' => $this->qualifyURL($url, true)
  6926. );
  6927. $options = array('verify' => false);
  6928. $response = Requests::get($url, array(), $options);
  6929. $data['response_code'] = $response->status_code;
  6930. if ($response->success) {
  6931. $data['result'] = 'Success';
  6932. switch ($type) {
  6933. case 'html':
  6934. $data['data'] = html_entity_decode($response->body);
  6935. break;
  6936. case 'json':
  6937. $data['data'] = json_decode($response->body);
  6938. break;
  6939. default:
  6940. $data['data'] = $response->body;
  6941. }
  6942. $this->setAPIResponse('success', null, 200, $data);
  6943. return $data;
  6944. } else {
  6945. $this->setAPIResponse('error', 'Error getting successful response', 500);
  6946. return false;
  6947. }
  6948. } catch (Requests_Exception $e) {
  6949. $this->setResponse(500, $e->getMessage());
  6950. return false;
  6951. }
  6952. }
  6953. public function chooseInstance($url = null, $token = null, $instance = 0, $type = null)
  6954. {
  6955. if (!$url || !$token) {
  6956. return false;
  6957. }
  6958. $list = $this->csvHomepageUrlToken($url, $token);
  6959. if ($type) {
  6960. $type = strtolower($type);
  6961. switch ($type) {
  6962. case 'url':
  6963. case 'token':
  6964. break;
  6965. default:
  6966. $type = 'url';
  6967. break;
  6968. }
  6969. if (is_numeric($instance)) {
  6970. return $list[$instance][$type];
  6971. } else {
  6972. return $list;
  6973. }
  6974. }
  6975. if (is_numeric($instance)) {
  6976. return $list[$instance];
  6977. } else {
  6978. return $list;
  6979. }
  6980. }
  6981. public function CBPFWTabs()
  6982. {
  6983. return '
  6984. <script>
  6985. /**
  6986. * cbpFWTabs.js v1.0.0
  6987. * http://www.codrops.com
  6988. *
  6989. * Licensed under the MIT license.
  6990. * http://www.opensource.org/licenses/mit-license.php
  6991. *
  6992. * Copyright 2014, Codrops
  6993. * http://www.codrops.com
  6994. */
  6995. ;( function( window ) {
  6996. \'use strict\';
  6997. function extend( a, b ) {
  6998. for( var key in b ) {
  6999. if( b.hasOwnProperty( key ) ) {
  7000. a[key] = b[key];
  7001. }
  7002. }
  7003. return a;
  7004. }
  7005. function CBPFWTabs( el, options ) {
  7006. this.el = el;
  7007. this.options = extend( {}, this.options );
  7008. extend( this.options, options );
  7009. this._init();
  7010. }
  7011. CBPFWTabs.prototype.options = {
  7012. start : 0
  7013. };
  7014. CBPFWTabs.prototype._init = function() {
  7015. // tabs elems
  7016. this.tabs = [].slice.call( this.el.querySelectorAll( \'nav > ul > li\' ) );
  7017. // content items
  7018. this.items = [].slice.call( this.el.querySelectorAll( \'.content-wrap > section\' ) );
  7019. // current index
  7020. this.current = -1;
  7021. // show current content item
  7022. try{
  7023. if(this.tabs[0].innerHTML.indexOf(\'#settings\') >= 0){
  7024. this._show(' . $this->config['defaultSettingsTab'] . ');
  7025. let tabId = $(this.items[' . $this->config['defaultSettingsTab'] . ']).attr("id") + "-anchor";
  7026. $("#" + tabId).click();
  7027. $("#" + tabId + " a").click();
  7028. }else{
  7029. this._show();
  7030. }
  7031. }catch{
  7032. this._show();
  7033. }
  7034. // init events
  7035. this._initEvents();
  7036. };
  7037. CBPFWTabs.prototype._initEvents = function() {
  7038. var self = this;
  7039. this.tabs.forEach( function( tab, idx ) {
  7040. tab.addEventListener( \'click\', function( ev ) {
  7041. ev.preventDefault();
  7042. self._show( idx );
  7043. } );
  7044. } );
  7045. };
  7046. CBPFWTabs.prototype._show = function( idx ) {
  7047. if( this.current >= 0 ) {
  7048. this.tabs[ this.current ].className = this.items[ this.current ].className = \'\';
  7049. }
  7050. // change current
  7051. this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
  7052. this.tabs[ this.current ].className = \'tab-current\';
  7053. this.items[ this.current ].className = \'content-current\';
  7054. };
  7055. // add to global namespace
  7056. window.CBPFWTabs = CBPFWTabs;
  7057. })( window );
  7058. </script>
  7059. ';
  7060. }
  7061. public function socksHeadingHTML($app)
  7062. {
  7063. return '
  7064. <h3 lang="en">' . ucwords($app) . ' SOCKS API Connection</h3>
  7065. <p>Using this feature allows you to access the API without having to reverse proxy it. Just access it from: </p>
  7066. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/socks/' . $app . '/</code>
  7067. <p>If you are using multiple URL\'s (using the csv method) you will have to use the url like these: </p>
  7068. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/1</code>
  7069. <br/>
  7070. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/2</code>
  7071. ';
  7072. }
  7073. public function socksListing($app = null)
  7074. {
  7075. switch ($app) {
  7076. case 'sonarr':
  7077. $appDetails = [
  7078. 'url' => 'sonarrURL',
  7079. 'enabled' => 'sonarrSocksEnabled',
  7080. 'auth' => 'sonarrSocksAuth',
  7081. 'header' => 'X-Api-Key'
  7082. ];
  7083. break;
  7084. case 'radarr':
  7085. $appDetails = [
  7086. 'url' => 'radarrURL',
  7087. 'enabled' => 'radarrSocksEnabled',
  7088. 'auth' => 'radarrSocksAuth',
  7089. 'header' => 'X-Api-Key'
  7090. ];
  7091. break;
  7092. case 'lidarr':
  7093. $appDetails = [
  7094. 'url' => 'lidarrURL',
  7095. 'enabled' => 'lidarrSocksEnabled',
  7096. 'auth' => 'lidarrSocksAuth',
  7097. 'header' => 'X-Api-Key'
  7098. ];
  7099. break;
  7100. case 'sabnzbd':
  7101. $appDetails = [
  7102. 'url' => 'sabnzbdURL',
  7103. 'enabled' => 'sabnzbdSocksEnabled',
  7104. 'auth' => 'sabnzbdSocksAuth',
  7105. 'header' => null
  7106. ];
  7107. break;
  7108. case 'nzbget':
  7109. $appDetails = [
  7110. 'url' => 'nzbgetURL',
  7111. 'enabled' => 'nzbgetSocksEnabled',
  7112. 'auth' => 'nzbgetSocksAuth',
  7113. 'header' => 'Authorization'
  7114. ];
  7115. break;
  7116. case 'tautulli':
  7117. $appDetails = [
  7118. 'url' => 'tautulliURL',
  7119. 'enabled' => 'tautulliSocksEnabled',
  7120. 'auth' => 'tautulliSocksAuth',
  7121. 'header' => null
  7122. ];
  7123. break;
  7124. case 'qbittorrent':
  7125. $appDetails = [
  7126. 'url' => 'qBittorrentURL',
  7127. 'enabled' => 'qBittorrentSocksEnabled',
  7128. 'auth' => 'qBittorrentSocksAuth',
  7129. 'header' => null
  7130. ];
  7131. break;
  7132. default:
  7133. $appDetails = null;
  7134. }
  7135. return $appDetails;
  7136. }
  7137. public function socks($appDetails, $requestObject, $multiple = null)
  7138. {
  7139. $url = $appDetails['url'];
  7140. $enabled = $appDetails['enabled'];
  7141. $auth = $appDetails['auth'];
  7142. $header = $appDetails['header'];
  7143. $error = false;
  7144. if (!$this->config[$enabled]) {
  7145. $error = true;
  7146. $this->setAPIResponse('error', 'SOCKS module is not enabled', 409);
  7147. }
  7148. if (!$this->qualifyRequest($this->config[$auth], true)) {
  7149. $error = true;
  7150. }
  7151. if (strpos($this->config[$url], ',') !== false) {
  7152. if (!$multiple) {
  7153. $error = true;
  7154. $this->setAPIResponse('error', 'Multiple URLs found in field, please use /api/v2/multiple/socks endpoint', 409);
  7155. }
  7156. } else {
  7157. if ($multiple) {
  7158. $error = true;
  7159. $this->setAPIResponse('error', 'Multiple endpoint accessed but multiple URLs not found in field, please use /api/v2/socks endpoint', 409);
  7160. }
  7161. }
  7162. if (!$error) {
  7163. if ($multiple) {
  7164. $instance = $multiple - 1;
  7165. $pre = explode('/api/v2/multiple/socks/', $requestObject->getUri()->getPath());
  7166. $pre[1] = $this->replace_first('/' . $multiple . '/', '/', $pre[1]);
  7167. // sent url twice since we arent using tokens
  7168. $list = $this->csvHomepageUrlToken($this->config[$url], $this->config[$url]);
  7169. $appURL = $list[$instance]['url'];
  7170. } else {
  7171. $pre = explode('/api/v2/socks/', $requestObject->getUri()->getPath());
  7172. $appURL = $this->config[$url];
  7173. }
  7174. $endpoint = explode('/', $pre[1]);
  7175. $new = urldecode(preg_replace('/' . $endpoint[0] . '/', '', $pre[1], 1));
  7176. $getParams = ($_GET) ? '?' . http_build_query($_GET) : '';
  7177. $url = $this->qualifyURL($appURL) . $new . $getParams;
  7178. $url = $this->cleanPath($url);
  7179. $options = ($this->localURL($appURL)) ? array('verify' => false, 'timeout' => 120) : array('timeout' => 120);
  7180. $headers = [];
  7181. $apiData = $this->apiData($requestObject, false);
  7182. if ($header) {
  7183. if ($requestObject->hasHeader($header)) {
  7184. $headerKey = $requestObject->getHeaderLine($header);
  7185. $headers[$header] = $headerKey;
  7186. }
  7187. }
  7188. if ($requestObject->hasHeader('Content-Type')) {
  7189. $headerKey = $requestObject->getHeaderLine('Content-Type');
  7190. $headers['Content-Type'] = $headerKey;
  7191. }
  7192. $debugInformation = [
  7193. 'type' => $requestObject->getMethod(),
  7194. 'headerType' => $requestObject->getHeaderLine('Content-Type'),
  7195. 'header' => $header,
  7196. 'headers' => $headers,
  7197. 'url' => $url,
  7198. 'options' => $options,
  7199. 'data' => $apiData,
  7200. ];
  7201. $this->setLoggerChannel('Socks');
  7202. $this->logger->debug('Sending Socks request', $debugInformation);
  7203. try {
  7204. switch ($requestObject->getMethod()) {
  7205. case 'GET':
  7206. $call = Requests::get($url, $headers, $options);
  7207. break;
  7208. case 'POST':
  7209. $call = Requests::post($url, $headers, $apiData, $options);
  7210. break;
  7211. case 'DELETE':
  7212. $call = Requests::delete($url, $headers, $options);
  7213. break;
  7214. case 'PUT':
  7215. $call = Requests::put($url, $headers, $apiData, $options);
  7216. break;
  7217. default:
  7218. $call = Requests::get($url, $headers, $options);
  7219. }
  7220. $this->logger->debug('Socks Response', $this->json_validator($call->body) ? json_decode($call->body, true) : $call->body);
  7221. return $call->body;
  7222. } catch (Requests_Exception $e) {
  7223. $this->setResponse(500, $e->getMessage());
  7224. $this->setLoggerChannel('Socks');
  7225. $this->logger->critical($e, $debugInformation);
  7226. return null;
  7227. }
  7228. } else {
  7229. return null;
  7230. }
  7231. }
  7232. public function getPlexServers()
  7233. {
  7234. if ($this->config['plexToken'] == '') {
  7235. $this->setAPIResponse('error', 'Plex Token cannot be empty', 422);
  7236. return false;
  7237. }
  7238. $ownedOnly = isset($_GET['owned']) ?? false;
  7239. $url = $this->qualifyURL('https://plex.tv/pms/servers');
  7240. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  7241. $headers = [
  7242. 'X-Plex-Product' => 'Organizr',
  7243. 'X-Plex-Version' => '2.0',
  7244. 'X-Plex-Client-Identifier' => '01010101-10101010',
  7245. 'X-Plex-Token' => $this->config['plexToken'],
  7246. ];
  7247. try {
  7248. $response = Requests::get($url, $headers, $options);
  7249. libxml_use_internal_errors(true);
  7250. if ($response->success) {
  7251. $items = array();
  7252. $plex = simplexml_load_string($response->body);
  7253. foreach ($plex as $server) {
  7254. if ($ownedOnly) {
  7255. if ($server['owned'] == 1) {
  7256. $items[] = array(
  7257. 'name' => (string)$server['name'],
  7258. 'address' => (string)$server['address'],
  7259. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7260. 'owned' => (float)$server['owned'],
  7261. );
  7262. }
  7263. } else {
  7264. $items[] = array(
  7265. 'name' => (string)$server['name'],
  7266. 'address' => (string)$server['address'],
  7267. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7268. 'owned' => (float)$server['owned'],
  7269. );
  7270. }
  7271. }
  7272. $this->setResponse(200, null, $items);
  7273. return $items;
  7274. } else {
  7275. $message = $this->testAndFormatString($response->body);
  7276. $this->setResponse(500, 'Plex Error occurred', $message['data']);
  7277. $this->setLoggerChannel('Plex Connection')->warning('Plex Error', $message);
  7278. return $message;
  7279. }
  7280. } catch (Requests_Exception $e) {
  7281. $this->setLoggerChannel('Plex Connection')->error($e);
  7282. $this->setResponse(500, $e->getMessage());
  7283. return false;
  7284. }
  7285. }
  7286. public function getIcons()
  7287. {
  7288. $term = $_GET['search'] ?? null;
  7289. $page = $_GET['page'] ?? 1;
  7290. $limit = $_GET['limit'] ?? 20;
  7291. $offset = ($page * $limit) - $limit;
  7292. $goodIcons['results'] = [];
  7293. $goodIcons['limit'] = $limit;
  7294. $goodIcons['page'] = $page;
  7295. $goodIcons['term'] = $term;
  7296. $allIcons = file_get_contents($this->root . '/js/icons.json');
  7297. $iconListing = json_decode($allIcons, true);
  7298. foreach ($iconListing as $setKey => $set) {
  7299. foreach ($set['children'] as $k => $v) {
  7300. if ($term) {
  7301. if (stripos($v['text'], $term) !== false) {
  7302. $goodIcons['results'][] = $v;
  7303. }
  7304. } else {
  7305. $goodIcons['results'][] = $v;
  7306. }
  7307. }
  7308. }
  7309. $total = count($goodIcons['results']);
  7310. $goodIcons['total'] = $total;
  7311. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  7312. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  7313. return $goodIcons;
  7314. }
  7315. public function getJournalMode()
  7316. {
  7317. $response = [
  7318. array(
  7319. 'function' => 'fetch',
  7320. 'query' => 'PRAGMA journal_mode',
  7321. ),
  7322. ];
  7323. $query = $this->processQueries($response);
  7324. if ($query) {
  7325. if ($query['journal_mode']) {
  7326. $this->setResponse(200, null, $query);
  7327. } else {
  7328. $this->setResponse(500, 'Error getting Journal Mode');
  7329. }
  7330. } else {
  7331. $this->setResponse(404, 'Journal Mode not found');
  7332. }
  7333. return $query;
  7334. }
  7335. public function setJournalMode($option = 'WAL')
  7336. {
  7337. $option = strtoupper($option);
  7338. switch ($option) {
  7339. case 'WAL':
  7340. case 'DELETE':
  7341. break;
  7342. default:
  7343. return false;
  7344. }
  7345. $response = [
  7346. array(
  7347. 'function' => 'fetch',
  7348. 'query' => 'PRAGMA journal_mode = \'' . $option . '\';',
  7349. ),
  7350. ];
  7351. $query = $this->processQueries($response);
  7352. if ($query) {
  7353. if ($query['journal_mode']) {
  7354. $this->setResponse(200, 'Journal Mode updated to: ' . $option, $query);
  7355. } else {
  7356. $this->setResponse(500, 'Error getting Journal Mode');
  7357. }
  7358. } else {
  7359. $this->setResponse(404, 'Journal Mode not found');
  7360. }
  7361. return $query;
  7362. }
  7363. public function testCronSchedule($schedule = null)
  7364. {
  7365. if (is_array($schedule)) {
  7366. $schedule = str_replace('_', ' ', array_keys($schedule)[0]);
  7367. }
  7368. if (!$schedule) {
  7369. $this->setResponse(409, 'Schedule was not supplied');
  7370. return false;
  7371. }
  7372. try {
  7373. $schedule = new Cron\CronExpression($schedule);
  7374. $this->setResponse(200, 'Schedule was validated');
  7375. return true;
  7376. } catch (InvalidArgumentException $e) {
  7377. $this->setResponse(500, $e->getMessage());
  7378. return false;
  7379. }
  7380. }
  7381. public function testFolder($folder = null)
  7382. {
  7383. $folder = $folder['folder'] ?? null;
  7384. if (!$folder) {
  7385. $this->setResponse(409, 'Folder was not supplied');
  7386. return false;
  7387. }
  7388. $testFolder = $this->makeDir($folder);
  7389. if ($testFolder) {
  7390. $this->setResponse(200, 'Folder approved for logs');
  7391. return true;
  7392. } else {
  7393. $this->setResponse(409, 'Folder path is not valid or permissions insufficient');
  7394. return false;
  7395. }
  7396. }
  7397. public function replaceStringInDatabase($string)
  7398. {
  7399. $databaseStringList = [
  7400. 'AUTOINCREMENT' => [
  7401. 'sqlite3' => 'AUTOINCREMENT',
  7402. 'mysqli' => 'AUTO_INCREMENT',
  7403. 'postgre' => 'AUTOINCREMENT'
  7404. ],
  7405. 'COLLATE NOCASE' => [
  7406. 'sqlite3' => 'COLLATE NOCASE',
  7407. 'mysqli' => '',
  7408. 'postgre' => ''
  7409. ],
  7410. 'INTEGER PRIMARY KEY AUTOINCREMENT' => [
  7411. 'sqlite3' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7412. 'mysqli' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7413. 'postgre' => 'SERIAL PRIMARY KEY'
  7414. ],
  7415. 'DATETIME' => [
  7416. 'sqlite3' => 'DATETIME',
  7417. 'mysqli' => 'DATETIME',
  7418. 'postgre' => 'TIMESTAMP'
  7419. ],
  7420. ];
  7421. if (gettype($string) == 'string') {
  7422. foreach ($databaseStringList as $item => $value) {
  7423. if (stripos($string, $item) !== false) {
  7424. $string = str_ireplace($item, $databaseStringList[$item][$this->config['driver']], $string);
  7425. }
  7426. }
  7427. }
  7428. return $string;
  7429. }
  7430. public function cleanDatabaseQuery($query)
  7431. {
  7432. if (is_array($query)) {
  7433. foreach ($query as $key => $value) {
  7434. $query[$key] = $this->cleanDatabaseQuery($value);
  7435. }
  7436. return $query;
  7437. } else {
  7438. return $this->replaceStringInDatabase($query);
  7439. }
  7440. }
  7441. protected function processQueries(array $request, $migration = false)
  7442. {
  7443. $results = array();
  7444. $firstKey = '';
  7445. if ($this->config['includeDatabaseQueriesInDebug']) {
  7446. $this->setLoggerChannel('Database');
  7447. $this->logger->debug('Query to database', $request);
  7448. }
  7449. foreach ($request as $k => $v) {
  7450. try {
  7451. $v['query'] = $this->cleanDatabaseQuery($v['query']);
  7452. $query = ($migration) ? $this->otherDb->query($v['query']) : $this->db->query($v['query']);
  7453. $keyName = (isset($v['key'])) ? $v['key'] : $k;
  7454. $firstKey = (isset($v['key']) && $k == 0) ? $v['key'] : $k;
  7455. switch ($v['function']) {
  7456. case 'fetchAll':
  7457. $results[$keyName] = $query->fetchAll();
  7458. break;
  7459. case 'fetch':
  7460. // PHP 8 Fix?
  7461. $query->setRowClass(null);
  7462. $results[$keyName] = $query->fetch();
  7463. break;
  7464. case 'getAffectedRows':
  7465. $results[$keyName] = $query->getAffectedRows();
  7466. break;
  7467. case 'getRowCount':
  7468. $results[$keyName] = $query->getRowCount();
  7469. break;
  7470. case 'fetchSingle':
  7471. // PHP 8 Fix?
  7472. $query->setRowClass(null);
  7473. $results[$keyName] = $query->fetchSingle();
  7474. break;
  7475. case 'query':
  7476. $results[$keyName] = $query;
  7477. break;
  7478. default:
  7479. return false;
  7480. }
  7481. } catch (Exception $e) {
  7482. $this->setLoggerChannel('Database');
  7483. $this->logger->critical($e, $v['query']);
  7484. return false;
  7485. }
  7486. }
  7487. if ($this->config['includeDatabaseQueriesInDebug']) {
  7488. $this->logger->debug('Results from database', $results);
  7489. }
  7490. return count($request) > 1 ? $results : $results[$firstKey];
  7491. }
  7492. }