organizr.class.php 214 KB

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