organizr.class.php 214 KB

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