organizr.class.php 207 KB

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