organizr.class.php 237 KB

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