organizr.class.php 249 KB

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