organizr.class.php 209 KB

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