organizr.class.php 214 KB

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