organizr.class.php 237 KB

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