organizr.class.php 255 KB

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