organizr.class.php 246 KB

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