organizr.class.php 243 KB

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