4
0

organizr.class.php 213 KB

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