organizr.class.php 248 KB

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