organizr.class.php 254 KB

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