organizr.class.php 240 KB

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