organizr.class.php 246 KB

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