organizr.class.php 250 KB

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