organizr.class.php 212 KB

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