organizr.class.php 216 KB

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