organizr.class.php 240 KB

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