4
0

organizr.class.php 244 KB

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