organizr.class.php 253 KB

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