organizr.class.php 214 KB

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