organizr.class.php 246 KB

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