organizr.class.php 253 KB

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