organizr.class.php 208 KB

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