organizr.class.php 179 KB

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