organizr.class.php 241 KB

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