organizr.class.php 214 KB

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