organizr.class.php 244 KB

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