organizr.class.php 250 KB

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