organizr.class.php 218 KB

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