organizr.class.php 255 KB

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