organizr.class.php 241 KB

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