organizr.class.php 248 KB

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