4
0

organizr.class.php 236 KB

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