organizr.class.php 205 KB

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