organizr.class.php 250 KB

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