organizr.class.php 254 KB

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