organizr.class.php 245 KB

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