organizr.class.php 255 KB

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