organizr.class.php 256 KB

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