organizr.class.php 264 KB

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