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