organizr.class.php 256 KB

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