4
0

organizr.class.php 267 KB

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