organizr.class.php 248 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718
  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 qualifyLength($string, $length = 100, $api = false)
  1816. {
  1817. if (strlen($string) <= $length) {
  1818. return true;
  1819. } else {
  1820. if ($api) {
  1821. $this->setResponse(409, 'String is over limit of: ' . $length);
  1822. }
  1823. return false;
  1824. }
  1825. }
  1826. public function getImages()
  1827. {
  1828. $allIconsPrep = array();
  1829. $allIcons = array();
  1830. $ignore = array(".", "..", "._.DS_Store", ".DS_Store", ".pydio_id", "index.html");
  1831. $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'tabs' . DIRECTORY_SEPARATOR;
  1832. $path = 'plugins/images/tabs/';
  1833. $images = scandir($dirname);
  1834. foreach ($images as $image) {
  1835. if (!in_array($image, $ignore)) {
  1836. $allIconsPrep[$image] = array(
  1837. 'path' => $path,
  1838. 'name' => $image
  1839. );
  1840. }
  1841. }
  1842. $dirname = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1843. $path = 'data/userTabs/';
  1844. if (file_exists($dirname)) {
  1845. $images = scandir($dirname);
  1846. foreach ($images as $image) {
  1847. if (!in_array($image, $ignore)) {
  1848. $allIconsPrep[$image] = array(
  1849. 'path' => $path,
  1850. 'name' => $image
  1851. );
  1852. }
  1853. }
  1854. }
  1855. uksort($allIconsPrep, 'strcasecmp');
  1856. foreach ($allIconsPrep as $item) {
  1857. $allIcons[] = $item['path'] . $item['name'];
  1858. }
  1859. return $allIcons;
  1860. }
  1861. public function getImagesSelect()
  1862. {
  1863. $term = $_GET['search'] ?? null;
  1864. $page = $_GET['page'] ?? 1;
  1865. $limit = $_GET['limit'] ?? 20;
  1866. $offset = ($page * $limit) - $limit;
  1867. $goodIcons['results'] = [];
  1868. $goodIcons['limit'] = $limit;
  1869. $goodIcons['page'] = $page;
  1870. $goodIcons['term'] = $term;
  1871. $imageListing = $this->getImages();
  1872. $newImageListing = [];
  1873. foreach ($imageListing as $image) {
  1874. $newImageListing[] = [
  1875. 'id' => $image,
  1876. 'text' => basename($image)
  1877. ];
  1878. }
  1879. foreach ($newImageListing as $k => $v) {
  1880. if ($term) {
  1881. if (stripos($v['text'], $term) !== false) {
  1882. $goodIcons['results'][] = $v;
  1883. }
  1884. } else {
  1885. $goodIcons['results'][] = $v;
  1886. }
  1887. }
  1888. $total = count($goodIcons['results']);
  1889. $goodIcons['total'] = $total;
  1890. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  1891. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  1892. return $goodIcons;
  1893. }
  1894. public function removeImage($image = null)
  1895. {
  1896. if (!$image) {
  1897. $this->setAPIResponse('error', 'No image supplied', 422);
  1898. return false;
  1899. }
  1900. $approvedPath = 'data/userTabs/';
  1901. $removeImage = $approvedPath . pathinfo($image, PATHINFO_BASENAME);
  1902. if ($this->approvedFileExtension($removeImage, 'image')) {
  1903. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage)) {
  1904. $this->setLoggerChannel('Image Manager');
  1905. $this->logger->info('Image Manager Function - Deleted Image [' . pathinfo($image, PATHINFO_BASENAME) . ']');
  1906. $this->setAPIResponse(null, pathinfo($image, PATHINFO_BASENAME) . ' has been deleted', null);
  1907. return (unlink(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . $removeImage));
  1908. } else {
  1909. $this->setAPIResponse('error', $removeImage . ' does not exist', 404);
  1910. return false;
  1911. }
  1912. } else {
  1913. $this->setAPIResponse('error', $removeImage . ' is not approved to be deleted', 409);
  1914. return false;
  1915. }
  1916. }
  1917. public function uploadImage()
  1918. {
  1919. $filesCheck = array_filter($_FILES);
  1920. if (!empty($filesCheck)) {
  1921. if (strpos($_FILES['file']['type'], 'image/') === false) {
  1922. $this->setResponse(403, 'File Type not approved', $_FILES['file']['type']);
  1923. return false;
  1924. }
  1925. if (!$this->approvedFileType($_FILES['file']['tmp_name'])) {
  1926. $this->setResponse(403, 'File Type not approved', $_FILES['file']['tmp_name']);
  1927. return false;
  1928. }
  1929. if ($this->approvedFileExtension($_FILES['file']['name'])) {
  1930. ini_set('upload_max_filesize', '10M');
  1931. ini_set('post_max_size', '10M');
  1932. $tempFile = $_FILES['file']['tmp_name'];
  1933. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1934. $this->makeDir($targetPath);
  1935. $targetFile = $targetPath . $this->sanitizeUserString($_FILES['file']['name']);
  1936. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  1937. return move_uploaded_file($tempFile, $targetFile);
  1938. } else {
  1939. $this->setResponse(403, 'File Extension not approved');
  1940. return false;
  1941. }
  1942. } else {
  1943. $this->setResponse(500, 'No File was uploaded');
  1944. return false;
  1945. }
  1946. }
  1947. public function formatPingHost($host)
  1948. {
  1949. $host = $this->qualifyURL($host, true);
  1950. if ($host['port'] !== '') {
  1951. $host['port'] = str_replace(':', '', $host['port']);
  1952. }
  1953. if ($host['host'] == '' && $host['path'] !== '') {
  1954. $host['host'] = $host['path'];
  1955. $host['path'] = '';
  1956. if (strpos($host['host'], '/') !== false) {
  1957. $host['host'] = explode('/', $host['host'])[0];
  1958. }
  1959. }
  1960. return $host;
  1961. }
  1962. public function ping($pings)
  1963. {
  1964. if ($this->qualifyRequest($this->config['pingAuth'], true)) {
  1965. if (!$pings['list']) {
  1966. $this->setAPIResponse('error', 'No ping hostname/IP\'s entered', 409);
  1967. return null;
  1968. }
  1969. $pings = $pings['list'];
  1970. $type = gettype($pings);
  1971. $ping = new Ping("");
  1972. $ping->setTtl(128);
  1973. $ping->setTimeout(2);
  1974. switch ($type) {
  1975. case "array":
  1976. $results = [];
  1977. foreach ($pings as $k => $v) {
  1978. $pingFormatted = $this->formatPingHost($v);
  1979. $ping->setHost($pingFormatted['host']);
  1980. if ($pingFormatted['port'] !== '') {
  1981. $ping->setPort($pingFormatted['port']);
  1982. $latency = $ping->ping('fsockopen');
  1983. } else {
  1984. $latency = $ping->ping();
  1985. }
  1986. if ($latency || $latency === 0) {
  1987. $results[$v] = $latency;
  1988. } else {
  1989. $results[$v] = false;
  1990. }
  1991. }
  1992. break;
  1993. case "string":
  1994. $pingFormatted = $this->formatPingHost($pings);
  1995. $ping->setHost($pingFormatted['host']);
  1996. if ($pingFormatted['port'] !== '') {
  1997. $ping->setPort($pingFormatted['port']);
  1998. $latency = $ping->ping('fsockopen');
  1999. } else {
  2000. $latency = $ping->ping();
  2001. }
  2002. if ($latency || $latency === 0) {
  2003. $results = $latency;
  2004. } else {
  2005. $results = null;
  2006. }
  2007. break;
  2008. }
  2009. return ($results) ?? null;
  2010. }
  2011. return null;
  2012. }
  2013. public function getPluginSettings()
  2014. {
  2015. return [
  2016. 'Marketplace' => [
  2017. $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.']),
  2018. $this->settingsOption('multiple-url', 'externalPluginMarketplaceRepos', ['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', 'checkForPluginUpdate', ['label' => 'Check for Plugin Updates', ['help' => 'Check for updates on page load']])
  2021. ]
  2022. ];
  2023. }
  2024. public function getThemeSettings()
  2025. {
  2026. return [
  2027. 'Marketplace' => [
  2028. $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.']),
  2029. $this->settingsOption('multiple-url', 'externalThemeMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  2030. $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']),
  2031. $this->settingsOption('switch', 'checkForThemeUpdate', ['label' => 'Check for Theme Updates', ['help' => 'Check for updates on page load']])
  2032. ]
  2033. ];
  2034. }
  2035. public function getCustomizeAppearance()
  2036. {
  2037. return [
  2038. 'Top Bar' => [
  2039. $this->settingsOption('input', 'logo', ['label' => 'Logo URL']),
  2040. $this->settingsOption('input', 'title', ['label' => 'Organizr Title']),
  2041. $this->settingsOption('switch', 'useLogo', ['label' => 'Use Logo instead of Title', 'help' => 'Also sets the title of your site']),
  2042. $this->settingsOption('input', 'description', ['label' => 'Meta Description', 'help' => 'Used to set the description for SEO meta tags']),
  2043. ],
  2044. 'Side Menu' => [
  2045. $this->settingsOption('switch', 'allowCollapsableSideMenu', ['label' => 'Allow Side Menu to be Collapsable']),
  2046. $this->settingsOption('switch', 'sideMenuCollapsed', ['label' => 'Side Menu Collapsed at Launch']),
  2047. $this->settingsOption('switch', 'collapseSideMenuOnClick', ['label' => 'Collapse Side Menu after clicking Tab']),
  2048. $this->settingsOption('switch', 'githubMenuLink', ['label' => 'Show GitHub Repo Link']),
  2049. $this->settingsOption('switch', 'organizrFeatureRequestLink', ['label' => 'Show Organizr Feature Request Link']),
  2050. $this->settingsOption('switch', 'organizrSupportMenuLink', ['label' => 'Show Organizr Support Link']),
  2051. $this->settingsOption('switch', 'organizrDocsMenuLink', ['label' => 'Show Organizr Docs Link']),
  2052. $this->settingsOption('switch', 'organizrSignoutMenuLink', ['label' => 'Show Organizr Sign out & in Button on Sidebar']),
  2053. $this->settingsOption('switch', 'expandCategoriesByDefault', ['label' => 'Expand All Categories']),
  2054. $this->settingsOption('switch', 'autoCollapseCategories', ['label' => 'Auto-Collapse Categories']),
  2055. $this->settingsOption('switch', 'autoExpandNavBar', ['label' => 'Auto-Expand Nav Bar']),
  2056. $this->settingsOption('select', 'unsortedTabs', ['label' => 'Unsorted Tab Placement', 'options' => [['name' => 'Top', 'value' => 'top'], ['name' => 'Bottom', 'value' => 'bottom']]]),
  2057. ],
  2058. 'Login Page' => [
  2059. $this->settingsOption('input', 'loginLogo', ['label' => 'Login Logo URL']),
  2060. $this->settingsOption('multiple-url', 'loginWallpaper', ['label' => 'Login Wallpaper URL', 'help' => 'You may enter multiple URL\'s']),
  2061. $this->settingsOption('switch', 'useLogoLogin', ['label' => 'Use Logo instead of Title on Login Page']),
  2062. $this->settingsOption('switch', 'minimalLoginScreen', ['label' => 'Minimal Login Screen']),
  2063. $this->settingsOption('switch', 'useRandomMediaImage', ['label' => 'Use Random Media Wallpaper From Media Server']),
  2064. ],
  2065. 'Options' => [
  2066. $this->settingsOption('switch', 'alternateHomepageHeaders', ['label' => 'Alternate Homepage Titles']),
  2067. $this->settingsOption('switch', 'debugErrors', ['label' => 'Show Debug Errors']),
  2068. $this->settingsOption('switch', 'easterEggs', ['label' => 'Show Easter Eggs']),
  2069. $this->settingsOption('input', 'gaTrackingID', ['label' => 'Google Analytics Tracking ID', 'placeholder' => 'e.g. UA-XXXXXXXXX-X']),
  2070. ],
  2071. 'Colors & Themes' => [
  2072. $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>']),
  2073. $this->settingsOption('blank'),
  2074. $this->settingsOption('button', '', ['label' => 'Reset Colors', 'icon' => 'fa fa-ticket', 'text' => 'Reset', 'attr' => 'onclick="resetCustomColors()"']),
  2075. $this->settingsOption('blank'),
  2076. $this->settingsOption('color', 'headerColor', ['label' => 'Nav Bar Color']),
  2077. $this->settingsOption('color', 'headerTextColor', ['label' => 'Nav Bar Text Color']),
  2078. $this->settingsOption('color', 'sidebarColor', ['label' => 'Side Bar Color']),
  2079. $this->settingsOption('color', 'sidebarTextColor', ['label' => 'Side Bar Text Color']),
  2080. $this->settingsOption('color', 'accentColor', ['label' => 'Accent Color']),
  2081. $this->settingsOption('color', 'accentTextColor', ['label' => 'Accent Text Color']),
  2082. $this->settingsOption('color', 'buttonColor', ['label' => 'Button Color']),
  2083. $this->settingsOption('color', 'buttonTextColor', ['label' => 'Button Text Color']),
  2084. $this->settingsOption('select', 'theme', ['label' => 'Theme', 'class' => 'themeChanger', 'options' => $this->getAllThemes()]),
  2085. $this->settingsOption('select', 'style', ['label' => 'Style', 'class' => 'styleChanger', 'options' => [['name' => 'Light', 'value' => 'light'], ['name' => 'Dark', 'value' => 'dark'], ['name' => 'Horizontal', 'value' => 'horizontal']]]),
  2086. ],
  2087. 'Notifications' => [
  2088. $this->settingsOption('select', 'notificationBackbone', ['label' => 'Type', 'class' => 'notifyChanger', 'options' => $this->notificationTypesOptions()]),
  2089. $this->settingsOption('select', 'notificationPosition', ['label' => 'Position', 'class' => 'notifyPositionChanger', 'options' => $this->notificationPositionsOptions()]),
  2090. $this->settingsOption('html', null, ['label' => 'Test Message', 'html' => '
  2091. <div class="btn-group m-r-10 dropup">
  2092. <button aria-expanded="false" data-toggle="dropdown" class="btn btn-info btn-outline dropdown-toggle waves-effect waves-light" type="button">
  2093. <i class="fa fa-comment m-r-5"></i>
  2094. <span>Test </span>
  2095. </button>
  2096. <ul role="menu" class="dropdown-menu">
  2097. <li><a onclick="message(\'Test Message\',\'This is a success Message\',activeInfo.settings.notifications.position,\'#FFF\',\'success\',\'5000\');">Success</a></li>
  2098. <li><a onclick="message(\'Test Message\',\'This is a info Message\',activeInfo.settings.notifications.position,\'#FFF\',\'info\',\'5000\');">Info</a></li>
  2099. <li><a onclick="message(\'Test Message\',\'This is a warning Message\',activeInfo.settings.notifications.position,\'#FFF\',\'warning\',\'5000\');">Warning</a></li>
  2100. <li><a onclick="message(\'Test Message\',\'This is a error Message\',activeInfo.settings.notifications.position,\'#FFF\',\'error\',\'5000\');">Error</a></li>
  2101. </ul>
  2102. </div>
  2103. ']
  2104. ),
  2105. ],
  2106. 'FavIcon' => [
  2107. $this->settingsOption('html', null, ['label' => 'Instructions', 'override' => 12, 'html' => '
  2108. <div class="panel panel-default">
  2109. <div class="panel-heading">
  2110. <a href="https://realfavicongenerator.net/" target="_blank"><span class="label label-info m-l-5">Visit FavIcon Site</span></a>
  2111. </div>
  2112. <div class="panel-wrapper collapse in">
  2113. <div class="panel-body">
  2114. <ul class="list-icons">
  2115. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Select your Favicon picture]</li>
  2116. <li lang="en"><i class="fa fa-caret-right text-info"></i> Choose your image to use</li>
  2117. <li lang="en"><i class="fa fa-caret-right text-info"></i> Edit settings to your liking</li>
  2118. <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>
  2119. <li lang="en"><i class="fa fa-caret-right text-info"></i> Enter this path <code>data/favicon</code></li>
  2120. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Generate your Favicons and HTML code]</li>
  2121. <li lang="en"><i class="fa fa-caret-right text-info"></i> Download and unzip file and place in <code>data/favicon</code></li>
  2122. <li lang="en"><i class="fa fa-caret-right text-info"></i> Copy code and paste inside left box</li>
  2123. </ul>
  2124. </div>
  2125. </div>
  2126. </div>
  2127. ']
  2128. ),
  2129. $this->settingsOption('code-editor', 'favIcon', ['label' => 'Fav Icon Code', 'mode' => 'html']),
  2130. ],
  2131. 'Custom CSS' => [
  2132. $this->settingsOption('code-editor', 'customCss', ['label' => 'Custom CSS', 'mode' => 'css']),
  2133. ],
  2134. 'Theme CSS' => [
  2135. $this->settingsOption('code-editor', 'customThemeCss', ['label' => 'Theme CSS', 'mode' => 'css']),
  2136. ],
  2137. 'Custom Javascript' => [
  2138. $this->settingsOption('code-editor', 'customJava', ['label' => 'Custom Javascript', 'mode' => 'javascript']),
  2139. ],
  2140. 'Theme Javascript' => [
  2141. $this->settingsOption('code-editor', 'customThemeJava', ['label' => 'Theme Javascript', 'mode' => 'javascript']),
  2142. ],
  2143. ];
  2144. }
  2145. public function loadAppearance()
  2146. {
  2147. $appearance['logo'] = $this->config['logo'];
  2148. $appearance['title'] = $this->config['title'];
  2149. $appearance['useLogo'] = $this->config['useLogo'];
  2150. $appearance['useLogoLogin'] = $this->config['useLogoLogin'];
  2151. $appearance['headerColor'] = $this->config['headerColor'];
  2152. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2153. $appearance['sidebarColor'] = $this->config['sidebarColor'];
  2154. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2155. $appearance['sidebarTextColor'] = $this->config['sidebarTextColor'];
  2156. $appearance['accentColor'] = $this->config['accentColor'];
  2157. $appearance['accentTextColor'] = $this->config['accentTextColor'];
  2158. $appearance['buttonColor'] = $this->config['buttonColor'];
  2159. $appearance['buttonTextColor'] = $this->config['buttonTextColor'];
  2160. $appearance['buttonTextHoverColor'] = $this->config['buttonTextHoverColor'];
  2161. $appearance['buttonHoverColor'] = $this->config['buttonHoverColor'];
  2162. $appearance['loginWallpaper'] = $this->config['loginWallpaper'];
  2163. $appearance['randomMediaImage'] = $this->getRandomMediaImage('np');
  2164. $appearance['loginLogo'] = $this->config['loginLogo'];
  2165. $appearance['customCss'] = $this->config['customCss'];
  2166. $appearance['customThemeCss'] = $this->config['customThemeCss'];
  2167. $appearance['customJava'] = $this->config['customJava'];
  2168. $appearance['customThemeJava'] = $this->config['customThemeJava'];
  2169. return $appearance;
  2170. }
  2171. public function getRandomMediaImage($type = null)
  2172. {
  2173. if (!$this->config['useRandomMediaImage']) {
  2174. return false;
  2175. }
  2176. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache')) {
  2177. $folder = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache';
  2178. try {
  2179. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  2180. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  2181. $image = null;
  2182. switch ($type) {
  2183. case 'np':
  2184. $i = 0;
  2185. $array = iterator_to_array($iteratorIterator);
  2186. if (count($array) > 0) {
  2187. shuffle($array);
  2188. $iteratorIterator = new ArrayIterator($array);
  2189. }
  2190. foreach ($iteratorIterator as $info) {
  2191. if (stripos($info->getFilename(), 'np') !== false) {
  2192. if ($i < 1) {
  2193. $imageInfo = getimagesize($folder . DIRECTORY_SEPARATOR . $info->getFilename());
  2194. if ($imageInfo[0] >= $this->getCacheImageSize('npw')) {
  2195. $image = 'data/cache/' . $info->getFilename();
  2196. $i++;
  2197. }
  2198. } else {
  2199. break;
  2200. }
  2201. }
  2202. }
  2203. return $image;
  2204. default:
  2205. return false;
  2206. }
  2207. } catch (Exception $e) {
  2208. return false;
  2209. }
  2210. } else {
  2211. return false;
  2212. }
  2213. }
  2214. public function getSettingsMain()
  2215. {
  2216. $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>';
  2217. $settings = [
  2218. 'Settings Page' => [
  2219. $this->settingsOption('select', 'defaultSettingsTab', ['label' => 'Default Settings Tab', 'options' => $this->getSettingsTabs(), 'help' => 'Choose which Settings Tab to be default when opening settings page']),
  2220. ],
  2221. 'Github' => [
  2222. $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']),
  2223. $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']),
  2224. ],
  2225. 'API' => [
  2226. $this->settingsOption('password-alt-copy', 'organizrAPI', ['label' => 'Organizr API']),
  2227. $this->settingsOption('button', null, ['label' => 'Generate New API Key', 'class' => 'newAPIKey', 'icon' => 'fa fa-refresh', 'text' => 'Generate']),
  2228. $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>'])
  2229. ],
  2230. 'Authentication' => [
  2231. $this->settingsOption('select', 'authType', ['id' => 'authSelect', 'label' => 'Authentication Type', 'value' => $this->config['authType'], 'options' => $this->getAuthTypes()]),
  2232. $this->settingsOption('select', 'authBackend', ['id' => 'authBackendSelect', 'label' => 'Authentication Backend', 'class' => 'backendAuth switchAuth', 'value' => $this->config['authBackend'], 'options' => $this->getAuthBackends()]),
  2233. $this->settingsOption('token', 'plexToken', ['class' => 'plexAuth switchAuth']),
  2234. $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]\')"']),
  2235. $this->settingsOption('password-alt', 'plexID', ['class' => 'plexAuth switchAuth', 'label' => 'Plex Machine', 'placeholder' => 'Use Get Plex Machine Button']),
  2236. $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]\')"']),
  2237. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email', 'class' => 'plexAuth switchAuth', 'placeholder' => 'Admin username for Plex']),
  2238. $this->settingsOption('switch', 'plexoAuth', ['label' => 'Enable Plex oAuth', 'class' => 'plexAuth switchAuth']),
  2239. $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']),
  2240. $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']),
  2241. $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']),
  2242. $this->settingsOption('url', 'authBackendHost', ['class' => 'ldapAuth ftpAuth switchAuth', 'label' => 'Host Address', 'placeholder' => 'http(s) | ftp(s) | ldap(s)://hostname:port']),
  2243. $this->settingsOption('input', 'authBaseDN', ['class' => 'ldapAuth switchAuth', 'label' => 'Host Base DN', 'placeholder' => 'cn=%s,dc=sub,dc=domain,dc=com']),
  2244. $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']),
  2245. $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']),
  2246. $this->settingsOption('input', 'ldapBindUsername', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Username']),
  2247. $this->settingsOption('password', 'ldapBindPassword', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Password']),
  2248. $this->settingsOption('select', 'ldapType', ['id' => 'ldapType', 'label' => 'LDAP Backend Type', 'class' => 'ldapAuth switchAuth', 'options' => $this->getLDAPOptions()]),
  2249. $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>']),
  2250. $this->settingsOption('blank', null, ['class' => 'ldapAuth switchAuth']),
  2251. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP SSL', 'help' => 'This will enable the use of SSL for LDAP connections']),
  2252. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP TLS', 'help' => 'This will enable the use of TLS for LDAP connections']),
  2253. $this->settingsOption('test', 'ldap', ['class' => 'ldapAuth switchAuth']),
  2254. $this->settingsOption('test', '', ['label' => 'Test Login', 'class' => 'ldapAuth switchAuth', 'text' => 'Test Login', 'attr' => 'onclick="showLDAPLoginTest()"']),
  2255. $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.']),
  2256. $this->settingsOption('token', 'embyToken', ['class' => 'embyAuth switchAuth', 'label' => 'Emby Token']),
  2257. $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.']),
  2258. $this->settingsOption('token', 'jellyfinToken', ['class' => 'jellyfinAuth switchAuth', 'label' => 'Jellyfin Token']),
  2259. ],
  2260. 'Security' => [
  2261. $this->settingsOption('number', 'loginAttempts', ['label' => 'Max Login Attempts']),
  2262. $this->settingsOption('select', 'loginLockout', ['label' => 'Login Lockout Seconds', 'options' => $this->timeOptions()]),
  2263. $this->settingsOption('number', 'lockoutTimeout', ['label' => 'Inactivity Timer [Minutes]']),
  2264. $this->settingsOption('switch', 'lockoutSystem', ['label' => 'Inactivity Lock']),
  2265. $this->settingsOption('select', 'lockoutMinAuth', ['label' => 'Lockout Groups From', 'options' => $this->groupSelect()]),
  2266. $this->settingsOption('select', 'lockoutMaxAuth', ['label' => 'Lockout Groups To', 'options' => $this->groupSelect()]),
  2267. $this->settingsOption('switch', 'traefikAuthEnable', ['label' => 'Enable Traefik Auth Redirect', 'help' => 'This will enable the webserver to forward errors so traefik will accept them']),
  2268. $this->settingsOption('input', 'traefikDomainOverride', ['label' => 'Traefik Domain for Return Override', 'help' => 'Please use a FQDN on this URL Override', 'placeholder' => 'http(s)://domain']),
  2269. $this->settingsOption('select', 'debugAreaAuth', ['label' => 'Minimum Authentication for Debug Area', 'options' => $this->groupSelect(), 'settings' => '{}']),
  2270. $this->settingsOption('multiple', 'sandbox', ['override' => 12, 'label' => 'iFrame Sandbox', 'help' => 'WARNING! This can potentially mess up your iFrames', 'options' => $this->sandboxOptions()]),
  2271. $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}']),
  2272. $this->settingsOption('code-editor', 'blacklistedMessage', ['mode' => 'html']),
  2273. ],
  2274. 'Logs' => [
  2275. $this->settingsOption('folder', 'logLocation', ['label' => 'Log Save Path', 'help' => 'Folder path to save Organizr Logs - Please test before saving', 'value' => $this->logLocation()]),
  2276. $this->settingsOption('select', 'logLevel', ['label' => 'Log Level', 'options' => $this->logLevels()]),
  2277. $this->settingsOption('switch', 'includeDatabaseQueriesInDebug', ['label' => 'Include Database Queries', 'help' => 'Include Database queries in debug logs']),
  2278. $this->settingsOption('number', 'maxLogFiles', ['label' => 'Maximum Log Files', 'help' => 'Number of log files to preserve', 'attr' => 'min="1"']),
  2279. $this->settingsOption('select', 'logLiveUpdateRefresh', ['label' => 'Live Update Refresh', 'options' => $this->timeOptions()]),
  2280. $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']]]),
  2281. $this->settingsOption('switch', 'sendLogsToSlack', ['label' => 'Send Logs to Slack', 'help' => 'Send Logs to Slack as well']),
  2282. $this->settingsOption('select', 'slackLogLevel', ['label' => 'Slack Log Level', 'options' => $this->logLevels()]),
  2283. $this->settingsOption('url', 'slackLogWebhook', ['label' => 'Slack Webhook URL', 'help' => 'If using Discord make sure to end the URL with /slack']),
  2284. $this->settingsOption('input', 'slackLogWebHookChannel', ['label' => 'Slack Channel for Webhook', 'help' => 'Channel ID for webhook - Not needed for Discord']),
  2285. $this->settingsOption('blank'),
  2286. $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']),
  2287. ],
  2288. 'Cron' => [
  2289. $this->settingsOption('cron-file'),
  2290. $this->settingsOption('blank'),
  2291. $this->settingsOption('enable', 'autoUpdateCronEnabled', ['label' => 'Auto-Update Organizr']),
  2292. $this->settingsOption('cron', 'autoUpdateCronSchedule'),
  2293. ],
  2294. 'Login' => [
  2295. $this->settingsOption('password', 'registrationPassword', ['label' => 'Registration Password', 'help' => 'Sets the password for the Registration form on the login screen']),
  2296. $this->settingsOption('switch', 'hideRegistration', ['label' => 'Hide Registration', 'help' => 'Enable this to hide the Registration button on the login screen']),
  2297. $this->settingsOption('number', 'rememberMeDays', ['label' => 'Remember Me Length', 'help' => 'Number of days cookies and tokens will be valid for', 'attr' => 'min="1"']),
  2298. $this->settingsOption('switch', 'rememberMe', ['label' => 'Remember Me', 'help' => 'Default status of Remember Me button on login screen']),
  2299. $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']),
  2300. $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']),
  2301. $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']),
  2302. $this->settingsOption('switch', 'enableLocalAddressForward', ['label' => 'Enable Local Address Forward', 'help' => 'Enables the local address forward if on local address and accessed from WAN Domain']),
  2303. $this->settingsOption('switch', 'disableRecoverPass', ['label' => 'Disable Recover Password', 'help' => 'Disables recover password area']),
  2304. $this->settingsOption('input', 'customForgotPassText', ['label' => 'Custom Recover Password Text', 'help' => 'Text or HTML for recovery password section']),
  2305. ],
  2306. 'Auth Proxy' => [
  2307. $this->settingsOption('switch', 'authProxyEnabled', ['label' => 'Auth Proxy', 'help' => 'Enable option to set Auth Proxy Header Login']),
  2308. $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']),
  2309. $this->settingsOption('input', 'authProxyHeaderName', ['label' => 'Auth Proxy Header Name', 'placeholder' => 'i.e. X-Forwarded-User', 'help' => 'Please choose a unique value for added security']),
  2310. $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']),
  2311. $this->settingsOption('switch', 'authProxyOverrideLogout', ['label' => 'Override Logout', 'help' => 'Enable option to set custom Logout URL for Auth Proxy']),
  2312. $this->settingsOption('input', 'authProxyLogoutURL', ['label' => 'Logout URL', 'help' => 'Logout URL to redirect user for Auth Proxy']),
  2313. ],
  2314. 'Ping' => [
  2315. $this->settingsOption('auth', 'pingAuth'),
  2316. $this->settingsOption('auth', 'pingAuthMessage', ['label' => 'Minimum Authentication for Message and Sound']),
  2317. $this->settingsOption('select', 'pingOnlineSound', ['label' => 'Online Sound', 'options' => $this->getSounds()]),
  2318. $this->settingsOption('select', 'pingOfflineSound', ['label' => 'Offline Sound', 'options' => $this->getSounds()]),
  2319. $this->settingsOption('switch', 'pingMs', ['label' => 'Show Ping Time']),
  2320. $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.']),
  2321. $this->settingsOption('auth', 'pingAuthMs', ['label' => 'Minimum Authentication for Time Display']),
  2322. $this->settingsOption('refresh', 'adminPingRefresh', ['label' => 'Admin Refresh Seconds']),
  2323. $this->settingsOption('refresh', 'otherPingRefresh', ['label' => 'Everyone Refresh Seconds']),
  2324. ],
  2325. 'Certificate' => [
  2326. $this->settingsOption('html', '', ['override' => 12,
  2327. 'html' => '
  2328. <script>
  2329. let myDropzone = new Dropzone("#upload-custom-certificate", {
  2330. url: "api/v2/certificate/custom",
  2331. headers:{ "formKey": local("g","formKey") },
  2332. init: function() {
  2333. this.on("complete", function(file) {
  2334. if(file["status"] === "success"){
  2335. $(".custom-certificate-status").html("<span lang=\"en\">Custom Certificate Loaded</span>");
  2336. }else{
  2337. $(".custom-certificate-status").html("<span lang=\"en\">Error Saving file...</span>");
  2338. }
  2339. });
  2340. }
  2341. });
  2342. </script>
  2343. <div class="row">
  2344. <div class="col-lg-12">
  2345. <div class="panel panel-info">
  2346. <div class="panel-heading"><span lang="en">Notice</span></div>
  2347. <div class="panel-wrapper collapse in" aria-expanded="true">
  2348. <div class="panel-body">
  2349. <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>
  2350. </div>
  2351. </div>
  2352. </div>
  2353. </div>
  2354. </div>
  2355. <div class="row">
  2356. <div class="col-md-12">
  2357. <div class="white-box">
  2358. <h3 class="box-title m-b-0" lang="en">Custom Certificate Status</h3>
  2359. <p class="text-muted m-b-30 custom-certificate-status">' . $certificateStatus . '</p>
  2360. <form action="#" class="dropzone dz-clickable" id="upload-custom-certificate">
  2361. <div class="dz-default dz-message"><span lang="en">Drop Certificate file here to upload</span></div>
  2362. </form>
  2363. </div>
  2364. </div>
  2365. </div>
  2366. ']
  2367. )
  2368. ],
  2369. ];
  2370. if ($this->config['driver'] == 'sqlite3') {
  2371. $database = [
  2372. 'Database' => [
  2373. $this->settingsOption('notice', '', ['notice' => 'danger', 'title' => 'Warning', 'body' => 'This feature is experimental - You may face unexpected database is locked errors in logs']),
  2374. $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>']),
  2375. $this->settingsOption('button', '', ['label' => 'Set DELETE Mode (Default)', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'DELETE\')"']),
  2376. $this->settingsOption('button', '', ['label' => 'Set WAL Mode', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'WAL\')"']),
  2377. ]
  2378. ];
  2379. $settings = array_merge($settings, $database);
  2380. }
  2381. ksort($settings);
  2382. return $settings;
  2383. }
  2384. public function getSettingsSSO()
  2385. {
  2386. return [
  2387. 'FYI' => [
  2388. $this->settingsOption('html', '', ['override' => 12,
  2389. 'html' => '
  2390. <div class="row">
  2391. <div class="col-lg-12">
  2392. <div class="panel panel-primary">
  2393. <div class="panel-heading"><span lang="en">Please Read First</span></div>
  2394. <div class="panel-wrapper collapse in" aria-expanded="true">
  2395. <div class="panel-body">
  2396. <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>
  2397. <br/><br/>
  2398. <div class="row">
  2399. <div class="col-lg-2 col-sm-4 col-xs-12">
  2400. <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>
  2401. </div>
  2402. </div>
  2403. <br/>
  2404. <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>
  2405. </div>
  2406. </div>
  2407. </div>
  2408. </div>
  2409. </div>'
  2410. ]
  2411. ),
  2412. ],
  2413. 'Plex' => [
  2414. $this->settingsOption('token', 'plexToken'),
  2415. $this->settingsOption('button', '', ['label' => 'Get Plex Token', 'icon' => 'fa fa-ticket', 'text' => 'Retrieve', 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#sso-form [name=plexToken]\')"']),
  2416. $this->settingsOption('password-alt', 'plexID', ['label' => 'Plex Machine']),
  2417. $this->settingsOption('button', '', ['label' => 'Get Plex Machine', 'icon' => 'fa fa-id-badge', 'text' => 'Retrieve', 'attr' => 'onclick="showPlexMachineForm(\'#sso-form [name=plexID]\')"']),
  2418. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email']),
  2419. $this->settingsOption('blank'),
  2420. $this->settingsOption('html', 'Plex Note', ['html' => '<span lang="en">Please make sure both Token and Machine are filled in</span>']),
  2421. $this->settingsOption('enable', 'ssoPlex'),
  2422. ],
  2423. 'Tautulli' => [
  2424. $this->settingsOption('multiple-url', 'tautulliURL'),
  2425. $this->settingsOption('auth', 'ssoTautulliAuth'),
  2426. $this->settingsOption('enable', 'ssoTautulli'),
  2427. ],
  2428. 'Overseerr' => [
  2429. $this->settingsOption('url', 'overseerrURL'),
  2430. $this->settingsOption('token', 'overseerrToken'),
  2431. $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']),
  2432. $this->settingsOption('password', 'overseerrFallbackPassword', ['label' => 'Overseerr Fallback Password']),
  2433. $this->settingsOption('enable', 'ssoOverseerr'),
  2434. ],
  2435. 'Petio' => [
  2436. $this->settingsOption('url', 'petioURL'),
  2437. $this->settingsOption('token', 'petioToken'),
  2438. $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']),
  2439. $this->settingsOption('password', 'petioFallbackPassword', ['label' => 'Petio Fallback Password']),
  2440. $this->settingsOption('enable', 'ssoPetio'),
  2441. ],
  2442. 'Ombi' => [
  2443. $this->settingsOption('url', 'ombiURL'),
  2444. $this->settingsOption('token', 'ombiToken'),
  2445. $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']),
  2446. $this->settingsOption('password', 'ombiFallbackPassword', ['label' => 'Ombi Fallback Password']),
  2447. $this->settingsOption('enable', 'ssoOmbi'),
  2448. ],
  2449. 'Jellyfin' => [
  2450. $this->settingsOption('url', 'jellyfinURL', ['label' => 'Jellyfin API URL', 'help' => 'Please make sure to use the local address to the API']),
  2451. $this->settingsOption('url', 'jellyfinSSOURL', ['label' => 'Jellyfin SSO URL', 'help' => 'Please make sure to use the same (sub)domain to access Jellyfin as Organizr\'s']),
  2452. $this->settingsOption('enable', 'ssoJellyfin'),
  2453. ],
  2454. 'Komga' => [
  2455. $this->settingsOption('url', 'komgaURL'),
  2456. $this->settingsOption('auth', 'ssoKomgaAuth'),
  2457. $this->settingsOption('enable', 'ssoKomga'),
  2458. $this->settingsOption('blank'),
  2459. $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']),
  2460. $this->settingsOption('password', 'komgaFallbackPassword', ['label' => 'Komga Fallback Password']),
  2461. ],
  2462. ];
  2463. }
  2464. public function systemMenuLists()
  2465. {
  2466. $pluginsMenu = [
  2467. [
  2468. 'active' => false,
  2469. 'api' => 'api/v2/page/settings_plugins_enabled',
  2470. 'anchor' => 'settings-plugins-enabled-anchor',
  2471. 'name' => 'Active',
  2472. ],
  2473. [
  2474. 'active' => false,
  2475. 'api' => 'api/v2/page/settings_plugins_disabled',
  2476. 'anchor' => 'settings-plugins-disabled-anchor',
  2477. 'name' => 'Inactive',
  2478. ],
  2479. [
  2480. 'active' => false,
  2481. 'api' => 'api/v2/page/settings_plugins_settings',
  2482. 'anchor' => 'settings-plugins-settings-anchor',
  2483. 'name' => 'Settings',
  2484. ],
  2485. [
  2486. 'active' => false,
  2487. 'api' => false,
  2488. 'anchor' => 'settings-plugins-marketplace-anchor',
  2489. 'name' => 'Marketplace',
  2490. 'onclick' => 'loadPluginMarketplace();'
  2491. ],
  2492. ];
  2493. $userManagementMenu = [
  2494. [
  2495. 'active' => false,
  2496. 'api' => 'api/v2/page/settings_user_manage_users',
  2497. 'anchor' => 'settings-user-manage-users-anchor',
  2498. 'name' => 'Manage Users'
  2499. ],
  2500. [
  2501. 'active' => false,
  2502. 'api' => 'api/v2/page/settings_user_manage_groups',
  2503. 'anchor' => 'settings-user-manage-groups-anchor',
  2504. 'name' => 'Manage Groups'
  2505. ],
  2506. [
  2507. 'active' => false,
  2508. 'api' => false,
  2509. 'anchor' => 'settings-user-import-users-anchor',
  2510. 'name' => 'Import Users'
  2511. ],
  2512. ];
  2513. $customizeMenu = [
  2514. [
  2515. 'active' => false,
  2516. 'api' => 'api/v2/page/settings_customize_appearance',
  2517. 'anchor' => 'settings-customize-appearance-anchor',
  2518. 'name' => 'Appearance',
  2519. ],
  2520. [
  2521. 'active' => false,
  2522. 'api' => 'api/v2/page/settings_customize_settings',
  2523. 'anchor' => 'settings-customize-settings-anchor',
  2524. 'name' => 'Marketplace Settings',
  2525. ],
  2526. [
  2527. 'active' => false,
  2528. 'api' => false,
  2529. 'anchor' => 'settings-customize-marketplace-anchor',
  2530. 'name' => 'Marketplace',
  2531. 'onclick' => 'loadThemeMarketplace();'
  2532. ],
  2533. ];
  2534. $tabEditorMenu = [
  2535. [
  2536. 'active' => false,
  2537. 'api' => 'api/v2/page/settings_tab_editor_tabs',
  2538. 'anchor' => 'settings-tab-editor-tabs-anchor',
  2539. 'name' => 'Tabs'
  2540. ],
  2541. [
  2542. 'active' => false,
  2543. 'api' => 'api/v2/page/settings_tab_editor_categories',
  2544. 'anchor' => 'settings-tab-editor-categories-anchor',
  2545. 'name' => 'Categories'
  2546. ],
  2547. [
  2548. 'active' => false,
  2549. 'api' => 'api/v2/page/settings_tab_editor_homepage',
  2550. 'anchor' => 'settings-tab-editor-homepage-anchor',
  2551. 'name' => 'Homepage Items'
  2552. ],
  2553. [
  2554. 'active' => false,
  2555. 'api' => 'api/v2/page/settings_tab_editor_homepage_order',
  2556. 'anchor' => 'settings-tab-editor-homepage-order-anchor',
  2557. 'name' => 'Homepage Order'
  2558. ],
  2559. ];
  2560. $systemSettingsMenu = [
  2561. [
  2562. 'active' => true,
  2563. 'api' => false,
  2564. 'anchor' => 'settings-settings-about-anchor',
  2565. 'name' => 'About'
  2566. ],
  2567. [
  2568. 'active' => false,
  2569. 'api' => 'api/v2/page/settings_settings_main',
  2570. 'anchor' => 'settings-settings-main-anchor',
  2571. 'name' => 'Main'
  2572. ],
  2573. [
  2574. 'active' => false,
  2575. 'api' => 'api/v2/page/settings_settings_sso',
  2576. 'anchor' => 'settings-settings-sso-anchor',
  2577. 'name' => 'SSO'
  2578. ],
  2579. [
  2580. 'active' => false,
  2581. 'api' => 'api/v2/page/settings_settings_logs',
  2582. 'anchor' => 'settings-settings-logs-anchor',
  2583. 'name' => 'Logs'
  2584. ],
  2585. [
  2586. 'active' => false,
  2587. 'api' => false,
  2588. 'anchor' => 'settings-settings-updates-anchor',
  2589. 'name' => 'Updates'
  2590. ],
  2591. [
  2592. 'active' => false,
  2593. 'api' => 'api/v2/page/settings_settings_backup',
  2594. 'anchor' => 'settings-settings-backup-anchor',
  2595. 'name' => 'Backup'
  2596. ],
  2597. [
  2598. 'active' => false,
  2599. 'api' => false,
  2600. 'anchor' => 'settings-settings-donate-anchor',
  2601. 'name' => 'Donate'
  2602. ],
  2603. ];
  2604. $systemMenus['system_settings'] = $this->buildSettingsMenus($systemSettingsMenu, 'System Settings');
  2605. $systemMenus['tab_editor'] = $this->buildSettingsMenus($tabEditorMenu, 'Tab Editor');
  2606. $systemMenus['customize'] = $this->buildSettingsMenus($customizeMenu, 'Customize');
  2607. $systemMenus['user_management'] = $this->buildSettingsMenus($userManagementMenu, 'User Management');
  2608. $systemMenus['plugins'] = $this->buildSettingsMenus($pluginsMenu, 'Plugins');
  2609. return $systemMenus;
  2610. }
  2611. public function updateConfigMultiple($array)
  2612. {
  2613. return (bool)$this->updateConfig($array);
  2614. }
  2615. public function updateConfigItems($array)
  2616. {
  2617. if (!count($array)) {
  2618. $this->setAPIResponse('error', 'No data submitted', 409);
  2619. return false;
  2620. }
  2621. $newItem = array();
  2622. foreach ($array as $k => $v) {
  2623. $v = $v ?? '';
  2624. switch ($v) {
  2625. case 'true':
  2626. $v = (bool)true;
  2627. break;
  2628. case 'false':
  2629. $v = (bool)false;
  2630. break;
  2631. }
  2632. // Hash
  2633. if ((stripos($k, 'password') !== false)) {
  2634. if (!$this->isEncrypted($v)) {
  2635. if ($v !== '') {
  2636. $v = $this->encrypt($v);
  2637. }
  2638. }
  2639. }
  2640. switch ($k) {
  2641. case 'logLocation':
  2642. case 'dbLocation':
  2643. if (!empty($v)) {
  2644. $v = $this->cleanDirectory($v);
  2645. }
  2646. break;
  2647. default:
  2648. break;
  2649. }
  2650. if (strtolower($k) !== 'formkey') {
  2651. $newItem[$k] = $v;
  2652. $this->config[$k] = $v;
  2653. }
  2654. }
  2655. $this->setAPIResponse('success', 'Config items updated', 200);
  2656. $this->setLoggerChannel('Config');
  2657. $this->logger->info('Config items updated', array_keys($array));
  2658. return (bool)$this->updateConfig($newItem);
  2659. }
  2660. public function updateConfigItem($array)
  2661. {
  2662. $array['value'] = $array['value'] ?? '';
  2663. switch ($array['value']) {
  2664. case 'true':
  2665. $array['value'] = (bool)true;
  2666. break;
  2667. case 'false':
  2668. $array['value'] = (bool)false;
  2669. break;
  2670. }
  2671. // Hash
  2672. if ($array['type'] == 'password') {
  2673. $array['value'] = $this->encrypt($array['value']);
  2674. }
  2675. $newItem = array(
  2676. $array['name'] => $array['value']
  2677. );
  2678. $this->config[$array['name']] = $array['value'];
  2679. return (bool)$this->updateConfig($newItem);
  2680. }
  2681. public function ignoreNewsId($id)
  2682. {
  2683. if (!$id) {
  2684. $this->setAPIResponse('error', 'News id was not supplied', 409);
  2685. return false;
  2686. }
  2687. $id = array(intval($id));
  2688. $newsIds = $this->config['ignoredNewsIds'];
  2689. $newsIds = array_merge($newsIds, $id);
  2690. $newsIds = array_unique($newsIds);
  2691. $this->updateConfig(['ignoredNewsIds' => $newsIds]);
  2692. $this->setAPIResponse('success', 'News id is now ignored', 200, null);
  2693. }
  2694. public function getNewsIds()
  2695. {
  2696. $newsIds = $this->config['ignoredNewsIds'];
  2697. $this->setAPIResponse('success', null, 200, $newsIds);
  2698. return $newsIds;
  2699. }
  2700. public function testWizardPath($array)
  2701. {
  2702. if ($this->hasDB()) {
  2703. $this->setAPIResponse('error', 'Endpoint disabled as database already exists', 401);
  2704. return false;
  2705. }
  2706. $path = $array['path'] ?? null;
  2707. if (file_exists($path)) {
  2708. if (is_writable($path)) {
  2709. $this->setAPIResponse('success', 'Path exists and is writable', 200);
  2710. return true;
  2711. } else {
  2712. $this->setAPIResponse('error', 'Path exists but is not writable', 403);
  2713. return false;
  2714. }
  2715. } else {
  2716. if (mkdir($path, 0760, true)) {
  2717. $this->setAPIResponse('success', 'Path is writable - Creating now', 200);
  2718. return true;
  2719. } else {
  2720. $this->setAPIResponse('error', 'Failed making directory - Check permissions', 403);
  2721. return false;
  2722. }
  2723. }
  2724. }
  2725. public function formatDatabaseDriver($driver)
  2726. {
  2727. $driver = strtolower($driver);
  2728. switch ($driver) {
  2729. case 'sqlite':
  2730. case 'sqlite3':
  2731. return 'sqlite3';
  2732. case 'mysql':
  2733. case 'mysqli':
  2734. return 'mysqli';
  2735. case 'postgre':
  2736. case 'postgres':
  2737. case 'postgresql':
  2738. return 'postgre';
  2739. default:
  2740. return $driver;
  2741. }
  2742. }
  2743. public function wizardConfig($array)
  2744. {
  2745. $array['driver'] = $array['driver'] ?? 'sqlite3';
  2746. $driver = $this->formatDatabaseDriver($array['driver']);
  2747. $dbName = $array['dbName'] ?? null;
  2748. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2749. $license = $array['license'] ?? null;
  2750. $hashKey = $array['hashKey'] ?? null;
  2751. $api = $array['api'] ?? null;
  2752. $registrationPassword = $array['registrationPassword'] ?? null;
  2753. $username = $array['username'] ?? null;
  2754. $password = $array['password'] ?? null;
  2755. $email = $array['email'] ?? null;
  2756. $dbHost = $array['dbHost'] ?? null;
  2757. $dbUsername = $array['dbUsername'] ?? null;
  2758. $dbPassword = $array['dbPassword'] ?? null;
  2759. $validation = [
  2760. 'dbPath' => $path,
  2761. 'dbName' => $dbName,
  2762. 'license' => $license,
  2763. 'hashKey' => $hashKey,
  2764. 'api' => $api,
  2765. 'registrationPassword' => $registrationPassword,
  2766. 'username' => $username,
  2767. 'password' => $password,
  2768. 'email' => $email,
  2769. 'driver' => $driver
  2770. ];
  2771. $dbName = $this->dbExtension($dbName);
  2772. if ($driver == 'mysqli' || $driver == 'postgre') {
  2773. $dbName = $this->removeDbExtension($dbName);
  2774. $validation = array_merge($validation, [
  2775. 'dbHost' => $dbHost,
  2776. 'dbUsername' => $dbUsername,
  2777. 'dbPassword' => $dbPassword,
  2778. ]);
  2779. }
  2780. foreach ($validation as $k => $v) {
  2781. if ($v == null) {
  2782. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2783. return false;
  2784. }
  2785. }
  2786. if ($path) {
  2787. $path = $this->cleanDirectory($path);
  2788. if (file_exists($path)) {
  2789. if (!is_writable($path)) {
  2790. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2791. return false;
  2792. }
  2793. } else {
  2794. if (!mkdir($path, 0760, true)) {
  2795. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2796. return false;
  2797. }
  2798. }
  2799. }
  2800. $configVersion = $this->version;
  2801. $configArray = array(
  2802. 'dbLocation' => $path,
  2803. 'driver' => $driver,
  2804. 'dbName' => $dbName,
  2805. 'license' => $license,
  2806. 'organizrHash' => $hashKey,
  2807. 'organizrAPI' => $api,
  2808. 'registrationPassword' => $registrationPassword,
  2809. 'uuid' => $this->gen_uuid()
  2810. );
  2811. if ($driver == 'mysqli' || $driver == 'postgre') {
  2812. $configArray = array_merge($configArray, [
  2813. 'dbHost' => $dbHost,
  2814. 'dbUsername' => $dbUsername,
  2815. 'dbPassword' => $this->encrypt($dbPassword, $hashKey),
  2816. ]);
  2817. }
  2818. //Test Database Connection before saving config
  2819. $testDatabaseConnection = $this->testDatabaseConnection($array);
  2820. if (!$testDatabaseConnection) {
  2821. // setResponse already defined
  2822. return false;
  2823. }
  2824. // Create Config
  2825. if ($this->createConfig($configArray)) {
  2826. $this->config = $this->config();
  2827. $this->refreshCookieName();
  2828. $this->connectDB();
  2829. // Call DB Create
  2830. if (!$this->createNewDB($dbName, false)) {
  2831. $this->setAPIResponse('error', 'error creating database using driver: ' . $driver, 500);
  2832. return false;
  2833. }
  2834. if ($this->createDB($path)) {
  2835. // Add in first user
  2836. if ($this->createFirstAdmin($username, $password, $email)) {
  2837. if ($this->createToken($username, $email, 1)) {
  2838. return true;
  2839. } else {
  2840. $this->setAPIResponse('error', 'error creating token', 500);
  2841. }
  2842. } else {
  2843. $this->setAPIResponse('error', 'error creating admin', 500);
  2844. }
  2845. } else {
  2846. $this->setAPIResponse('error', 'error creating database', 500);
  2847. }
  2848. } else {
  2849. $this->setAPIResponse('error', 'error creating config', 500);
  2850. }
  2851. return false;
  2852. }
  2853. public function testDatabaseConnection($array)
  2854. {
  2855. $driver = $array['driver'] ?? 'sqlite3';
  2856. $driver = $this->formatDatabaseDriver($driver);
  2857. $dbName = $array['dbName'] ?? null;
  2858. $dbHost = $array['dbHost'] ?? null;
  2859. $dbUsername = $array['dbUsername'] ?? null;
  2860. $dbPassword = $array['dbPassword'] ?? null;
  2861. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2862. switch ($driver) {
  2863. case 'mysqli':
  2864. if (!extension_loaded('mysqli')) {
  2865. $this->setResponse(500, 'PHP Extension `mysqli` is not loaded');
  2866. return false;
  2867. }
  2868. $config = [
  2869. 'driver' => 'mysqli',
  2870. 'host' => $dbHost,
  2871. 'username' => $dbUsername,
  2872. 'password' => $dbPassword,
  2873. 'options' => [
  2874. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2875. ],
  2876. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2877. ];
  2878. $validation = [
  2879. 'dbHost' => $dbHost,
  2880. 'dbUsername' => $dbUsername,
  2881. 'dbPassword' => $dbPassword,
  2882. ];
  2883. break;
  2884. case 'postgre':
  2885. // DISABLE FOR NOW
  2886. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2887. return false;
  2888. $config = [
  2889. //host, hostaddr, port, dbname, user, password, connect_timeout, options, sslmode, service => see PostgreSQL API
  2890. 'driver' => 'postgre',
  2891. 'username' => $dbUsername,
  2892. 'password' => $dbPassword,
  2893. 'persistent' => true,
  2894. ];
  2895. $host = $this->qualifyURL($dbHost, true);
  2896. if ($host['port']) {
  2897. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  2898. }
  2899. if (($host['host'])) {
  2900. $config = array_merge($config, ['host' => $host['host']]);
  2901. }
  2902. if (!$host['host'] && $host['path']) {
  2903. $config = array_merge($config, ['host' => $host['path']]);
  2904. }
  2905. $validation = [
  2906. 'dbHost' => $dbHost,
  2907. 'dbUsername' => $dbUsername,
  2908. 'dbPassword' => $dbPassword,
  2909. ];
  2910. break;
  2911. case 'sqlite3':
  2912. $path = $this->cleanDirectory($path);
  2913. if (file_exists($path)) {
  2914. if (!is_writable($path)) {
  2915. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2916. return false;
  2917. }
  2918. } else {
  2919. if (is_writable(dirname($path, 1))) {
  2920. if (!mkdir($path, 0760, true)) {
  2921. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2922. return false;
  2923. }
  2924. } else {
  2925. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2926. return false;
  2927. }
  2928. }
  2929. return true;
  2930. default:
  2931. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2932. return false;
  2933. }
  2934. foreach ($validation as $k => $v) {
  2935. if ($v == null) {
  2936. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2937. return false;
  2938. }
  2939. }
  2940. try {
  2941. $connection = new Connection($config);
  2942. $testConnection = $connection->isConnected();
  2943. if ($testConnection) {
  2944. $this->setResponse(200, 'Database connection successful');
  2945. return true;
  2946. } else {
  2947. $this->setResponse(409, 'Database connection unsuccessful');
  2948. return false;
  2949. }
  2950. } catch (Dibi\Exception $e) {
  2951. $this->setResponse(500, $e->getMessage());
  2952. return false;
  2953. }
  2954. }
  2955. public function createNewDB($dbName, $migration = false)
  2956. {
  2957. if ($this->config['driver'] == 'mysqli') {
  2958. $config = [
  2959. 'driver' => 'mysqli',
  2960. 'host' => $this->config['dbHost'],
  2961. 'username' => $this->config['dbUsername'],
  2962. 'password' => $this->decrypt($this->config['dbPassword']),
  2963. 'options' => [
  2964. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2965. ],
  2966. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2967. ];
  2968. if ($migration) {
  2969. try {
  2970. $this->otherDb = new Connection($config);
  2971. } catch (Dibi\Exception $e) {
  2972. $this->otherDb = null;
  2973. }
  2974. } else {
  2975. try {
  2976. $this->db = new Connection($config);
  2977. } catch (Dibi\Exception $e) {
  2978. $this->db = null;
  2979. }
  2980. }
  2981. if ($dbName == 'tempMigration') {
  2982. $response = [
  2983. array(
  2984. 'function' => 'query',
  2985. 'query' => [
  2986. 'DROP DATABASE IF EXISTS tempMigration'
  2987. ]
  2988. ),
  2989. ];
  2990. $drop = $this->processQueries($response, $migration);
  2991. }
  2992. $response = [
  2993. array(
  2994. 'function' => 'query',
  2995. 'query' => ['CREATE DATABASE IF NOT EXISTS %n',
  2996. $dbName
  2997. ]
  2998. )
  2999. ];
  3000. $results = $this->processQueries($response, $migration);
  3001. if ($results) {
  3002. if ($migration) {
  3003. $this->connectOtherDB();
  3004. } else {
  3005. $this->connectDB();
  3006. }
  3007. return true;
  3008. } else {
  3009. return false;
  3010. }
  3011. } elseif ($this->config['driver'] == 'postgre') {
  3012. $config = [
  3013. 'driver' => 'postgre',
  3014. 'username' => $this->config['dbUsername'],
  3015. 'password' => $this->decrypt($this->config['dbPassword']),
  3016. 'persistent' => true,
  3017. ];
  3018. $host = $this->qualifyURL($this->config['dbHost'], true);
  3019. if ($host['port']) {
  3020. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  3021. }
  3022. if ($host['host']) {
  3023. $config = array_merge($config, ['host' => $host['host']]);
  3024. }
  3025. if (!$host['host'] && $host['path']) {
  3026. $config = array_merge($config, ['host' => $host['path']]);
  3027. }
  3028. try {
  3029. $this->db = new Connection($config);
  3030. } catch (Dibi\Exception $e) {
  3031. $this->db = null;
  3032. }
  3033. $response = [
  3034. array(
  3035. 'function' => 'query',
  3036. 'query' => ['CREATE DATABASE %n',
  3037. $dbName
  3038. ]
  3039. )
  3040. ];
  3041. $results = $this->processQueries($response, $migration);
  3042. if ($results) {
  3043. $this->connectDB();
  3044. return true;
  3045. } else {
  3046. return false;
  3047. }
  3048. } else {
  3049. return true;
  3050. }
  3051. }
  3052. public function getDefaultTablesFormatted()
  3053. {
  3054. $list = [];
  3055. $tables = $this->defaultTables();
  3056. foreach ($tables as $table) {
  3057. $string = trim($table['query']);
  3058. preg_match('/CREATE TABLE `(.*?)`/', $string, $output_array);
  3059. if (count($output_array) > 1) {
  3060. $list[] = $output_array[1];
  3061. }
  3062. }
  3063. return $list;
  3064. }
  3065. public function defaultTables()
  3066. {
  3067. return [
  3068. array(
  3069. 'function' => 'query',
  3070. 'query' => '
  3071. CREATE TABLE `users` (
  3072. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3073. `username` TEXT UNIQUE,
  3074. `password` TEXT,
  3075. `email` TEXT,
  3076. `plex_token` TEXT,
  3077. `group` TEXT,
  3078. `group_id` INTEGER,
  3079. `locked` INTEGER,
  3080. `image` TEXT,
  3081. `register_date` DATETIME,
  3082. `auth_service` TEXT DEFAULT \'internal\'
  3083. );
  3084. '
  3085. ),
  3086. array(
  3087. 'function' => 'query',
  3088. 'query' => 'CREATE TABLE `chatroom` (
  3089. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3090. `username` TEXT,
  3091. `gravatar` TEXT,
  3092. `uid` TEXT,
  3093. `date` DATETIME,
  3094. `ip` TEXT,
  3095. `message` TEXT
  3096. );'
  3097. ),
  3098. array(
  3099. 'function' => 'query',
  3100. 'query' => 'CREATE TABLE `tokens` (
  3101. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3102. `token` TEXT UNIQUE,
  3103. `user_id` INTEGER,
  3104. `browser` TEXT,
  3105. `ip` TEXT,
  3106. `created` DATETIME,
  3107. `expires` DATETIME
  3108. );'
  3109. ),
  3110. array(
  3111. 'function' => 'query',
  3112. 'query' => 'CREATE TABLE `groups` (
  3113. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3114. `group` TEXT UNIQUE,
  3115. `group_id` INTEGER,
  3116. `image` TEXT,
  3117. `default` INTEGER
  3118. );'
  3119. ),
  3120. array(
  3121. 'function' => 'query',
  3122. 'query' => 'CREATE TABLE `categories` (
  3123. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3124. `order` INTEGER,
  3125. `category` TEXT UNIQUE,
  3126. `category_id` INTEGER,
  3127. `image` TEXT,
  3128. `default` INTEGER
  3129. );'
  3130. ),
  3131. array(
  3132. 'function' => 'query',
  3133. 'query' => 'CREATE TABLE `tabs` (
  3134. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3135. `order` INTEGER,
  3136. `category_id` INTEGER,
  3137. `name` TEXT,
  3138. `url` TEXT,
  3139. `url_local` TEXT,
  3140. `default` INTEGER,
  3141. `enabled` INTEGER,
  3142. `group_id` INTEGER,
  3143. `group_id_min` INTEGER DEFAULT \'1\',
  3144. `add_to_admin` INTEGER DEFAULT \'0\',
  3145. `image` TEXT,
  3146. `type` INTEGER,
  3147. `splash` INTEGER,
  3148. `ping` INTEGER,
  3149. `ping_url` TEXT,
  3150. `timeout` INTEGER,
  3151. `timeout_ms` INTEGER,
  3152. `preload` INTEGER
  3153. );'
  3154. ),
  3155. array(
  3156. 'function' => 'query',
  3157. 'query' => 'CREATE TABLE `options` (
  3158. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3159. `name` TEXT UNIQUE,
  3160. `value` TEXT
  3161. );'
  3162. ),
  3163. array(
  3164. 'function' => 'query',
  3165. 'query' => 'CREATE TABLE `invites` (
  3166. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3167. `code` TEXT UNIQUE,
  3168. `date` DATETIME,
  3169. `email` TEXT,
  3170. `username` TEXT,
  3171. `dateused` TIMESTAMP,
  3172. `usedby` TEXT,
  3173. `ip` TEXT,
  3174. `valid` TEXT,
  3175. `type` TEXT,
  3176. `invitedby` TEXT
  3177. );'
  3178. ),
  3179. array(
  3180. 'function' => 'query',
  3181. 'query' => 'CREATE TABLE `BOOKMARK-categories` (
  3182. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3183. `order` INTEGER,
  3184. `category` TEXT UNIQUE,
  3185. `category_id` INTEGER,
  3186. `default` INTEGER
  3187. );'
  3188. ),
  3189. array(
  3190. 'function' => 'query',
  3191. 'query' => 'CREATE TABLE `BOOKMARK-tabs` (
  3192. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3193. `order` INTEGER,
  3194. `category_id` INTEGER,
  3195. `name` TEXT,
  3196. `url` TEXT,
  3197. `enabled` INTEGER,
  3198. `group_id` INTEGER,
  3199. `image` TEXT,
  3200. `background_color` TEXT,
  3201. `text_color` TEXT
  3202. );'
  3203. )
  3204. ];
  3205. }
  3206. public function createDB($path, $migration = false)
  3207. {
  3208. if (!file_exists($path)) {
  3209. mkdir($path, 0777, true);
  3210. }
  3211. $tables = $this->defaultTables();
  3212. return $this->processQueries($tables, $migration);
  3213. }
  3214. public function createFirstAdmin($username, $password, $email)
  3215. {
  3216. $userInfo = [
  3217. 'username' => $username,
  3218. 'password' => password_hash($password, PASSWORD_BCRYPT),
  3219. 'email' => $email,
  3220. 'group' => 'Admin',
  3221. 'group_id' => 0,
  3222. 'image' => $this->gravatar($email),
  3223. 'register_date' => gmdate('Y-m-d H:i:s'),
  3224. ];
  3225. $groupInfo0 = [
  3226. 'group' => 'Admin',
  3227. 'group_id' => 0,
  3228. 'default' => 0,
  3229. 'image' => 'plugins/images/groups/admin.png',
  3230. ];
  3231. $groupInfo1 = [
  3232. 'group' => 'Co-Admin',
  3233. 'group_id' => 1,
  3234. 'default' => 0,
  3235. 'image' => 'plugins/images/groups/coadmin.png',
  3236. ];
  3237. $groupInfo2 = [
  3238. 'group' => 'Super User',
  3239. 'group_id' => 2,
  3240. 'default' => 0,
  3241. 'image' => 'plugins/images/groups/superuser.png',
  3242. ];
  3243. $groupInfo3 = [
  3244. 'group' => 'Power User',
  3245. 'group_id' => 3,
  3246. 'default' => 0,
  3247. 'image' => 'plugins/images/groups/poweruser.png',
  3248. ];
  3249. $groupInfo4 = [
  3250. 'group' => 'User',
  3251. 'group_id' => 4,
  3252. 'default' => 1,
  3253. 'image' => 'plugins/images/groups/user.png',
  3254. ];
  3255. $groupInfoGuest = [
  3256. 'group' => 'Guest',
  3257. 'group_id' => 999,
  3258. 'default' => 0,
  3259. 'image' => 'plugins/images/groups/guest.png',
  3260. ];
  3261. $settingsInfo = [
  3262. 'order' => 1,
  3263. 'category_id' => 0,
  3264. 'name' => 'Settings',
  3265. 'url' => 'api/v2/page/settings',
  3266. 'default' => 0,
  3267. 'enabled' => 1,
  3268. 'group_id' => 1,
  3269. 'image' => 'fontawesome::cog',
  3270. 'type' => 0
  3271. ];
  3272. $homepageInfo = [
  3273. 'order' => 2,
  3274. 'category_id' => 0,
  3275. 'name' => 'Homepage',
  3276. 'url' => 'api/v2/page/homepage',
  3277. 'default' => 0,
  3278. 'enabled' => 0,
  3279. 'group_id' => 4,
  3280. 'image' => 'fontawesome::home',
  3281. 'type' => 0
  3282. ];
  3283. $unsortedInfo = [
  3284. 'order' => 1,
  3285. 'category' => 'Unsorted',
  3286. 'category_id' => 0,
  3287. 'image' => 'fontawesome::question',
  3288. 'default' => 1
  3289. ];
  3290. $response = [
  3291. array(
  3292. 'function' => 'query',
  3293. 'query' => array(
  3294. 'INSERT INTO [users]',
  3295. $userInfo
  3296. )
  3297. ),
  3298. array(
  3299. 'function' => 'query',
  3300. 'query' => array(
  3301. 'INSERT INTO [groups]',
  3302. $groupInfo0
  3303. )
  3304. ),
  3305. array(
  3306. 'function' => 'query',
  3307. 'query' => array(
  3308. 'INSERT INTO [groups]',
  3309. $groupInfo1
  3310. )
  3311. ),
  3312. array(
  3313. 'function' => 'query',
  3314. 'query' => array(
  3315. 'INSERT INTO [groups]',
  3316. $groupInfo2
  3317. )
  3318. ),
  3319. array(
  3320. 'function' => 'query',
  3321. 'query' => array(
  3322. 'INSERT INTO [groups]',
  3323. $groupInfo3
  3324. )
  3325. ),
  3326. array(
  3327. 'function' => 'query',
  3328. 'query' => array(
  3329. 'INSERT INTO [groups]',
  3330. $groupInfo4
  3331. )
  3332. ),
  3333. array(
  3334. 'function' => 'query',
  3335. 'query' => array(
  3336. 'INSERT INTO [groups]',
  3337. $groupInfoGuest
  3338. )
  3339. ),
  3340. array(
  3341. 'function' => 'query',
  3342. 'query' => array(
  3343. 'INSERT INTO [tabs]',
  3344. $settingsInfo
  3345. )
  3346. ),
  3347. array(
  3348. 'function' => 'query',
  3349. 'query' => array(
  3350. 'INSERT INTO [tabs]',
  3351. $homepageInfo
  3352. )
  3353. ),
  3354. array(
  3355. 'function' => 'query',
  3356. 'query' => array(
  3357. 'INSERT INTO [categories]',
  3358. $unsortedInfo
  3359. )
  3360. ),
  3361. ];
  3362. return $this->processQueries($response);
  3363. }
  3364. public function getUserByUsernameAndEmail($username, $email)
  3365. {
  3366. $response = [
  3367. array(
  3368. 'function' => 'fetch',
  3369. 'query' => array(
  3370. 'SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',
  3371. [$username],
  3372. [$email]
  3373. )
  3374. ),
  3375. ];
  3376. return $this->processQueries($response);
  3377. }
  3378. public function createToken($username, $email, $days = 1)
  3379. {
  3380. $this->setLoggerChannel('Authentication', $username);
  3381. $this->logger->debug('Starting token creation function');
  3382. $days = ($days > 365) ? 365 : $days;
  3383. //Quick get user ID
  3384. $result = $this->getUserByUsernameAndEmail($username, $email);
  3385. $config = $this->configToken();
  3386. assert($config instanceof Lcobucci\JWT\Configuration);
  3387. $now = new DateTimeImmutable();
  3388. $token = $config->builder()
  3389. // Configures the issuer (iss claim)
  3390. ->issuedBy('Organizr')
  3391. // Configures the audience (aud claim)
  3392. ->permittedFor('Organizr')
  3393. // Configures the id (jti claim)
  3394. ->identifiedBy('4f1g23a12aa')
  3395. // Configures the time that the token was issue (iat claim)
  3396. ->issuedAt($now)
  3397. // Configures the time that the token can be used (nbf claim)
  3398. ->canOnlyBeUsedAfter($now)
  3399. // Configures the expiration time of the token (exp claim)
  3400. ->expiresAt($now->modify('+' . $days . ' days'))
  3401. // Configures a new claim, called "uid"
  3402. ->withClaim('name', $result['username'])// Configures a new claim, called "name"
  3403. ->withClaim('group', $result['group'])// Configures a new claim, called "group"
  3404. ->withClaim('groupID', $result['group_id'])// Configures a new claim, called "groupID"
  3405. ->withClaim('email', $result['email'])// Configures a new claim, called "email"
  3406. ->withClaim('image', $result['image'])// Configures a new claim, called "image"
  3407. ->withClaim('userID', $result['id'])// Configures a new claim, called "image"
  3408. // Configures a new header, called "foo"
  3409. //->withHeader('foo', 'bar')
  3410. // Builds a new token
  3411. ->getToken($config->signer(), $config->signingKey());
  3412. //$token->headers(); // Retrieves the token headers
  3413. //$token->claims(); // Retrieves the token claims
  3414. $this->coookie('set', $this->cookieName, $token->toString(), $days);
  3415. // Add token to DB
  3416. $addToken = [
  3417. 'token' => $token->toString(),
  3418. 'user_id' => $result['id'],
  3419. 'created' => gmdate('Y-m-d H:i:s'),
  3420. 'browser' => $_SERVER ['HTTP_USER_AGENT'] ?? null,
  3421. 'ip' => $this->userIP(),
  3422. 'expires' => gmdate('Y-m-d H:i:s', time() + (86400 * $days))
  3423. ];
  3424. $response = [
  3425. array(
  3426. 'function' => 'query',
  3427. 'query' => array(
  3428. 'INSERT INTO [tokens]',
  3429. $addToken
  3430. )
  3431. ),
  3432. ];
  3433. $this->processQueries($response);
  3434. if ($token) {
  3435. $this->logger->debug('Token has been created');
  3436. } else {
  3437. $this->logger->warning('Token creation error');
  3438. }
  3439. $this->logger->debug('Token creation function has finished');
  3440. return $token->toString();
  3441. }
  3442. public function login($array)
  3443. {
  3444. // Grab username, Password & other optional items from api call
  3445. $username = $array['username'] ?? null;
  3446. $password = $array['password'] ?? null;
  3447. $oAuth = $array['oAuth'] ?? null;
  3448. $oAuthType = $array['oAuthType'] ?? null;
  3449. $remember = $array['remember'] ?? null;
  3450. $tfaCode = $array['tfaCode'] ?? null;
  3451. $loginAttempts = $array['loginAttempts'] ?? null;
  3452. $output = $array['output'] ?? null;
  3453. $username = (strpos($this->config['authBackend'], 'emby') !== false) ? $username : strtolower($username);
  3454. $days = (isset($remember)) ? $this->config['rememberMeDays'] : 1;
  3455. // Set logger channel
  3456. $this->setLoggerChannel('Authentication', $username);
  3457. $this->logger->debug('Starting login function');
  3458. // Set other variables
  3459. $function = 'plugin_auth_' . $this->config['authBackend'];
  3460. $authSuccess = false;
  3461. $authProxy = false;
  3462. $addEmailToAuthProxy = true;
  3463. // Check Login attempts and kill if over limit
  3464. if ($loginAttempts > $this->config['loginAttempts'] || isset($_COOKIE['lockout'])) {
  3465. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3466. $this->logger->warning('User is locked out');
  3467. $this->setAPIResponse('error', 'User is locked out', 403);
  3468. return false;
  3469. }
  3470. // Check if Auth Proxy is enabled
  3471. if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
  3472. if (isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])]) || isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])])) {
  3473. $usernameHeader = $this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])] ?? null;
  3474. $emailHeader = $this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])] ?? null;
  3475. $headerForLogin = $usernameHeader ?: ($emailHeader ?: null);
  3476. $this->setLoggerChannel('Authentication', $headerForLogin);
  3477. $this->logger->debug('Starting Auth Proxy verification');
  3478. $whitelistRange = $this->analyzeIP($this->config['authProxyWhitelist']);
  3479. $authProxy = $this->authProxyRangeCheck($whitelistRange['from'], $whitelistRange['to']);
  3480. $username = ($authProxy) ? $headerForLogin : $username;
  3481. $password = ($password == null) ? $this->random_ascii_string(10) : $password;
  3482. $addEmailToAuthProxy = ($authProxy && $emailHeader) ? ['email' => $emailHeader] : true;
  3483. if ($authProxy) {
  3484. $this->logger->info('User has been verified using Auth Proxy');
  3485. } else {
  3486. $this->logger->warning('User has failed verification using Auth Proxy');
  3487. }
  3488. }
  3489. }
  3490. // Check if Login method was an oAuth login
  3491. if (!$oAuth) {
  3492. $result = $this->getUserByUsernameAndEmail($username, $username);
  3493. $result['password'] = $result['password'] ?? '';
  3494. // Switch AuthType - internal - external - both
  3495. switch ($this->config['authType']) {
  3496. case 'external':
  3497. if (method_exists($this, $function)) {
  3498. $authSuccess = $this->$function($username, $password);
  3499. }
  3500. break;
  3501. /** @noinspection PhpMissingBreakStatementInspection */
  3502. case 'both':
  3503. if (method_exists($this, $function)) {
  3504. $authSuccess = $this->$function($username, $password);
  3505. }
  3506. // no break
  3507. default: // Internal
  3508. if (!$authSuccess) {
  3509. // perform the internal authentication step
  3510. if (password_verify($password, $result['password'])) {
  3511. $this->logger->debug('User password has been verified');
  3512. $authSuccess = true;
  3513. }
  3514. }
  3515. }
  3516. $authSuccess = ($authProxy) ? $addEmailToAuthProxy : $authSuccess;
  3517. } else {
  3518. // Has oAuth Token!
  3519. switch ($oAuthType) {
  3520. case 'plex':
  3521. if ($this->config['plexoAuth']) {
  3522. $this->logger->debug('Starting Plex oAuth verification');
  3523. $tokenInfo = $this->checkPlexToken($oAuth);
  3524. if ($tokenInfo) {
  3525. $authSuccess = [
  3526. 'username' => $tokenInfo['user']['username'],
  3527. 'email' => $tokenInfo['user']['email'],
  3528. 'image' => $tokenInfo['user']['thumb'],
  3529. 'token' => $tokenInfo['user']['authToken'],
  3530. 'oauth' => 'plex'
  3531. ];
  3532. $this->logger->debug('User\'s Plex Token has been verified');
  3533. $this->coookie('set', 'oAuth', 'true', $this->config['rememberMeDays']);
  3534. $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;
  3535. } else {
  3536. $this->logger->warning('User\'s Plex Token has failed verification');
  3537. }
  3538. } else {
  3539. $this->logger->debug('Plex oAuth is not setup');
  3540. $this->setAPIResponse('error', 'Plex oAuth is not setup', 422);
  3541. return false;
  3542. }
  3543. break;
  3544. default:
  3545. return ($output) ? 'No oAuthType defined' : 'error';
  3546. }
  3547. $result = ($authSuccess) ? $this->getUserByUsernameAndEmail($authSuccess['username'], $authSuccess['email']) : '';
  3548. }
  3549. if ($authSuccess) {
  3550. // Make sure user exists in database
  3551. $userExists = false;
  3552. $passwordMatches = $oAuth || $authProxy;
  3553. $token = (is_array($authSuccess) && isset($authSuccess['token']) ? $authSuccess['token'] : '');
  3554. if (isset($result['username'])) {
  3555. $userExists = true;
  3556. $username = $result['username'];
  3557. if ($passwordMatches == false) {
  3558. $passwordMatches = password_verify($password, $result['password']);
  3559. }
  3560. }
  3561. if ($userExists) {
  3562. //does org password need to be updated
  3563. if (!$passwordMatches) {
  3564. $this->updateUserPassword($password, $result['id']);
  3565. $this->setLoggerChannel('Authentication', $username);
  3566. $this->logger->info('User Password updated from backend');
  3567. }
  3568. if ($token !== '') {
  3569. if ($token !== $result['plex_token']) {
  3570. $this->updateUserPlexToken($token, $result['id']);
  3571. $this->setLoggerChannel('Authentication', $username);
  3572. $this->logger->info('User Plex Token updated from backend');
  3573. }
  3574. }
  3575. // 2FA might go here
  3576. if ($result['auth_service'] !== 'internal' && strpos($result['auth_service'], '::') !== false) {
  3577. $tfaProceed = true;
  3578. // Add check for local or not
  3579. if ($this->config['ignoreTFALocal'] !== false) {
  3580. $tfaProceed = !$this->isLocal();
  3581. }
  3582. // Is Plex Oauth?
  3583. if ($this->config['ignoreTFAIfPlexOAuth'] !== false) {
  3584. if (isset($authSuccess['oauth'])) {
  3585. if ($authSuccess['oauth'] == 'plex') {
  3586. $tfaProceed = false;
  3587. }
  3588. }
  3589. }
  3590. if ($tfaProceed) {
  3591. $this->setLoggerChannel('Authentication', $username);
  3592. $this->logger->debug('Starting 2FA verification');
  3593. $TFA = explode('::', $result['auth_service']);
  3594. // Is code with login info?
  3595. if ($tfaCode == '') {
  3596. $this->logger->debug('Sending 2FA response to login UI');
  3597. $this->setAPIResponse('warning', '2FA Code Needed', 422);
  3598. return false;
  3599. } else {
  3600. if (!$this->verify2FA($TFA[1], $tfaCode, $TFA[0])) {
  3601. $this->logger->warning('Incorrect 2FA');
  3602. $this->setAPIResponse('error', 'Wrong 2FA', 422);
  3603. return false;
  3604. } else {
  3605. $this->logger->info('2FA verification passed');
  3606. }
  3607. }
  3608. }
  3609. }
  3610. // End 2FA
  3611. // authentication passed - 1) mark active and update token
  3612. $createToken = $this->createToken($result['username'], $result['email'], $days);
  3613. if ($createToken) {
  3614. $this->logger->info('User has logged in');
  3615. $ssoUserObject = ($token !== '') ? $authSuccess : $result;
  3616. $this->ssoCheck($ssoUserObject, $password, $token); //need to work on this
  3617. return ($output) ? array('name' => $this->cookieName, 'token' => (string)$createToken) : true;
  3618. } else {
  3619. $this->setAPIResponse('error', 'Token creation error', 500);
  3620. return false;
  3621. }
  3622. } else {
  3623. // Create User
  3624. $this->setLoggerChannel('Authentication', (is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username));
  3625. $this->logger->debug('Starting Registration function');
  3626. return $this->authRegister((is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username), $password, (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $token);
  3627. }
  3628. } else {
  3629. // authentication failed
  3630. $this->setLoggerChannel('Authentication', $username);
  3631. $this->logger->warning('Wrong Password');
  3632. if ($loginAttempts >= $this->config['loginAttempts']) {
  3633. $this->logger->warning('User exceeded maximum login attempts');
  3634. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3635. $this->setAPIResponse('error', 'User is locked out', 403);
  3636. return false;
  3637. } else {
  3638. $this->logger->debug('User has not exceeded maximum login attempts');
  3639. $this->setAPIResponse('error', 'User credentials incorrect', 401);
  3640. return false;
  3641. }
  3642. }
  3643. }
  3644. public function logout()
  3645. {
  3646. $this->setLoggerChannel('Authentication');
  3647. $this->logger->debug('Starting log out process');
  3648. $this->logger->info('User has logged out');
  3649. $this->coookie('delete', $this->cookieName);
  3650. $this->coookie('delete', 'mpt');
  3651. $this->coookie('delete', 'Auth');
  3652. $this->coookie('delete', 'oAuth');
  3653. $this->coookie('delete', 'connect.sid');
  3654. $this->coookie('delete', 'petio_jwt');
  3655. $this->clearTautulliTokens();
  3656. $this->clearJellyfinTokens();
  3657. $this->revokeTokenCurrentUser($this->user['token']);
  3658. $this->clearKomgaToken();
  3659. $this->refreshDeviceUUID();
  3660. $this->logger->debug('Log out process has finished');
  3661. $this->user = null;
  3662. return true;
  3663. }
  3664. public function recover($array)
  3665. {
  3666. $email = $array['email'] ?? null;
  3667. if (!$email) {
  3668. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3669. return false;
  3670. }
  3671. $newPassword = $this->randString(10);
  3672. $isUser = $this->getUserByEmail($email);
  3673. if ($isUser) {
  3674. $this->updateUserPassword($newPassword, $isUser['id']);
  3675. $this->setAPIResponse('success', 'User password has been reset', 200);
  3676. $this->setLoggerChannel('User Management');
  3677. $this->logger->info('User Management Function - User: ' . $isUser['username'] . '\'s password was reset');
  3678. if ($this->config['PHPMAILER-enabled']) {
  3679. $PhpMailer = new PhpMailer();
  3680. $emailTemplate = array(
  3681. 'type' => 'reset',
  3682. 'body' => $this->config['PHPMAILER-emailTemplateReset'],
  3683. 'subject' => $this->config['PHPMAILER-emailTemplateResetSubject'],
  3684. 'user' => $isUser['username'],
  3685. 'password' => $newPassword,
  3686. 'inviteCode' => null,
  3687. );
  3688. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3689. $sendEmail = array(
  3690. 'to' => $email,
  3691. 'user' => $isUser['username'],
  3692. 'subject' => $emailTemplate['subject'],
  3693. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3694. );
  3695. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3696. $this->setAPIResponse('success', 'User password has been reset and email has been sent', 200);
  3697. }
  3698. return true;
  3699. } else {
  3700. $this->setAPIResponse('error', 'User not found', 404);
  3701. return false;
  3702. }
  3703. }
  3704. public function register($array)
  3705. {
  3706. $email = $array['email'] ?? null;
  3707. $username = $array['username'] ?? null;
  3708. $password = $array['password'] ?? null;
  3709. $registrationPassword = $array['registrationPassword'] ?? null;
  3710. if (!$email) {
  3711. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3712. return false;
  3713. }
  3714. if (!$username) {
  3715. $this->setAPIResponse('error', 'Username was not supplied', 422);
  3716. return false;
  3717. }
  3718. if (!$password) {
  3719. $this->setAPIResponse('error', 'Password was not supplied', 422);
  3720. return false;
  3721. }
  3722. if (!$registrationPassword) {
  3723. $this->setAPIResponse('error', 'Registration Password was not supplied', 422);
  3724. return false;
  3725. }
  3726. $this->setLoggerChannel('User Registration');
  3727. if ($registrationPassword == $this->decrypt($this->config['registrationPassword'])) {
  3728. $this->logger->debug('Registration Password Verified');
  3729. if ($this->createUser($username, $password, $email)) {
  3730. $this->logger->info('A User has registered');
  3731. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3732. $this->setLoggerChannel('Authentication', $username);
  3733. $this->logger->info('User has logged in');
  3734. return true;
  3735. }
  3736. } else {
  3737. return false;
  3738. }
  3739. } else {
  3740. $this->logger->warning('Wrong Password');
  3741. $this->setAPIResponse('error', 'Registration Password was incorrect', 401);
  3742. return false;
  3743. }
  3744. }
  3745. public function authRegister($username, $password, $email, $token = null)
  3746. {
  3747. $this->setLoggerChannel('Authentication', $username);
  3748. if ($this->config['authBackend'] !== '') {
  3749. $this->ombiImport($this->config['authBackend']);
  3750. }
  3751. $this->ssoCheck($username, $password, $token);
  3752. if ($token && (!$password || $password == '')) {
  3753. $password = $this->random_ascii_string(10);
  3754. }
  3755. if ($this->createUser($username, $password, $email)) {
  3756. $this->logger->info('A User has registered');
  3757. if ($this->config['PHPMAILER-enabled'] && $email !== '') {
  3758. $PhpMailer = new PhpMailer();
  3759. $emailTemplate = array(
  3760. 'type' => 'registration',
  3761. 'body' => $this->config['PHPMAILER-emailTemplateRegisterUser'],
  3762. 'subject' => $this->config['PHPMAILER-emailTemplateRegisterUserSubject'],
  3763. 'user' => $username,
  3764. 'password' => null,
  3765. 'inviteCode' => null,
  3766. );
  3767. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3768. $sendEmail = array(
  3769. 'to' => $email,
  3770. 'user' => $username,
  3771. 'subject' => $emailTemplate['subject'],
  3772. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3773. );
  3774. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3775. }
  3776. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3777. $this->logger->info('User has logged in');
  3778. return true;
  3779. } else {
  3780. return false;
  3781. }
  3782. } else {
  3783. $this->logger->warning('Registration error occurred');
  3784. return false;
  3785. }
  3786. }
  3787. public function revokeTokenCurrentUser($token = null)
  3788. {
  3789. if ($token) {
  3790. $response = [
  3791. array(
  3792. 'function' => 'query',
  3793. 'query' => array(
  3794. 'DELETE FROM tokens WHERE token = ?',
  3795. [$token]
  3796. )
  3797. ),
  3798. ];
  3799. } else {
  3800. $response = [
  3801. array(
  3802. 'function' => 'query',
  3803. 'query' => array(
  3804. 'DELETE FROM tokens WHERE user_id = ?',
  3805. [$this->user['userID']]
  3806. )
  3807. ),
  3808. ];
  3809. }
  3810. return $this->processQueries($response);
  3811. }
  3812. public function revokeToken($token = null)
  3813. {
  3814. if (!$token) {
  3815. $this->setAPIResponse('error', 'Token was not supplied', 422);
  3816. return false;
  3817. }
  3818. $response = [
  3819. array(
  3820. 'function' => 'query',
  3821. 'query' => array(
  3822. 'DELETE FROM tokens WHERE token = ?',
  3823. [$token]
  3824. )
  3825. ),
  3826. ];
  3827. $this->setAPIResponse('success', 'Token revoked', 204);
  3828. return $this->processQueries($response);
  3829. }
  3830. public function revokeTokenByIdCurrentUser($id = null)
  3831. {
  3832. if (!$id) {
  3833. $this->setAPIResponse('error', 'Id was not supplied', 422);
  3834. return false;
  3835. }
  3836. $response = [
  3837. array(
  3838. 'function' => 'query',
  3839. 'query' => array(
  3840. 'DELETE FROM tokens WHERE id = ? AND user_id = ?',
  3841. $id,
  3842. $this->user['userID']
  3843. )
  3844. ),
  3845. ];
  3846. $this->setAPIResponse('success', 'Token revoked', 204);
  3847. return $this->processQueries($response);
  3848. }
  3849. public function updateUserPassword($password, $id)
  3850. {
  3851. $response = [
  3852. array(
  3853. 'function' => 'query',
  3854. 'query' => array(
  3855. 'UPDATE users SET',
  3856. ['password' => password_hash($password, PASSWORD_BCRYPT)],
  3857. 'WHERE id = ?',
  3858. $id
  3859. )
  3860. ),
  3861. ];
  3862. return $this->processQueries($response);
  3863. }
  3864. public function updateUserPlexToken($token, $id)
  3865. {
  3866. $response = [
  3867. array(
  3868. 'function' => 'query',
  3869. 'query' => array(
  3870. 'UPDATE users SET',
  3871. ['plex_token' => $token],
  3872. 'WHERE id = ?',
  3873. $id
  3874. )
  3875. ),
  3876. ];
  3877. return $this->processQueries($response);
  3878. }
  3879. public function getUserTabsAndCategories($type = null)
  3880. {
  3881. if (!$this->hasDB()) {
  3882. return false;
  3883. }
  3884. $sort = ($this->config['unsortedTabs'] == 'top') ? 'DESC' : 'ASC';
  3885. $response = [
  3886. array(
  3887. 'function' => 'fetchAll',
  3888. 'query' => array(
  3889. 'SELECT * FROM tabs WHERE `group_id` >= ? AND `group_id_min` <= ? AND `enabled` = 1 ORDER BY `order` ' . $sort,
  3890. $this->user['groupID'],
  3891. $this->user['groupID'],
  3892. ),
  3893. 'key' => 'tabs'
  3894. ),
  3895. array(
  3896. 'function' => 'fetchAll',
  3897. 'query' => array(
  3898. 'SELECT * FROM tabs WHERE `add_to_admin` = 1 AND `enabled` = 1 ORDER BY `order` ' . $sort
  3899. ),
  3900. 'key' => 'tabs-admin'
  3901. ),
  3902. array(
  3903. 'function' => 'fetchAll',
  3904. 'query' => array(
  3905. 'SELECT * FROM categories ORDER BY `order` ASC',
  3906. ),
  3907. 'key' => 'categories'
  3908. ),
  3909. ];
  3910. $queries = $this->processQueries($response);
  3911. $this->applyTabVariables($queries['tabs']);
  3912. if ($this->qualifyRequest(1)) {
  3913. $this->applyTabVariables($queries['tabs-admin']);
  3914. $all['tabs'] = array_merge($queries['tabs'], $queries['tabs-admin']);
  3915. $newArray = [];
  3916. $ids = [];
  3917. foreach ($all['tabs'] as $key => $line) {
  3918. if (!in_array($line['id'], $ids)) {
  3919. $ids[] = $line['id'];
  3920. $newArray[$key] = $line;
  3921. }
  3922. }
  3923. $all['tabs'] = $newArray;
  3924. if (count($all['tabs']) > 0) {
  3925. usort($all['tabs'], function ($a, $b) {
  3926. if ($this->config['unsortedTabs'] == 'top') {
  3927. return $b['order'] <=> $a['order'];
  3928. } else {
  3929. return $a['order'] <=> $b['order'];
  3930. }
  3931. });
  3932. }
  3933. $newArray = NULL;
  3934. $ids = NULL;
  3935. } else {
  3936. $all['tabs'] = $queries['tabs'];
  3937. }
  3938. foreach ($all['tabs'] as $k => $v) {
  3939. $v['url_local'] = $v['type'] !== 0 ? $this->checkTabURL($v['url_local']) : $v['url_local'];
  3940. $v['url'] = $v['type'] !== 0 ? $this->checkTabURL($v['url']) : $v['url'];
  3941. $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'];
  3942. }
  3943. $count = array_map(function ($element) {
  3944. return $element['category_id'];
  3945. }, $all['tabs']);
  3946. $count = (array_count_values($count));
  3947. foreach ($queries['categories'] as $k => $v) {
  3948. $v['count'] = $count[$v['category_id']] ?? 0;
  3949. }
  3950. $all['categories'] = $queries['categories'];
  3951. switch ($type) {
  3952. case 'categories':
  3953. return $all['categories'];
  3954. case 'tabs':
  3955. return $all['tabs'];
  3956. default:
  3957. return $all;
  3958. }
  3959. }
  3960. public function checkTabURL($url = null)
  3961. {
  3962. return $url !== '' && $url !== null & $url !== 'null' ? $this->qualifyURL($url, false, true) : '';
  3963. }
  3964. public function refreshList()
  3965. {
  3966. $searchTerm = "Refresh";
  3967. return array_filter($this->config, function ($k) use ($searchTerm) {
  3968. return stripos($k, $searchTerm) !== false;
  3969. }, ARRAY_FILTER_USE_KEY);
  3970. }
  3971. public function homepageOrderList()
  3972. {
  3973. $searchTerm = "homepageOrder";
  3974. $order = array_filter($this->config, function ($k) use ($searchTerm) {
  3975. return stripos($k, $searchTerm) !== false;
  3976. }, ARRAY_FILTER_USE_KEY);
  3977. asort($order);
  3978. return $order;
  3979. }
  3980. public function tautulliList()
  3981. {
  3982. $searchTerm = "tautulli_token";
  3983. return array_filter($this->config, function ($k) use ($searchTerm) {
  3984. return stripos($k, $searchTerm) !== false;
  3985. }, ARRAY_FILTER_USE_KEY);
  3986. }
  3987. public function checkPlexAdminFilled()
  3988. {
  3989. if ($this->config['plexAdmin'] == '') {
  3990. return false;
  3991. } else {
  3992. if ((strpos($this->config['plexAdmin'], '@') !== false)) {
  3993. return 'email';
  3994. } else {
  3995. return 'username';
  3996. }
  3997. }
  3998. }
  3999. public function organizrSpecialSettings()
  4000. {
  4001. // js activeInfo
  4002. return [
  4003. 'homepage' => [
  4004. 'refresh' => $this->refreshList(),
  4005. 'order' => $this->homepageOrderList(),
  4006. 'search' => [
  4007. 'enabled' => $this->qualifyRequest($this->config['mediaSearchAuth']) && $this->config['mediaSearch'] == true && $this->config['plexToken'],
  4008. 'type' => $this->config['mediaSearchType'],
  4009. ],
  4010. 'requests' => [
  4011. 'service' => $this->config['defaultRequestService'],
  4012. ],
  4013. 'ombi' => [
  4014. 'enabled' => $this->qualifyRequest($this->config['homepageOmbiAuth']) && $this->qualifyRequest($this->config['homepageOmbiRequestAuth']) && $this->config['homepageOmbiEnabled'] == true && $this->config['ssoOmbi'] && isset($_COOKIE['Auth']),
  4015. 'authView' => $this->qualifyRequest($this->config['homepageOmbiAuth']),
  4016. 'authRequest' => $this->qualifyRequest($this->config['homepageOmbiRequestAuth']),
  4017. 'sso' => (bool)$this->config['ssoOmbi'],
  4018. 'cookie' => isset($_COOKIE['Auth']),
  4019. 'alias' => (bool)$this->config['ombiAlias'],
  4020. 'ombiDefaultFilterAvailable' => (bool)$this->config['ombiDefaultFilterAvailable'],
  4021. 'ombiDefaultFilterUnavailable' => (bool)$this->config['ombiDefaultFilterUnavailable'],
  4022. 'ombiDefaultFilterApproved' => (bool)$this->config['ombiDefaultFilterApproved'],
  4023. 'ombiDefaultFilterUnapproved' => (bool)$this->config['ombiDefaultFilterUnapproved'],
  4024. 'ombiDefaultFilterDenied' => (bool)$this->config['ombiDefaultFilterDenied']
  4025. ],
  4026. 'overseerr' => [
  4027. 'enabled' => $this->qualifyRequest($this->config['homepageOverseerrAuth']) && $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']) && $this->config['homepageOverseerrEnabled'] == true && $this->config['ssoOverseerr'] && isset($_COOKIE['connect_sid']),
  4028. 'authView' => $this->qualifyRequest($this->config['homepageOverseerrAuth']),
  4029. 'authRequest' => $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']),
  4030. 'sso' => (bool)$this->config['ssoOverseerr'],
  4031. 'cookie' => isset($_COOKIE['connect_sid']),
  4032. 'userSelectTv' => (bool)$this->config['homepageOverseerrRequestAuth'] == 'user',
  4033. 'overseerrDefaultFilterAvailable' => (bool)$this->config['overseerrDefaultFilterAvailable'],
  4034. 'overseerrDefaultFilterUnavailable' => (bool)$this->config['overseerrDefaultFilterUnavailable'],
  4035. 'overseerrDefaultFilterApproved' => (bool)$this->config['overseerrDefaultFilterApproved'],
  4036. 'overseerrDefaultFilterUnapproved' => (bool)$this->config['overseerrDefaultFilterUnapproved'],
  4037. 'overseerrDefaultFilterDenied' => (bool)$this->config['overseerrDefaultFilterDenied']
  4038. ],
  4039. 'jackett' => [
  4040. 'homepageJackettBackholeDownload' => $this->config['homepageJackettBackholeDownload'] ? true : false
  4041. ],
  4042. 'options' => [
  4043. 'alternateHomepageHeaders' => $this->config['alternateHomepageHeaders'],
  4044. 'healthChecksTags' => $this->config['healthChecksTags'],
  4045. 'titles' => [
  4046. 'tautulli' => $this->config['tautulliHeader']
  4047. ]
  4048. ],
  4049. 'media' => [
  4050. 'jellyfin' => $this->config['homepageJellyfinInstead']
  4051. ]
  4052. ],
  4053. 'sso' => [
  4054. 'misc' => [
  4055. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4056. 'rememberMe' => $this->config['rememberMe'],
  4057. 'rememberMeDays' => $this->config['rememberMeDays']
  4058. ],
  4059. 'plex' => [
  4060. 'enabled' => (bool)$this->config['ssoPlex'],
  4061. 'cookie' => isset($_COOKIE['mpt']),
  4062. 'machineID' => strlen($this->config['plexID']) == 40,
  4063. 'token' => $this->config['plexToken'] !== '',
  4064. 'plexAdmin' => $this->checkPlexAdminFilled(),
  4065. 'strict' => (bool)$this->config['plexStrictFriends'],
  4066. 'oAuthEnabled' => (bool)$this->config['plexoAuth'],
  4067. 'backend' => $this->config['authBackend'] == 'plex',
  4068. ],
  4069. 'tautulli' => [
  4070. 'enabled' => (bool)$this->config['ssoTautulli'],
  4071. 'cookie' => !empty($this->tautulliList()),
  4072. 'url' => ($this->config['tautulliURL'] !== '') ? $this->config['tautulliURL'] : false,
  4073. ],
  4074. 'overseerr' => [
  4075. 'enabled' => (bool)$this->config['ssoOverseerr'],
  4076. 'cookie' => isset($_COOKIE['connect.sid']),
  4077. 'url' => ($this->config['overseerrURL'] !== '') ? $this->config['overseerrURL'] : false,
  4078. 'api' => $this->config['overseerrToken'] !== '',
  4079. ],
  4080. 'petio' => [
  4081. 'enabled' => (bool)$this->config['ssoPetio'],
  4082. 'cookie' => isset($_COOKIE['petio_jwt']),
  4083. 'url' => ($this->config['petioURL'] !== '') ? $this->config['petioURL'] : false,
  4084. 'api' => $this->config['petioToken'] !== '',
  4085. ],
  4086. 'ombi' => [
  4087. 'enabled' => (bool)$this->config['ssoOmbi'],
  4088. 'cookie' => isset($_COOKIE['Auth']),
  4089. 'url' => ($this->config['ombiURL'] !== '') ? $this->config['ombiURL'] : false,
  4090. 'api' => $this->config['ombiToken'] !== '',
  4091. ],
  4092. 'jellyfin' => [
  4093. 'enabled' => (bool)$this->config['ssoJellyfin'],
  4094. 'url' => ($this->config['jellyfinURL'] !== '') ? $this->config['jellyfinURL'] : false,
  4095. 'ssoUrl' => ($this->config['jellyfinSSOURL'] !== '') ? $this->config['jellyfinSSOURL'] : false,
  4096. ],
  4097. 'komga' => [
  4098. 'enabled' => (bool)$this->config['ssoKomga'],
  4099. 'cookie' => isset($_COOKIE['komga_token']),
  4100. 'url' => ($this->config['komgaURL'] !== '') ? $this->config['komgaURL'] : false,
  4101. ]
  4102. ],
  4103. 'ping' => [
  4104. 'onlineSound' => $this->config['pingOnlineSound'],
  4105. 'offlineSound' => $this->config['pingOfflineSound'],
  4106. 'statusSounds' => $this->config['statusSounds'],
  4107. 'auth' => $this->config['pingAuth'],
  4108. 'authMessage' => $this->config['pingAuthMessage'],
  4109. 'authMs' => $this->config['pingAuthMs'],
  4110. 'ms' => $this->config['pingMs'],
  4111. 'adminRefresh' => $this->config['adminPingRefresh'],
  4112. 'everyoneRefresh' => $this->config['otherPingRefresh'],
  4113. ],
  4114. 'notifications' => [
  4115. 'backbone' => $this->config['notificationBackbone'],
  4116. 'position' => $this->config['notificationPosition']
  4117. ],
  4118. 'lockout' => [
  4119. 'enabled' => $this->config['lockoutSystem'],
  4120. 'timer' => $this->config['lockoutTimeout'],
  4121. 'minGroup' => $this->config['lockoutMinAuth'],
  4122. 'maxGroup' => $this->config['lockoutMaxAuth']
  4123. ],
  4124. 'user' => [
  4125. 'agent' => isset($_SERVER ['HTTP_USER_AGENT']) ? $_SERVER ['HTTP_USER_AGENT'] : null,
  4126. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4127. 'local' => $this->isLocal(),
  4128. 'ip' => $this->userIP()
  4129. ],
  4130. 'login' => [
  4131. 'rememberMe' => $this->config['rememberMe'],
  4132. 'rememberMeDays' => $this->config['rememberMeDays'],
  4133. 'wanDomain' => $this->config['wanDomain'],
  4134. 'localAddress' => $this->config['localAddress'],
  4135. 'enableLocalAddressForward' => $this->config['enableLocalAddressForward'],
  4136. ],
  4137. 'misc' => [
  4138. 'installedPlugins' => $this->qualifyRequest(1) ? $this->config['installedPlugins'] : '',
  4139. 'installedThemes' => $this->qualifyRequest(1) ? $this->config['installedThemes'] : '',
  4140. 'return' => $_SERVER['HTTP_REFERER'] ?? false,
  4141. 'authDebug' => $this->config['authDebug'],
  4142. 'minimalLoginScreen' => $this->config['minimalLoginScreen'],
  4143. 'unsortedTabs' => $this->config['unsortedTabs'],
  4144. 'authType' => $this->config['authType'],
  4145. 'authBackend' => $this->config['authBackend'],
  4146. 'newMessageSound' => (isset($this->config['CHAT-newMessageSound-include'])) ? $this->config['CHAT-newMessageSound-include'] : '',
  4147. 'uuid' => ($this->config['uuid']) ?? null,
  4148. 'docker' => $this->qualifyRequest(1) ? $this->docker : '',
  4149. 'githubCommit' => $this->qualifyRequest(1) ? $this->commit : '',
  4150. 'schema' => $this->qualifyRequest(1) ? $this->getSchema() : '',
  4151. 'debugArea' => $this->qualifyRequest($this->config['debugAreaAuth']),
  4152. 'debugErrors' => $this->config['debugErrors'],
  4153. 'sandbox' => $this->config['sandbox'],
  4154. 'expandCategoriesByDefault' => $this->config['expandCategoriesByDefault'],
  4155. 'autoCollapseCategories' => $this->config['autoCollapseCategories'],
  4156. 'autoExpandNavBar' => $this->config['autoExpandNavBar'],
  4157. 'sideMenuCollapsed' => $this->config['allowCollapsableSideMenu'] && $this->config['sideMenuCollapsed'],
  4158. 'collapseSideMenuOnClick' => $this->config['allowCollapsableSideMenu'] && $this->config['collapseSideMenuOnClick'],
  4159. 'authProxyOverrideLogout' => $this->config['authProxyOverrideLogout'],
  4160. 'authProxyLogoutURL' => $this->config['authProxyLogoutURL'],
  4161. ],
  4162. 'menuLink' => [
  4163. 'githubMenuLink' => $this->config['githubMenuLink'],
  4164. 'organizrSupportMenuLink' => $this->config['organizrSupportMenuLink'],
  4165. 'organizrDocsMenuLink' => $this->config['organizrDocsMenuLink'],
  4166. 'organizrSignoutMenuLink' => $this->config['organizrSignoutMenuLink'],
  4167. 'organizrFeatureRequestLink' => $this->config['organizrFeatureRequestLink']
  4168. ]
  4169. ];
  4170. }
  4171. public function checkLog($path)
  4172. {
  4173. if (file_exists($path)) {
  4174. if (filesize($path) > 500000) {
  4175. rename($path, $path . '[' . date('Y-m-d') . '].json');
  4176. return false;
  4177. }
  4178. return true;
  4179. } else {
  4180. return false;
  4181. }
  4182. }
  4183. public function writeLog($type = 'error', $message = null, $username = null)
  4184. {
  4185. $this->timeExecution = $this->timeExecution($this->timeExecution);
  4186. $message = $message . ' [Execution Time: ' . $this->formatSeconds($this->timeExecution) . ']';
  4187. $username = ($username) ? htmlspecialchars($username, ENT_QUOTES) : $this->user['username'] ?? 'SYSTEM';
  4188. if ($this->checkLog($this->organizrLog)) {
  4189. $getLog = str_replace("\r\ndate", "date", file_get_contents($this->organizrLog));
  4190. $gotLog = json_decode($getLog, true);
  4191. }
  4192. $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)));
  4193. $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $this->currentTime, 'type' => $type, 'username' => $username, 'ip' => $this->userIP(), 'message' => $message);
  4194. if (isset($gotLog)) {
  4195. array_push($gotLog["log_items"], $logEntry);
  4196. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
  4197. } else {
  4198. $writeFailLog = str_replace("date", "\r\ndate", json_encode($logEntryFirst));
  4199. }
  4200. file_put_contents($this->organizrLog, $writeFailLog);
  4201. }
  4202. public function isApprovedRequest($method, $data)
  4203. {
  4204. $requesterToken = $this->getallheadersi()['token'] ?? ($_GET['apikey'] ?? false);
  4205. $apiKey = ($this->config['organizrAPI']) ?? null;
  4206. if (isset($data['formKey'])) {
  4207. $formKey = $data['formKey'];
  4208. } elseif (isset($this->getallheadersi()['formkey'])) {
  4209. $formKey = $this->getallheadersi()['formkey'];
  4210. } else {
  4211. $formKey = false;
  4212. }
  4213. // Check token or API key
  4214. // If API key, return 0 for admin
  4215. if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
  4216. //DO API CHECK
  4217. return true;
  4218. } elseif ($method == 'POST') {
  4219. if ($this->checkFormKey($formKey)) {
  4220. return true;
  4221. } else {
  4222. $this->setLoggerChannel('Authentication');
  4223. $this->logger->warning('Unable to authenticate Form Key: ' . $formKey);
  4224. return false;
  4225. }
  4226. } else {
  4227. return true;
  4228. }
  4229. return false;
  4230. }
  4231. public function checkFormKey($formKey = '')
  4232. {
  4233. return password_verify(substr($this->config['organizrHash'], 2, 10), $formKey);
  4234. }
  4235. public function buildHomepage()
  4236. {
  4237. $homepageOrder = $this->homepageOrderList();
  4238. $homepageBuilt = '';
  4239. foreach ($homepageOrder as $key => $value) {
  4240. //new way
  4241. if (method_exists($this, $key)) {
  4242. $homepageBuilt .= $this->$key();
  4243. } elseif (strpos($key, 'homepageOrdercustomhtml') !== false) {
  4244. $iteration = substr($key, -2);
  4245. $homepageBuilt .= $this->homepageOrdercustomhtml($iteration);
  4246. } else {
  4247. $homepageBuilt .= '<div id="' . $key . '"></div>';
  4248. }
  4249. //old way
  4250. //$homepageBuilt .= $this->buildHomepageItem($key);
  4251. }
  4252. return $homepageBuilt;
  4253. }
  4254. public function buildHomepageSettings()
  4255. {
  4256. $homepageOrder = $this->homepageOrderList();
  4257. $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">';
  4258. $inputList = '<form id="homepage-values" class="row">';
  4259. foreach ($homepageOrder as $key => $val) {
  4260. switch ($key) {
  4261. case 'homepageOrdercustomhtml01':
  4262. case 'homepageOrdercustomhtml02':
  4263. case 'homepageOrdercustomhtml03':
  4264. case 'homepageOrdercustomhtml04':
  4265. case 'homepageOrdercustomhtml05':
  4266. case 'homepageOrdercustomhtml06':
  4267. case 'homepageOrdercustomhtml07':
  4268. case 'homepageOrdercustomhtml08':
  4269. $iteration = substr($key, -2);
  4270. $class = 'bg-info';
  4271. $image = 'plugins/images/tabs/HTML5.png';
  4272. if (!$this->config['homepageCustomHTML' . $iteration . 'Enabled']) {
  4273. $class .= ' faded';
  4274. }
  4275. break;
  4276. case 'homepageOrdertransmission':
  4277. $class = 'bg-transmission';
  4278. $image = 'plugins/images/tabs/transmission.png';
  4279. if (!$this->config['homepageTransmissionEnabled']) {
  4280. $class .= ' faded';
  4281. }
  4282. break;
  4283. case 'homepageOrdernzbget':
  4284. $class = 'bg-nzbget';
  4285. $image = 'plugins/images/tabs/nzbget.png';
  4286. if (!$this->config['homepageNzbgetEnabled']) {
  4287. $class .= ' faded';
  4288. }
  4289. break;
  4290. case 'homepageOrderjdownloader':
  4291. $class = 'bg-sab';
  4292. $image = 'plugins/images/tabs/jdownloader.png';
  4293. if (!$this->config['homepageJdownloaderEnabled']) {
  4294. $class .= ' faded';
  4295. }
  4296. break;
  4297. case 'homepageOrdersabnzbd':
  4298. $class = 'bg-sab';
  4299. $image = 'plugins/images/tabs/sabnzbd.png';
  4300. if (!$this->config['homepageSabnzbdEnabled']) {
  4301. $class .= ' faded';
  4302. }
  4303. break;
  4304. case 'homepageOrderdeluge':
  4305. $class = 'bg-deluge';
  4306. $image = 'plugins/images/tabs/deluge.png';
  4307. if (!$this->config['homepageDelugeEnabled']) {
  4308. $class .= ' faded';
  4309. }
  4310. break;
  4311. case 'homepageOrderqBittorrent':
  4312. $class = 'bg-qbit';
  4313. $image = 'plugins/images/tabs/qBittorrent.png';
  4314. if (!$this->config['homepageqBittorrentEnabled']) {
  4315. $class .= ' faded';
  4316. }
  4317. break;
  4318. case 'homepageOrderuTorrent':
  4319. $class = 'bg-qbit';
  4320. $image = 'plugins/images/tabs/utorrent.png';
  4321. if (!$this->config['homepageuTorrentEnabled']) {
  4322. $class .= ' faded';
  4323. }
  4324. break;
  4325. case 'homepageOrderrTorrent':
  4326. $class = 'bg-qbit';
  4327. $image = 'plugins/images/tabs/rTorrent.png';
  4328. if (!$this->config['homepagerTorrentEnabled']) {
  4329. $class .= ' faded';
  4330. }
  4331. break;
  4332. case 'homepageOrderplexnowplaying':
  4333. case 'homepageOrderplexrecent':
  4334. case 'homepageOrderplexplaylist':
  4335. $class = 'bg-plex';
  4336. $image = 'plugins/images/tabs/plex.png';
  4337. if (!$this->config['homepagePlexEnabled']) {
  4338. $class .= ' faded';
  4339. }
  4340. break;
  4341. case 'homepageOrderembynowplaying':
  4342. case 'homepageOrderembyrecent':
  4343. $class = 'bg-emby';
  4344. $image = 'plugins/images/tabs/emby.png';
  4345. if (!$this->config['homepageEmbyEnabled']) {
  4346. $class .= ' faded';
  4347. }
  4348. break;
  4349. case 'homepageOrderjellyfinnowplaying':
  4350. case 'homepageOrderjellyfinrecent':
  4351. $class = 'bg-jellyfin';
  4352. $image = 'plugins/images/tabs/jellyfin.png';
  4353. if (!$this->config['homepageJellyfinEnabled']) {
  4354. $class .= ' faded';
  4355. }
  4356. break;
  4357. case 'homepageOrderombi':
  4358. $class = 'bg-inverse';
  4359. $image = 'plugins/images/tabs/ombi.png';
  4360. if (!$this->config['homepageOmbiEnabled']) {
  4361. $class .= ' faded';
  4362. }
  4363. break;
  4364. case 'homepageOrderoverseerr':
  4365. $class = 'bg-inverse';
  4366. $image = 'plugins/images/tabs/overseerr.png';
  4367. if (!$this->config['homepageOverseerrEnabled']) {
  4368. $class .= ' faded';
  4369. }
  4370. break;
  4371. case 'homepageOrderDonate':
  4372. $class = 'bg-primary';
  4373. $image = 'plugins/images/tabs/donate.png';
  4374. if (!$this->config['homepageDonateEnabled']) {
  4375. $class .= ' faded';
  4376. }
  4377. break;
  4378. case 'homepageOrdercalendar':
  4379. $class = 'bg-primary';
  4380. $image = 'plugins/images/tabs/calendar.png';
  4381. if (!$this->config['homepageCalendarEnabled'] && !$this->config['homepageSonarrEnabled'] && !$this->config['homepageRadarrEnabled'] && !$this->config['homepageSickrageEnabled'] && !$this->config['homepageCouchpotatoEnabled']) {
  4382. $class .= ' faded';
  4383. }
  4384. break;
  4385. case 'homepageOrderdownloader':
  4386. $class = 'bg-inverse';
  4387. $image = 'plugins/images/tabs/downloader.png';
  4388. 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']) {
  4389. $class .= ' faded';
  4390. }
  4391. break;
  4392. case 'homepageOrderhealthchecks':
  4393. $class = 'bg-healthchecks';
  4394. $image = 'plugins/images/tabs/healthchecks.png';
  4395. if (!$this->config['homepageHealthChecksEnabled']) {
  4396. $class .= ' faded';
  4397. }
  4398. break;
  4399. case 'homepageOrderunifi':
  4400. $class = 'bg-info';
  4401. $image = 'plugins/images/tabs/ubnt.png';
  4402. if (!$this->config['homepageUnifiEnabled']) {
  4403. $class .= ' faded';
  4404. }
  4405. break;
  4406. case 'homepageOrdertautulli':
  4407. $class = 'bg-info';
  4408. $image = 'plugins/images/tabs/tautulli.png';
  4409. if (!$this->config['homepageTautulliEnabled']) {
  4410. $class .= ' faded';
  4411. }
  4412. break;
  4413. case 'homepageOrderPihole':
  4414. $class = 'bg-info';
  4415. $image = 'plugins/images/tabs/pihole.png';
  4416. if (!$this->config['homepagePiholeEnabled']) {
  4417. $class .= ' faded';
  4418. }
  4419. break;
  4420. case 'homepageOrderMonitorr':
  4421. $class = 'bg-info';
  4422. $image = 'plugins/images/tabs/monitorr.png';
  4423. if (!$this->config['homepageMonitorrEnabled']) {
  4424. $class .= ' faded';
  4425. }
  4426. break;
  4427. case 'homepageOrderWeatherAndAir':
  4428. $class = 'bg-success';
  4429. $image = 'plugins/images/tabs/wind.png';
  4430. if (!$this->config['homepageWeatherAndAirEnabled']) {
  4431. $class .= ' faded';
  4432. }
  4433. break;
  4434. case 'homepageOrderSpeedtest':
  4435. $class = 'bg-success';
  4436. $image = 'plugins/images/tabs/speedtest-icon.png';
  4437. if (!$this->config['homepageSpeedtestEnabled']) {
  4438. $class .= ' faded';
  4439. }
  4440. break;
  4441. case 'homepageOrderNetdata':
  4442. $class = 'bg-success';
  4443. $image = 'plugins/images/tabs/netdata.png';
  4444. if (!$this->config['homepageNetdataEnabled']) {
  4445. $class .= ' faded';
  4446. }
  4447. break;
  4448. case 'homepageOrderOctoprint':
  4449. $class = 'bg-success';
  4450. $image = 'plugins/images/tabs/octoprint.png';
  4451. if (!$this->config['homepageOctoprintEnabled']) {
  4452. $class .= ' faded';
  4453. }
  4454. break;
  4455. case 'homepageOrderSonarrQueue':
  4456. $class = 'bg-sonarr';
  4457. $image = 'plugins/images/tabs/sonarr.png';
  4458. if (!$this->config['homepageSonarrQueueEnabled']) {
  4459. $class .= ' faded';
  4460. }
  4461. break;
  4462. case 'homepageOrderRadarrQueue':
  4463. $class = 'bg-radarr';
  4464. $image = 'plugins/images/tabs/radarr.png';
  4465. if (!$this->config['homepageRadarrQueueEnabled']) {
  4466. $class .= ' faded';
  4467. }
  4468. break;
  4469. case 'homepageOrderJackett':
  4470. $class = 'bg-inverse';
  4471. $image = 'plugins/images/tabs/jackett.png';
  4472. if (!$this->config['homepageJackettEnabled']) {
  4473. $class .= ' faded';
  4474. }
  4475. break;
  4476. case 'homepageOrderBookmarks':
  4477. $class = 'bg-bookmarks';
  4478. $image = 'plugins/images/bookmark.png';
  4479. if (!$this->config['homepageBookmarksEnabled']) {
  4480. $class .= ' faded';
  4481. }
  4482. break;
  4483. default:
  4484. $class = 'blue-bg';
  4485. $image = '';
  4486. break;
  4487. }
  4488. $homepageList .= '
  4489. <div class="col-md-3 col-xs-12 sort-homepage m-t-10 hvr-grow clearfix">
  4490. <div class="homepage-drag fc-event ' . $class . ' lazyload" data-src="' . $image . '">
  4491. <span class="ordinal-position text-uppercase badge bg-org homepage-number" data-link="' . $key . '" style="float:left;width: 30px;">' . $val . '</span>
  4492. <span class="homepage-text">&nbsp; ' . strtoupper(substr($key, 13)) . '</span>
  4493. </div>
  4494. </div>
  4495. ';
  4496. $inputList .= '<input type="hidden" name="' . $key . '">';
  4497. }
  4498. $homepageList .= '</div>';
  4499. $inputList .= '</form>';
  4500. return $homepageList . $inputList;
  4501. }
  4502. public function setGroupOptionsVariable()
  4503. {
  4504. $this->groupOptions = $this->groupSelect();
  4505. }
  4506. public function getSettingsHomepageItem($item)
  4507. {
  4508. $items = $this->getSettingsHomepage();
  4509. foreach ($items as $k => $v) {
  4510. if (strtolower($v['name']) === strtolower($item)) {
  4511. $functionName = $v['settingsArray'];
  4512. return $this->$functionName();
  4513. }
  4514. }
  4515. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4516. return null;
  4517. }
  4518. public function getSettingsHomepageItemDebug($service)
  4519. {
  4520. $service = $this->getSettingsHomepageItem($service);
  4521. if ($service) {
  4522. $debug = [];
  4523. foreach ($service['settings'] as $category => $items) {
  4524. if ($category !== 'About' && $category !== 'Test Connection') {
  4525. foreach ($items as $item) {
  4526. if ($item['type'] !== 'html' && $item['type'] !== 'blank' && $item['type'] !== 'button') {
  4527. if ((stripos($item['name'], 'token') !== false) || (stripos($item['name'], 'key') !== false) || (stripos($item['name'], 'password'))) {
  4528. if ($item['value'] !== '') {
  4529. $item['value'] = '***redacted***';
  4530. }
  4531. }
  4532. $debug[$category][$item['name']] = $item['value'];
  4533. }
  4534. }
  4535. }
  4536. }
  4537. return $debug;
  4538. }
  4539. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4540. return null;
  4541. }
  4542. public function getSettingsHomepage()
  4543. {
  4544. $this->setGroupOptionsVariable();
  4545. return $this->getHomepageSettingsCombined();
  4546. }
  4547. public function isTabNameTaken($name, $id = null)
  4548. {
  4549. if ($id) {
  4550. $response = [
  4551. array(
  4552. 'function' => 'fetchAll',
  4553. 'query' => array(
  4554. 'SELECT * FROM tabs WHERE `name` LIKE ? AND `id` != ?',
  4555. $name,
  4556. $id
  4557. )
  4558. ),
  4559. ];
  4560. } else {
  4561. $response = [
  4562. array(
  4563. 'function' => 'fetchAll',
  4564. 'query' => array(
  4565. 'SELECT * FROM tabs WHERE `name` LIKE ?',
  4566. $name
  4567. )
  4568. ),
  4569. ];
  4570. }
  4571. return $this->processQueries($response);
  4572. }
  4573. public function isCategoryNameTaken($name, $id = null)
  4574. {
  4575. if ($id) {
  4576. $response = [
  4577. array(
  4578. 'function' => 'fetchAll',
  4579. 'query' => array(
  4580. 'SELECT * FROM categories WHERE `category` LIKE ? AND `id` != ?',
  4581. $name,
  4582. $id
  4583. )
  4584. ),
  4585. ];
  4586. } else {
  4587. $response = [
  4588. array(
  4589. 'function' => 'fetchAll',
  4590. 'query' => array(
  4591. 'SELECT * FROM categories WHERE `category` LIKE ?',
  4592. $name
  4593. )
  4594. ),
  4595. ];
  4596. }
  4597. return $this->processQueries($response);
  4598. }
  4599. public function isGroupNameTaken($name, $id = null)
  4600. {
  4601. if ($id) {
  4602. $response = [
  4603. array(
  4604. 'function' => 'fetchAll',
  4605. 'query' => array(
  4606. 'SELECT * FROM groups WHERE `group` LIKE ? AND `id` != ?',
  4607. $name,
  4608. $id
  4609. )
  4610. ),
  4611. ];
  4612. } else {
  4613. $response = [
  4614. array(
  4615. 'function' => 'fetchAll',
  4616. 'query' => array(
  4617. 'SELECT * FROM groups WHERE `group` LIKE ?',
  4618. $name
  4619. )
  4620. ),
  4621. ];
  4622. }
  4623. return $this->processQueries($response);
  4624. }
  4625. public function getTableColumns($table)
  4626. {
  4627. if ($this->config['driver'] == 'sqlite3') {
  4628. $query = 'PRAGMA table_info(?)';
  4629. } else {
  4630. $query = 'DESCRIBE %n';
  4631. }
  4632. $response = [
  4633. array(
  4634. 'function' => 'fetchAll',
  4635. 'query' => [
  4636. $query, $table
  4637. ]
  4638. ),
  4639. ];
  4640. return $this->processQueries($response);
  4641. }
  4642. public function getTableColumnsFormatted($table)
  4643. {
  4644. if ($this->config['driver'] == 'sqlite3') {
  4645. $name = 'name';
  4646. } else {
  4647. $name = 'Field';
  4648. }
  4649. $columns = $this->getTableColumns($table);
  4650. if ($columns) {
  4651. $columnsFormatted = [];
  4652. foreach ($columns as $k => $v) {
  4653. $columnsFormatted[$v[$name]] = $v;
  4654. }
  4655. return $columnsFormatted;
  4656. } else {
  4657. return false;
  4658. }
  4659. }
  4660. public function getTabById($id)
  4661. {
  4662. $response = [
  4663. array(
  4664. 'function' => 'fetch',
  4665. 'query' => array(
  4666. 'SELECT * FROM tabs WHERE `id` = ?',
  4667. $id
  4668. )
  4669. ),
  4670. ];
  4671. return $this->processQueries($response);
  4672. }
  4673. public function getTabGroupByTabName($tab)
  4674. {
  4675. $response = [
  4676. array(
  4677. 'function' => 'fetch',
  4678. 'query' => array(
  4679. 'SELECT group_id FROM tabs WHERE name LIKE %~like~',
  4680. $tab
  4681. )
  4682. ),
  4683. ];
  4684. $query = $this->processQueries($response);
  4685. return $query ? $query['group_id'] : 0;
  4686. }
  4687. public function getCategoryById($id)
  4688. {
  4689. $response = [
  4690. array(
  4691. 'function' => 'fetch',
  4692. 'query' => array(
  4693. 'SELECT * FROM categories WHERE `id` = ?',
  4694. $id
  4695. )
  4696. ),
  4697. ];
  4698. return $this->processQueries($response);
  4699. }
  4700. public function getGroupUserCountById($id)
  4701. {
  4702. $response = [
  4703. array(
  4704. 'function' => 'fetchSingle',
  4705. 'query' => array(
  4706. 'SELECT count(username) AS count FROM groups INNER JOIN users ON users.group_id = groups.group_id AND groups.id = ?',
  4707. $id
  4708. )
  4709. ),
  4710. ];
  4711. return $this->processQueries($response);
  4712. }
  4713. public function getGroupById($id)
  4714. {
  4715. $response = [
  4716. array(
  4717. 'function' => 'fetch',
  4718. 'query' => array(
  4719. 'SELECT * FROM groups WHERE `id` = ?',
  4720. $id
  4721. )
  4722. ),
  4723. ];
  4724. return $this->processQueries($response);
  4725. }
  4726. public function getGroupByGroupId($id)
  4727. {
  4728. $response = [
  4729. array(
  4730. 'function' => 'fetch',
  4731. 'query' => array(
  4732. 'SELECT * FROM groups WHERE `group_id` = ?',
  4733. $id
  4734. )
  4735. ),
  4736. ];
  4737. return $this->processQueries($response);
  4738. }
  4739. public function getDefaultGroup()
  4740. {
  4741. $response = [
  4742. array(
  4743. 'function' => 'fetch',
  4744. 'query' => array(
  4745. 'SELECT * FROM groups WHERE `default` = 1'
  4746. )
  4747. ),
  4748. ];
  4749. return $this->processQueries($response);
  4750. }
  4751. public function getDefaultGroupId()
  4752. {
  4753. $response = [
  4754. array(
  4755. 'function' => 'fetchSingle',
  4756. 'query' => array(
  4757. 'SELECT `group_id` FROM groups WHERE `default` = 1'
  4758. )
  4759. ),
  4760. ];
  4761. return $this->processQueries($response);
  4762. }
  4763. public function getDefaultCategory()
  4764. {
  4765. $response = [
  4766. array(
  4767. 'function' => 'fetch',
  4768. 'query' => array(
  4769. 'SELECT * FROM categories WHERE `default` = 1'
  4770. )
  4771. ),
  4772. ];
  4773. return $this->processQueries($response);
  4774. }
  4775. public function getDefaultCategoryId()
  4776. {
  4777. $response = [
  4778. array(
  4779. 'function' => 'fetchSingle',
  4780. 'query' => array(
  4781. 'SELECT `category_id` FROM categories WHERE `default` = 1'
  4782. )
  4783. ),
  4784. ];
  4785. return $this->processQueries($response);
  4786. }
  4787. public function getNextTabOrder()
  4788. {
  4789. $response = [
  4790. array(
  4791. 'function' => 'fetchSingle',
  4792. 'query' => array(
  4793. 'SELECT `order` from tabs ORDER BY `order` DESC'
  4794. )
  4795. ),
  4796. ];
  4797. return $this->processQueries($response);
  4798. }
  4799. public function getNextCategoryOrder()
  4800. {
  4801. $response = [
  4802. array(
  4803. 'function' => 'fetchSingle',
  4804. 'query' => array(
  4805. 'SELECT `order` from categories ORDER BY `order` DESC'
  4806. )
  4807. ),
  4808. ];
  4809. return $this->processQueries($response);
  4810. }
  4811. public function getNextGroupOrder()
  4812. {
  4813. $response = [
  4814. array(
  4815. 'function' => 'fetchSingle',
  4816. 'query' => array(
  4817. 'SELECT `group_id` from groups WHERE `group_id` != "999" ORDER BY `group_id` DESC'
  4818. )
  4819. ),
  4820. ];
  4821. return $this->processQueries($response);
  4822. }
  4823. public function getNextCategoryId()
  4824. {
  4825. $response = [
  4826. array(
  4827. 'function' => 'fetchSingle',
  4828. 'query' => array(
  4829. 'SELECT `category_id` from categories ORDER BY `category_id` DESC'
  4830. )
  4831. ),
  4832. ];
  4833. return $this->processQueries($response);
  4834. }
  4835. public function clearTabDefault()
  4836. {
  4837. $response = [
  4838. array(
  4839. 'function' => 'query',
  4840. 'query' => array(
  4841. 'UPDATE tabs SET `default` = 0'
  4842. )
  4843. ),
  4844. ];
  4845. return $this->processQueries($response);
  4846. }
  4847. public function clearCategoryDefault()
  4848. {
  4849. $response = [
  4850. array(
  4851. 'function' => 'query',
  4852. 'query' => array(
  4853. 'UPDATE categories SET `default` = 0'
  4854. )
  4855. ),
  4856. ];
  4857. return $this->processQueries($response);
  4858. }
  4859. public function clearGroupDefault()
  4860. {
  4861. $response = [
  4862. array(
  4863. 'function' => 'query',
  4864. 'query' => array(
  4865. 'UPDATE groups SET `default` = 0'
  4866. )
  4867. ),
  4868. ];
  4869. return $this->processQueries($response);
  4870. }
  4871. public function checkKeys($tabInfo, $newData)
  4872. {
  4873. foreach ($newData as $k => $v) {
  4874. if (!array_key_exists($k, $tabInfo)) {
  4875. unset($newData[$k]);
  4876. }
  4877. }
  4878. return $newData;
  4879. }
  4880. public function getTabByIdCheckUser($id)
  4881. {
  4882. $tabInfo = $this->getTabById($id);
  4883. if ($tabInfo) {
  4884. if ($this->qualifyRequest($tabInfo['group_id'], true)) {
  4885. return $tabInfo;
  4886. }
  4887. } else {
  4888. $this->setAPIResponse('error', 'id not found', 404);
  4889. return false;
  4890. }
  4891. }
  4892. public function deleteTab($id)
  4893. {
  4894. $response = [
  4895. array(
  4896. 'function' => 'query',
  4897. 'query' => array(
  4898. 'DELETE FROM tabs WHERE id = ?',
  4899. $id
  4900. )
  4901. ),
  4902. ];
  4903. $tabInfo = $this->getTabById($id);
  4904. if ($tabInfo) {
  4905. $this->setLoggerChannel('Tab Management');
  4906. $this->logger->debug('Deleted Tab [' . $tabInfo['name'] . ']');
  4907. $this->setAPIResponse('success', 'Tab deleted', 204);
  4908. return $this->processQueries($response);
  4909. } else {
  4910. $this->setAPIResponse('error', 'id not found', 404);
  4911. return false;
  4912. }
  4913. }
  4914. public function addTab($array)
  4915. {
  4916. if (!$array) {
  4917. $this->setAPIResponse('error', 'no data was sent', 422);
  4918. return null;
  4919. }
  4920. $array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
  4921. $array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
  4922. $array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
  4923. $array['enabled'] = ($array['enabled']) ?? 0;
  4924. $array['default'] = ($array['default']) ?? 0;
  4925. $array['type'] = ($array['type']) ?? 1;
  4926. $array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
  4927. if (array_key_exists('name', $array)) {
  4928. $array['name'] = $this->sanitizeUserString($array['name']);
  4929. if ($this->isTabNameTaken($array['name'])) {
  4930. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  4931. return false;
  4932. }
  4933. } else {
  4934. $this->setAPIResponse('error', 'Tab name was not supplied', 422);
  4935. return false;
  4936. }
  4937. if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
  4938. $this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
  4939. return false;
  4940. }
  4941. if (!array_key_exists('image', $array)) {
  4942. $this->setAPIResponse('error', 'Tab image was not supplied', 422);
  4943. return false;
  4944. }
  4945. $response = [
  4946. array(
  4947. 'function' => 'query',
  4948. 'query' => array(
  4949. 'INSERT INTO [tabs]',
  4950. $array
  4951. )
  4952. ),
  4953. ];
  4954. $this->setAPIResponse(null, 'Tab added');
  4955. $this->setLoggerChannel('Tab Management');
  4956. $this->logger->debug('Added Tab for [' . $array['name'] . ']');
  4957. return $this->processQueries($response);
  4958. }
  4959. public function updateTab($id, $array)
  4960. {
  4961. if (!$id || $id == '') {
  4962. $this->setAPIResponse('error', 'id was not set', 422);
  4963. return null;
  4964. }
  4965. if (!$array) {
  4966. $this->setAPIResponse('error', 'no data was sent', 422);
  4967. return null;
  4968. }
  4969. $tabInfo = $this->getTabById($id);
  4970. if ($tabInfo) {
  4971. $array = $this->checkKeys($tabInfo, $array);
  4972. } else {
  4973. $this->setAPIResponse('error', 'No tab info found', 404);
  4974. return false;
  4975. }
  4976. if (array_key_exists('name', $array)) {
  4977. $array['name'] = $this->sanitizeUserString($array['name']);
  4978. if ($this->isTabNameTaken($array['name'], $id)) {
  4979. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  4980. return false;
  4981. }
  4982. }
  4983. if (array_key_exists('default', $array)) {
  4984. if ($array['default']) {
  4985. $this->clearTabDefault();
  4986. }
  4987. }
  4988. if (array_key_exists('group_id', $array)) {
  4989. $groupCheck = (array_key_exists('group_id_min', $array)) ? $array['group_id_min'] : $tabInfo['group_id_min'];
  4990. if ($array['group_id'] < $groupCheck) {
  4991. $this->setAPIResponse('error', 'Tab name: ' . $tabInfo['name'] . ' cannot have a lower Group Id Max than Group Id Min', 409);
  4992. return false;
  4993. }
  4994. }
  4995. if (array_key_exists('group_id_min', $array)) {
  4996. $groupCheck = (array_key_exists('group_id', $array)) ? $array['group_id'] : $tabInfo['group_id'];
  4997. if ($array['group_id_min'] > $groupCheck) {
  4998. $this->setAPIResponse('error', 'Tab name: ' . $tabInfo['name'] . ' cannot have a higher Group Id Min than Group Id Max', 409);
  4999. return false;
  5000. }
  5001. }
  5002. $response = [
  5003. array(
  5004. 'function' => 'query',
  5005. 'query' => array(
  5006. 'UPDATE tabs SET',
  5007. $array,
  5008. 'WHERE id = ?',
  5009. $id
  5010. )
  5011. ),
  5012. ];
  5013. $this->setAPIResponse(null, 'Tab info updated');
  5014. $this->setLoggerChannel('Tab Management');
  5015. $this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
  5016. return $this->processQueries($response);
  5017. }
  5018. public function updateTabOrder($array)
  5019. {
  5020. if (count($array) >= 1) {
  5021. foreach ($array as $tab) {
  5022. if (count($tab) !== 2) {
  5023. $this->setAPIResponse('error', 'data is malformed', 422);
  5024. break;
  5025. }
  5026. $id = $tab['id'] ?? null;
  5027. $order = $tab['order'] ?? null;
  5028. if ($id && $order) {
  5029. $response = [
  5030. array(
  5031. 'function' => 'query',
  5032. 'query' => array(
  5033. 'UPDATE tabs set `order` = ? WHERE `id` = ?',
  5034. $order,
  5035. $id
  5036. )
  5037. ),
  5038. ];
  5039. $this->processQueries($response);
  5040. $this->setAPIResponse(null, 'Tab Order updated');
  5041. } else {
  5042. $this->setAPIResponse('error', 'data is malformed', 422);
  5043. }
  5044. }
  5045. } else {
  5046. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5047. return false;
  5048. }
  5049. }
  5050. public function addCategory($array)
  5051. {
  5052. if (!$array) {
  5053. $this->setAPIResponse('error', 'no data was sent', 422);
  5054. return null;
  5055. }
  5056. $array = $this->checkKeys($this->getTableColumnsFormatted('categories'), $array);
  5057. $array['default'] = ($array['default']) ?? 0;
  5058. $array['order'] = ($array['order']) ?? $this->getNextCategoryOrder() + 1;
  5059. $array['category_id'] = ($array['category_id']) ?? $this->getNextCategoryId() + 1;
  5060. if (array_key_exists('category', $array)) {
  5061. $array['category'] = $this->sanitizeUserString($array['category']);
  5062. if ($this->isCategoryNameTaken($array['category'])) {
  5063. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  5064. return false;
  5065. }
  5066. } else {
  5067. $this->setAPIResponse('error', 'Category name was not supplied', 422);
  5068. return false;
  5069. }
  5070. if (!array_key_exists('image', $array)) {
  5071. $this->setAPIResponse('error', 'Category image was not supplied', 422);
  5072. return false;
  5073. } else {
  5074. $array['image'] = $this->sanitizeUserString($array['image']);
  5075. }
  5076. $response = [
  5077. array(
  5078. 'function' => 'query',
  5079. 'query' => array(
  5080. 'INSERT INTO [categories]',
  5081. $array
  5082. )
  5083. ),
  5084. ];
  5085. $this->setAPIResponse(null, 'Category added');
  5086. $this->setLoggerChannel('Category Management');
  5087. $this->logger->debug('Added Category for [' . $array['category'] . ']');
  5088. return $this->processQueries($response);
  5089. }
  5090. public function updateCategory($id, $array)
  5091. {
  5092. if (!$id || $id == '') {
  5093. $this->setAPIResponse('error', 'id was not set', 422);
  5094. return null;
  5095. }
  5096. if (!$array) {
  5097. $this->setAPIResponse('error', 'no data was sent', 422);
  5098. return null;
  5099. }
  5100. $categoryInfo = $this->getCategoryById($id);
  5101. if ($categoryInfo) {
  5102. $array = $this->checkKeys($categoryInfo, $array);
  5103. } else {
  5104. $this->setAPIResponse('error', 'No category info found', 404);
  5105. return false;
  5106. }
  5107. if (array_key_exists('category', $array)) {
  5108. $array['category'] = $this->sanitizeUserString($array['category']);
  5109. if ($this->isCategoryNameTaken($array['category'], $id)) {
  5110. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  5111. return false;
  5112. }
  5113. }
  5114. if (array_key_exists('image', $array)) {
  5115. $array['image'] = $this->sanitizeUserString($array['image']);
  5116. }
  5117. if (array_key_exists('default', $array)) {
  5118. if ($array['default']) {
  5119. $this->clearCategoryDefault();
  5120. }
  5121. }
  5122. $response = [
  5123. array(
  5124. 'function' => 'query',
  5125. 'query' => array(
  5126. 'UPDATE categories SET',
  5127. $array,
  5128. 'WHERE id = ?',
  5129. $id
  5130. )
  5131. ),
  5132. ];
  5133. $this->setAPIResponse(null, 'Category info updated');
  5134. $this->setLoggerChannel('Category Management');
  5135. $this->logger->debug('Edited Category [' . $categoryInfo['category'] . ']');
  5136. return $this->processQueries($response);
  5137. }
  5138. public function updateCategoryOrder($array)
  5139. {
  5140. if (count($array) >= 1) {
  5141. foreach ($array as $category) {
  5142. if (count($category) !== 2) {
  5143. $this->setAPIResponse('error', 'data is malformed', 422);
  5144. break;
  5145. }
  5146. $id = $category['id'] ?? null;
  5147. $order = $category['order'] ?? null;
  5148. if ($id && $order) {
  5149. $response = [
  5150. array(
  5151. 'function' => 'query',
  5152. 'query' => array(
  5153. 'UPDATE categories set `order` = ? WHERE `id` = ?',
  5154. $order,
  5155. $id
  5156. )
  5157. ),
  5158. ];
  5159. $this->processQueries($response);
  5160. $this->setAPIResponse(null, 'Category Order updated');
  5161. } else {
  5162. $this->setAPIResponse('error', 'data is malformed', 422);
  5163. }
  5164. }
  5165. } else {
  5166. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5167. return false;
  5168. }
  5169. }
  5170. public function deleteCategory($id)
  5171. {
  5172. $response = [
  5173. array(
  5174. 'function' => 'query',
  5175. 'query' => array(
  5176. 'DELETE FROM categories WHERE id = ?',
  5177. $id
  5178. )
  5179. ),
  5180. ];
  5181. $categoryInfo = $this->getCategoryById($id);
  5182. if ($categoryInfo) {
  5183. $this->setLoggerChannel('Category Management');
  5184. $this->logger->debug('Deleted Category [' . $categoryInfo['category'] . ']');
  5185. $this->setAPIResponse('success', 'Category deleted', 204);
  5186. return $this->processQueries($response);
  5187. } else {
  5188. $this->setAPIResponse('error', 'id not found', 404);
  5189. return false;
  5190. }
  5191. }
  5192. public function inconspicuous(): string
  5193. {
  5194. if ($this->hasDB()) {
  5195. if ($this->config['easterEggs']) {
  5196. return '
  5197. <div class="org-rox-trigger">
  5198. <div class="org-rox">
  5199. <div class="hair"></div>
  5200. <div class="head">
  5201. <div class="ear left"></div>
  5202. <div class="ear right"></div>
  5203. <div class="face">
  5204. <div class="eye left"></div>
  5205. <div class="eye right"></div>
  5206. <div class="nose"></div>
  5207. <div class="mouth"></div>
  5208. </div>
  5209. </div>
  5210. </div>
  5211. </div>';
  5212. }
  5213. }
  5214. return '';
  5215. }
  5216. public function marketplaceFileListFormat($files, $folder, $type)
  5217. {
  5218. foreach ($files as $k => $v) {
  5219. $splitFiles = explode('|', $v);
  5220. $prePath = (strlen($k) !== 1) ? $k . '/' : $k;
  5221. foreach ($splitFiles as $file) {
  5222. $filesList[] = array(
  5223. 'fileName' => $file,
  5224. 'path' => $prePath,
  5225. 'githubPath' => 'https://raw.githubusercontent.com/causefx/Organizr/v2-' . $type . '/' . $folder . $prePath . $file
  5226. );
  5227. }
  5228. }
  5229. return $filesList;
  5230. }
  5231. public function removeTheme($theme)
  5232. {
  5233. $this->setLoggerChannel('Theme Marketplace');
  5234. $theme = $this->cleanClassName($theme, '_');
  5235. $array = $this->getThemesMarketplace();
  5236. $arrayLower = array_change_key_case($array);
  5237. if (!$array) {
  5238. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5239. return false;
  5240. }
  5241. if (!isset($arrayLower[$theme])) {
  5242. $this->setAPIResponse('error', 'Theme does not exist in marketplace', 404);
  5243. return false;
  5244. } else {
  5245. $key = array_search($theme, array_keys($arrayLower));
  5246. $theme = array_keys($array)[$key];
  5247. }
  5248. $array = $array[$theme];
  5249. $themeDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5250. $dirExists = file_exists($themeDir);
  5251. if ($dirExists) {
  5252. if (!$this->rrmdir($themeDir)) {
  5253. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5254. return false;
  5255. }
  5256. } else {
  5257. $this->setAPIResponse('error', 'Theme is not installed', 404);
  5258. return false;
  5259. }
  5260. $this->updateInstalledThemes('uninstall', $theme, $array);
  5261. $this->setAPIResponse('success', 'Theme removed', 200, $array);
  5262. return true;
  5263. }
  5264. public function installTheme($theme)
  5265. {
  5266. $this->setLoggerChannel('Theme Marketplace');
  5267. $theme = $this->cleanClassName($theme, '_');
  5268. $array = $this->getThemesMarketplace();
  5269. $arrayLower = array_change_key_case($array);
  5270. if (!$array) {
  5271. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5272. return false;
  5273. }
  5274. if (!isset($arrayLower[$theme])) {
  5275. $this->setAPIResponse('error', 'Theme [' . $theme . '] does not exist in marketplace', 404, $arrayLower);
  5276. return false;
  5277. } else {
  5278. $key = array_search($theme, array_keys($arrayLower));
  5279. $theme = array_keys($array)[$key];
  5280. }
  5281. $array = $array[$theme];
  5282. // Check Version of Organizr against minimum version needed
  5283. $compare = new Composer\Semver\Comparator;
  5284. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5285. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5286. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5287. return true;
  5288. }
  5289. // It is okay to user Plugin function - we should rename it so it is universal
  5290. $files = $this->getPluginFilesFromRepo($theme, $array);
  5291. if ($files) {
  5292. $downloadList = $this->themeFileListFormat($files, $array['project_folder']);
  5293. } else {
  5294. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5295. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5296. return false;
  5297. }
  5298. if (!$downloadList) {
  5299. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5300. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5301. return false;
  5302. }
  5303. foreach ($downloadList as $k => $v) {
  5304. $file = array(
  5305. 'from' => $v['githubPath'],
  5306. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5307. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5308. );
  5309. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes');
  5310. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5311. $this->setLoggerChannel('Theme Marketplace');
  5312. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5313. $this->setAPIResponse('error', 'Theme download failed', 500);
  5314. return false;
  5315. }
  5316. }
  5317. $this->updateInstalledThemes('install', $theme, $array);
  5318. $this->setAPIResponse('success', 'Theme installed', 200, $array);
  5319. return true;
  5320. }
  5321. public function themeFileListFormat($files, $folder)
  5322. {
  5323. $filesList = false;
  5324. foreach ($files as $k => $v) {
  5325. if ($v['type'] !== 'dir') {
  5326. $filesList[] = array(
  5327. 'fileName' => $v['name'],
  5328. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5329. 'githubPath' => $v['download_url']
  5330. );
  5331. }
  5332. }
  5333. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder);
  5334. return $filesList;
  5335. }
  5336. public function pluginFileListFormat($files, $folder)
  5337. {
  5338. $filesList = false;
  5339. foreach ($files as $k => $v) {
  5340. if ($v['type'] !== 'dir') {
  5341. $filesList[] = array(
  5342. 'fileName' => $v['name'],
  5343. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5344. 'githubPath' => $v['download_url']
  5345. );
  5346. }
  5347. }
  5348. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder);
  5349. return $filesList;
  5350. }
  5351. public function getPluginFilesFromGithub($plugin = 'test')
  5352. {
  5353. $url = 'https://api.github.com/repos/causefx/organizr/contents/' . $plugin . '?ref=v2-plugins';
  5354. $options = array('verify' => false);
  5355. $response = Requests::get($url, array(), $options);
  5356. if ($response->success) {
  5357. return json_decode($response->body, true);
  5358. }
  5359. return false;
  5360. }
  5361. public function getBranchFromGithub($repo)
  5362. {
  5363. $url = 'https://api.github.com/repos/' . $repo;
  5364. $options = array('verify' => false);
  5365. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5366. try {
  5367. if ($response->success) {
  5368. $github = json_decode($response->body, true);
  5369. return $github['default_branch'] ?? null;
  5370. } else {
  5371. $this->setLoggerChannel('Plugins');
  5372. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5373. return false;
  5374. }
  5375. } catch (Requests_Exception $e) {
  5376. $this->logger->error($e);
  5377. $this->setAPIResponse('error', $e->getMessage(), 401);
  5378. return false;
  5379. }
  5380. }
  5381. public function getFilesFromGithub($repo, $branch)
  5382. {
  5383. if (!$repo || !$branch) {
  5384. return false;
  5385. }
  5386. $url = 'https://api.github.com/repos/' . $repo . '/git/trees/' . $branch . '?recursive=1';
  5387. $options = array('verify' => false);
  5388. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5389. try {
  5390. if ($response->success) {
  5391. $github = json_decode($response->body, true);
  5392. return is_array($github) ? $github : null;
  5393. } else {
  5394. $this->setLoggerChannel('Plugins');
  5395. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5396. return false;
  5397. }
  5398. } catch (Requests_Exception $e) {
  5399. $this->logger->error($e);
  5400. $this->setAPIResponse('error', $e->getMessage(), 401);
  5401. return false;
  5402. }
  5403. }
  5404. public function formatFilesFromGithub($files, $repo, $branch, $folder)
  5405. {
  5406. if (!$files || !$repo || !$branch || !$folder) {
  5407. return false;
  5408. }
  5409. if (isset($files['tree'])) {
  5410. $fileList = [];
  5411. foreach ($files['tree'] as $k => $v) {
  5412. if ($v['type'] !== 'tree') {
  5413. $fileInfo = pathinfo($v['path']);
  5414. $v['name'] = $fileInfo['basename'];
  5415. $v['download_url'] = 'https://raw.githubusercontent.com/' . $repo . '/' . $branch . '/' . $v['path'];
  5416. if ($folder == 'root') {
  5417. $fileList[] = $v;
  5418. } else {
  5419. if (stripos($v['path'], $folder) !== false) {
  5420. $v['path'] = (substr($v['path'], 0, strlen($folder)) == $folder) ? substr($v['path'], (strlen($folder) + 1)) : $v['path'];
  5421. $fileList[] = $v;
  5422. }
  5423. }
  5424. }
  5425. }
  5426. return $fileList;
  5427. }
  5428. return false;
  5429. }
  5430. public function getPluginFilesFromRepo($plugin, $pluginDetails)
  5431. {
  5432. if (stripos($pluginDetails['repo'], 'github.com') !== false) {
  5433. $repo = explode('https://github.com/', $pluginDetails['repo']);
  5434. } else {
  5435. return false;
  5436. }
  5437. $branch = $this->getBranchFromGithub($repo[1]);
  5438. if ($branch) {
  5439. return $this->formatFilesFromGithub($this->getFilesFromGithub($repo[1], $branch), $repo[1], $branch, $pluginDetails['github_folder']);
  5440. }
  5441. return false;
  5442. }
  5443. public function installPlugin($plugin)
  5444. {
  5445. $this->setLoggerChannel('Plugin Marketplace');
  5446. $plugin = $this->reverseCleanClassName($plugin);
  5447. $array = $this->getPluginsMarketplace();
  5448. $arrayLower = array_change_key_case($array);
  5449. if (!$array) {
  5450. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5451. return false;
  5452. }
  5453. if (!$arrayLower[$plugin]) {
  5454. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5455. return false;
  5456. } else {
  5457. $key = array_search($plugin, array_keys($arrayLower));
  5458. $plugin = array_keys($array)[$key];
  5459. }
  5460. $array = $array[$plugin];
  5461. // Check Version of Organizr against minimum version needed
  5462. $compare = new Composer\Semver\Comparator;
  5463. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5464. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5465. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5466. return true;
  5467. }
  5468. $files = $this->getPluginFilesFromRepo($plugin, $array);
  5469. if ($files) {
  5470. $downloadList = $this->pluginFileListFormat($files, $array['project_folder']);
  5471. } else {
  5472. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5473. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5474. return false;
  5475. }
  5476. if (!$downloadList) {
  5477. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5478. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5479. return false;
  5480. }
  5481. foreach ($downloadList as $k => $v) {
  5482. $file = array(
  5483. 'from' => $v['githubPath'],
  5484. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5485. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5486. );
  5487. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins');
  5488. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5489. $this->setLoggerChannel('Plugin Marketplace');
  5490. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5491. $this->setAPIResponse('error', 'Plugin download failed', 500);
  5492. return false;
  5493. }
  5494. }
  5495. $this->updateInstalledPlugins('install', $plugin, $array);
  5496. $this->setAPIResponse('success', 'Plugin installed', 200, $array);
  5497. return true;
  5498. }
  5499. public function removePlugin($plugin)
  5500. {
  5501. $this->setLoggerChannel('Plugin Marketplace');
  5502. $plugin = $this->reverseCleanClassName($plugin);
  5503. $array = $this->getPluginsMarketplace();
  5504. $arrayLower = array_change_key_case($array);
  5505. if (!$array) {
  5506. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5507. return false;
  5508. }
  5509. if (!$arrayLower[$plugin]) {
  5510. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5511. return false;
  5512. } else {
  5513. $key = array_search($plugin, array_keys($arrayLower));
  5514. $plugin = array_keys($array)[$key];
  5515. }
  5516. $array = $array[$plugin];
  5517. $pluginDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5518. $dirExists = file_exists($pluginDir);
  5519. if ($dirExists) {
  5520. if (!$this->rrmdir($pluginDir)) {
  5521. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5522. return false;
  5523. }
  5524. } else {
  5525. $this->setAPIResponse('error', 'Plugin is not installed', 404);
  5526. return false;
  5527. }
  5528. $this->updateInstalledPlugins('uninstall', $plugin, $array);
  5529. $this->setAPIResponse('success', 'Plugin removed', 200, $array);
  5530. return true;
  5531. }
  5532. public function updateInstalledPlugins($action, $plugin, $pluginDetails)
  5533. {
  5534. if (!$action || !$plugin || !$pluginDetails) {
  5535. return false;
  5536. }
  5537. $config = $this->config['installedPlugins'];
  5538. $config = is_array($config) ? $config : [];
  5539. switch ($action) {
  5540. case 'install':
  5541. case 'update':
  5542. $update[$plugin] = [
  5543. 'name' => $plugin,
  5544. 'version' => $pluginDetails['version'],
  5545. 'repo' => $pluginDetails['repo']
  5546. ];
  5547. $config = array_merge($config, $update);
  5548. break;
  5549. default:
  5550. unset($config[$plugin]);
  5551. break;
  5552. }
  5553. $this->updateConfig(['installedPlugins' => $config]);
  5554. }
  5555. public function updateInstalledThemes($action, $theme, $themeDetails)
  5556. {
  5557. if (!$action || !$theme || !$themeDetails) {
  5558. return false;
  5559. }
  5560. $config = $this->config['installedThemes'];
  5561. $config = is_array($config) ? $config : [];
  5562. switch ($action) {
  5563. case 'install':
  5564. case 'update':
  5565. $update[$theme] = [
  5566. 'name' => $theme,
  5567. 'version' => $themeDetails['version'],
  5568. 'repo' => $themeDetails['repo'],
  5569. 'path' => 'data/themes/' . $themeDetails['project_folder']
  5570. ];
  5571. $config = array_merge($config, $update);
  5572. break;
  5573. default:
  5574. unset($config[$theme]);
  5575. break;
  5576. }
  5577. $this->updateConfig(['installedThemes' => $config]);
  5578. }
  5579. public function getThemesGithub()
  5580. {
  5581. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-themes/themes.json';
  5582. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5583. $response = Requests::get($url, array(), $options);
  5584. if ($response->success) {
  5585. return json_decode($response->body, true);
  5586. }
  5587. return false;
  5588. }
  5589. public function getPluginsGithub()
  5590. {
  5591. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-plugins/plugins.json';
  5592. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5593. try {
  5594. $response = Requests::get($url, array(), $options);
  5595. if ($response->success) {
  5596. return json_decode($response->body, true);
  5597. }
  5598. } catch (Requests_Exception $e) {
  5599. return false;
  5600. }
  5601. return false;
  5602. }
  5603. public function getPluginsMarketplace()
  5604. {
  5605. $plugins = $this->getPluginsGithubCombined();
  5606. foreach ($plugins as $pluginName => $pluginDetails) {
  5607. $plugins[$pluginName]['installed'] = (isset($this->config['installedPlugins'][$pluginName]));
  5608. $plugins[$pluginName]['installed_version'] = $this->config['installedPlugins'][$pluginName]['version'] ?? null;
  5609. $plugins[$pluginName]['needs_update'] = ($plugins[$pluginName]['installed'] && ($plugins[$pluginName]['installed_version'] !== $plugins[$pluginName]['version']));
  5610. $plugins[$pluginName]['status'] = $this->getPluginStatus($plugins[$pluginName]);
  5611. }
  5612. return $plugins;
  5613. }
  5614. public function getThemesMarketplace()
  5615. {
  5616. $themes = $this->getThemesGithubCombined();
  5617. foreach ($themes as $themeName => $themeDetails) {
  5618. $themes[$themeName]['installed'] = (isset($this->config['installedThemes'][$themeName]));
  5619. $themes[$themeName]['installed_version'] = $this->config['installedThemes'][$themeName]['version'] ?? null;
  5620. $themes[$themeName]['needs_update'] = ($themes[$themeName]['installed'] && ($themes[$themeName]['installed_version'] !== $themes[$themeName]['version']));
  5621. $themes[$themeName]['status'] = $this->getPluginStatus($themes[$themeName]);
  5622. }
  5623. return $themes;
  5624. }
  5625. public function getThemesGithubCombined()
  5626. {
  5627. // Organizr Repo
  5628. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Themes')];
  5629. foreach (explode(',', $this->config['externalThemeMarketplaceRepos']) as $repo) {
  5630. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5631. }
  5632. $themes = [];
  5633. foreach ($urls as $repo) {
  5634. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5635. try {
  5636. $response = Requests::get($repo, array(), $options);
  5637. if ($response->success) {
  5638. $themes = array_merge($themes, json_decode($response->body, true));
  5639. } else {
  5640. $this->setLoggerChannel('Themes');
  5641. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5642. return false;
  5643. }
  5644. } catch (Requests_Exception $e) {
  5645. //return false;
  5646. }
  5647. }
  5648. return $themes;
  5649. }
  5650. public function getPluginStatus($pluginDetails)
  5651. {
  5652. if ($pluginDetails['needs_update']) {
  5653. return 'Update Available';
  5654. } elseif ($pluginDetails['installed']) {
  5655. return 'Up to date';
  5656. } else {
  5657. return 'Not Installed';
  5658. }
  5659. }
  5660. public function getPluginsGithubCombined()
  5661. {
  5662. // Organizr Repo
  5663. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Plugins')];
  5664. foreach (explode(',', $this->config['externalPluginMarketplaceRepos']) as $repo) {
  5665. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5666. }
  5667. $plugins = [];
  5668. foreach ($urls as $repo) {
  5669. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5670. try {
  5671. $response = Requests::get($repo, array(), $options);
  5672. if ($response->success) {
  5673. $plugins = array_merge($plugins, json_decode($response->body, true));
  5674. } else {
  5675. $this->setLoggerChannel('Plugins');
  5676. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5677. return false;
  5678. }
  5679. } catch (Requests_Exception $e) {
  5680. //return false;
  5681. }
  5682. }
  5683. return $plugins;
  5684. }
  5685. public function getMarketplaceJSONFromRepo($url)
  5686. {
  5687. if (stripos($url, '.json') !== false) {
  5688. return $url;
  5689. } elseif (stripos($url, 'github.com') !== false) {
  5690. $repo = explode('https://github.com/', $url);
  5691. $newURL = 'https://api.github.com/repos/' . $repo[1] . '/contents';
  5692. $options = ($this->localURL($newURL)) ? array('verify' => false) : array();
  5693. try {
  5694. $response = Requests::get($newURL, $this->setGithubAccessToken(), $options);
  5695. if ($response->success) {
  5696. $jsonFiles = json_decode($response->body, true);
  5697. foreach ($jsonFiles as $file) {
  5698. if (stripos($file['name'], '.json') !== false) {
  5699. return $file['download_url'];
  5700. }
  5701. }
  5702. return false;
  5703. } else {
  5704. $this->setLoggerChannel('Plugins');
  5705. $this->logger->warning('Getting Marketplace JSON from Github', $this->apiResponseFormatter($response->body));
  5706. return false;
  5707. }
  5708. } catch (Requests_Exception $e) {
  5709. return false;
  5710. }
  5711. }
  5712. return false;
  5713. }
  5714. public function setGithubAccessToken()
  5715. {
  5716. return ($this->config['githubAccessToken'] !== '') ? ['Authorization' => 'token ' . $this->config['githubAccessToken']] : [];
  5717. }
  5718. public function formatGithubAccessToken()
  5719. {
  5720. $accessToken = $this->setGithubAccessToken();
  5721. if (count($accessToken) >= 1) {
  5722. return key($accessToken) . ': ' . $accessToken[key($accessToken)];
  5723. } else {
  5724. return '';
  5725. }
  5726. }
  5727. public function getOpenCollectiveBackers()
  5728. {
  5729. $url = 'https://opencollective.com/organizr/members/users.json?limit=100&offset=0';
  5730. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5731. try {
  5732. $response = Requests::get($url, array(), $options);
  5733. if ($response->success) {
  5734. $api = json_decode($response->body, true);
  5735. foreach ($api as $k => $backer) {
  5736. $api[$k] = array_merge($api[$k], ['sortName' => strtolower($backer['name'])]);
  5737. }
  5738. $this->setAPIResponse('success', '', 200, $api);
  5739. return $api;
  5740. }
  5741. } catch (Requests_Exception $e) {
  5742. $this->setResponse(500, $e->getMessage());
  5743. return false;
  5744. }
  5745. $this->setAPIResponse('error', 'Error connecting to Open Collective', 409);
  5746. return false;
  5747. }
  5748. public function getGithubSponsors()
  5749. {
  5750. $url = 'https://github.com/sponsors/causefx';
  5751. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5752. $response = Requests::get($url, array(), $options);
  5753. if ($response->success) {
  5754. $sponsors = [];
  5755. $dom = new PHPHtmlParser\Dom;
  5756. try {
  5757. $dom->loadStr($response->body);
  5758. $contents = $dom->find('#sponsors .clearfix div');
  5759. foreach ($contents as $content) {
  5760. $html = $content->innerHtml;
  5761. preg_match('/(@[a-zA-Z])\w+/', $html, $username);
  5762. preg_match('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»""\'\']))/', $html, $image);
  5763. if (isset($image[0]) && isset($username[0])) {
  5764. $sponsors[] = [
  5765. 'name' => str_replace('@', '', $username[0]),
  5766. 'sortName' => str_replace('@', '', strtolower($username[0])),
  5767. 'image' => str_replace('s=60', 's=200', $image[0]),
  5768. 'isActive' => true,
  5769. 'type' => 'USER',
  5770. 'role' => 'BACKER'
  5771. ];
  5772. }
  5773. }
  5774. $this->setAPIResponse('success', '', 200, $sponsors);
  5775. return $sponsors;
  5776. } catch (\PHPHtmlParser\Exceptions\ChildNotFoundException | \PHPHtmlParser\Exceptions\CircularException | \PHPHtmlParser\Exceptions\LogicalException | \PHPHtmlParser\Exceptions\StrictException | \PHPHtmlParser\Exceptions\ContentLengthException | \PHPHtmlParser\Exceptions\NotLoadedException $e) {
  5777. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5778. return false;
  5779. }
  5780. }
  5781. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5782. return false;
  5783. }
  5784. public function getAllSponsors()
  5785. {
  5786. $sponsors = [];
  5787. $list = [
  5788. 'openCollective' => $this->getOpenCollectiveBackers(),
  5789. 'github' => $this->getGithubSponsors()
  5790. ];
  5791. foreach ($list as $k => $sponsor) {
  5792. if ($sponsor) {
  5793. $sponsors = array_merge($sponsor, $sponsors);
  5794. }
  5795. }
  5796. if ($sponsors) {
  5797. usort($sponsors, function ($a, $b) {
  5798. return $a['sortName'] <=> $b['sortName'];
  5799. });
  5800. }
  5801. $this->setAPIResponse('success', '', 200, $sponsors);
  5802. return $sponsors;
  5803. }
  5804. public function getOrganizrSmtpFromAPI()
  5805. {
  5806. $url = 'https://api.organizr.app/?cmd=smtp';
  5807. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5808. try {
  5809. $response = Requests::get($url, array(), $options);
  5810. if ($response->success) {
  5811. return json_decode($response->body, true);
  5812. }
  5813. } catch (Requests_Exception $e) {
  5814. $this->setResponse(500, $e->getMessage());
  5815. return false;
  5816. }
  5817. return false;
  5818. }
  5819. public function saveOrganizrSmtpFromAPI()
  5820. {
  5821. $api = $this->getOrganizrSmtpFromAPI();
  5822. if ($api) {
  5823. $this->updateConfigItems($api['response']['data']);
  5824. $this->setAPIResponse(null, 'SMTP activated with Organizr SMTP account');
  5825. return true;
  5826. } else {
  5827. return false;
  5828. }
  5829. }
  5830. public function guestHash($start, $end)
  5831. {
  5832. $ip = $this->userIP();
  5833. $ip = md5($ip);
  5834. return substr($ip, $start, $end);
  5835. }
  5836. public function rrmdir($dir)
  5837. {
  5838. ini_set('max_execution_time', 0);
  5839. set_time_limit(0);
  5840. if (is_dir($dir)) {
  5841. $files = scandir($dir);
  5842. foreach ($files as $file) {
  5843. if ($file != "." && $file != "..") {
  5844. $this->rrmdir("$dir/$file");
  5845. }
  5846. }
  5847. rmdir($dir);
  5848. } elseif (file_exists($dir)) {
  5849. unlink($dir);
  5850. }
  5851. return true;
  5852. }
  5853. public function rcopy($src, $dst)
  5854. {
  5855. ini_set('max_execution_time', 0);
  5856. set_time_limit(0);
  5857. $src = $this->cleanPath($src);
  5858. $dst = $this->cleanPath($dst);
  5859. if (is_dir($src)) {
  5860. if (!file_exists($dst)) : mkdir($dst);
  5861. endif;
  5862. $files = scandir($src);
  5863. foreach ($files as $file) {
  5864. if ($file != "." && $file != "..") {
  5865. $this->rcopy("$src/$file", "$dst/$file");
  5866. }
  5867. }
  5868. } elseif (file_exists($src)) {
  5869. copy($src, $dst);
  5870. }
  5871. return true;
  5872. }
  5873. public function unzipFile($zipFile)
  5874. {
  5875. ini_set('max_execution_time', 0);
  5876. set_time_limit(0);
  5877. $zip = new ZipArchive;
  5878. $extractPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade/";
  5879. $this->setLoggerChannel('File Management');
  5880. if ($zip->open($extractPath . $zipFile) != "true") {
  5881. $this->logger->warning('organizr could not unzip upgrade.zip');
  5882. } else {
  5883. $this->logger->debug('organizr unzipped upgrade.zip');
  5884. }
  5885. /* Extract Zip File */
  5886. $zip->extractTo($extractPath);
  5887. $zip->close();
  5888. return true;
  5889. }
  5890. public function downloadFile($url, $path)
  5891. {
  5892. ini_set('max_execution_time', 0);
  5893. set_time_limit(0);
  5894. $folderPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade" . DIRECTORY_SEPARATOR;
  5895. $this->setLoggerChannel('File Management');
  5896. if (!file_exists($folderPath)) {
  5897. if (@!mkdir($folderPath)) {
  5898. $this->logger->warning('Folder Creation failed');
  5899. return false;
  5900. }
  5901. }
  5902. $newfname = $folderPath . $path;
  5903. $context = stream_context_create(
  5904. array(
  5905. 'ssl' => array(
  5906. 'verify_peer' => true,
  5907. 'cafile' => $this->getCert()
  5908. )
  5909. )
  5910. );
  5911. $file = fopen($url, 'rb', false, $context);
  5912. if ($file) {
  5913. $newf = fopen($newfname, 'wb');
  5914. if ($newf) {
  5915. while (!feof($file)) {
  5916. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  5917. }
  5918. }
  5919. } else {
  5920. $this->logger->warning('Organizr could not download ' . $url);
  5921. return false;
  5922. }
  5923. if ($file) {
  5924. fclose($file);
  5925. $this->logger->debug('Organizr finished downloading the github zip file');
  5926. } else {
  5927. $this->logger->warning('Organizr could not download the github zip file');
  5928. return false;
  5929. }
  5930. if ($newf) {
  5931. fclose($newf);
  5932. $this->logger->debug('Organizr created upgrade zip file from github zip file');
  5933. } else {
  5934. $this->logger->warning('Organizr could not create upgrade zip file from github zip file');
  5935. return false;
  5936. }
  5937. return true;
  5938. }
  5939. public function downloadFileToPath($from, $to, $path)
  5940. {
  5941. if (((stripos($from, 'api.github.com') !== false) || (stripos($from, 'raw.githubusercontent.com') !== false)) && $this->config['githubAccessToken'] !== '') {
  5942. $context = stream_context_create(
  5943. array(
  5944. 'ssl' => array(
  5945. 'verify_peer' => false,
  5946. 'cafile' => $this->getCert()
  5947. ),
  5948. 'http' => array(
  5949. 'method' => 'GET',
  5950. 'header' => $this->formatGithubAccessToken()
  5951. )
  5952. )
  5953. );
  5954. } else {
  5955. $context = stream_context_create([]);
  5956. }
  5957. ini_set('max_execution_time', 0);
  5958. set_time_limit(0);
  5959. $this->makeDir($path);
  5960. $file = fopen($from, 'rb', false, $context);
  5961. if ($file) {
  5962. $newf = fopen($to, 'wb', false, $context);
  5963. if ($newf) {
  5964. while (!feof($file)) {
  5965. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  5966. }
  5967. }
  5968. } else {
  5969. $this->logger->warning('Organizr could not download file');
  5970. }
  5971. if ($file) {
  5972. fclose($file);
  5973. $this->logger->debug('Organizr finished downloading the file');
  5974. } else {
  5975. $this->logger->warning('Organizr could not download file');
  5976. }
  5977. if ($newf) {
  5978. fclose($newf);
  5979. $this->logger->debug('Organizr saved and/or moved the file');
  5980. } else {
  5981. $this->logger->warning('Organizr could not save and/or move the file');
  5982. }
  5983. return true;
  5984. }
  5985. public function getAllUsers($includeGroups = false)
  5986. {
  5987. $response = [
  5988. array(
  5989. 'function' => 'fetchAll',
  5990. 'query' => array(
  5991. 'SELECT * FROM users'
  5992. ),
  5993. 'key' => 'users'
  5994. ),
  5995. ];
  5996. $groups = array(
  5997. 'function' => 'fetchAll',
  5998. 'query' => array(
  5999. 'SELECT * FROM groups ORDER BY group_id ASC'
  6000. ),
  6001. 'key' => 'groups'
  6002. );
  6003. $addGroups = (isset($_GET['includeGroups']) || $includeGroups) ?? false;
  6004. if ($addGroups) {
  6005. array_push($response, $groups);
  6006. }
  6007. return $this->processQueries($response);
  6008. }
  6009. public function getAllGroups()
  6010. {
  6011. $response = [
  6012. array(
  6013. 'function' => 'fetchAll',
  6014. 'query' => array(
  6015. 'SELECT * FROM groups ORDER BY group_id ASC'
  6016. ),
  6017. 'key' => 'groups'
  6018. ),
  6019. ];
  6020. $users = array(
  6021. 'function' => 'fetchAll',
  6022. 'query' => array(
  6023. 'SELECT * FROM users'
  6024. ),
  6025. 'key' => 'users'
  6026. );
  6027. $addUsers = (isset($_GET['includeUsers'])) ?? false;
  6028. if ($addUsers) {
  6029. array_push($response, $users);
  6030. }
  6031. return $this->processQueries($response);
  6032. }
  6033. public function importUsers($array)
  6034. {
  6035. $imported = 0;
  6036. if ($array) {
  6037. foreach ($array as $user) {
  6038. $password = $this->random_ascii_string(30);
  6039. if ($user['username'] !== '' && $user['email'] !== '' && $password !== '') {
  6040. $newUser = $this->createUser($user['username'], $password, $user['email']);
  6041. if (!$newUser) {
  6042. $this->setLoggerChannel('User Management');
  6043. $this->logger->warning('An error occurred during user import');
  6044. } else {
  6045. $imported++;
  6046. }
  6047. }
  6048. }
  6049. }
  6050. $this->setAPIResponse('success', 'Imported ' . $imported . ' users', 200);
  6051. return true;
  6052. }
  6053. public function importUsersType($type)
  6054. {
  6055. if ($type !== '') {
  6056. switch ($type) {
  6057. case 'plex':
  6058. return $this->importUsers($this->allPlexUsers(true));
  6059. case 'jellyfin':
  6060. return $this->importUsers($this->allJellyfinUsers(true));
  6061. case 'emby':
  6062. return $this->importUsers($this->allEmbyUsers(true));
  6063. default:
  6064. return false;
  6065. }
  6066. }
  6067. return false;
  6068. }
  6069. public function allPlexUsers($newOnly = false, $friendsOnly = false)
  6070. {
  6071. try {
  6072. if (!empty($this->config['plexToken'])) {
  6073. $url = 'https://plex.tv/api/users';
  6074. $headers = array(
  6075. 'X-Plex-Token' => $this->config['plexToken'],
  6076. );
  6077. $response = Requests::get($url, $headers);
  6078. if ($response->success) {
  6079. libxml_use_internal_errors(true);
  6080. $userXML = simplexml_load_string($response->body);
  6081. if (is_array($userXML) || is_object($userXML)) {
  6082. $results = array();
  6083. foreach ($userXML as $child) {
  6084. if (((string)$child['restricted'] == '0')) {
  6085. if ($newOnly) {
  6086. $taken = $this->usernameTaken((string)$child['username'], (string)$child['email']);
  6087. if (!$taken) {
  6088. $results[] = array(
  6089. 'username' => (string)$child['username'],
  6090. 'email' => (string)$child['email'],
  6091. 'id' => (string)$child['id'],
  6092. );
  6093. }
  6094. } elseif ($friendsOnly) {
  6095. $machineMatches = false;
  6096. foreach ($child->Server as $server) {
  6097. if ((string)$server['machineIdentifier'] == $this->config['plexID']) {
  6098. $machineMatches = true;
  6099. $shareId = $server['id'];
  6100. }
  6101. }
  6102. if ($machineMatches) {
  6103. $results[] = array(
  6104. 'username' => (string)$child['username'],
  6105. 'email' => (string)$child['email'],
  6106. 'id' => (string)$child['id'],
  6107. 'shareId' => (string)$shareId
  6108. );
  6109. }
  6110. } else {
  6111. $results[] = array(
  6112. 'username' => (string)$child['username'],
  6113. 'email' => (string)$child['email'],
  6114. 'id' => (string)$child['id'],
  6115. );
  6116. }
  6117. }
  6118. }
  6119. return $results;
  6120. }
  6121. }
  6122. }
  6123. return false;
  6124. } catch (Requests_Exception $e) {
  6125. $this->setLoggerChannel('User Management');
  6126. $this->logger->error($e);
  6127. }
  6128. return false;
  6129. }
  6130. public function allJellyfinUsers($newOnly = false)
  6131. {
  6132. try {
  6133. if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
  6134. $url = $this->qualifyURL($this->config['jellyfinURL']) . '/Users?api_key=' . $this->config['jellyfinToken'];
  6135. $headers = array();
  6136. $response = Requests::get($url, $headers);
  6137. if ($response->success) {
  6138. $users = json_decode($response->body, true);
  6139. if (is_array($users) || is_object($users)) {
  6140. $results = array();
  6141. foreach ($users as $child) {
  6142. // Jellyfin doesn't list emails for some reason
  6143. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6144. if ($newOnly) {
  6145. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6146. if (!$taken) {
  6147. $results[] = array(
  6148. 'username' => (string)$child['Name'],
  6149. 'email' => $email
  6150. );
  6151. }
  6152. } else {
  6153. $results[] = array(
  6154. 'username' => (string)$child['Name'],
  6155. 'email' => $email,
  6156. );
  6157. }
  6158. }
  6159. return $results;
  6160. }
  6161. }
  6162. }
  6163. return false;
  6164. } catch (Requests_Exception $e) {
  6165. $this->setLoggerChannel('User Management');
  6166. $this->logger->error($e);
  6167. }
  6168. return false;
  6169. }
  6170. public function allEmbyUsers($newOnly = false)
  6171. {
  6172. try {
  6173. if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
  6174. $url = $this->qualifyURL($this->config['embyURL']) . '/Users?api_key=' . $this->config['embyToken'];
  6175. $headers = array();
  6176. $response = Requests::get($url, $headers);
  6177. if ($response->success) {
  6178. $users = json_decode($response->body, true);
  6179. if (is_array($users) || is_object($users)) {
  6180. $results = array();
  6181. foreach ($users as $child) {
  6182. // Emby doesn't list emails for some reason
  6183. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6184. if ($newOnly) {
  6185. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6186. if (!$taken) {
  6187. $results[] = array(
  6188. 'username' => (string)$child['Name'],
  6189. 'email' => $email
  6190. );
  6191. }
  6192. } else {
  6193. $results[] = array(
  6194. 'username' => (string)$child['Name'],
  6195. 'email' => $email,
  6196. );
  6197. }
  6198. }
  6199. return $results;
  6200. }
  6201. }
  6202. }
  6203. return false;
  6204. } catch (Requests_Exception $e) {
  6205. $this->setLoggerChannel('User Management');
  6206. $this->logger->error($e);
  6207. }
  6208. return false;
  6209. }
  6210. public function validateEmail($email)
  6211. {
  6212. return filter_var(trim($email), FILTER_VALIDATE_EMAIL);
  6213. }
  6214. public function sanitizeEmail($email)
  6215. {
  6216. return filter_var(trim($email), FILTER_SANITIZE_EMAIL);
  6217. }
  6218. public function sanitizeUserString($string)
  6219. {
  6220. return htmlspecialchars(trim($string));
  6221. }
  6222. public function updateUser($id, $array)
  6223. {
  6224. if (!$id) {
  6225. $this->setAPIResponse('error', 'Id was not supplied', 422);
  6226. return false;
  6227. }
  6228. if ((int)$id !== $this->user['userID']) {
  6229. if (!$this->qualifyRequest('1', true)) {
  6230. return false;
  6231. }
  6232. }
  6233. $user = $this->getUserById($id);
  6234. if ($user) {
  6235. $array = $this->checkKeys($user, $array);
  6236. } else {
  6237. $this->setAPIResponse('error', 'User was not found', 404);
  6238. return false;
  6239. }
  6240. if ($user['group_id'] == 0 && $this->user['groupID'] !== 0) {
  6241. $this->setAPIResponse('error', 'Cannot update admin unless you are admin', 401);
  6242. return false;
  6243. }
  6244. if (array_key_exists('username', $array)) {
  6245. if ($array['username'] == '') {
  6246. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6247. return false;
  6248. }
  6249. $array['username'] = $this->sanitizeUserString($array['username']);
  6250. if ($this->usernameTaken($array['username'], $array['username'], $id)) {
  6251. $this->setAPIResponse('error', 'Username: ' . $array['username'] . ' is already taken', 409);
  6252. return false;
  6253. }
  6254. }
  6255. if (array_key_exists('email', $array)) {
  6256. if ($array['email'] == '') {
  6257. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6258. return false;
  6259. }
  6260. if ($this->validateEmail($array['email'])) {
  6261. $array['email'] = $this->sanitizeEmail($array['email']);
  6262. } else {
  6263. $this->setResponse(409, 'Email is not a valid email', ['email' => $array['email']]);
  6264. return false;
  6265. }
  6266. if ($this->usernameTaken($array['email'], $array['email'], $id)) {
  6267. $this->setAPIResponse('error', 'Email: ' . $array['email'] . ' is already taken', 409);
  6268. return false;
  6269. }
  6270. }
  6271. if (array_key_exists('group_id', $array)) {
  6272. if ($array['group_id'] == '') {
  6273. $array['group_id'] = 0;
  6274. //$this->setAPIResponse('error', 'group_id was set but empty', 409);
  6275. //return false;
  6276. }
  6277. if (!$this->qualifyRequest('1', false)) {
  6278. $this->setAPIResponse('error', 'Cannot change your own group_id', 401);
  6279. return false;
  6280. }
  6281. if (($id == $this->user['userID']) && $this->user['groupID'] == 0) {
  6282. $array['group_id'] = 0;
  6283. }
  6284. if (($id == $this->user['userID']) && ($array['group_id'] == 0 && $this->user['groupID'] !== 0)) {
  6285. $this->setAPIResponse('error', 'Only admins can make others admins', 401);
  6286. return false;
  6287. }
  6288. $array['group'] = $this->getGroupByGroupId($array['group_id'])['group'];
  6289. if (!$array['group']) {
  6290. $this->setAPIResponse('error', 'group_id does not exist', 404);
  6291. return false;
  6292. }
  6293. }
  6294. if (array_key_exists('locked', $array)) {
  6295. //$this->setAPIResponse('error', 'Cannot use endpoint to unlock or lock user - please use /users/{id}/lock', 409);
  6296. //return false;
  6297. }
  6298. if (array_key_exists('password', $array)) {
  6299. if ($array['password'] == '') {
  6300. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6301. return false;
  6302. }
  6303. $array['password'] = password_hash($array['password'], PASSWORD_BCRYPT);
  6304. }
  6305. if (array_key_exists('image', $array)) {
  6306. $array['image'] = $this->sanitizeUserString($array['image']);
  6307. }
  6308. if (array_key_exists('register_date', $array)) {
  6309. $this->setAPIResponse('error', 'Cannot update register date', 409);
  6310. return false;
  6311. }
  6312. $response = [
  6313. array(
  6314. 'function' => 'query',
  6315. 'query' => array(
  6316. 'UPDATE users SET',
  6317. $array,
  6318. 'WHERE id = ?',
  6319. $id
  6320. )
  6321. ),
  6322. ];
  6323. $this->setAPIResponse(null, 'User info updated');
  6324. $this->setLoggerChannel('User Management');
  6325. $this->logger->info('Updated User Info for [' . $user['username'] . ']');
  6326. return $this->processQueries($response);
  6327. }
  6328. public function deleteUser($id)
  6329. {
  6330. $response = [
  6331. array(
  6332. 'function' => 'query',
  6333. 'query' => array(
  6334. 'DELETE FROM users WHERE id = ?',
  6335. $id
  6336. )
  6337. ),
  6338. ];
  6339. $userInfo = $this->getUserById($id);
  6340. if ($id == $this->user['userID']) {
  6341. $this->setAPIResponse('error', 'Cannot delete your own user', 409);
  6342. return false;
  6343. }
  6344. if ($userInfo) {
  6345. $this->setLoggerChannel('User Management');
  6346. $this->logger->info('Deleted User [' . $userInfo['username'] . ']');
  6347. $this->setAPIResponse('success', 'User deleted', 204);
  6348. return $this->processQueries($response);
  6349. } else {
  6350. $this->setAPIResponse('error', 'id not found', 404);
  6351. return false;
  6352. }
  6353. }
  6354. public function addUser($array)
  6355. {
  6356. $username = $array['username'] ?? null;
  6357. $password = $array['password'] ?? null;
  6358. $email = $array['email'] ?? null;
  6359. if (!$username) {
  6360. $this->setAPIResponse('error', 'Username was not supplied', 409);
  6361. return false;
  6362. }
  6363. if ($username == '') {
  6364. $this->setResponse(409, 'Username was set but empty');
  6365. return false;
  6366. } else {
  6367. $username = $this->sanitizeUserString($username);
  6368. }
  6369. if (!$password) {
  6370. $this->setAPIResponse('error', 'Password was not supplied', 409);
  6371. return false;
  6372. }
  6373. if (!$email) {
  6374. $this->setAPIResponse('error', 'Email was set not supplied', 409);
  6375. return false;
  6376. }
  6377. if ($email == '') {
  6378. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6379. return false;
  6380. }
  6381. if ($this->validateEmail($email)) {
  6382. $email = $this->sanitizeEmail($email);
  6383. } else {
  6384. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6385. return false;
  6386. }
  6387. $this->setLoggerChannel('User Management');
  6388. if ($this->createUser($username, $password, $email)) {
  6389. $this->logger->info('Account created for [' . $username . ']');
  6390. return true;
  6391. } else {
  6392. $this->logger->warning('An error occurred');
  6393. return false;
  6394. }
  6395. }
  6396. public function createUser($username, $password, $email = null)
  6397. {
  6398. $username = $username ?? null;
  6399. $password = $password ?? null;
  6400. $email = ($email) ? $email : $this->random_ascii_string(10) . '@placeholder.eml';
  6401. if (!$username) {
  6402. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6403. return false;
  6404. }
  6405. $username = $this->sanitizeUserString($username);
  6406. if (!$password) {
  6407. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6408. return false;
  6409. }
  6410. if ($email == '') {
  6411. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6412. return false;
  6413. }
  6414. if ($this->validateEmail($email)) {
  6415. $email = $this->sanitizeEmail($email);
  6416. } else {
  6417. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6418. return false;
  6419. }
  6420. if ($this->usernameTaken($username, $email)) {
  6421. $this->setAPIResponse('error', 'Username: ' . $username . ' or Email: ' . $email . ' is already taken', 409);
  6422. return false;
  6423. }
  6424. $defaults = $this->getDefaultGroup();
  6425. $userInfo = [
  6426. 'username' => $username,
  6427. 'password' => password_hash($password, PASSWORD_BCRYPT),
  6428. 'email' => $email,
  6429. 'group' => $defaults['group'],
  6430. 'group_id' => $defaults['group_id'],
  6431. 'image' => $this->gravatar($email),
  6432. 'register_date' => gmdate('Y-m-d H:i:s'),
  6433. ];
  6434. $response = [
  6435. array(
  6436. 'function' => 'query',
  6437. 'query' => array(
  6438. 'INSERT INTO [users]',
  6439. $userInfo
  6440. )
  6441. ),
  6442. ];
  6443. $this->setAPIResponse('success', 'User created', 200);
  6444. return $this->processQueries($response);
  6445. }
  6446. public function updateGroup($id, $array)
  6447. {
  6448. if (!$id || $id == '') {
  6449. $this->setAPIResponse('error', 'id was not set', 422);
  6450. return null;
  6451. }
  6452. if (!$array) {
  6453. $this->setAPIResponse('error', 'no data was sent', 422);
  6454. return null;
  6455. }
  6456. $groupInfo = $this->getGroupById($id);
  6457. if ($groupInfo) {
  6458. $array = $this->checkKeys($groupInfo, $array);
  6459. } else {
  6460. $this->setAPIResponse('error', 'No category info found', 404);
  6461. return false;
  6462. }
  6463. if (array_key_exists('group_id', $array)) {
  6464. $this->setAPIResponse('error', 'Cannot change group_id', 409);
  6465. return false;
  6466. }
  6467. if (array_key_exists('group', $array)) {
  6468. if ($array['group'] == '') {
  6469. $this->setAPIResponse('error', 'Group was set but empty', 409);
  6470. return false;
  6471. }
  6472. $array['group'] = $this->sanitizeUserString($array['group']);
  6473. if ($this->isGroupNameTaken($array['group'], $id)) {
  6474. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6475. return false;
  6476. }
  6477. }
  6478. if (array_key_exists('image', $array)) {
  6479. if ($array['image'] == '') {
  6480. $this->setAPIResponse('error', 'Image was set but empty', 409);
  6481. return false;
  6482. }
  6483. }
  6484. if (array_key_exists('default', $array)) {
  6485. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6486. $this->setAPIResponse('error', 'Setting ' . $groupInfo['group'] . ' as default group is not allowed', 409);
  6487. return false;
  6488. }
  6489. if ($array['default']) {
  6490. $this->clearGroupDefault();
  6491. $array['default'] = 1;
  6492. }
  6493. }
  6494. $response = [
  6495. array(
  6496. 'function' => 'query',
  6497. 'query' => array(
  6498. 'UPDATE groups SET',
  6499. $array,
  6500. 'WHERE id = ?',
  6501. $id
  6502. )
  6503. ),
  6504. ];
  6505. $this->setAPIResponse(null, 'Group info updated');
  6506. $this->setLoggerChannel('Group Management');
  6507. $this->logger->info('Edited Group Info for [' . $groupInfo['group'] . ']');
  6508. return $this->processQueries($response);
  6509. }
  6510. public function deleteGroup($id)
  6511. {
  6512. $response = [
  6513. array(
  6514. 'function' => 'query',
  6515. 'query' => array(
  6516. 'DELETE FROM groups WHERE id = ?',
  6517. $id
  6518. )
  6519. ),
  6520. ];
  6521. $groupInfo = $this->getGroupById($id);
  6522. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6523. $this->setAPIResponse('error', 'Cannot delete group: ' . $groupInfo['group'] . ' as it is not allowed', 409);
  6524. return false;
  6525. }
  6526. if ($this->getGroupUserCountById($id) >= 1) {
  6527. $this->setAPIResponse('error', 'Cannot delete group as group still has users assigned to it', 409);
  6528. return false;
  6529. }
  6530. if ($groupInfo) {
  6531. $this->setLoggerChannel('Group Management');
  6532. $this->logger->info('Deleted Group [' . $groupInfo['group'] . ']');
  6533. $this->setAPIResponse('success', 'Group deleted', 204);
  6534. return $this->processQueries($response);
  6535. } else {
  6536. $this->setAPIResponse('error', 'id not found', 404);
  6537. return false;
  6538. }
  6539. }
  6540. public function addGroup($array)
  6541. {
  6542. if (!$array) {
  6543. $this->setAPIResponse('error', 'no data was sent', 422);
  6544. return null;
  6545. }
  6546. $array = $this->checkKeys($this->getTableColumnsFormatted('groups'), $array);
  6547. $array['default'] = ($array['default']) ?? 0;
  6548. $array['group_id'] = $this->getNextGroupOrder() + 1;
  6549. if (array_key_exists('group', $array)) {
  6550. $array['group'] = $this->sanitizeUserString($array['group']);
  6551. if ($this->isGroupNameTaken($array['group'])) {
  6552. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6553. return false;
  6554. }
  6555. } else {
  6556. $this->setAPIResponse('error', 'Group name was not supplied', 422);
  6557. return false;
  6558. }
  6559. if (array_key_exists('image', $array)) {
  6560. if ($array['image'] == '') {
  6561. $this->setAPIResponse('error', 'Group image cannot be empty', 422);
  6562. return false;
  6563. }
  6564. } else {
  6565. $this->setAPIResponse('error', 'Group image was not supplied', 422);
  6566. return false;
  6567. }
  6568. $response = [
  6569. array(
  6570. 'function' => 'query',
  6571. 'query' => array(
  6572. 'INSERT INTO [groups]',
  6573. $array
  6574. )
  6575. ),
  6576. ];
  6577. $this->setAPIResponse(null, 'Group added');
  6578. $this->setLoggerChannel('Group Management');
  6579. $this->logger->info('Added Group for [' . $array['group'] . ']');
  6580. return $this->processQueries($response);
  6581. }
  6582. public function userList($type = null)
  6583. {
  6584. switch ($type) {
  6585. case 'plex':
  6586. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  6587. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'] . '/shared_servers';
  6588. try {
  6589. $headers = array(
  6590. "Accept" => "application/json",
  6591. "X-Plex-Token" => $this->config['plexToken']
  6592. );
  6593. $response = Requests::get($url, $headers, array());
  6594. libxml_use_internal_errors(true);
  6595. if ($response->success) {
  6596. $libraryList = array();
  6597. $plex = simplexml_load_string($response->body);
  6598. foreach ($plex->SharedServer as $child) {
  6599. if (!empty($child['username'])) {
  6600. $username = (string)strtolower($child['username']);
  6601. $email = (string)strtolower($child['email']);
  6602. $libraryList['users'][$username] = (string)$child['id'];
  6603. $libraryList['emails'][$email] = (string)$child['id'];
  6604. $libraryList['both'][$username] = $email;
  6605. }
  6606. }
  6607. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  6608. return $libraryList;
  6609. }
  6610. } catch (Requests_Exception $e) {
  6611. $this->setLoggerChannel('User Management');
  6612. $this->logger->error($e);
  6613. }
  6614. }
  6615. break;
  6616. default:
  6617. # code...
  6618. break;
  6619. }
  6620. return false;
  6621. }
  6622. public function encrypt($password, $key = null)
  6623. {
  6624. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6625. return openssl_encrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6626. }
  6627. public function decrypt($password, $key = null)
  6628. {
  6629. if (empty($password)) {
  6630. return '';
  6631. }
  6632. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6633. return openssl_decrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6634. }
  6635. public function checkValidCert($file)
  6636. {
  6637. if (file_exists($file)) {
  6638. return filesize($file) > 0;
  6639. } else {
  6640. return false;
  6641. }
  6642. }
  6643. public function getCert()
  6644. {
  6645. $url = 'http://curl.haxx.se/ca/cacert.pem';
  6646. $file = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  6647. $file2 = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  6648. $useCert = ($this->checkValidCert($file)) ? $file : $file2;
  6649. if ($this->config['selfSignedCert'] !== '') {
  6650. if (file_exists($this->config['selfSignedCert'])) {
  6651. return $this->config['selfSignedCert'];
  6652. }
  6653. }
  6654. $context = stream_context_create(
  6655. array(
  6656. 'ssl' => array(
  6657. 'verify_peer' => true,
  6658. 'cafile' => $useCert
  6659. )
  6660. )
  6661. );
  6662. if (!$this->checkValidCert($file) || (file_exists($file) && time() - 2592000 > filemtime($file))) {
  6663. file_put_contents($file, fopen($url, 'r', false, $context));
  6664. }
  6665. return ($this->checkValidCert($file)) ? $file : $file2;
  6666. }
  6667. public function hasCustomCert()
  6668. {
  6669. return file_exists($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem');
  6670. }
  6671. public function getCustomCert()
  6672. {
  6673. return ($this->hasCustomCert()) ? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem' : false;
  6674. }
  6675. public function uploadCert()
  6676. {
  6677. $filesCheck = array_filter($_FILES);
  6678. if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'cert')) {
  6679. ini_set('upload_max_filesize', '10M');
  6680. ini_set('post_max_size', '10M');
  6681. $tempFile = $_FILES['file']['tmp_name'];
  6682. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR;
  6683. $targetFile = $targetPath . 'custom.pem';
  6684. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  6685. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert');
  6686. return move_uploaded_file($tempFile, $targetFile);
  6687. } else {
  6688. $this->setAPIResponse('error', pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' is not approved to be uploaded', 403);
  6689. return false;
  6690. }
  6691. }
  6692. public function createCronFile()
  6693. {
  6694. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6695. file_put_contents($file, time());
  6696. }
  6697. public function checkCronFile()
  6698. {
  6699. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6700. return file_exists($file) && time() - 120 < filemtime($file);
  6701. }
  6702. public function plexJoinAPI($array)
  6703. {
  6704. $username = ($array['username']) ?? null;
  6705. $email = ($array['email']) ?? null;
  6706. $password = ($array['password']) ?? null;
  6707. if (!$username) {
  6708. $this->setAPIResponse('error', 'Username not supplied', 409);
  6709. return false;
  6710. }
  6711. if (!$email) {
  6712. $this->setAPIResponse('error', 'Email not supplied', 409);
  6713. return false;
  6714. }
  6715. if (!$password) {
  6716. $this->setAPIResponse('error', 'Password not supplied', 409);
  6717. return false;
  6718. }
  6719. return $this->plexJoin($username, $email, $password);
  6720. }
  6721. public function plexJoin($username, $email, $password)
  6722. {
  6723. try {
  6724. $url = 'https://plex.tv/api/v2/users';
  6725. $headers = array(
  6726. 'Accept' => 'application/json',
  6727. 'Content-Type' => 'application/x-www-form-urlencoded',
  6728. 'X-Plex-Product' => 'Organizr',
  6729. 'X-Plex-Version' => '2.0',
  6730. 'X-Plex-Client-Identifier' => $this->config['uuid'],
  6731. );
  6732. $data = array(
  6733. 'email' => $email,
  6734. 'username' => $username,
  6735. 'password' => $password,
  6736. );
  6737. $response = Requests::post($url, $headers, $data, array());
  6738. $json = json_decode($response->body, true);
  6739. $errors = !empty($json['errors']);
  6740. $success = empty($json['errors']);
  6741. //Use This for later
  6742. $errorMessage = '';
  6743. if ($errors) {
  6744. foreach ($json['errors'] as $error) {
  6745. if (isset($error['message']) && isset($error['field'])) {
  6746. $errorMessage .= "[Plex.tv Error: " . $error['message'] . " for field: (" . $error['field'] . ")]";
  6747. }
  6748. }
  6749. }
  6750. $msg = (!empty($success) && empty($errors)) ? 'User has joined Plex' : $errorMessage;
  6751. $status = (!empty($success) && empty($errors)) ? 'success' : 'error';
  6752. $code = (!empty($success) && empty($errors)) ? 200 : 422;
  6753. $this->setAPIResponse($status, $msg, $code);
  6754. return (!empty($success) && empty($errors));
  6755. } catch (Requests_Exception $e) {
  6756. $this->setLoggerChannel('User Management');
  6757. $this->logger->error($e);
  6758. $this->setAPIResponse('error', 'An Error Occurred', 409);
  6759. return false;
  6760. }
  6761. return false;
  6762. }
  6763. public function lockCurrentUser()
  6764. {
  6765. if ($this->user['userID'] == '999') {
  6766. $this->setAPIResponse('error', 'Locking not allowed on Guest users', 409);
  6767. return false;
  6768. }
  6769. return $this->lockUser($this->user['userID']);
  6770. }
  6771. public function lockUser($id)
  6772. {
  6773. $user = $this->getUserById($id);
  6774. if (!$user) {
  6775. $this->setAPIResponse('error', 'User not found', 404);
  6776. return false;
  6777. }
  6778. $response = [
  6779. array(
  6780. 'function' => 'query',
  6781. 'query' => array(
  6782. 'UPDATE users SET',
  6783. ['locked' => '1'],
  6784. 'WHERE id = ?',
  6785. $id
  6786. )
  6787. ),
  6788. ];
  6789. $this->setLoggerChannel('User Management');
  6790. $this->logger->info('User: ' . $user['username'] . ' account locked');
  6791. $this->setAPIResponse('success', 'User account locked', 200);
  6792. return $this->processQueries($response);
  6793. }
  6794. public function unlockCurrentUser($array)
  6795. {
  6796. if ($array['password'] == '') {
  6797. $this->setAPIResponse('error', 'Password Not Set', 422);
  6798. return false;
  6799. }
  6800. $user = $this->getUserById($this->user['userID']);
  6801. if (!password_verify($array['password'], $user['password'])) {
  6802. $this->setAPIResponse('error', 'Password Incorrect', 401);
  6803. return false;
  6804. }
  6805. return $this->unlockUser($this->user['userID']);
  6806. }
  6807. public function unlockUser($id)
  6808. {
  6809. $user = $this->getUserById($id);
  6810. if (!$user) {
  6811. $this->setAPIResponse('error', 'User not found', 404);
  6812. return false;
  6813. }
  6814. $response = [
  6815. array(
  6816. 'function' => 'query',
  6817. 'query' => array(
  6818. 'UPDATE users SET',
  6819. ['locked' => '0'],
  6820. 'WHERE id = ?',
  6821. $id
  6822. )
  6823. ),
  6824. ];
  6825. $this->setLoggerChannel('User Management');
  6826. $this->logger->info('User: ' . $user['username'] . ' account unlocked');
  6827. $this->setAPIResponse('success', 'User account unlocked', 200);
  6828. return $this->processQueries($response);
  6829. }
  6830. public function youtubeSearch($query)
  6831. {
  6832. if (!$query) {
  6833. $this->setAPIResponse('error', 'No query supplied', 422);
  6834. return false;
  6835. }
  6836. $keys = array(
  6837. 'AIzaSyBsdt8nLJRMTwOq5PY5A5GLZ2q7scgn01w',
  6838. 'AIzaSyD-8SHutB60GCcSM8q_Fle38rJUV7ujd8k',
  6839. 'AIzaSyBzOpVBT6VII-b-8gWD0MOEosGg4hyhCsQ',
  6840. 'AIzaSyBKnRe1P8fpfBHgooJpmT0WOsrdUtZ4cpk'
  6841. );
  6842. $randomKeyIndex = array_rand($keys);
  6843. $key = $keys[$randomKeyIndex];
  6844. $apikey = ($this->config['youtubeAPI'] !== '') ? $this->config['youtubeAPI'] : $key;
  6845. $results = false;
  6846. $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=$query+official+trailer&part=snippet&maxResults=1&type=video&videoDuration=short&key=$apikey";
  6847. $response = Requests::get($url);
  6848. if ($response->success) {
  6849. $results = json_decode($response->body, true);
  6850. $this->setAPIResponse('success', null, 200, $results);
  6851. return $results;
  6852. } else {
  6853. $this->setAPIResponse('error', 'Bad response from YouTube', 500);
  6854. return false;
  6855. }
  6856. }
  6857. public function scrapePage($array)
  6858. {
  6859. try {
  6860. $url = $array['url'] ?? false;
  6861. $type = $array['type'] ?? false;
  6862. if (!$url) {
  6863. $this->setAPIResponse('error', 'URL was not supplied', 422);
  6864. return false;
  6865. }
  6866. $url = $this->qualifyURL($url);
  6867. $data = array(
  6868. 'full_url' => $url,
  6869. 'drill_url' => $this->qualifyURL($url, true)
  6870. );
  6871. $options = array('verify' => false);
  6872. $response = Requests::get($url, array(), $options);
  6873. $data['response_code'] = $response->status_code;
  6874. if ($response->success) {
  6875. $data['result'] = 'Success';
  6876. switch ($type) {
  6877. case 'html':
  6878. $data['data'] = html_entity_decode($response->body);
  6879. break;
  6880. case 'json':
  6881. $data['data'] = json_decode($response->body);
  6882. break;
  6883. default:
  6884. $data['data'] = $response->body;
  6885. }
  6886. $this->setAPIResponse('success', null, 200, $data);
  6887. return $data;
  6888. } else {
  6889. $this->setAPIResponse('error', 'Error getting successful response', 500);
  6890. return false;
  6891. }
  6892. } catch (Requests_Exception $e) {
  6893. $this->setResponse(500, $e->getMessage());
  6894. return false;
  6895. }
  6896. }
  6897. public function chooseInstance($url = null, $token = null, $instance = 0, $type = null)
  6898. {
  6899. if (!$url || !$token) {
  6900. return false;
  6901. }
  6902. $list = $this->csvHomepageUrlToken($url, $token);
  6903. if ($type) {
  6904. $type = strtolower($type);
  6905. switch ($type) {
  6906. case 'url':
  6907. case 'token':
  6908. break;
  6909. default:
  6910. $type = 'url';
  6911. break;
  6912. }
  6913. if (is_numeric($instance)) {
  6914. return $list[$instance][$type];
  6915. } else {
  6916. return $list;
  6917. }
  6918. }
  6919. if (is_numeric($instance)) {
  6920. return $list[$instance];
  6921. } else {
  6922. return $list;
  6923. }
  6924. }
  6925. public function CBPFWTabs()
  6926. {
  6927. return '
  6928. <script>
  6929. /**
  6930. * cbpFWTabs.js v1.0.0
  6931. * http://www.codrops.com
  6932. *
  6933. * Licensed under the MIT license.
  6934. * http://www.opensource.org/licenses/mit-license.php
  6935. *
  6936. * Copyright 2014, Codrops
  6937. * http://www.codrops.com
  6938. */
  6939. ;( function( window ) {
  6940. \'use strict\';
  6941. function extend( a, b ) {
  6942. for( var key in b ) {
  6943. if( b.hasOwnProperty( key ) ) {
  6944. a[key] = b[key];
  6945. }
  6946. }
  6947. return a;
  6948. }
  6949. function CBPFWTabs( el, options ) {
  6950. this.el = el;
  6951. this.options = extend( {}, this.options );
  6952. extend( this.options, options );
  6953. this._init();
  6954. }
  6955. CBPFWTabs.prototype.options = {
  6956. start : 0
  6957. };
  6958. CBPFWTabs.prototype._init = function() {
  6959. // tabs elems
  6960. this.tabs = [].slice.call( this.el.querySelectorAll( \'nav > ul > li\' ) );
  6961. // content items
  6962. this.items = [].slice.call( this.el.querySelectorAll( \'.content-wrap > section\' ) );
  6963. // current index
  6964. this.current = -1;
  6965. // show current content item
  6966. try{
  6967. if(this.tabs[0].innerHTML.indexOf(\'#settings\') >= 0){
  6968. this._show(' . $this->config['defaultSettingsTab'] . ');
  6969. let tabId = $(this.items[' . $this->config['defaultSettingsTab'] . ']).attr("id") + "-anchor";
  6970. $("#" + tabId).click();
  6971. $("#" + tabId + " a").click();
  6972. }else{
  6973. this._show();
  6974. }
  6975. }catch{
  6976. this._show();
  6977. }
  6978. // init events
  6979. this._initEvents();
  6980. };
  6981. CBPFWTabs.prototype._initEvents = function() {
  6982. var self = this;
  6983. this.tabs.forEach( function( tab, idx ) {
  6984. tab.addEventListener( \'click\', function( ev ) {
  6985. ev.preventDefault();
  6986. self._show( idx );
  6987. } );
  6988. } );
  6989. };
  6990. CBPFWTabs.prototype._show = function( idx ) {
  6991. if( this.current >= 0 ) {
  6992. this.tabs[ this.current ].className = this.items[ this.current ].className = \'\';
  6993. }
  6994. // change current
  6995. this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
  6996. this.tabs[ this.current ].className = \'tab-current\';
  6997. this.items[ this.current ].className = \'content-current\';
  6998. };
  6999. // add to global namespace
  7000. window.CBPFWTabs = CBPFWTabs;
  7001. })( window );
  7002. </script>
  7003. ';
  7004. }
  7005. public function socksHeadingHTML($app)
  7006. {
  7007. return '
  7008. <h3 lang="en">' . ucwords($app) . ' SOCKS API Connection</h3>
  7009. <p>Using this feature allows you to access the API without having to reverse proxy it. Just access it from: </p>
  7010. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/socks/' . $app . '/</code>
  7011. <p>If you are using multiple URL\'s (using the csv method) you will have to use the url like these: </p>
  7012. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/1</code>
  7013. <br/>
  7014. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/2</code>
  7015. ';
  7016. }
  7017. public function socksListing($app = null)
  7018. {
  7019. switch ($app) {
  7020. case 'sonarr':
  7021. $appDetails = [
  7022. 'url' => 'sonarrURL',
  7023. 'enabled' => 'sonarrSocksEnabled',
  7024. 'auth' => 'sonarrSocksAuth',
  7025. 'header' => 'X-Api-Key'
  7026. ];
  7027. break;
  7028. case 'radarr':
  7029. $appDetails = [
  7030. 'url' => 'radarrURL',
  7031. 'enabled' => 'radarrSocksEnabled',
  7032. 'auth' => 'radarrSocksAuth',
  7033. 'header' => 'X-Api-Key'
  7034. ];
  7035. break;
  7036. case 'lidarr':
  7037. $appDetails = [
  7038. 'url' => 'lidarrURL',
  7039. 'enabled' => 'lidarrSocksEnabled',
  7040. 'auth' => 'lidarrSocksAuth',
  7041. 'header' => 'X-Api-Key'
  7042. ];
  7043. break;
  7044. case 'sabnzbd':
  7045. $appDetails = [
  7046. 'url' => 'sabnzbdURL',
  7047. 'enabled' => 'sabnzbdSocksEnabled',
  7048. 'auth' => 'sabnzbdSocksAuth',
  7049. 'header' => null
  7050. ];
  7051. break;
  7052. case 'nzbget':
  7053. $appDetails = [
  7054. 'url' => 'nzbgetURL',
  7055. 'enabled' => 'nzbgetSocksEnabled',
  7056. 'auth' => 'nzbgetSocksAuth',
  7057. 'header' => 'Authorization'
  7058. ];
  7059. break;
  7060. case 'tautulli':
  7061. $appDetails = [
  7062. 'url' => 'tautulliURL',
  7063. 'enabled' => 'tautulliSocksEnabled',
  7064. 'auth' => 'tautulliSocksAuth',
  7065. 'header' => null
  7066. ];
  7067. break;
  7068. case 'qbittorrent':
  7069. $appDetails = [
  7070. 'url' => 'qBittorrentURL',
  7071. 'enabled' => 'qBittorrentSocksEnabled',
  7072. 'auth' => 'qBittorrentSocksAuth',
  7073. 'header' => null
  7074. ];
  7075. break;
  7076. default:
  7077. $appDetails = null;
  7078. }
  7079. return $appDetails;
  7080. }
  7081. public function socks($appDetails, $requestObject, $multiple = null)
  7082. {
  7083. $url = $appDetails['url'];
  7084. $enabled = $appDetails['enabled'];
  7085. $auth = $appDetails['auth'];
  7086. $header = $appDetails['header'];
  7087. $error = false;
  7088. if (!$this->config[$enabled]) {
  7089. $error = true;
  7090. $this->setAPIResponse('error', 'SOCKS module is not enabled', 409);
  7091. }
  7092. if (!$this->qualifyRequest($this->config[$auth], true)) {
  7093. $error = true;
  7094. }
  7095. if (strpos($this->config[$url], ',') !== false) {
  7096. if (!$multiple) {
  7097. $error = true;
  7098. $this->setAPIResponse('error', 'Multiple URLs found in field, please use /api/v2/multiple/socks endpoint', 409);
  7099. }
  7100. } else {
  7101. if ($multiple) {
  7102. $error = true;
  7103. $this->setAPIResponse('error', 'Multiple endpoint accessed but multiple URLs not found in field, please use /api/v2/socks endpoint', 409);
  7104. }
  7105. }
  7106. if (!$error) {
  7107. if ($multiple) {
  7108. $instance = $multiple - 1;
  7109. $pre = explode('/api/v2/multiple/socks/', $requestObject->getUri()->getPath());
  7110. $pre[1] = $this->replace_first('/' . $multiple . '/', '/', $pre[1]);
  7111. // sent url twice since we arent using tokens
  7112. $list = $this->csvHomepageUrlToken($this->config[$url], $this->config[$url]);
  7113. $appURL = $list[$instance]['url'];
  7114. } else {
  7115. $pre = explode('/api/v2/socks/', $requestObject->getUri()->getPath());
  7116. $appURL = $this->config[$url];
  7117. }
  7118. $endpoint = explode('/', $pre[1]);
  7119. $new = urldecode(preg_replace('/' . $endpoint[0] . '/', '', $pre[1], 1));
  7120. $getParams = ($_GET) ? '?' . http_build_query($_GET) : '';
  7121. $url = $this->qualifyURL($appURL) . $new . $getParams;
  7122. $url = $this->cleanPath($url);
  7123. $options = ($this->localURL($appURL)) ? array('verify' => false, 'timeout' => 120) : array('timeout' => 120);
  7124. $headers = [];
  7125. $apiData = $this->apiData($requestObject, false);
  7126. if ($header) {
  7127. if ($requestObject->hasHeader($header)) {
  7128. $headerKey = $requestObject->getHeaderLine($header);
  7129. $headers[$header] = $headerKey;
  7130. }
  7131. }
  7132. if ($requestObject->hasHeader('Content-Type')) {
  7133. $headerKey = $requestObject->getHeaderLine('Content-Type');
  7134. $headers['Content-Type'] = $headerKey;
  7135. }
  7136. $debugInformation = [
  7137. 'type' => $requestObject->getMethod(),
  7138. 'headerType' => $requestObject->getHeaderLine('Content-Type'),
  7139. 'header' => $header,
  7140. 'headers' => $headers,
  7141. 'url' => $url,
  7142. 'options' => $options,
  7143. 'data' => $apiData,
  7144. ];
  7145. $this->setLoggerChannel('Socks');
  7146. $this->logger->debug('Sending Socks request', $debugInformation);
  7147. try {
  7148. switch ($requestObject->getMethod()) {
  7149. case 'GET':
  7150. $call = Requests::get($url, $headers, $options);
  7151. break;
  7152. case 'POST':
  7153. $call = Requests::post($url, $headers, $apiData, $options);
  7154. break;
  7155. case 'DELETE':
  7156. $call = Requests::delete($url, $headers, $options);
  7157. break;
  7158. case 'PUT':
  7159. $call = Requests::put($url, $headers, $apiData, $options);
  7160. break;
  7161. default:
  7162. $call = Requests::get($url, $headers, $options);
  7163. }
  7164. $this->logger->debug('Socks Response', $this->json_validator($call->body) ? json_decode($call->body, true) : $call->body);
  7165. return $call->body;
  7166. } catch (Requests_Exception $e) {
  7167. $this->setResponse(500, $e->getMessage());
  7168. $this->setLoggerChannel('Socks');
  7169. $this->logger->critical($e, $debugInformation);
  7170. return null;
  7171. }
  7172. } else {
  7173. return null;
  7174. }
  7175. }
  7176. public function getPlexServers()
  7177. {
  7178. if ($this->config['plexToken'] == '') {
  7179. $this->setAPIResponse('error', 'Plex Token cannot be empty', 422);
  7180. return false;
  7181. }
  7182. $ownedOnly = isset($_GET['owned']) ?? false;
  7183. $url = $this->qualifyURL('https://plex.tv/pms/servers');
  7184. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  7185. $headers = [
  7186. 'X-Plex-Product' => 'Organizr',
  7187. 'X-Plex-Version' => '2.0',
  7188. 'X-Plex-Client-Identifier' => '01010101-10101010',
  7189. 'X-Plex-Token' => $this->config['plexToken'],
  7190. ];
  7191. try {
  7192. $response = Requests::get($url, $headers, $options);
  7193. libxml_use_internal_errors(true);
  7194. if ($response->success) {
  7195. $items = array();
  7196. $plex = simplexml_load_string($response->body);
  7197. foreach ($plex as $server) {
  7198. if ($ownedOnly) {
  7199. if ($server['owned'] == 1) {
  7200. $items[] = array(
  7201. 'name' => (string)$server['name'],
  7202. 'address' => (string)$server['address'],
  7203. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7204. 'owned' => (float)$server['owned'],
  7205. );
  7206. }
  7207. } else {
  7208. $items[] = array(
  7209. 'name' => (string)$server['name'],
  7210. 'address' => (string)$server['address'],
  7211. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7212. 'owned' => (float)$server['owned'],
  7213. );
  7214. }
  7215. }
  7216. $this->setResponse(200, null, $items);
  7217. return $items;
  7218. } else {
  7219. $message = $this->testAndFormatString($response->body);
  7220. $this->setResponse(500, 'Plex Error occurred', $message['data']);
  7221. $this->setLoggerChannel('Plex Connection')->warning('Plex Error', $message);
  7222. return $message;
  7223. }
  7224. } catch (Requests_Exception $e) {
  7225. $this->setLoggerChannel('Plex Connection')->error($e);
  7226. $this->setResponse(500, $e->getMessage());
  7227. return false;
  7228. }
  7229. }
  7230. public function getIcons()
  7231. {
  7232. $term = $_GET['search'] ?? null;
  7233. $page = $_GET['page'] ?? 1;
  7234. $limit = $_GET['limit'] ?? 20;
  7235. $offset = ($page * $limit) - $limit;
  7236. $goodIcons['results'] = [];
  7237. $goodIcons['limit'] = $limit;
  7238. $goodIcons['page'] = $page;
  7239. $goodIcons['term'] = $term;
  7240. $allIcons = file_get_contents($this->root . '/js/icons.json');
  7241. $iconListing = json_decode($allIcons, true);
  7242. foreach ($iconListing as $setKey => $set) {
  7243. foreach ($set['children'] as $k => $v) {
  7244. if (stripos($v['text'], $term) !== false || !$term) {
  7245. $goodIcons['results'][] = $v;
  7246. }
  7247. }
  7248. }
  7249. $total = count($goodIcons['results']);
  7250. $goodIcons['total'] = $total;
  7251. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  7252. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  7253. return $goodIcons;
  7254. }
  7255. public function getJournalMode()
  7256. {
  7257. $response = [
  7258. array(
  7259. 'function' => 'fetch',
  7260. 'query' => 'PRAGMA journal_mode',
  7261. ),
  7262. ];
  7263. $query = $this->processQueries($response);
  7264. if ($query) {
  7265. if ($query['journal_mode']) {
  7266. $this->setResponse(200, null, $query);
  7267. } else {
  7268. $this->setResponse(500, 'Error getting Journal Mode');
  7269. }
  7270. } else {
  7271. $this->setResponse(404, 'Journal Mode not found');
  7272. }
  7273. return $query;
  7274. }
  7275. public function setJournalMode($option = 'WAL')
  7276. {
  7277. $option = strtoupper($option);
  7278. switch ($option) {
  7279. case 'WAL':
  7280. case 'DELETE':
  7281. break;
  7282. default:
  7283. return false;
  7284. }
  7285. $response = [
  7286. array(
  7287. 'function' => 'fetch',
  7288. 'query' => 'PRAGMA journal_mode = \'' . $option . '\';',
  7289. ),
  7290. ];
  7291. $query = $this->processQueries($response);
  7292. if ($query) {
  7293. if ($query['journal_mode']) {
  7294. $this->setResponse(200, 'Journal Mode updated to: ' . $option, $query);
  7295. } else {
  7296. $this->setResponse(500, 'Error getting Journal Mode');
  7297. }
  7298. } else {
  7299. $this->setResponse(404, 'Journal Mode not found');
  7300. }
  7301. return $query;
  7302. }
  7303. public function testCronSchedule($schedule = null)
  7304. {
  7305. if (is_array($schedule)) {
  7306. $schedule = str_replace('_', ' ', array_keys($schedule)[0]);
  7307. }
  7308. if (!$schedule) {
  7309. $this->setResponse(409, 'Schedule was not supplied');
  7310. return false;
  7311. }
  7312. try {
  7313. $schedule = new Cron\CronExpression($schedule);
  7314. $this->setResponse(200, 'Schedule was validated');
  7315. return true;
  7316. } catch (InvalidArgumentException $e) {
  7317. $this->setResponse(500, $e->getMessage());
  7318. return false;
  7319. }
  7320. }
  7321. public function testFolder($folder = null)
  7322. {
  7323. $folder = $folder['folder'] ?? null;
  7324. if (!$folder) {
  7325. $this->setResponse(409, 'Folder was not supplied');
  7326. return false;
  7327. }
  7328. $testFolder = $this->makeDir($folder);
  7329. if ($testFolder) {
  7330. $this->setResponse(200, 'Folder approved for logs');
  7331. return true;
  7332. } else {
  7333. $this->setResponse(409, 'Folder path is not valid or permissions insufficient');
  7334. return false;
  7335. }
  7336. }
  7337. public function replaceStringInDatabase($string)
  7338. {
  7339. $databaseStringList = [
  7340. 'AUTOINCREMENT' => [
  7341. 'sqlite3' => 'AUTOINCREMENT',
  7342. 'mysqli' => 'AUTO_INCREMENT',
  7343. 'postgre' => 'AUTOINCREMENT'
  7344. ],
  7345. 'COLLATE NOCASE' => [
  7346. 'sqlite3' => 'COLLATE NOCASE',
  7347. 'mysqli' => '',
  7348. 'postgre' => ''
  7349. ],
  7350. 'INTEGER PRIMARY KEY AUTOINCREMENT' => [
  7351. 'sqlite3' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7352. 'mysqli' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7353. 'postgre' => 'SERIAL PRIMARY KEY'
  7354. ],
  7355. 'DATETIME' => [
  7356. 'sqlite3' => 'DATETIME',
  7357. 'mysqli' => 'DATETIME',
  7358. 'postgre' => 'TIMESTAMP'
  7359. ],
  7360. ];
  7361. if (gettype($string) == 'string') {
  7362. foreach ($databaseStringList as $item => $value) {
  7363. if (stripos($string, $item) !== false) {
  7364. $string = str_ireplace($item, $databaseStringList[$item][$this->config['driver']], $string);
  7365. }
  7366. }
  7367. }
  7368. return $string;
  7369. }
  7370. public function cleanDatabaseQuery($query)
  7371. {
  7372. if (is_array($query)) {
  7373. foreach ($query as $key => $value) {
  7374. $query[$key] = $this->cleanDatabaseQuery($value);
  7375. }
  7376. return $query;
  7377. } else {
  7378. return $this->replaceStringInDatabase($query);
  7379. }
  7380. }
  7381. protected function processQueries(array $request, $migration = false)
  7382. {
  7383. $results = array();
  7384. $firstKey = '';
  7385. if ($this->config['includeDatabaseQueriesInDebug']) {
  7386. $this->setLoggerChannel('Database');
  7387. $this->logger->debug('Query to database', $request);
  7388. }
  7389. foreach ($request as $k => $v) {
  7390. try {
  7391. $v['query'] = $this->cleanDatabaseQuery($v['query']);
  7392. $query = ($migration) ? $this->otherDb->query($v['query']) : $this->db->query($v['query']);
  7393. $keyName = (isset($v['key'])) ? $v['key'] : $k;
  7394. $firstKey = (isset($v['key']) && $k == 0) ? $v['key'] : $k;
  7395. switch ($v['function']) {
  7396. case 'fetchAll':
  7397. $results[$keyName] = $query->fetchAll();
  7398. break;
  7399. case 'fetch':
  7400. // PHP 8 Fix?
  7401. $query->setRowClass(null);
  7402. $results[$keyName] = $query->fetch();
  7403. break;
  7404. case 'getAffectedRows':
  7405. $results[$keyName] = $query->getAffectedRows();
  7406. break;
  7407. case 'getRowCount':
  7408. $results[$keyName] = $query->getRowCount();
  7409. break;
  7410. case 'fetchSingle':
  7411. // PHP 8 Fix?
  7412. $query->setRowClass(null);
  7413. $results[$keyName] = $query->fetchSingle();
  7414. break;
  7415. case 'query':
  7416. $results[$keyName] = $query;
  7417. break;
  7418. default:
  7419. return false;
  7420. }
  7421. } catch (Exception $e) {
  7422. $this->setLoggerChannel('Database');
  7423. $this->logger->critical($e, $v['query']);
  7424. return false;
  7425. }
  7426. }
  7427. if ($this->config['includeDatabaseQueriesInDebug']) {
  7428. $this->logger->debug('Results from database', $results);
  7429. }
  7430. return count($request) > 1 ? $results : $results[$firstKey];
  7431. }
  7432. }