4
0

organizr.class.php 218 KB

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