organizr.class.php 246 KB

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