organizr.class.php 208 KB

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