organizr.class.php 251 KB

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