organizr.class.php 250 KB

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