organizr.class.php 246 KB

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