organizr.class.php 236 KB

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