organizr.class.php 264 KB

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