organizr.class.php 213 KB

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