organizr.class.php 204 KB

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