organizr.class.php 191 KB

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