organizr.class.php 243 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586
  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)) {
  1867. if (strpos($_FILES['file']['type'], 'image/') === false) {
  1868. $this->setResponse(403, 'File Type not approved', $_FILES['file']['type']);
  1869. return false;
  1870. }
  1871. if (!$this->approvedFileType($_FILES['file']['tmp_name'])) {
  1872. $this->setResponse(403, 'File Type not approved', $_FILES['file']['tmp_name']);
  1873. return false;
  1874. }
  1875. if ($this->approvedFileExtension($_FILES['file']['name'])) {
  1876. ini_set('upload_max_filesize', '10M');
  1877. ini_set('post_max_size', '10M');
  1878. $tempFile = $_FILES['file']['tmp_name'];
  1879. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  1880. $this->makeDir($targetPath);
  1881. $targetFile = $targetPath . $this->sanitizeUserString($_FILES['file']['name']);
  1882. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  1883. return move_uploaded_file($tempFile, $targetFile);
  1884. } else {
  1885. $this->setResponse(403, 'File Extension not approved');
  1886. return false;
  1887. }
  1888. } else {
  1889. $this->setResponse(500, 'No File was uploaded');
  1890. return false;
  1891. }
  1892. }
  1893. public function formatPingHost($host)
  1894. {
  1895. $host = $this->qualifyURL($host, true);
  1896. if ($host['port'] !== '') {
  1897. $host['port'] = str_replace(':', '', $host['port']);
  1898. }
  1899. if ($host['host'] == '' && $host['path'] !== '') {
  1900. $host['host'] = $host['path'];
  1901. $host['path'] = '';
  1902. if (strpos($host['host'], '/') !== false) {
  1903. $host['host'] = explode('/', $host['host'])[0];
  1904. }
  1905. }
  1906. return $host;
  1907. }
  1908. public function ping($pings)
  1909. {
  1910. if ($this->qualifyRequest($this->config['pingAuth'], true)) {
  1911. if (!$pings['list']) {
  1912. $this->setAPIResponse('error', 'No ping hostname/IP\'s entered', 409);
  1913. return null;
  1914. }
  1915. $pings = $pings['list'];
  1916. $type = gettype($pings);
  1917. $ping = new Ping("");
  1918. $ping->setTtl(128);
  1919. $ping->setTimeout(2);
  1920. switch ($type) {
  1921. case "array":
  1922. $results = [];
  1923. foreach ($pings as $k => $v) {
  1924. $pingFormatted = $this->formatPingHost($v);
  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[$v] = $latency;
  1934. } else {
  1935. $results[$v] = false;
  1936. }
  1937. }
  1938. break;
  1939. case "string":
  1940. $pingFormatted = $this->formatPingHost($pings);
  1941. $ping->setHost($pingFormatted['host']);
  1942. if ($pingFormatted['port'] !== '') {
  1943. $ping->setPort($pingFormatted['port']);
  1944. $latency = $ping->ping('fsockopen');
  1945. } else {
  1946. $latency = $ping->ping();
  1947. }
  1948. if ($latency || $latency === 0) {
  1949. $results = $latency;
  1950. } else {
  1951. $results = null;
  1952. }
  1953. break;
  1954. }
  1955. return ($results) ?? null;
  1956. }
  1957. return null;
  1958. }
  1959. public function getPluginSettings()
  1960. {
  1961. return [
  1962. 'Marketplace' => [
  1963. $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.']),
  1964. $this->settingsOption('multiple-url', 'externalPluginMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  1965. $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']),
  1966. $this->settingsOption('switch', 'checkForPluginUpdate', ['label' => 'Check for Plugin Updates', ['help' => 'Check for updates on page load']])
  1967. ]
  1968. ];
  1969. }
  1970. public function getThemeSettings()
  1971. {
  1972. return [
  1973. 'Marketplace' => [
  1974. $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.']),
  1975. $this->settingsOption('multiple-url', 'externalThemeMarketplaceRepos', ['override' => 12, 'label' => 'External Marketplace Repo', 'help' => 'Only supports Github repos']),
  1976. $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']),
  1977. $this->settingsOption('switch', 'checkForThemeUpdate', ['label' => 'Check for Theme Updates', ['help' => 'Check for updates on page load']])
  1978. ]
  1979. ];
  1980. }
  1981. public function getCustomizeAppearance()
  1982. {
  1983. return [
  1984. 'Top Bar' => [
  1985. $this->settingsOption('input', 'logo', ['label' => 'Logo URL']),
  1986. $this->settingsOption('input', 'title', ['label' => 'Organizr Title']),
  1987. $this->settingsOption('switch', 'useLogo', ['label' => 'Use Logo instead of Title', 'help' => 'Also sets the title of your site']),
  1988. $this->settingsOption('input', 'description', ['label' => 'Meta Description', 'help' => 'Used to set the description for SEO meta tags']),
  1989. ],
  1990. 'Side Menu' => [
  1991. $this->settingsOption('switch', 'allowCollapsableSideMenu', ['label' => 'Allow Side Menu to be Collapsable']),
  1992. $this->settingsOption('switch', 'sideMenuCollapsed', ['label' => 'Side Menu Collapsed at Launch']),
  1993. $this->settingsOption('switch', 'collapseSideMenuOnClick', ['label' => 'Collapse Side Menu after clicking Tab']),
  1994. $this->settingsOption('switch', 'githubMenuLink', ['label' => 'Show GitHub Repo Link']),
  1995. $this->settingsOption('switch', 'organizrFeatureRequestLink', ['label' => 'Show Organizr Feature Request Link']),
  1996. $this->settingsOption('switch', 'organizrSupportMenuLink', ['label' => 'Show Organizr Support Link']),
  1997. $this->settingsOption('switch', 'organizrDocsMenuLink', ['label' => 'Show Organizr Docs Link']),
  1998. $this->settingsOption('switch', 'organizrSignoutMenuLink', ['label' => 'Show Organizr Sign out & in Button on Sidebar']),
  1999. $this->settingsOption('switch', 'expandCategoriesByDefault', ['label' => 'Expand All Categories']),
  2000. $this->settingsOption('switch', 'autoCollapseCategories', ['label' => 'Auto-Collapse Categories']),
  2001. $this->settingsOption('switch', 'autoExpandNavBar', ['label' => 'Auto-Expand Nav Bar']),
  2002. $this->settingsOption('select', 'unsortedTabs', ['label' => 'Unsorted Tab Placement', 'options' => [['name' => 'Top', 'value' => 'top'], ['name' => 'Bottom', 'value' => 'bottom']]]),
  2003. ],
  2004. 'Login Page' => [
  2005. $this->settingsOption('input', 'loginLogo', ['label' => 'Login Logo URL']),
  2006. $this->settingsOption('multiple-url', 'loginWallpaper', ['label' => 'Login Wallpaper URL', 'help' => 'You may enter multiple URL\'s']),
  2007. $this->settingsOption('switch', 'useLogoLogin', ['label' => 'Use Logo instead of Title on Login Page']),
  2008. $this->settingsOption('switch', 'minimalLoginScreen', ['label' => 'Minimal Login Screen']),
  2009. $this->settingsOption('switch', 'useRandomMediaImage', ['label' => 'Use Random Media Wallpaper From Media Server']),
  2010. ],
  2011. 'Options' => [
  2012. $this->settingsOption('switch', 'alternateHomepageHeaders', ['label' => 'Alternate Homepage Titles']),
  2013. $this->settingsOption('switch', 'debugErrors', ['label' => 'Show Debug Errors']),
  2014. $this->settingsOption('switch', 'easterEggs', ['label' => 'Show Easter Eggs']),
  2015. $this->settingsOption('input', 'gaTrackingID', ['label' => 'Google Analytics Tracking ID', 'placeholder' => 'e.g. UA-XXXXXXXXX-X']),
  2016. ],
  2017. 'Colors & Themes' => [
  2018. $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>']),
  2019. $this->settingsOption('blank'),
  2020. $this->settingsOption('button', '', ['label' => 'Reset Colors', 'icon' => 'fa fa-ticket', 'text' => 'Reset', 'attr' => 'onclick="resetCustomColors()"']),
  2021. $this->settingsOption('blank'),
  2022. $this->settingsOption('color', 'headerColor', ['label' => 'Nav Bar Color']),
  2023. $this->settingsOption('color', 'headerTextColor', ['label' => 'Nav Bar Text Color']),
  2024. $this->settingsOption('color', 'sidebarColor', ['label' => 'Side Bar Color']),
  2025. $this->settingsOption('color', 'sidebarTextColor', ['label' => 'Side Bar Text Color']),
  2026. $this->settingsOption('color', 'accentColor', ['label' => 'Accent Color']),
  2027. $this->settingsOption('color', 'accentTextColor', ['label' => 'Accent Text Color']),
  2028. $this->settingsOption('color', 'buttonColor', ['label' => 'Button Color']),
  2029. $this->settingsOption('color', 'buttonTextColor', ['label' => 'Button Text Color']),
  2030. $this->settingsOption('select', 'theme', ['label' => 'Theme', 'class' => 'themeChanger', 'options' => $this->getAllThemes()]),
  2031. $this->settingsOption('select', 'style', ['label' => 'Style', 'class' => 'styleChanger', 'options' => [['name' => 'Light', 'value' => 'light'], ['name' => 'Dark', 'value' => 'dark'], ['name' => 'Horizontal', 'value' => 'horizontal']]]),
  2032. ],
  2033. 'Notifications' => [
  2034. $this->settingsOption('select', 'notificationBackbone', ['label' => 'Type', 'class' => 'notifyChanger', 'options' => $this->notificationTypesOptions()]),
  2035. $this->settingsOption('select', 'notificationPosition', ['label' => 'Position', 'class' => 'notifyPositionChanger', 'options' => $this->notificationPositionsOptions()]),
  2036. $this->settingsOption('html', null, ['label' => 'Test Message', 'html' => '
  2037. <div class="btn-group m-r-10 dropup">
  2038. <button aria-expanded="false" data-toggle="dropdown" class="btn btn-info btn-outline dropdown-toggle waves-effect waves-light" type="button">
  2039. <i class="fa fa-comment m-r-5"></i>
  2040. <span>Test </span>
  2041. </button>
  2042. <ul role="menu" class="dropdown-menu">
  2043. <li><a onclick="message(\'Test Message\',\'This is a success Message\',activeInfo.settings.notifications.position,\'#FFF\',\'success\',\'5000\');">Success</a></li>
  2044. <li><a onclick="message(\'Test Message\',\'This is a info Message\',activeInfo.settings.notifications.position,\'#FFF\',\'info\',\'5000\');">Info</a></li>
  2045. <li><a onclick="message(\'Test Message\',\'This is a warning Message\',activeInfo.settings.notifications.position,\'#FFF\',\'warning\',\'5000\');">Warning</a></li>
  2046. <li><a onclick="message(\'Test Message\',\'This is a error Message\',activeInfo.settings.notifications.position,\'#FFF\',\'error\',\'5000\');">Error</a></li>
  2047. </ul>
  2048. </div>
  2049. ']
  2050. ),
  2051. ],
  2052. 'FavIcon' => [
  2053. $this->settingsOption('html', null, ['label' => 'Instructions', 'override' => 12, 'html' => '
  2054. <div class="panel panel-default">
  2055. <div class="panel-heading">
  2056. <a href="https://realfavicongenerator.net/" target="_blank"><span class="label label-info m-l-5">Visit FavIcon Site</span></a>
  2057. </div>
  2058. <div class="panel-wrapper collapse in">
  2059. <div class="panel-body">
  2060. <ul class="list-icons">
  2061. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Select your Favicon picture]</li>
  2062. <li lang="en"><i class="fa fa-caret-right text-info"></i> Choose your image to use</li>
  2063. <li lang="en"><i class="fa fa-caret-right text-info"></i> Edit settings to your liking</li>
  2064. <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>
  2065. <li lang="en"><i class="fa fa-caret-right text-info"></i> Enter this path <code>data/favicon</code></li>
  2066. <li lang="en"><i class="fa fa-caret-right text-info"></i> Click [Generate your Favicons and HTML code]</li>
  2067. <li lang="en"><i class="fa fa-caret-right text-info"></i> Download and unzip file and place in <code>data/favicon</code></li>
  2068. <li lang="en"><i class="fa fa-caret-right text-info"></i> Copy code and paste inside left box</li>
  2069. </ul>
  2070. </div>
  2071. </div>
  2072. </div>
  2073. ']
  2074. ),
  2075. $this->settingsOption('code-editor', 'favIcon', ['label' => 'Fav Icon Code', 'mode' => 'html']),
  2076. ],
  2077. 'Custom CSS' => [
  2078. $this->settingsOption('code-editor', 'customCss', ['label' => 'Custom CSS', 'mode' => 'css']),
  2079. ],
  2080. 'Theme CSS' => [
  2081. $this->settingsOption('code-editor', 'customThemeCss', ['label' => 'Theme CSS', 'mode' => 'css']),
  2082. ],
  2083. 'Custom Javascript' => [
  2084. $this->settingsOption('code-editor', 'customJava', ['label' => 'Custom Javascript', 'mode' => 'javascript']),
  2085. ],
  2086. 'Theme Javascript' => [
  2087. $this->settingsOption('code-editor', 'customThemeJava', ['label' => 'Theme Javascript', 'mode' => 'javascript']),
  2088. ],
  2089. ];
  2090. }
  2091. public function loadAppearance()
  2092. {
  2093. $appearance['logo'] = $this->config['logo'];
  2094. $appearance['title'] = $this->config['title'];
  2095. $appearance['useLogo'] = $this->config['useLogo'];
  2096. $appearance['useLogoLogin'] = $this->config['useLogoLogin'];
  2097. $appearance['headerColor'] = $this->config['headerColor'];
  2098. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2099. $appearance['sidebarColor'] = $this->config['sidebarColor'];
  2100. $appearance['headerTextColor'] = $this->config['headerTextColor'];
  2101. $appearance['sidebarTextColor'] = $this->config['sidebarTextColor'];
  2102. $appearance['accentColor'] = $this->config['accentColor'];
  2103. $appearance['accentTextColor'] = $this->config['accentTextColor'];
  2104. $appearance['buttonColor'] = $this->config['buttonColor'];
  2105. $appearance['buttonTextColor'] = $this->config['buttonTextColor'];
  2106. $appearance['buttonTextHoverColor'] = $this->config['buttonTextHoverColor'];
  2107. $appearance['buttonHoverColor'] = $this->config['buttonHoverColor'];
  2108. $appearance['loginWallpaper'] = $this->config['loginWallpaper'];
  2109. $appearance['randomMediaImage'] = $this->getRandomMediaImage('np');
  2110. $appearance['loginLogo'] = $this->config['loginLogo'];
  2111. $appearance['customCss'] = $this->config['customCss'];
  2112. $appearance['customThemeCss'] = $this->config['customThemeCss'];
  2113. $appearance['customJava'] = $this->config['customJava'];
  2114. $appearance['customThemeJava'] = $this->config['customThemeJava'];
  2115. return $appearance;
  2116. }
  2117. public function getRandomMediaImage($type = null)
  2118. {
  2119. if (!$this->config['useRandomMediaImage']) {
  2120. return false;
  2121. }
  2122. if (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache')) {
  2123. $folder = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache';
  2124. $directoryIterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS);
  2125. $iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
  2126. $images = [];
  2127. switch ($type) {
  2128. case 'np':
  2129. foreach ($iteratorIterator as $info) {
  2130. if (stripos($info->getFilename(), 'np') !== false) {
  2131. $images[] = 'data/cache/' . $info->getFilename();
  2132. }
  2133. }
  2134. if (count($images) > 0) {
  2135. return $images[rand(0, count($images))];
  2136. } else {
  2137. return false;
  2138. }
  2139. default:
  2140. return false;
  2141. }
  2142. } else {
  2143. return false;
  2144. }
  2145. }
  2146. public function getSettingsMain()
  2147. {
  2148. $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>';
  2149. $settings = [
  2150. 'Settings Page' => [
  2151. $this->settingsOption('select', 'defaultSettingsTab', ['label' => 'Default Settings Tab', 'options' => $this->getSettingsTabs(), 'help' => 'Choose which Settings Tab to be default when opening settings page']),
  2152. ],
  2153. 'Github' => [
  2154. $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']),
  2155. $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']),
  2156. ],
  2157. 'API' => [
  2158. $this->settingsOption('password-alt-copy', 'organizrAPI', ['label' => 'Organizr API']),
  2159. $this->settingsOption('button', null, ['label' => 'Generate New API Key', 'class' => 'newAPIKey', 'icon' => 'fa fa-refresh', 'text' => 'Generate']),
  2160. $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>'])
  2161. ],
  2162. 'Authentication' => [
  2163. $this->settingsOption('select', 'authType', ['id' => 'authSelect', 'label' => 'Authentication Type', 'value' => $this->config['authType'], 'options' => $this->getAuthTypes()]),
  2164. $this->settingsOption('select', 'authBackend', ['id' => 'authBackendSelect', 'label' => 'Authentication Backend', 'class' => 'backendAuth switchAuth', 'value' => $this->config['authBackend'], 'options' => $this->getAuthBackends()]),
  2165. $this->settingsOption('token', 'plexToken', ['class' => 'plexAuth switchAuth']),
  2166. $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]\')"']),
  2167. $this->settingsOption('password-alt', 'plexID', ['class' => 'plexAuth switchAuth', 'label' => 'Plex Machine', 'placeholder' => 'Use Get Plex Machine Button']),
  2168. $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]\')"']),
  2169. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email', 'class' => 'plexAuth switchAuth', 'placeholder' => 'Admin username for Plex']),
  2170. $this->settingsOption('switch', 'plexoAuth', ['label' => 'Enable Plex oAuth', 'class' => 'plexAuth switchAuth']),
  2171. $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']),
  2172. $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']),
  2173. $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']),
  2174. $this->settingsOption('url', 'authBackendHost', ['class' => 'ldapAuth ftpAuth switchAuth', 'label' => 'Host Address', 'placeholder' => 'http(s) | ftp(s) | ldap(s)://hostname:port']),
  2175. $this->settingsOption('input', 'authBaseDN', ['class' => 'ldapAuth switchAuth', 'label' => 'Host Base DN', 'placeholder' => 'cn=%s,dc=sub,dc=domain,dc=com']),
  2176. $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']),
  2177. $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']),
  2178. $this->settingsOption('input', 'ldapBindUsername', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Username']),
  2179. $this->settingsOption('password', 'ldapBindPassword', ['class' => 'ldapAuth switchAuth', 'label' => 'Bind Password']),
  2180. $this->settingsOption('select', 'ldapType', ['id' => 'ldapType', 'label' => 'LDAP Backend Type', 'class' => 'ldapAuth switchAuth', 'options' => $this->getLDAPOptions()]),
  2181. $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>']),
  2182. $this->settingsOption('blank', null, ['class' => 'ldapAuth switchAuth']),
  2183. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP SSL', 'help' => 'This will enable the use of SSL for LDAP connections']),
  2184. $this->settingsOption('switch', 'ldapSSL', ['class' => 'ldapAuth switchAuth', 'label' => 'Enable LDAP TLS', 'help' => 'This will enable the use of TLS for LDAP connections']),
  2185. $this->settingsOption('test', 'ldap', ['class' => 'ldapAuth switchAuth']),
  2186. $this->settingsOption('test', '', ['label' => 'Test Login', 'class' => 'ldapAuth switchAuth', 'text' => 'Test Login', 'attr' => 'onclick="showLDAPLoginTest()"']),
  2187. $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.']),
  2188. $this->settingsOption('token', 'embyToken', ['class' => 'embyAuth switchAuth', 'label' => 'Emby Token']),
  2189. $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.']),
  2190. $this->settingsOption('token', 'jellyfinToken', ['class' => 'jellyfinAuth switchAuth', 'label' => 'Jellyfin Token']),
  2191. ],
  2192. 'Security' => [
  2193. $this->settingsOption('number', 'loginAttempts', ['label' => 'Max Login Attempts']),
  2194. $this->settingsOption('select', 'loginLockout', ['label' => 'Login Lockout Seconds', 'options' => $this->timeOptions()]),
  2195. $this->settingsOption('number', 'lockoutTimeout', ['label' => 'Inactivity Timer [Minutes]']),
  2196. $this->settingsOption('switch', 'lockoutSystem', ['label' => 'Inactivity Lock']),
  2197. $this->settingsOption('select', 'lockoutMinAuth', ['label' => 'Lockout Groups From', 'options' => $this->groupSelect()]),
  2198. $this->settingsOption('select', 'lockoutMaxAuth', ['label' => 'Lockout Groups To', 'options' => $this->groupSelect()]),
  2199. $this->settingsOption('switch', 'traefikAuthEnable', ['label' => 'Enable Traefik Auth Redirect', 'help' => 'This will enable the webserver to forward errors so traefik will accept them']),
  2200. $this->settingsOption('input', 'traefikDomainOverride', ['label' => 'Traefik Domain for Return Override', 'help' => 'Please use a FQDN on this URL Override', 'placeholder' => 'http(s)://domain']),
  2201. $this->settingsOption('select', 'debugAreaAuth', ['label' => 'Minimum Authentication for Debug Area', 'options' => $this->groupSelect(), 'settings' => '{}']),
  2202. $this->settingsOption('multiple', 'sandbox', ['override' => 12, 'label' => 'iFrame Sandbox', 'help' => 'WARNING! This can potentially mess up your iFrames', 'options' => $this->sandboxOptions()]),
  2203. $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}']),
  2204. $this->settingsOption('code-editor', 'blacklistedMessage', ['mode' => 'html']),
  2205. ],
  2206. 'Logs' => [
  2207. $this->settingsOption('folder', 'logLocation', ['label' => 'Log Save Path', 'help' => 'Folder path to save Organizr Logs - Please test before saving', 'value' => $this->logLocation()]),
  2208. $this->settingsOption('select', 'logLevel', ['label' => 'Log Level', 'options' => $this->logLevels()]),
  2209. $this->settingsOption('switch', 'includeDatabaseQueriesInDebug', ['label' => 'Include Database Queries', 'help' => 'Include Database queries in debug logs']),
  2210. $this->settingsOption('number', 'maxLogFiles', ['label' => 'Maximum Log Files', 'help' => 'Number of log files to preserve', 'attr' => 'min="1"']),
  2211. $this->settingsOption('select', 'logLiveUpdateRefresh', ['label' => 'Live Update Refresh', 'options' => $this->timeOptions()]),
  2212. $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']]]),
  2213. ],
  2214. 'Cron' => [
  2215. $this->settingsOption('cron-file'),
  2216. $this->settingsOption('blank'),
  2217. $this->settingsOption('enable', 'autoUpdateCronEnabled', ['label' => 'Auto-Update Organizr']),
  2218. $this->settingsOption('cron', 'autoUpdateCronSchedule'),
  2219. ],
  2220. 'Login' => [
  2221. $this->settingsOption('password', 'registrationPassword', ['label' => 'Registration Password', 'help' => 'Sets the password for the Registration form on the login screen']),
  2222. $this->settingsOption('switch', 'hideRegistration', ['label' => 'Hide Registration', 'help' => 'Enable this to hide the Registration button on the login screen']),
  2223. $this->settingsOption('number', 'rememberMeDays', ['label' => 'Remember Me Length', 'help' => 'Number of days cookies and tokens will be valid for', 'attr' => 'min="1"']),
  2224. $this->settingsOption('switch', 'rememberMe', ['label' => 'Remember Me', 'help' => 'Default status of Remember Me button on login screen']),
  2225. $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']),
  2226. $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']),
  2227. $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']),
  2228. $this->settingsOption('switch', 'enableLocalAddressForward', ['label' => 'Enable Local Address Forward', 'help' => 'Enables the local address forward if on local address and accessed from WAN Domain']),
  2229. $this->settingsOption('switch', 'disableRecoverPass', ['label' => 'Disable Recover Password', 'help' => 'Disables recover password area']),
  2230. $this->settingsOption('input', 'customForgotPassText', ['label' => 'Custom Recover Password Text', 'help' => 'Text or HTML for recovery password section']),
  2231. ],
  2232. 'Auth Proxy' => [
  2233. $this->settingsOption('switch', 'authProxyEnabled', ['label' => 'Auth Proxy', 'help' => 'Enable option to set Auth Proxy Header Login']),
  2234. $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']),
  2235. $this->settingsOption('input', 'authProxyHeaderName', ['label' => 'Auth Proxy Header Name', 'placeholder' => 'i.e. X-Forwarded-User', 'help' => 'Please choose a unique value for added security']),
  2236. $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']),
  2237. $this->settingsOption('switch', 'authProxyOverrideLogout', ['label' => 'Override Logout', 'help' => 'Enable option to set custom Logout URL for Auth Proxy']),
  2238. $this->settingsOption('input', 'authProxyLogoutURL', ['label' => 'Logout URL', 'help' => 'Logout URL to redirect user for Auth Proxy']),
  2239. ],
  2240. 'Ping' => [
  2241. $this->settingsOption('auth', 'pingAuth'),
  2242. $this->settingsOption('auth', 'pingAuthMessage', ['label' => 'Minimum Authentication for Message and Sound']),
  2243. $this->settingsOption('select', 'pingOnlineSound', ['label' => 'Online Sound', 'options' => $this->getSounds()]),
  2244. $this->settingsOption('select', 'pingOfflineSound', ['label' => 'Offline Sound', 'options' => $this->getSounds()]),
  2245. $this->settingsOption('switch', 'pingMs', ['label' => 'Show Ping Time']),
  2246. $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.']),
  2247. $this->settingsOption('auth', 'pingAuthMs', ['label' => 'Minimum Authentication for Time Display']),
  2248. $this->settingsOption('refresh', 'adminPingRefresh', ['label' => 'Admin Refresh Seconds']),
  2249. $this->settingsOption('refresh', 'otherPingRefresh', ['label' => 'Everyone Refresh Seconds']),
  2250. ],
  2251. 'Certificate' => [
  2252. $this->settingsOption('html', '', ['override' => 12,
  2253. 'html' => '
  2254. <script>
  2255. let myDropzone = new Dropzone("#upload-custom-certificate", {
  2256. url: "api/v2/certificate/custom",
  2257. headers:{ "formKey": local("g","formKey") },
  2258. init: function() {
  2259. this.on("complete", function(file) {
  2260. if(file["status"] === "success"){
  2261. $(".custom-certificate-status").html("<span lang=\"en\">Custom Certificate Loaded</span>");
  2262. }else{
  2263. $(".custom-certificate-status").html("<span lang=\"en\">Error Saving file...</span>");
  2264. }
  2265. });
  2266. }
  2267. });
  2268. </script>
  2269. <div class="row">
  2270. <div class="col-lg-12">
  2271. <div class="panel panel-info">
  2272. <div class="panel-heading"><span lang="en">Notice</span></div>
  2273. <div class="panel-wrapper collapse in" aria-expanded="true">
  2274. <div class="panel-body">
  2275. <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>
  2276. </div>
  2277. </div>
  2278. </div>
  2279. </div>
  2280. </div>
  2281. <div class="row">
  2282. <div class="col-md-12">
  2283. <div class="white-box">
  2284. <h3 class="box-title m-b-0" lang="en">Custom Certificate Status</h3>
  2285. <p class="text-muted m-b-30 custom-certificate-status">' . $certificateStatus . '</p>
  2286. <form action="#" class="dropzone dz-clickable" id="upload-custom-certificate">
  2287. <div class="dz-default dz-message"><span lang="en">Drop Certificate file here to upload</span></div>
  2288. </form>
  2289. </div>
  2290. </div>
  2291. </div>
  2292. ']
  2293. )
  2294. ],
  2295. ];
  2296. if ($this->config['driver'] == 'sqlite3') {
  2297. $database = [
  2298. 'Database' => [
  2299. $this->settingsOption('notice', '', ['notice' => 'danger', 'title' => 'Warning', 'body' => 'This feature is experimental - You may face unexpected database is locked errors in logs']),
  2300. $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>']),
  2301. $this->settingsOption('button', '', ['label' => 'Set DELETE Mode (Default)', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'DELETE\')"']),
  2302. $this->settingsOption('button', '', ['label' => 'Set WAL Mode', 'icon' => 'icon-notebook', 'text' => 'Set', 'attr' => 'onclick="setJournalMode(\'WAL\')"']),
  2303. ]
  2304. ];
  2305. $settings = array_merge($settings, $database);
  2306. }
  2307. ksort($settings);
  2308. return $settings;
  2309. }
  2310. public function getSettingsSSO()
  2311. {
  2312. return [
  2313. 'FYI' => [
  2314. $this->settingsOption('html', '', ['override' => 12,
  2315. 'html' => '
  2316. <div class="row">
  2317. <div class="col-lg-12">
  2318. <div class="panel panel-primary">
  2319. <div class="panel-heading"><span lang="en">Please Read First</span></div>
  2320. <div class="panel-wrapper collapse in" aria-expanded="true">
  2321. <div class="panel-body">
  2322. <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>
  2323. <br/><br/>
  2324. <div class="row">
  2325. <div class="col-lg-2 col-sm-4 col-xs-12">
  2326. <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>
  2327. </div>
  2328. </div>
  2329. <br/>
  2330. <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>
  2331. </div>
  2332. </div>
  2333. </div>
  2334. </div>
  2335. </div>'
  2336. ]
  2337. ),
  2338. ],
  2339. 'Plex' => [
  2340. $this->settingsOption('token', 'plexToken'),
  2341. $this->settingsOption('button', '', ['label' => 'Get Plex Token', 'icon' => 'fa fa-ticket', 'text' => 'Retrieve', 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#sso-form [name=plexToken]\')"']),
  2342. $this->settingsOption('password-alt', 'plexID', ['label' => 'Plex Machine']),
  2343. $this->settingsOption('button', '', ['label' => 'Get Plex Machine', 'icon' => 'fa fa-id-badge', 'text' => 'Retrieve', 'attr' => 'onclick="showPlexMachineForm(\'#sso-form [name=plexID]\')"']),
  2344. $this->settingsOption('input', 'plexAdmin', ['label' => 'Plex Admin Username or Email']),
  2345. $this->settingsOption('blank'),
  2346. $this->settingsOption('html', 'Plex Note', ['html' => '<span lang="en">Please make sure both Token and Machine are filled in</span>']),
  2347. $this->settingsOption('enable', 'ssoPlex'),
  2348. ],
  2349. 'Tautulli' => [
  2350. $this->settingsOption('multiple-url', 'tautulliURL'),
  2351. $this->settingsOption('auth', 'ssoTautulliAuth'),
  2352. $this->settingsOption('enable', 'ssoTautulli'),
  2353. ],
  2354. 'Overseerr' => [
  2355. $this->settingsOption('url', 'overseerrURL'),
  2356. $this->settingsOption('token', 'overseerrToken'),
  2357. $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']),
  2358. $this->settingsOption('password', 'overseerrFallbackPassword', ['label' => 'Overseerr Fallback Password']),
  2359. $this->settingsOption('enable', 'ssoOverseerr'),
  2360. ],
  2361. 'Petio' => [
  2362. $this->settingsOption('url', 'petioURL'),
  2363. $this->settingsOption('token', 'petioToken'),
  2364. $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']),
  2365. $this->settingsOption('password', 'petioFallbackPassword', ['label' => 'Petio Fallback Password']),
  2366. $this->settingsOption('enable', 'ssoPetio'),
  2367. ],
  2368. 'Ombi' => [
  2369. $this->settingsOption('url', 'ombiURL'),
  2370. $this->settingsOption('token', 'ombiToken'),
  2371. $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']),
  2372. $this->settingsOption('password', 'ombiFallbackPassword', ['label' => 'Ombi Fallback Password']),
  2373. $this->settingsOption('enable', 'ssoOmbi'),
  2374. ],
  2375. 'Jellyfin' => [
  2376. $this->settingsOption('url', 'jellyfinURL', ['label' => 'Jellyfin API URL', 'help' => 'Please make sure to use the local address to the API']),
  2377. $this->settingsOption('url', 'jellyfinSSOURL', ['label' => 'Jellyfin SSO URL', 'help' => 'Please make sure to use the same (sub)domain to access Jellyfin as Organizr\'s']),
  2378. $this->settingsOption('enable', 'ssoJellyfin'),
  2379. ],
  2380. 'Komga' => [
  2381. $this->settingsOption('url', 'komgaURL'),
  2382. $this->settingsOption('auth', 'ssoKomgaAuth'),
  2383. $this->settingsOption('enable', 'ssoKomga'),
  2384. $this->settingsOption('blank'),
  2385. $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']),
  2386. $this->settingsOption('password', 'komgaFallbackPassword', ['label' => 'Komga Fallback Password']),
  2387. ],
  2388. ];
  2389. }
  2390. public function systemMenuLists()
  2391. {
  2392. $pluginsMenu = [
  2393. [
  2394. 'active' => false,
  2395. 'api' => 'api/v2/page/settings_plugins_enabled',
  2396. 'anchor' => 'settings-plugins-enabled-anchor',
  2397. 'name' => 'Active',
  2398. ],
  2399. [
  2400. 'active' => false,
  2401. 'api' => 'api/v2/page/settings_plugins_disabled',
  2402. 'anchor' => 'settings-plugins-disabled-anchor',
  2403. 'name' => 'Inactive',
  2404. ],
  2405. [
  2406. 'active' => false,
  2407. 'api' => 'api/v2/page/settings_plugins_settings',
  2408. 'anchor' => 'settings-plugins-settings-anchor',
  2409. 'name' => 'Settings',
  2410. ],
  2411. [
  2412. 'active' => false,
  2413. 'api' => false,
  2414. 'anchor' => 'settings-plugins-marketplace-anchor',
  2415. 'name' => 'Marketplace',
  2416. 'onclick' => 'loadPluginMarketplace();'
  2417. ],
  2418. ];
  2419. $userManagementMenu = [
  2420. [
  2421. 'active' => false,
  2422. 'api' => 'api/v2/page/settings_user_manage_users',
  2423. 'anchor' => 'settings-user-manage-users-anchor',
  2424. 'name' => 'Manage Users'
  2425. ],
  2426. [
  2427. 'active' => false,
  2428. 'api' => 'api/v2/page/settings_user_manage_groups',
  2429. 'anchor' => 'settings-user-manage-groups-anchor',
  2430. 'name' => 'Manage Groups'
  2431. ],
  2432. [
  2433. 'active' => false,
  2434. 'api' => false,
  2435. 'anchor' => 'settings-user-import-users-anchor',
  2436. 'name' => 'Import Users'
  2437. ],
  2438. ];
  2439. $customizeMenu = [
  2440. [
  2441. 'active' => false,
  2442. 'api' => 'api/v2/page/settings_customize_appearance',
  2443. 'anchor' => 'settings-customize-appearance-anchor',
  2444. 'name' => 'Appearance',
  2445. ],
  2446. [
  2447. 'active' => false,
  2448. 'api' => 'api/v2/page/settings_customize_settings',
  2449. 'anchor' => 'settings-customize-settings-anchor',
  2450. 'name' => 'Marketplace Settings',
  2451. ],
  2452. [
  2453. 'active' => false,
  2454. 'api' => false,
  2455. 'anchor' => 'settings-customize-marketplace-anchor',
  2456. 'name' => 'Marketplace',
  2457. 'onclick' => 'loadThemeMarketplace();'
  2458. ],
  2459. ];
  2460. $tabEditorMenu = [
  2461. [
  2462. 'active' => false,
  2463. 'api' => 'api/v2/page/settings_tab_editor_tabs',
  2464. 'anchor' => 'settings-tab-editor-tabs-anchor',
  2465. 'name' => 'Tabs'
  2466. ],
  2467. [
  2468. 'active' => false,
  2469. 'api' => 'api/v2/page/settings_tab_editor_categories',
  2470. 'anchor' => 'settings-tab-editor-categories-anchor',
  2471. 'name' => 'Categories'
  2472. ],
  2473. [
  2474. 'active' => false,
  2475. 'api' => 'api/v2/page/settings_tab_editor_homepage',
  2476. 'anchor' => 'settings-tab-editor-homepage-anchor',
  2477. 'name' => 'Homepage Items'
  2478. ],
  2479. [
  2480. 'active' => false,
  2481. 'api' => 'api/v2/page/settings_tab_editor_homepage_order',
  2482. 'anchor' => 'settings-tab-editor-homepage-order-anchor',
  2483. 'name' => 'Homepage Order'
  2484. ],
  2485. ];
  2486. $systemSettingsMenu = [
  2487. [
  2488. 'active' => true,
  2489. 'api' => false,
  2490. 'anchor' => 'settings-settings-about-anchor',
  2491. 'name' => 'About'
  2492. ],
  2493. [
  2494. 'active' => false,
  2495. 'api' => 'api/v2/page/settings_settings_main',
  2496. 'anchor' => 'settings-settings-main-anchor',
  2497. 'name' => 'Main'
  2498. ],
  2499. [
  2500. 'active' => false,
  2501. 'api' => 'api/v2/page/settings_settings_sso',
  2502. 'anchor' => 'settings-settings-sso-anchor',
  2503. 'name' => 'SSO'
  2504. ],
  2505. [
  2506. 'active' => false,
  2507. 'api' => 'api/v2/page/settings_settings_logs',
  2508. 'anchor' => 'settings-settings-logs-anchor',
  2509. 'name' => 'Logs'
  2510. ],
  2511. [
  2512. 'active' => false,
  2513. 'api' => false,
  2514. 'anchor' => 'settings-settings-updates-anchor',
  2515. 'name' => 'Updates'
  2516. ],
  2517. [
  2518. 'active' => false,
  2519. 'api' => 'api/v2/page/settings_settings_backup',
  2520. 'anchor' => 'settings-settings-backup-anchor',
  2521. 'name' => 'Backup'
  2522. ],
  2523. [
  2524. 'active' => false,
  2525. 'api' => false,
  2526. 'anchor' => 'settings-settings-donate-anchor',
  2527. 'name' => 'Donate'
  2528. ],
  2529. ];
  2530. $systemMenus['system_settings'] = $this->buildSettingsMenus($systemSettingsMenu, 'System Settings');
  2531. $systemMenus['tab_editor'] = $this->buildSettingsMenus($tabEditorMenu, 'Tab Editor');
  2532. $systemMenus['customize'] = $this->buildSettingsMenus($customizeMenu, 'Customize');
  2533. $systemMenus['user_management'] = $this->buildSettingsMenus($userManagementMenu, 'User Management');
  2534. $systemMenus['plugins'] = $this->buildSettingsMenus($pluginsMenu, 'Plugins');
  2535. return $systemMenus;
  2536. }
  2537. public function updateConfigMultiple($array)
  2538. {
  2539. return (bool)$this->updateConfig($array);
  2540. }
  2541. public function updateConfigItems($array)
  2542. {
  2543. if (!count($array)) {
  2544. $this->setAPIResponse('error', 'No data submitted', 409);
  2545. return false;
  2546. }
  2547. $newItem = array();
  2548. foreach ($array as $k => $v) {
  2549. $v = $v ?? '';
  2550. switch ($v) {
  2551. case 'true':
  2552. $v = (bool)true;
  2553. break;
  2554. case 'false':
  2555. $v = (bool)false;
  2556. break;
  2557. }
  2558. // Hash
  2559. if ((stripos($k, 'password') !== false)) {
  2560. if (!$this->isEncrypted($v)) {
  2561. if ($v !== '') {
  2562. $v = $this->encrypt($v);
  2563. }
  2564. }
  2565. }
  2566. switch ($k) {
  2567. case 'logLocation':
  2568. case 'dbLocation':
  2569. if (!empty($v)) {
  2570. $v = $this->cleanDirectory($v);
  2571. }
  2572. break;
  2573. default:
  2574. break;
  2575. }
  2576. if (strtolower($k) !== 'formkey') {
  2577. $newItem[$k] = $v;
  2578. $this->config[$k] = $v;
  2579. }
  2580. }
  2581. $this->setAPIResponse('success', 'Config items updated', 200);
  2582. $this->setLoggerChannel('Config');
  2583. $this->logger->info('Config items updated', array_keys($array));
  2584. return (bool)$this->updateConfig($newItem);
  2585. }
  2586. public function updateConfigItem($array)
  2587. {
  2588. $array['value'] = $array['value'] ?? '';
  2589. switch ($array['value']) {
  2590. case 'true':
  2591. $array['value'] = (bool)true;
  2592. break;
  2593. case 'false':
  2594. $array['value'] = (bool)false;
  2595. break;
  2596. }
  2597. // Hash
  2598. if ($array['type'] == 'password') {
  2599. $array['value'] = $this->encrypt($array['value']);
  2600. }
  2601. $newItem = array(
  2602. $array['name'] => $array['value']
  2603. );
  2604. $this->config[$array['name']] = $array['value'];
  2605. return (bool)$this->updateConfig($newItem);
  2606. }
  2607. public function ignoreNewsId($id)
  2608. {
  2609. if (!$id) {
  2610. $this->setAPIResponse('error', 'News id was not supplied', 409);
  2611. return false;
  2612. }
  2613. $id = array(intval($id));
  2614. $newsIds = $this->config['ignoredNewsIds'];
  2615. $newsIds = array_merge($newsIds, $id);
  2616. $newsIds = array_unique($newsIds);
  2617. $this->updateConfig(['ignoredNewsIds' => $newsIds]);
  2618. $this->setAPIResponse('success', 'News id is now ignored', 200, null);
  2619. }
  2620. public function getNewsIds()
  2621. {
  2622. $newsIds = $this->config['ignoredNewsIds'];
  2623. $this->setAPIResponse('success', null, 200, $newsIds);
  2624. return $newsIds;
  2625. }
  2626. public function testWizardPath($array)
  2627. {
  2628. if ($this->hasDB()) {
  2629. $this->setAPIResponse('error', 'Endpoint disabled as database already exists', 401);
  2630. return false;
  2631. }
  2632. $path = $array['path'] ?? null;
  2633. if (file_exists($path)) {
  2634. if (is_writable($path)) {
  2635. $this->setAPIResponse('success', 'Path exists and is writable', 200);
  2636. return true;
  2637. } else {
  2638. $this->setAPIResponse('error', 'Path exists but is not writable', 403);
  2639. return false;
  2640. }
  2641. } else {
  2642. if (mkdir($path, 0760, true)) {
  2643. $this->setAPIResponse('success', 'Path is writable - Creating now', 200);
  2644. return true;
  2645. } else {
  2646. $this->setAPIResponse('error', 'Failed making directory - Check permissions', 403);
  2647. return false;
  2648. }
  2649. }
  2650. }
  2651. public function formatDatabaseDriver($driver)
  2652. {
  2653. $driver = strtolower($driver);
  2654. switch ($driver) {
  2655. case 'sqlite':
  2656. case 'sqlite3':
  2657. return 'sqlite3';
  2658. case 'mysql':
  2659. case 'mysqli':
  2660. return 'mysqli';
  2661. case 'postgre':
  2662. case 'postgres':
  2663. case 'postgresql':
  2664. return 'postgre';
  2665. default:
  2666. return $driver;
  2667. }
  2668. }
  2669. public function wizardConfig($array)
  2670. {
  2671. $array['driver'] = $array['driver'] ?? 'sqlite3';
  2672. $driver = $this->formatDatabaseDriver($array['driver']);
  2673. $dbName = $array['dbName'] ?? null;
  2674. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2675. $license = $array['license'] ?? null;
  2676. $hashKey = $array['hashKey'] ?? null;
  2677. $api = $array['api'] ?? null;
  2678. $registrationPassword = $array['registrationPassword'] ?? null;
  2679. $username = $array['username'] ?? null;
  2680. $password = $array['password'] ?? null;
  2681. $email = $array['email'] ?? null;
  2682. $dbHost = $array['dbHost'] ?? null;
  2683. $dbUsername = $array['dbUsername'] ?? null;
  2684. $dbPassword = $array['dbPassword'] ?? null;
  2685. $validation = [
  2686. 'dbPath' => $path,
  2687. 'dbName' => $dbName,
  2688. 'license' => $license,
  2689. 'hashKey' => $hashKey,
  2690. 'api' => $api,
  2691. 'registrationPassword' => $registrationPassword,
  2692. 'username' => $username,
  2693. 'password' => $password,
  2694. 'email' => $email,
  2695. 'driver' => $driver
  2696. ];
  2697. $dbName = $this->dbExtension($dbName);
  2698. if ($driver == 'mysqli' || $driver == 'postgre') {
  2699. $dbName = $this->removeDbExtension($dbName);
  2700. $validation = array_merge($validation, [
  2701. 'dbHost' => $dbHost,
  2702. 'dbUsername' => $dbUsername,
  2703. 'dbPassword' => $dbPassword,
  2704. ]);
  2705. }
  2706. foreach ($validation as $k => $v) {
  2707. if ($v == null) {
  2708. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2709. return false;
  2710. }
  2711. }
  2712. if ($path) {
  2713. $path = $this->cleanDirectory($path);
  2714. if (file_exists($path)) {
  2715. if (!is_writable($path)) {
  2716. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2717. return false;
  2718. }
  2719. } else {
  2720. if (!mkdir($path, 0760, true)) {
  2721. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2722. return false;
  2723. }
  2724. }
  2725. }
  2726. $configVersion = $this->version;
  2727. $configArray = array(
  2728. 'dbLocation' => $path,
  2729. 'driver' => $driver,
  2730. 'dbName' => $dbName,
  2731. 'license' => $license,
  2732. 'organizrHash' => $hashKey,
  2733. 'organizrAPI' => $api,
  2734. 'registrationPassword' => $registrationPassword,
  2735. 'uuid' => $this->gen_uuid()
  2736. );
  2737. if ($driver == 'mysqli' || $driver == 'postgre') {
  2738. $configArray = array_merge($configArray, [
  2739. 'dbHost' => $dbHost,
  2740. 'dbUsername' => $dbUsername,
  2741. 'dbPassword' => $this->encrypt($dbPassword, $hashKey),
  2742. ]);
  2743. }
  2744. //Test Database Connection before saving config
  2745. $testDatabaseConnection = $this->testDatabaseConnection($array);
  2746. if (!$testDatabaseConnection) {
  2747. // setResponse already defined
  2748. return false;
  2749. }
  2750. // Create Config
  2751. if ($this->createConfig($configArray)) {
  2752. $this->config = $this->config();
  2753. $this->refreshCookieName();
  2754. $this->connectDB();
  2755. // Call DB Create
  2756. if (!$this->createNewDB($dbName, false)) {
  2757. $this->setAPIResponse('error', 'error creating database using driver: ' . $driver, 500);
  2758. return false;
  2759. }
  2760. if ($this->createDB($path)) {
  2761. // Add in first user
  2762. if ($this->createFirstAdmin($username, $password, $email)) {
  2763. if ($this->createToken($username, $email, 1)) {
  2764. return true;
  2765. } else {
  2766. $this->setAPIResponse('error', 'error creating token', 500);
  2767. }
  2768. } else {
  2769. $this->setAPIResponse('error', 'error creating admin', 500);
  2770. }
  2771. } else {
  2772. $this->setAPIResponse('error', 'error creating database', 500);
  2773. }
  2774. } else {
  2775. $this->setAPIResponse('error', 'error creating config', 500);
  2776. }
  2777. return false;
  2778. }
  2779. public function testDatabaseConnection($array)
  2780. {
  2781. $driver = $array['driver'] ?? 'sqlite3';
  2782. $driver = $this->formatDatabaseDriver($driver);
  2783. $dbName = $array['dbName'] ?? null;
  2784. $dbHost = $array['dbHost'] ?? null;
  2785. $dbUsername = $array['dbUsername'] ?? null;
  2786. $dbPassword = $array['dbPassword'] ?? null;
  2787. $path = $array['dbPath'] ?? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . $this->random_ascii_string(10) . DIRECTORY_SEPARATOR;
  2788. switch ($driver) {
  2789. case 'mysqli':
  2790. if (!extension_loaded('mysqli')) {
  2791. $this->setResponse(500, 'PHP Extension `mysqli` is not loaded');
  2792. return false;
  2793. }
  2794. $config = [
  2795. 'driver' => 'mysqli',
  2796. 'host' => $dbHost,
  2797. 'username' => $dbUsername,
  2798. 'password' => $dbPassword,
  2799. 'options' => [
  2800. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2801. ],
  2802. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2803. ];
  2804. $validation = [
  2805. 'dbHost' => $dbHost,
  2806. 'dbUsername' => $dbUsername,
  2807. 'dbPassword' => $dbPassword,
  2808. ];
  2809. break;
  2810. case 'postgre':
  2811. // DISABLE FOR NOW
  2812. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2813. return false;
  2814. $config = [
  2815. //host, hostaddr, port, dbname, user, password, connect_timeout, options, sslmode, service => see PostgreSQL API
  2816. 'driver' => 'postgre',
  2817. 'username' => $dbUsername,
  2818. 'password' => $dbPassword,
  2819. 'persistent' => true,
  2820. ];
  2821. $host = $this->qualifyURL($dbHost, true);
  2822. if ($host['port']) {
  2823. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  2824. }
  2825. if (($host['host'])) {
  2826. $config = array_merge($config, ['host' => $host['host']]);
  2827. }
  2828. if (!$host['host'] && $host['path']) {
  2829. $config = array_merge($config, ['host' => $host['path']]);
  2830. }
  2831. $validation = [
  2832. 'dbHost' => $dbHost,
  2833. 'dbUsername' => $dbUsername,
  2834. 'dbPassword' => $dbPassword,
  2835. ];
  2836. break;
  2837. case 'sqlite3':
  2838. $path = $this->cleanDirectory($path);
  2839. if (file_exists($path)) {
  2840. if (!is_writable($path)) {
  2841. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2842. return false;
  2843. }
  2844. } else {
  2845. if (is_writable(dirname($path, 1))) {
  2846. if (!mkdir($path, 0760, true)) {
  2847. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2848. return false;
  2849. }
  2850. } else {
  2851. $this->setAPIResponse('error', '[' . $path . '] is not writable', 422);
  2852. return false;
  2853. }
  2854. }
  2855. return true;
  2856. default:
  2857. $this->setResponse(409, 'Database connection test not available for driver: ' . $driver);
  2858. return false;
  2859. }
  2860. foreach ($validation as $k => $v) {
  2861. if ($v == null) {
  2862. $this->setAPIResponse('error', '[' . $k . '] cannot be empty', 422);
  2863. return false;
  2864. }
  2865. }
  2866. try {
  2867. $connection = new Connection($config);
  2868. $testConnection = $connection->isConnected();
  2869. if ($testConnection) {
  2870. $this->setResponse(200, 'Database connection successful');
  2871. return true;
  2872. } else {
  2873. $this->setResponse(409, 'Database connection unsuccessful');
  2874. return false;
  2875. }
  2876. } catch (Dibi\Exception $e) {
  2877. $this->setResponse(500, $e->getMessage());
  2878. return false;
  2879. }
  2880. }
  2881. public function createNewDB($dbName, $migration = false)
  2882. {
  2883. if ($this->config['driver'] == 'mysqli') {
  2884. $config = [
  2885. 'driver' => 'mysqli',
  2886. 'host' => $this->config['dbHost'],
  2887. 'username' => $this->config['dbUsername'],
  2888. 'password' => $this->decrypt($this->config['dbPassword']),
  2889. 'options' => [
  2890. MYSQLI_OPT_CONNECT_TIMEOUT => 60,
  2891. ],
  2892. 'flags' => MYSQLI_CLIENT_COMPRESS,
  2893. ];
  2894. if ($migration) {
  2895. try {
  2896. $this->otherDb = new Connection($config);
  2897. } catch (Dibi\Exception $e) {
  2898. $this->otherDb = null;
  2899. }
  2900. } else {
  2901. try {
  2902. $this->db = new Connection($config);
  2903. } catch (Dibi\Exception $e) {
  2904. $this->db = null;
  2905. }
  2906. }
  2907. if ($dbName == 'tempMigration') {
  2908. $response = [
  2909. array(
  2910. 'function' => 'query',
  2911. 'query' => [
  2912. 'DROP DATABASE IF EXISTS tempMigration'
  2913. ]
  2914. ),
  2915. ];
  2916. $drop = $this->processQueries($response, $migration);
  2917. }
  2918. $response = [
  2919. array(
  2920. 'function' => 'query',
  2921. 'query' => ['CREATE DATABASE IF NOT EXISTS %n',
  2922. $dbName
  2923. ]
  2924. )
  2925. ];
  2926. $results = $this->processQueries($response, $migration);
  2927. if ($results) {
  2928. if ($migration) {
  2929. $this->connectOtherDB();
  2930. } else {
  2931. $this->connectDB();
  2932. }
  2933. return true;
  2934. } else {
  2935. return false;
  2936. }
  2937. } elseif ($this->config['driver'] == 'postgre') {
  2938. $config = [
  2939. 'driver' => 'postgre',
  2940. 'username' => $this->config['dbUsername'],
  2941. 'password' => $this->decrypt($this->config['dbPassword']),
  2942. 'persistent' => true,
  2943. ];
  2944. $host = $this->qualifyURL($this->config['dbHost'], true);
  2945. if ($host['port']) {
  2946. $config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
  2947. }
  2948. if ($host['host']) {
  2949. $config = array_merge($config, ['host' => $host['host']]);
  2950. }
  2951. if (!$host['host'] && $host['path']) {
  2952. $config = array_merge($config, ['host' => $host['path']]);
  2953. }
  2954. try {
  2955. $this->db = new Connection($config);
  2956. } catch (Dibi\Exception $e) {
  2957. $this->db = null;
  2958. }
  2959. $response = [
  2960. array(
  2961. 'function' => 'query',
  2962. 'query' => ['CREATE DATABASE %n',
  2963. $dbName
  2964. ]
  2965. )
  2966. ];
  2967. $results = $this->processQueries($response, $migration);
  2968. if ($results) {
  2969. $this->connectDB();
  2970. return true;
  2971. } else {
  2972. return false;
  2973. }
  2974. } else {
  2975. return true;
  2976. }
  2977. }
  2978. public function getDefaultTablesFormatted()
  2979. {
  2980. $list = [];
  2981. $tables = $this->defaultTables();
  2982. foreach ($tables as $table) {
  2983. $string = trim($table['query']);
  2984. preg_match('/CREATE TABLE `(.*?)`/', $string, $output_array);
  2985. if (count($output_array) > 1) {
  2986. $list[] = $output_array[1];
  2987. }
  2988. }
  2989. return $list;
  2990. }
  2991. public function defaultTables()
  2992. {
  2993. return [
  2994. array(
  2995. 'function' => 'query',
  2996. 'query' => '
  2997. CREATE TABLE `users` (
  2998. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  2999. `username` TEXT UNIQUE,
  3000. `password` TEXT,
  3001. `email` TEXT,
  3002. `plex_token` TEXT,
  3003. `group` TEXT,
  3004. `group_id` INTEGER,
  3005. `locked` INTEGER,
  3006. `image` TEXT,
  3007. `register_date` DATETIME,
  3008. `auth_service` TEXT DEFAULT \'internal\'
  3009. );
  3010. '
  3011. ),
  3012. array(
  3013. 'function' => 'query',
  3014. 'query' => 'CREATE TABLE `chatroom` (
  3015. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3016. `username` TEXT,
  3017. `gravatar` TEXT,
  3018. `uid` TEXT,
  3019. `date` DATETIME,
  3020. `ip` TEXT,
  3021. `message` TEXT
  3022. );'
  3023. ),
  3024. array(
  3025. 'function' => 'query',
  3026. 'query' => 'CREATE TABLE `tokens` (
  3027. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3028. `token` TEXT UNIQUE,
  3029. `user_id` INTEGER,
  3030. `browser` TEXT,
  3031. `ip` TEXT,
  3032. `created` DATETIME,
  3033. `expires` DATETIME
  3034. );'
  3035. ),
  3036. array(
  3037. 'function' => 'query',
  3038. 'query' => 'CREATE TABLE `groups` (
  3039. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3040. `group` TEXT UNIQUE,
  3041. `group_id` INTEGER,
  3042. `image` TEXT,
  3043. `default` INTEGER
  3044. );'
  3045. ),
  3046. array(
  3047. 'function' => 'query',
  3048. 'query' => 'CREATE TABLE `categories` (
  3049. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3050. `order` INTEGER,
  3051. `category` TEXT UNIQUE,
  3052. `category_id` INTEGER,
  3053. `image` TEXT,
  3054. `default` INTEGER
  3055. );'
  3056. ),
  3057. array(
  3058. 'function' => 'query',
  3059. 'query' => 'CREATE TABLE `tabs` (
  3060. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3061. `order` INTEGER,
  3062. `category_id` INTEGER,
  3063. `name` TEXT,
  3064. `url` TEXT,
  3065. `url_local` TEXT,
  3066. `default` INTEGER,
  3067. `enabled` INTEGER,
  3068. `group_id` INTEGER,
  3069. `image` TEXT,
  3070. `type` INTEGER,
  3071. `splash` INTEGER,
  3072. `ping` INTEGER,
  3073. `ping_url` TEXT,
  3074. `timeout` INTEGER,
  3075. `timeout_ms` INTEGER,
  3076. `preload` INTEGER
  3077. );'
  3078. ),
  3079. array(
  3080. 'function' => 'query',
  3081. 'query' => 'CREATE TABLE `options` (
  3082. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3083. `name` TEXT UNIQUE,
  3084. `value` TEXT
  3085. );'
  3086. ),
  3087. array(
  3088. 'function' => 'query',
  3089. 'query' => 'CREATE TABLE `invites` (
  3090. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3091. `code` TEXT UNIQUE,
  3092. `date` DATETIME,
  3093. `email` TEXT,
  3094. `username` TEXT,
  3095. `dateused` TIMESTAMP,
  3096. `usedby` TEXT,
  3097. `ip` TEXT,
  3098. `valid` TEXT,
  3099. `type` TEXT,
  3100. `invitedby` TEXT
  3101. );'
  3102. ),
  3103. array(
  3104. 'function' => 'query',
  3105. 'query' => 'CREATE TABLE `BOOKMARK-categories` (
  3106. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3107. `order` INTEGER,
  3108. `category` TEXT UNIQUE,
  3109. `category_id` INTEGER,
  3110. `default` INTEGER
  3111. );'
  3112. ),
  3113. array(
  3114. 'function' => 'query',
  3115. 'query' => 'CREATE TABLE `BOOKMARK-tabs` (
  3116. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  3117. `order` INTEGER,
  3118. `category_id` INTEGER,
  3119. `name` TEXT,
  3120. `url` TEXT,
  3121. `enabled` INTEGER,
  3122. `group_id` INTEGER,
  3123. `image` TEXT,
  3124. `background_color` TEXT,
  3125. `text_color` TEXT
  3126. );'
  3127. )
  3128. ];
  3129. }
  3130. public function createDB($path, $migration = false)
  3131. {
  3132. if (!file_exists($path)) {
  3133. mkdir($path, 0777, true);
  3134. }
  3135. $tables = $this->defaultTables();
  3136. return $this->processQueries($tables, $migration);
  3137. }
  3138. public function createFirstAdmin($username, $password, $email)
  3139. {
  3140. $userInfo = [
  3141. 'username' => $username,
  3142. 'password' => password_hash($password, PASSWORD_BCRYPT),
  3143. 'email' => $email,
  3144. 'group' => 'Admin',
  3145. 'group_id' => 0,
  3146. 'image' => $this->gravatar($email),
  3147. 'register_date' => gmdate('Y-m-d H:i:s'),
  3148. ];
  3149. $groupInfo0 = [
  3150. 'group' => 'Admin',
  3151. 'group_id' => 0,
  3152. 'default' => 0,
  3153. 'image' => 'plugins/images/groups/admin.png',
  3154. ];
  3155. $groupInfo1 = [
  3156. 'group' => 'Co-Admin',
  3157. 'group_id' => 1,
  3158. 'default' => 0,
  3159. 'image' => 'plugins/images/groups/coadmin.png',
  3160. ];
  3161. $groupInfo2 = [
  3162. 'group' => 'Super User',
  3163. 'group_id' => 2,
  3164. 'default' => 0,
  3165. 'image' => 'plugins/images/groups/superuser.png',
  3166. ];
  3167. $groupInfo3 = [
  3168. 'group' => 'Power User',
  3169. 'group_id' => 3,
  3170. 'default' => 0,
  3171. 'image' => 'plugins/images/groups/poweruser.png',
  3172. ];
  3173. $groupInfo4 = [
  3174. 'group' => 'User',
  3175. 'group_id' => 4,
  3176. 'default' => 1,
  3177. 'image' => 'plugins/images/groups/user.png',
  3178. ];
  3179. $groupInfoGuest = [
  3180. 'group' => 'Guest',
  3181. 'group_id' => 999,
  3182. 'default' => 0,
  3183. 'image' => 'plugins/images/groups/guest.png',
  3184. ];
  3185. $settingsInfo = [
  3186. 'order' => 1,
  3187. 'category_id' => 0,
  3188. 'name' => 'Settings',
  3189. 'url' => 'api/v2/page/settings',
  3190. 'default' => 0,
  3191. 'enabled' => 1,
  3192. 'group_id' => 1,
  3193. 'image' => 'fontawesome::cog',
  3194. 'type' => 0
  3195. ];
  3196. $homepageInfo = [
  3197. 'order' => 2,
  3198. 'category_id' => 0,
  3199. 'name' => 'Homepage',
  3200. 'url' => 'api/v2/page/homepage',
  3201. 'default' => 0,
  3202. 'enabled' => 0,
  3203. 'group_id' => 4,
  3204. 'image' => 'fontawesome::home',
  3205. 'type' => 0
  3206. ];
  3207. $unsortedInfo = [
  3208. 'order' => 1,
  3209. 'category' => 'Unsorted',
  3210. 'category_id' => 0,
  3211. 'image' => 'fontawesome::question',
  3212. 'default' => 1
  3213. ];
  3214. $response = [
  3215. array(
  3216. 'function' => 'query',
  3217. 'query' => array(
  3218. 'INSERT INTO [users]',
  3219. $userInfo
  3220. )
  3221. ),
  3222. array(
  3223. 'function' => 'query',
  3224. 'query' => array(
  3225. 'INSERT INTO [groups]',
  3226. $groupInfo0
  3227. )
  3228. ),
  3229. array(
  3230. 'function' => 'query',
  3231. 'query' => array(
  3232. 'INSERT INTO [groups]',
  3233. $groupInfo1
  3234. )
  3235. ),
  3236. array(
  3237. 'function' => 'query',
  3238. 'query' => array(
  3239. 'INSERT INTO [groups]',
  3240. $groupInfo2
  3241. )
  3242. ),
  3243. array(
  3244. 'function' => 'query',
  3245. 'query' => array(
  3246. 'INSERT INTO [groups]',
  3247. $groupInfo3
  3248. )
  3249. ),
  3250. array(
  3251. 'function' => 'query',
  3252. 'query' => array(
  3253. 'INSERT INTO [groups]',
  3254. $groupInfo4
  3255. )
  3256. ),
  3257. array(
  3258. 'function' => 'query',
  3259. 'query' => array(
  3260. 'INSERT INTO [groups]',
  3261. $groupInfoGuest
  3262. )
  3263. ),
  3264. array(
  3265. 'function' => 'query',
  3266. 'query' => array(
  3267. 'INSERT INTO [tabs]',
  3268. $settingsInfo
  3269. )
  3270. ),
  3271. array(
  3272. 'function' => 'query',
  3273. 'query' => array(
  3274. 'INSERT INTO [tabs]',
  3275. $homepageInfo
  3276. )
  3277. ),
  3278. array(
  3279. 'function' => 'query',
  3280. 'query' => array(
  3281. 'INSERT INTO [categories]',
  3282. $unsortedInfo
  3283. )
  3284. ),
  3285. ];
  3286. return $this->processQueries($response);
  3287. }
  3288. public function getUserByUsernameAndEmail($username, $email)
  3289. {
  3290. $response = [
  3291. array(
  3292. 'function' => 'fetch',
  3293. 'query' => array(
  3294. 'SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',
  3295. [$username],
  3296. [$email]
  3297. )
  3298. ),
  3299. ];
  3300. return $this->processQueries($response);
  3301. }
  3302. public function createToken($username, $email, $days = 1)
  3303. {
  3304. $this->setLoggerChannel('Authentication', $username);
  3305. $this->logger->debug('Starting token creation function');
  3306. $days = ($days > 365) ? 365 : $days;
  3307. //Quick get user ID
  3308. $result = $this->getUserByUsernameAndEmail($username, $email);
  3309. // Create JWT
  3310. // Set key
  3311. // SHA256 Encryption
  3312. $signer = new Lcobucci\JWT\Signer\Hmac\Sha256();
  3313. // Start Builder
  3314. $jwttoken = (new Lcobucci\JWT\Builder())->issuedBy('Organizr')// Configures the issuer (iss claim)
  3315. ->permittedFor('Organizr')// Configures the audience (aud claim)
  3316. ->identifiedBy('4f1g23a12aa', true)// Configures the id (jti claim), replicating as a header item
  3317. ->issuedAt(time())// Configures the time that the token was issue (iat claim)
  3318. ->expiresAt(time() + (86400 * $days))// Configures the expiration time of the token (exp claim)
  3319. ->withClaim('name', $result['username'])// Configures a new claim, called "name"
  3320. ->withClaim('group', $result['group'])// Configures a new claim, called "group"
  3321. ->withClaim('groupID', $result['group_id'])// Configures a new claim, called "groupID"
  3322. ->withClaim('email', $result['email'])// Configures a new claim, called "email"
  3323. ->withClaim('image', $result['image'])// Configures a new claim, called "image"
  3324. ->withClaim('userID', $result['id'])// Configures a new claim, called "image"
  3325. ->sign($signer, $this->config['organizrHash'])// creates a signature using "testing" as key
  3326. ->getToken(); // Retrieves the generated token
  3327. $jwttoken->getHeaders(); // Retrieves the token headers
  3328. $jwttoken->getClaims(); // Retrieves the token claims
  3329. $this->coookie('set', $this->cookieName, $jwttoken, $days);
  3330. // Add token to DB
  3331. $addToken = [
  3332. 'token' => (string)$jwttoken,
  3333. 'user_id' => $result['id'],
  3334. 'created' => gmdate('Y-m-d H:i:s'),
  3335. 'browser' => $_SERVER ['HTTP_USER_AGENT'] ?? null,
  3336. 'ip' => $this->userIP(),
  3337. 'expires' => gmdate('Y-m-d H:i:s', time() + (86400 * $days))
  3338. ];
  3339. $response = [
  3340. array(
  3341. 'function' => 'query',
  3342. 'query' => array(
  3343. 'INSERT INTO [tokens]',
  3344. $addToken
  3345. )
  3346. ),
  3347. ];
  3348. $token = $this->processQueries($response);
  3349. if ($jwttoken) {
  3350. $this->logger->debug('Token has been created');
  3351. } else {
  3352. $this->logger->warning('Token creation error');
  3353. }
  3354. $this->logger->debug('Token creation function has finished');
  3355. return $jwttoken;
  3356. }
  3357. public function login($array)
  3358. {
  3359. // Grab username, Password & other optional items from api call
  3360. $username = $array['username'] ?? null;
  3361. $password = $array['password'] ?? null;
  3362. $oAuth = $array['oAuth'] ?? null;
  3363. $oAuthType = $array['oAuthType'] ?? null;
  3364. $remember = $array['remember'] ?? null;
  3365. $tfaCode = $array['tfaCode'] ?? null;
  3366. $loginAttempts = $array['loginAttempts'] ?? null;
  3367. $output = $array['output'] ?? null;
  3368. $username = (strpos($this->config['authBackend'], 'emby') !== false) ? $username : strtolower($username);
  3369. $days = (isset($remember)) ? $this->config['rememberMeDays'] : 1;
  3370. // Set logger channel
  3371. $this->setLoggerChannel('Authentication', $username);
  3372. $this->logger->debug('Starting login function');
  3373. // Set other variables
  3374. $function = 'plugin_auth_' . $this->config['authBackend'];
  3375. $authSuccess = false;
  3376. $authProxy = false;
  3377. $addEmailToAuthProxy = true;
  3378. // Check Login attempts and kill if over limit
  3379. if ($loginAttempts > $this->config['loginAttempts'] || isset($_COOKIE['lockout'])) {
  3380. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3381. $this->logger->warning('User is locked out');
  3382. $this->setAPIResponse('error', 'User is locked out', 403);
  3383. return false;
  3384. }
  3385. // Check if Auth Proxy is enabled
  3386. if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
  3387. if (isset($this->getallheaders()[$this->config['authProxyHeaderName']]) || isset($this->getallheaders()[$this->config['authProxyHeaderNameEmail']])) {
  3388. $usernameHeader = $this->getallheaders()[$this->config['authProxyHeaderName']] ?? null;
  3389. $emailHeader = $this->getallheaders()[$this->config['authProxyHeaderNameEmail']] ?? null;
  3390. $headerForLogin = $usernameHeader ?: ($emailHeader ?: null);
  3391. $this->setLoggerChannel('Authentication', $headerForLogin);
  3392. $this->logger->debug('Starting Auth Proxy verification');
  3393. $whitelistRange = $this->analyzeIP($this->config['authProxyWhitelist']);
  3394. $authProxy = $this->authProxyRangeCheck($whitelistRange['from'], $whitelistRange['to']);
  3395. $username = ($authProxy) ? $headerForLogin : $username;
  3396. $password = ($password == null) ? $this->random_ascii_string(10) : $password;
  3397. $addEmailToAuthProxy = ($authProxy && $emailHeader) ? ['email' => $emailHeader] : true;
  3398. if ($authProxy) {
  3399. $this->logger->info('User has been verified using Auth Proxy');
  3400. } else {
  3401. $this->logger->warning('User has failed verification using Auth Proxy');
  3402. }
  3403. }
  3404. }
  3405. // Check if Login method was an oAuth login
  3406. if (!$oAuth) {
  3407. $result = $this->getUserByUsernameAndEmail($username, $username);
  3408. $result['password'] = $result['password'] ?? '';
  3409. // Switch AuthType - internal - external - both
  3410. switch ($this->config['authType']) {
  3411. case 'external':
  3412. if (method_exists($this, $function)) {
  3413. $authSuccess = $this->$function($username, $password);
  3414. }
  3415. break;
  3416. /** @noinspection PhpMissingBreakStatementInspection */
  3417. case 'both':
  3418. if (method_exists($this, $function)) {
  3419. $authSuccess = $this->$function($username, $password);
  3420. }
  3421. // no break
  3422. default: // Internal
  3423. if (!$authSuccess) {
  3424. // perform the internal authentication step
  3425. if (password_verify($password, $result['password'])) {
  3426. $this->logger->debug('User password has been verified');
  3427. $authSuccess = true;
  3428. }
  3429. }
  3430. }
  3431. $authSuccess = ($authProxy) ? $addEmailToAuthProxy : $authSuccess;
  3432. } else {
  3433. // Has oAuth Token!
  3434. switch ($oAuthType) {
  3435. case 'plex':
  3436. if ($this->config['plexoAuth']) {
  3437. $this->logger->debug('Starting Plex oAuth verification');
  3438. $tokenInfo = $this->checkPlexToken($oAuth);
  3439. if ($tokenInfo) {
  3440. $authSuccess = [
  3441. 'username' => $tokenInfo['user']['username'],
  3442. 'email' => $tokenInfo['user']['email'],
  3443. 'image' => $tokenInfo['user']['thumb'],
  3444. 'token' => $tokenInfo['user']['authToken'],
  3445. 'oauth' => 'plex'
  3446. ];
  3447. $this->logger->debug('User\'s Plex Token has been verified');
  3448. $this->coookie('set', 'oAuth', 'true', $this->config['rememberMeDays']);
  3449. $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;
  3450. } else {
  3451. $this->logger->warning('User\'s Plex Token has failed verification');
  3452. }
  3453. } else {
  3454. $this->logger->debug('Plex oAuth is not setup');
  3455. $this->setAPIResponse('error', 'Plex oAuth is not setup', 422);
  3456. return false;
  3457. }
  3458. break;
  3459. default:
  3460. return ($output) ? 'No oAuthType defined' : 'error';
  3461. }
  3462. $result = ($authSuccess) ? $this->getUserByUsernameAndEmail($authSuccess['username'], $authSuccess['email']) : '';
  3463. }
  3464. if ($authSuccess) {
  3465. // Make sure user exists in database
  3466. $userExists = false;
  3467. $passwordMatches = $oAuth || $authProxy;
  3468. $token = (is_array($authSuccess) && isset($authSuccess['token']) ? $authSuccess['token'] : '');
  3469. if (isset($result['username'])) {
  3470. $userExists = true;
  3471. $username = $result['username'];
  3472. if ($passwordMatches == false) {
  3473. $passwordMatches = password_verify($password, $result['password']);
  3474. }
  3475. }
  3476. if ($userExists) {
  3477. //does org password need to be updated
  3478. if (!$passwordMatches) {
  3479. $this->updateUserPassword($password, $result['id']);
  3480. $this->setLoggerChannel('Authentication', $username);
  3481. $this->logger->info('User Password updated from backend');
  3482. }
  3483. if ($token !== '') {
  3484. if ($token !== $result['plex_token']) {
  3485. $this->updateUserPlexToken($token, $result['id']);
  3486. $this->setLoggerChannel('Authentication', $username);
  3487. $this->logger->info('User Plex Token updated from backend');
  3488. }
  3489. }
  3490. // 2FA might go here
  3491. if ($result['auth_service'] !== 'internal' && strpos($result['auth_service'], '::') !== false) {
  3492. $tfaProceed = true;
  3493. // Add check for local or not
  3494. if ($this->config['ignoreTFALocal'] !== false) {
  3495. $tfaProceed = !$this->isLocal();
  3496. }
  3497. // Is Plex Oauth?
  3498. if ($this->config['ignoreTFAIfPlexOAuth'] !== false) {
  3499. if (isset($authSuccess['oauth'])) {
  3500. if ($authSuccess['oauth'] == 'plex') {
  3501. $tfaProceed = false;
  3502. }
  3503. }
  3504. }
  3505. if ($tfaProceed) {
  3506. $this->setLoggerChannel('Authentication', $username);
  3507. $this->logger->debug('Starting 2FA verification');
  3508. $TFA = explode('::', $result['auth_service']);
  3509. // Is code with login info?
  3510. if ($tfaCode == '') {
  3511. $this->logger->debug('Sending 2FA response to login UI');
  3512. $this->setAPIResponse('warning', '2FA Code Needed', 422);
  3513. return false;
  3514. } else {
  3515. if (!$this->verify2FA($TFA[1], $tfaCode, $TFA[0])) {
  3516. $this->logger->warning('Incorrect 2FA');
  3517. $this->setAPIResponse('error', 'Wrong 2FA', 422);
  3518. return false;
  3519. } else {
  3520. $this->logger->info('2FA verification passed');
  3521. }
  3522. }
  3523. }
  3524. }
  3525. // End 2FA
  3526. // authentication passed - 1) mark active and update token
  3527. $createToken = $this->createToken($result['username'], $result['email'], $days);
  3528. if ($createToken) {
  3529. $this->logger->info('User has logged in');
  3530. $ssoUserObject = ($token !== '') ? $authSuccess : $result;
  3531. $this->ssoCheck($ssoUserObject, $password, $token); //need to work on this
  3532. return ($output) ? array('name' => $this->cookieName, 'token' => (string)$createToken) : true;
  3533. } else {
  3534. $this->setAPIResponse('error', 'Token creation error', 500);
  3535. return false;
  3536. }
  3537. } else {
  3538. // Create User
  3539. $this->setLoggerChannel('Authentication', (is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username));
  3540. $this->logger->debug('Starting Registration function');
  3541. return $this->authRegister((is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username), $password, (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $token);
  3542. }
  3543. } else {
  3544. // authentication failed
  3545. $this->setLoggerChannel('Authentication', $username);
  3546. $this->logger->warning('Wrong Password');
  3547. if ($loginAttempts >= $this->config['loginAttempts']) {
  3548. $this->logger->warning('User exceeded maximum login attempts');
  3549. $this->coookieSeconds('set', 'lockout', $this->config['loginLockout'], $this->config['loginLockout']);
  3550. $this->setAPIResponse('error', 'User is locked out', 403);
  3551. return false;
  3552. } else {
  3553. $this->logger->debug('User has not exceeded maximum login attempts');
  3554. $this->setAPIResponse('error', 'User credentials incorrect', 401);
  3555. return false;
  3556. }
  3557. }
  3558. }
  3559. public function logout()
  3560. {
  3561. $this->setLoggerChannel('Authentication');
  3562. $this->logger->debug('Starting log out process');
  3563. $this->logger->info('User has logged out');
  3564. $this->coookie('delete', $this->cookieName);
  3565. $this->coookie('delete', 'mpt');
  3566. $this->coookie('delete', 'Auth');
  3567. $this->coookie('delete', 'oAuth');
  3568. $this->coookie('delete', 'connect.sid');
  3569. $this->coookie('delete', 'petio_jwt');
  3570. $this->clearTautulliTokens();
  3571. $this->clearJellyfinTokens();
  3572. $this->revokeTokenCurrentUser($this->user['token']);
  3573. $this->clearKomgaToken();
  3574. $this->refreshDeviceUUID();
  3575. $this->logger->debug('Log out process has finished');
  3576. $this->user = null;
  3577. return true;
  3578. }
  3579. public function recover($array)
  3580. {
  3581. $email = $array['email'] ?? null;
  3582. if (!$email) {
  3583. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3584. return false;
  3585. }
  3586. $newPassword = $this->randString(10);
  3587. $isUser = $this->getUserByEmail($email);
  3588. if ($isUser) {
  3589. $this->updateUserPassword($newPassword, $isUser['id']);
  3590. $this->setAPIResponse('success', 'User password has been reset', 200);
  3591. $this->setLoggerChannel('User Management');
  3592. $this->logger->info('User Management Function - User: ' . $isUser['username'] . '\'s password was reset');
  3593. if ($this->config['PHPMAILER-enabled']) {
  3594. $PhpMailer = new PhpMailer();
  3595. $emailTemplate = array(
  3596. 'type' => 'reset',
  3597. 'body' => $this->config['PHPMAILER-emailTemplateReset'],
  3598. 'subject' => $this->config['PHPMAILER-emailTemplateResetSubject'],
  3599. 'user' => $isUser['username'],
  3600. 'password' => $newPassword,
  3601. 'inviteCode' => null,
  3602. );
  3603. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3604. $sendEmail = array(
  3605. 'to' => $email,
  3606. 'user' => $isUser['username'],
  3607. 'subject' => $emailTemplate['subject'],
  3608. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3609. );
  3610. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3611. $this->setAPIResponse('success', 'User password has been reset and email has been sent', 200);
  3612. }
  3613. return true;
  3614. } else {
  3615. $this->setAPIResponse('error', 'User not found', 404);
  3616. return false;
  3617. }
  3618. }
  3619. public function register($array)
  3620. {
  3621. $email = $array['email'] ?? null;
  3622. $username = $array['username'] ?? null;
  3623. $password = $array['password'] ?? null;
  3624. $registrationPassword = $array['registrationPassword'] ?? null;
  3625. if (!$email) {
  3626. $this->setAPIResponse('error', 'Email was not supplied', 422);
  3627. return false;
  3628. }
  3629. if (!$username) {
  3630. $this->setAPIResponse('error', 'Username was not supplied', 422);
  3631. return false;
  3632. }
  3633. if (!$password) {
  3634. $this->setAPIResponse('error', 'Password was not supplied', 422);
  3635. return false;
  3636. }
  3637. if (!$registrationPassword) {
  3638. $this->setAPIResponse('error', 'Registration Password was not supplied', 422);
  3639. return false;
  3640. }
  3641. $this->setLoggerChannel('User Registration');
  3642. if ($registrationPassword == $this->decrypt($this->config['registrationPassword'])) {
  3643. $this->logger->debug('Registration Password Verified');
  3644. if ($this->createUser($username, $password, $email)) {
  3645. $this->logger->info('A User has registered');
  3646. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3647. $this->setLoggerChannel('Authentication', $username);
  3648. $this->logger->info('User has logged in');
  3649. return true;
  3650. }
  3651. } else {
  3652. return false;
  3653. }
  3654. } else {
  3655. $this->logger->warning('Wrong Password');
  3656. $this->setAPIResponse('error', 'Registration Password was incorrect', 401);
  3657. return false;
  3658. }
  3659. }
  3660. public function authRegister($username, $password, $email, $token = null)
  3661. {
  3662. $this->setLoggerChannel('Authentication', $username);
  3663. if ($this->config['authBackend'] !== '') {
  3664. $this->ombiImport($this->config['authBackend']);
  3665. }
  3666. $this->ssoCheck($username, $password, $token);
  3667. if ($token && (!$password || $password == '')) {
  3668. $password = $this->random_ascii_string(10);
  3669. }
  3670. if ($this->createUser($username, $password, $email)) {
  3671. $this->logger->info('A User has registered');
  3672. if ($this->config['PHPMAILER-enabled'] && $email !== '') {
  3673. $PhpMailer = new PhpMailer();
  3674. $emailTemplate = array(
  3675. 'type' => 'registration',
  3676. 'body' => $this->config['PHPMAILER-emailTemplateRegisterUser'],
  3677. 'subject' => $this->config['PHPMAILER-emailTemplateRegisterUserSubject'],
  3678. 'user' => $username,
  3679. 'password' => null,
  3680. 'inviteCode' => null,
  3681. );
  3682. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  3683. $sendEmail = array(
  3684. 'to' => $email,
  3685. 'user' => $username,
  3686. 'subject' => $emailTemplate['subject'],
  3687. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  3688. );
  3689. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  3690. }
  3691. if ($this->createToken($username, $email, $this->config['rememberMeDays'])) {
  3692. $this->logger->info('User has logged in');
  3693. return true;
  3694. } else {
  3695. return false;
  3696. }
  3697. } else {
  3698. $this->logger->warning('Registration error occurred');
  3699. return false;
  3700. }
  3701. }
  3702. public function revokeTokenCurrentUser($token = null)
  3703. {
  3704. if ($token) {
  3705. $response = [
  3706. array(
  3707. 'function' => 'query',
  3708. 'query' => array(
  3709. 'DELETE FROM tokens WHERE token = ?',
  3710. [$token]
  3711. )
  3712. ),
  3713. ];
  3714. } else {
  3715. $response = [
  3716. array(
  3717. 'function' => 'query',
  3718. 'query' => array(
  3719. 'DELETE FROM tokens WHERE user_id = ?',
  3720. [$this->user['userID']]
  3721. )
  3722. ),
  3723. ];
  3724. }
  3725. return $this->processQueries($response);
  3726. }
  3727. public function revokeToken($token = null)
  3728. {
  3729. if (!$token) {
  3730. $this->setAPIResponse('error', 'Token was not supplied', 422);
  3731. return false;
  3732. }
  3733. $response = [
  3734. array(
  3735. 'function' => 'query',
  3736. 'query' => array(
  3737. 'DELETE FROM tokens WHERE token = ?',
  3738. [$token]
  3739. )
  3740. ),
  3741. ];
  3742. $this->setAPIResponse('success', 'Token revoked', 204);
  3743. return $this->processQueries($response);
  3744. }
  3745. public function revokeTokenByIdCurrentUser($id = null)
  3746. {
  3747. if (!$id) {
  3748. $this->setAPIResponse('error', 'Id was not supplied', 422);
  3749. return false;
  3750. }
  3751. $response = [
  3752. array(
  3753. 'function' => 'query',
  3754. 'query' => array(
  3755. 'DELETE FROM tokens WHERE id = ? AND user_id = ?',
  3756. $id,
  3757. $this->user['userID']
  3758. )
  3759. ),
  3760. ];
  3761. $this->setAPIResponse('success', 'Token revoked', 204);
  3762. return $this->processQueries($response);
  3763. }
  3764. public function updateUserPassword($password, $id)
  3765. {
  3766. $response = [
  3767. array(
  3768. 'function' => 'query',
  3769. 'query' => array(
  3770. 'UPDATE users SET',
  3771. ['password' => password_hash($password, PASSWORD_BCRYPT)],
  3772. 'WHERE id = ?',
  3773. $id
  3774. )
  3775. ),
  3776. ];
  3777. return $this->processQueries($response);
  3778. }
  3779. public function updateUserPlexToken($token, $id)
  3780. {
  3781. $response = [
  3782. array(
  3783. 'function' => 'query',
  3784. 'query' => array(
  3785. 'UPDATE users SET',
  3786. ['plex_token' => $token],
  3787. 'WHERE id = ?',
  3788. $id
  3789. )
  3790. ),
  3791. ];
  3792. return $this->processQueries($response);
  3793. }
  3794. public function getUserTabsAndCategories($type = null)
  3795. {
  3796. if (!$this->hasDB()) {
  3797. return false;
  3798. }
  3799. $sort = ($this->config['unsortedTabs'] == 'top') ? 'DESC' : 'ASC';
  3800. $response = [
  3801. array(
  3802. 'function' => 'fetchAll',
  3803. 'query' => array(
  3804. 'SELECT * FROM tabs WHERE `group_id` >= ? AND `enabled` = 1 ORDER BY `order` ' . $sort,
  3805. $this->user['groupID']
  3806. ),
  3807. 'key' => 'tabs'
  3808. ),
  3809. array(
  3810. 'function' => 'fetchAll',
  3811. 'query' => array(
  3812. 'SELECT * FROM categories ORDER BY `order` ASC',
  3813. ),
  3814. 'key' => 'categories'
  3815. ),
  3816. ];
  3817. $queries = $this->processQueries($response);
  3818. $this->applyTabVariables($queries['tabs']);
  3819. $all['tabs'] = $queries['tabs'];
  3820. foreach ($queries['tabs'] as $k => $v) {
  3821. $v['url_local'] = $v['type'] !== 0 ? $this->checkTabURL($v['url_local']) : $v['url_local'];
  3822. $v['url'] = $v['type'] !== 0 ? $this->checkTabURL($v['url']) : $v['url'];
  3823. $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'];
  3824. }
  3825. $count = array_map(function ($element) {
  3826. return $element['category_id'];
  3827. }, $queries['tabs']);
  3828. $count = (array_count_values($count));
  3829. foreach ($queries['categories'] as $k => $v) {
  3830. $v['count'] = $count[$v['category_id']] ?? 0;
  3831. }
  3832. $all['categories'] = $queries['categories'];
  3833. switch ($type) {
  3834. case 'categories':
  3835. return $all['categories'];
  3836. case 'tabs':
  3837. return $all['tabs'];
  3838. default:
  3839. return $all;
  3840. }
  3841. }
  3842. public function checkTabURL($url = null)
  3843. {
  3844. return $url !== '' && $url !== null & $url !== 'null' ? $this->qualifyURL($url, false, true) : '';
  3845. }
  3846. public function refreshList()
  3847. {
  3848. $searchTerm = "Refresh";
  3849. return array_filter($this->config, function ($k) use ($searchTerm) {
  3850. return stripos($k, $searchTerm) !== false;
  3851. }, ARRAY_FILTER_USE_KEY);
  3852. }
  3853. public function homepageOrderList()
  3854. {
  3855. $searchTerm = "homepageOrder";
  3856. $order = array_filter($this->config, function ($k) use ($searchTerm) {
  3857. return stripos($k, $searchTerm) !== false;
  3858. }, ARRAY_FILTER_USE_KEY);
  3859. asort($order);
  3860. return $order;
  3861. }
  3862. public function tautulliList()
  3863. {
  3864. $searchTerm = "tautulli_token";
  3865. return array_filter($this->config, function ($k) use ($searchTerm) {
  3866. return stripos($k, $searchTerm) !== false;
  3867. }, ARRAY_FILTER_USE_KEY);
  3868. }
  3869. public function checkPlexAdminFilled()
  3870. {
  3871. if ($this->config['plexAdmin'] == '') {
  3872. return false;
  3873. } else {
  3874. if ((strpos($this->config['plexAdmin'], '@') !== false)) {
  3875. return 'email';
  3876. } else {
  3877. return 'username';
  3878. }
  3879. }
  3880. }
  3881. public function organizrSpecialSettings()
  3882. {
  3883. // js activeInfo
  3884. return [
  3885. 'homepage' => [
  3886. 'refresh' => $this->refreshList(),
  3887. 'order' => $this->homepageOrderList(),
  3888. 'search' => [
  3889. 'enabled' => $this->qualifyRequest($this->config['mediaSearchAuth']) && $this->config['mediaSearch'] == true && $this->config['plexToken'],
  3890. 'type' => $this->config['mediaSearchType'],
  3891. ],
  3892. 'requests' => [
  3893. 'service' => $this->config['defaultRequestService'],
  3894. ],
  3895. 'ombi' => [
  3896. 'enabled' => $this->qualifyRequest($this->config['homepageOmbiAuth']) && $this->qualifyRequest($this->config['homepageOmbiRequestAuth']) && $this->config['homepageOmbiEnabled'] == true && $this->config['ssoOmbi'] && isset($_COOKIE['Auth']),
  3897. 'authView' => $this->qualifyRequest($this->config['homepageOmbiAuth']),
  3898. 'authRequest' => $this->qualifyRequest($this->config['homepageOmbiRequestAuth']),
  3899. 'sso' => (bool)$this->config['ssoOmbi'],
  3900. 'cookie' => isset($_COOKIE['Auth']),
  3901. 'alias' => (bool)$this->config['ombiAlias'],
  3902. 'ombiDefaultFilterAvailable' => (bool)$this->config['ombiDefaultFilterAvailable'],
  3903. 'ombiDefaultFilterUnavailable' => (bool)$this->config['ombiDefaultFilterUnavailable'],
  3904. 'ombiDefaultFilterApproved' => (bool)$this->config['ombiDefaultFilterApproved'],
  3905. 'ombiDefaultFilterUnapproved' => (bool)$this->config['ombiDefaultFilterUnapproved'],
  3906. 'ombiDefaultFilterDenied' => (bool)$this->config['ombiDefaultFilterDenied']
  3907. ],
  3908. 'overseerr' => [
  3909. 'enabled' => $this->qualifyRequest($this->config['homepageOverseerrAuth']) && $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']) && $this->config['homepageOverseerrEnabled'] == true && $this->config['ssoOverseerr'] && isset($_COOKIE['connect_sid']),
  3910. 'authView' => $this->qualifyRequest($this->config['homepageOverseerrAuth']),
  3911. 'authRequest' => $this->qualifyRequest($this->config['homepageOverseerrRequestAuth']),
  3912. 'sso' => (bool)$this->config['ssoOverseerr'],
  3913. 'cookie' => isset($_COOKIE['connect_sid']),
  3914. 'userSelectTv' => (bool)$this->config['homepageOverseerrRequestAuth'] == 'user',
  3915. 'overseerrDefaultFilterAvailable' => (bool)$this->config['overseerrDefaultFilterAvailable'],
  3916. 'overseerrDefaultFilterUnavailable' => (bool)$this->config['overseerrDefaultFilterUnavailable'],
  3917. 'overseerrDefaultFilterApproved' => (bool)$this->config['overseerrDefaultFilterApproved'],
  3918. 'overseerrDefaultFilterUnapproved' => (bool)$this->config['overseerrDefaultFilterUnapproved'],
  3919. 'overseerrDefaultFilterDenied' => (bool)$this->config['overseerrDefaultFilterDenied']
  3920. ],
  3921. 'jackett' => [
  3922. 'homepageJackettBackholeDownload' => $this->config['homepageJackettBackholeDownload'] ? true : false
  3923. ],
  3924. 'options' => [
  3925. 'alternateHomepageHeaders' => $this->config['alternateHomepageHeaders'],
  3926. 'healthChecksTags' => $this->config['healthChecksTags'],
  3927. 'titles' => [
  3928. 'tautulli' => $this->config['tautulliHeader']
  3929. ]
  3930. ],
  3931. 'media' => [
  3932. 'jellyfin' => $this->config['homepageJellyfinInstead']
  3933. ]
  3934. ],
  3935. 'sso' => [
  3936. 'misc' => [
  3937. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  3938. 'rememberMe' => $this->config['rememberMe'],
  3939. 'rememberMeDays' => $this->config['rememberMeDays']
  3940. ],
  3941. 'plex' => [
  3942. 'enabled' => (bool)$this->config['ssoPlex'],
  3943. 'cookie' => isset($_COOKIE['mpt']),
  3944. 'machineID' => strlen($this->config['plexID']) == 40,
  3945. 'token' => $this->config['plexToken'] !== '',
  3946. 'plexAdmin' => $this->checkPlexAdminFilled(),
  3947. 'strict' => (bool)$this->config['plexStrictFriends'],
  3948. 'oAuthEnabled' => (bool)$this->config['plexoAuth'],
  3949. 'backend' => $this->config['authBackend'] == 'plex',
  3950. ],
  3951. 'tautulli' => [
  3952. 'enabled' => (bool)$this->config['ssoTautulli'],
  3953. 'cookie' => !empty($this->tautulliList()),
  3954. 'url' => ($this->config['tautulliURL'] !== '') ? $this->config['tautulliURL'] : false,
  3955. ],
  3956. 'overseerr' => [
  3957. 'enabled' => (bool)$this->config['ssoOverseerr'],
  3958. 'cookie' => isset($_COOKIE['connect.sid']),
  3959. 'url' => ($this->config['overseerrURL'] !== '') ? $this->config['overseerrURL'] : false,
  3960. 'api' => $this->config['overseerrToken'] !== '',
  3961. ],
  3962. 'petio' => [
  3963. 'enabled' => (bool)$this->config['ssoPetio'],
  3964. 'cookie' => isset($_COOKIE['petio_jwt']),
  3965. 'url' => ($this->config['petioURL'] !== '') ? $this->config['petioURL'] : false,
  3966. 'api' => $this->config['petioToken'] !== '',
  3967. ],
  3968. 'ombi' => [
  3969. 'enabled' => (bool)$this->config['ssoOmbi'],
  3970. 'cookie' => isset($_COOKIE['Auth']),
  3971. 'url' => ($this->config['ombiURL'] !== '') ? $this->config['ombiURL'] : false,
  3972. 'api' => $this->config['ombiToken'] !== '',
  3973. ],
  3974. 'jellyfin' => [
  3975. 'enabled' => (bool)$this->config['ssoJellyfin'],
  3976. 'url' => ($this->config['jellyfinURL'] !== '') ? $this->config['jellyfinURL'] : false,
  3977. 'ssoUrl' => ($this->config['jellyfinSSOURL'] !== '') ? $this->config['jellyfinSSOURL'] : false,
  3978. ],
  3979. 'komga' => [
  3980. 'enabled' => (bool)$this->config['ssoKomga'],
  3981. 'cookie' => isset($_COOKIE['komga_token']),
  3982. 'url' => ($this->config['komgaURL'] !== '') ? $this->config['komgaURL'] : false,
  3983. ]
  3984. ],
  3985. 'ping' => [
  3986. 'onlineSound' => $this->config['pingOnlineSound'],
  3987. 'offlineSound' => $this->config['pingOfflineSound'],
  3988. 'statusSounds' => $this->config['statusSounds'],
  3989. 'auth' => $this->config['pingAuth'],
  3990. 'authMessage' => $this->config['pingAuthMessage'],
  3991. 'authMs' => $this->config['pingAuthMs'],
  3992. 'ms' => $this->config['pingMs'],
  3993. 'adminRefresh' => $this->config['adminPingRefresh'],
  3994. 'everyoneRefresh' => $this->config['otherPingRefresh'],
  3995. ],
  3996. 'notifications' => [
  3997. 'backbone' => $this->config['notificationBackbone'],
  3998. 'position' => $this->config['notificationPosition']
  3999. ],
  4000. 'lockout' => [
  4001. 'enabled' => $this->config['lockoutSystem'],
  4002. 'timer' => $this->config['lockoutTimeout'],
  4003. 'minGroup' => $this->config['lockoutMinAuth'],
  4004. 'maxGroup' => $this->config['lockoutMaxAuth']
  4005. ],
  4006. 'user' => [
  4007. 'agent' => isset($_SERVER ['HTTP_USER_AGENT']) ? $_SERVER ['HTTP_USER_AGENT'] : null,
  4008. 'oAuthLogin' => isset($_COOKIE['oAuth']),
  4009. 'local' => $this->isLocal(),
  4010. 'ip' => $this->userIP()
  4011. ],
  4012. 'login' => [
  4013. 'rememberMe' => $this->config['rememberMe'],
  4014. 'rememberMeDays' => $this->config['rememberMeDays'],
  4015. 'wanDomain' => $this->config['wanDomain'],
  4016. 'localAddress' => $this->config['localAddress'],
  4017. 'enableLocalAddressForward' => $this->config['enableLocalAddressForward'],
  4018. ],
  4019. 'misc' => [
  4020. 'installedPlugins' => $this->qualifyRequest(1) ? $this->config['installedPlugins'] : '',
  4021. 'installedThemes' => $this->qualifyRequest(1) ? $this->config['installedThemes'] : '',
  4022. 'return' => $_SERVER['HTTP_REFERER'] ?? false,
  4023. 'authDebug' => $this->config['authDebug'],
  4024. 'minimalLoginScreen' => $this->config['minimalLoginScreen'],
  4025. 'unsortedTabs' => $this->config['unsortedTabs'],
  4026. 'authType' => $this->config['authType'],
  4027. 'authBackend' => $this->config['authBackend'],
  4028. 'newMessageSound' => (isset($this->config['CHAT-newMessageSound-include'])) ? $this->config['CHAT-newMessageSound-include'] : '',
  4029. 'uuid' => ($this->config['uuid']) ?? null,
  4030. 'docker' => $this->qualifyRequest(1) ? $this->docker : '',
  4031. 'githubCommit' => $this->qualifyRequest(1) ? $this->commit : '',
  4032. 'schema' => $this->qualifyRequest(1) ? $this->getSchema() : '',
  4033. 'debugArea' => $this->qualifyRequest($this->config['debugAreaAuth']),
  4034. 'debugErrors' => $this->config['debugErrors'],
  4035. 'sandbox' => $this->config['sandbox'],
  4036. 'expandCategoriesByDefault' => $this->config['expandCategoriesByDefault'],
  4037. 'autoCollapseCategories' => $this->config['autoCollapseCategories'],
  4038. 'autoExpandNavBar' => $this->config['autoExpandNavBar'],
  4039. 'sideMenuCollapsed' => $this->config['allowCollapsableSideMenu'] && $this->config['sideMenuCollapsed'],
  4040. 'collapseSideMenuOnClick' => $this->config['allowCollapsableSideMenu'] && $this->config['collapseSideMenuOnClick'],
  4041. 'authProxyOverrideLogout' => $this->config['authProxyOverrideLogout'],
  4042. 'authProxyLogoutURL' => $this->config['authProxyLogoutURL'],
  4043. ],
  4044. 'menuLink' => [
  4045. 'githubMenuLink' => $this->config['githubMenuLink'],
  4046. 'organizrSupportMenuLink' => $this->config['organizrSupportMenuLink'],
  4047. 'organizrDocsMenuLink' => $this->config['organizrDocsMenuLink'],
  4048. 'organizrSignoutMenuLink' => $this->config['organizrSignoutMenuLink'],
  4049. 'organizrFeatureRequestLink' => $this->config['organizrFeatureRequestLink']
  4050. ]
  4051. ];
  4052. }
  4053. public function checkLog($path)
  4054. {
  4055. if (file_exists($path)) {
  4056. if (filesize($path) > 500000) {
  4057. rename($path, $path . '[' . date('Y-m-d') . '].json');
  4058. return false;
  4059. }
  4060. return true;
  4061. } else {
  4062. return false;
  4063. }
  4064. }
  4065. public function writeLog($type = 'error', $message = null, $username = null)
  4066. {
  4067. $this->timeExecution = $this->timeExecution($this->timeExecution);
  4068. $message = $message . ' [Execution Time: ' . $this->formatSeconds($this->timeExecution) . ']';
  4069. $username = ($username) ? htmlspecialchars($username, ENT_QUOTES) : $this->user['username'] ?? 'SYSTEM';
  4070. if ($this->checkLog($this->organizrLog)) {
  4071. $getLog = str_replace("\r\ndate", "date", file_get_contents($this->organizrLog));
  4072. $gotLog = json_decode($getLog, true);
  4073. }
  4074. $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)));
  4075. $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $this->currentTime, 'type' => $type, 'username' => $username, 'ip' => $this->userIP(), 'message' => $message);
  4076. if (isset($gotLog)) {
  4077. array_push($gotLog["log_items"], $logEntry);
  4078. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
  4079. } else {
  4080. $writeFailLog = str_replace("date", "\r\ndate", json_encode($logEntryFirst));
  4081. }
  4082. file_put_contents($this->organizrLog, $writeFailLog);
  4083. }
  4084. public function isApprovedRequest($method, $data)
  4085. {
  4086. $requesterToken = $this->getallheaders()['Token'] ?? ($_GET['apikey'] ?? false);
  4087. $apiKey = ($this->config['organizrAPI']) ?? null;
  4088. if (isset($data['formKey'])) {
  4089. $formKey = $data['formKey'];
  4090. } elseif (isset($this->getallheaders()['Formkey'])) {
  4091. $formKey = $this->getallheaders()['Formkey'];
  4092. } elseif (isset($this->getallheaders()['formkey'])) {
  4093. $formKey = $this->getallheaders()['formkey'];
  4094. } elseif (isset($this->getallheaders()['formKey'])) {
  4095. $formKey = $this->getallheaders()['formKey'];
  4096. } elseif (isset($this->getallheaders()['FormKey'])) {
  4097. $formKey = $this->getallheaders()['FormKey'];
  4098. } else {
  4099. $formKey = false;
  4100. }
  4101. // Check token or API key
  4102. // If API key, return 0 for admin
  4103. if (strlen($requesterToken) == 20 && $requesterToken == $apiKey) {
  4104. //DO API CHECK
  4105. return true;
  4106. } elseif ($method == 'POST') {
  4107. if ($this->checkFormKey($formKey)) {
  4108. return true;
  4109. } else {
  4110. $this->setLoggerChannel('Authentication');
  4111. $this->logger->warning('Unable to authenticate Form Key: ' . $formKey);
  4112. return false;
  4113. }
  4114. } else {
  4115. return true;
  4116. }
  4117. return false;
  4118. }
  4119. public function checkFormKey($formKey = '')
  4120. {
  4121. return password_verify(substr($this->config['organizrHash'], 2, 10), $formKey);
  4122. }
  4123. public function buildHomepage()
  4124. {
  4125. $homepageOrder = $this->homepageOrderList();
  4126. $homepageBuilt = '';
  4127. foreach ($homepageOrder as $key => $value) {
  4128. //new way
  4129. if (method_exists($this, $key)) {
  4130. $homepageBuilt .= $this->$key();
  4131. } elseif (strpos($key, 'homepageOrdercustomhtml') !== false) {
  4132. $iteration = substr($key, -2);
  4133. $homepageBuilt .= $this->homepageOrdercustomhtml($iteration);
  4134. } else {
  4135. $homepageBuilt .= '<div id="' . $key . '"></div>';
  4136. }
  4137. //old way
  4138. //$homepageBuilt .= $this->buildHomepageItem($key);
  4139. }
  4140. return $homepageBuilt;
  4141. }
  4142. public function buildHomepageSettings()
  4143. {
  4144. $homepageOrder = $this->homepageOrderList();
  4145. $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">';
  4146. $inputList = '<form id="homepage-values" class="row">';
  4147. foreach ($homepageOrder as $key => $val) {
  4148. switch ($key) {
  4149. case 'homepageOrdercustomhtml01':
  4150. case 'homepageOrdercustomhtml02':
  4151. case 'homepageOrdercustomhtml03':
  4152. case 'homepageOrdercustomhtml04':
  4153. case 'homepageOrdercustomhtml05':
  4154. case 'homepageOrdercustomhtml06':
  4155. case 'homepageOrdercustomhtml07':
  4156. case 'homepageOrdercustomhtml08':
  4157. $iteration = substr($key, -2);
  4158. $class = 'bg-info';
  4159. $image = 'plugins/images/tabs/HTML5.png';
  4160. if (!$this->config['homepageCustomHTML' . $iteration . 'Enabled']) {
  4161. $class .= ' faded';
  4162. }
  4163. break;
  4164. case 'homepageOrdertransmission':
  4165. $class = 'bg-transmission';
  4166. $image = 'plugins/images/tabs/transmission.png';
  4167. if (!$this->config['homepageTransmissionEnabled']) {
  4168. $class .= ' faded';
  4169. }
  4170. break;
  4171. case 'homepageOrdernzbget':
  4172. $class = 'bg-nzbget';
  4173. $image = 'plugins/images/tabs/nzbget.png';
  4174. if (!$this->config['homepageNzbgetEnabled']) {
  4175. $class .= ' faded';
  4176. }
  4177. break;
  4178. case 'homepageOrderjdownloader':
  4179. $class = 'bg-sab';
  4180. $image = 'plugins/images/tabs/jdownloader.png';
  4181. if (!$this->config['homepageJdownloaderEnabled']) {
  4182. $class .= ' faded';
  4183. }
  4184. break;
  4185. case 'homepageOrdersabnzbd':
  4186. $class = 'bg-sab';
  4187. $image = 'plugins/images/tabs/sabnzbd.png';
  4188. if (!$this->config['homepageSabnzbdEnabled']) {
  4189. $class .= ' faded';
  4190. }
  4191. break;
  4192. case 'homepageOrderdeluge':
  4193. $class = 'bg-deluge';
  4194. $image = 'plugins/images/tabs/deluge.png';
  4195. if (!$this->config['homepageDelugeEnabled']) {
  4196. $class .= ' faded';
  4197. }
  4198. break;
  4199. case 'homepageOrderqBittorrent':
  4200. $class = 'bg-qbit';
  4201. $image = 'plugins/images/tabs/qBittorrent.png';
  4202. if (!$this->config['homepageqBittorrentEnabled']) {
  4203. $class .= ' faded';
  4204. }
  4205. break;
  4206. case 'homepageOrderuTorrent':
  4207. $class = 'bg-qbit';
  4208. $image = 'plugins/images/tabs/utorrent.png';
  4209. if (!$this->config['homepageuTorrentEnabled']) {
  4210. $class .= ' faded';
  4211. }
  4212. break;
  4213. case 'homepageOrderrTorrent':
  4214. $class = 'bg-qbit';
  4215. $image = 'plugins/images/tabs/rTorrent.png';
  4216. if (!$this->config['homepagerTorrentEnabled']) {
  4217. $class .= ' faded';
  4218. }
  4219. break;
  4220. case 'homepageOrderplexnowplaying':
  4221. case 'homepageOrderplexrecent':
  4222. case 'homepageOrderplexplaylist':
  4223. $class = 'bg-plex';
  4224. $image = 'plugins/images/tabs/plex.png';
  4225. if (!$this->config['homepagePlexEnabled']) {
  4226. $class .= ' faded';
  4227. }
  4228. break;
  4229. case 'homepageOrderembynowplaying':
  4230. case 'homepageOrderembyrecent':
  4231. $class = 'bg-emby';
  4232. $image = 'plugins/images/tabs/emby.png';
  4233. if (!$this->config['homepageEmbyEnabled']) {
  4234. $class .= ' faded';
  4235. }
  4236. break;
  4237. case 'homepageOrderjellyfinnowplaying':
  4238. case 'homepageOrderjellyfinrecent':
  4239. $class = 'bg-jellyfin';
  4240. $image = 'plugins/images/tabs/jellyfin.png';
  4241. if (!$this->config['homepageJellyfinEnabled']) {
  4242. $class .= ' faded';
  4243. }
  4244. break;
  4245. case 'homepageOrderombi':
  4246. $class = 'bg-inverse';
  4247. $image = 'plugins/images/tabs/ombi.png';
  4248. if (!$this->config['homepageOmbiEnabled']) {
  4249. $class .= ' faded';
  4250. }
  4251. break;
  4252. case 'homepageOrderoverseerr':
  4253. $class = 'bg-inverse';
  4254. $image = 'plugins/images/tabs/overseerr.png';
  4255. if (!$this->config['homepageOverseerrEnabled']) {
  4256. $class .= ' faded';
  4257. }
  4258. break;
  4259. case 'homepageOrderDonate':
  4260. $class = 'bg-primary';
  4261. $image = 'plugins/images/tabs/donate.png';
  4262. if (!$this->config['homepageDonateEnabled']) {
  4263. $class .= ' faded';
  4264. }
  4265. break;
  4266. case 'homepageOrdercalendar':
  4267. $class = 'bg-primary';
  4268. $image = 'plugins/images/tabs/calendar.png';
  4269. if (!$this->config['homepageCalendarEnabled'] && !$this->config['homepageSonarrEnabled'] && !$this->config['homepageRadarrEnabled'] && !$this->config['homepageSickrageEnabled'] && !$this->config['homepageCouchpotatoEnabled']) {
  4270. $class .= ' faded';
  4271. }
  4272. break;
  4273. case 'homepageOrderdownloader':
  4274. $class = 'bg-inverse';
  4275. $image = 'plugins/images/tabs/downloader.png';
  4276. 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']) {
  4277. $class .= ' faded';
  4278. }
  4279. break;
  4280. case 'homepageOrderhealthchecks':
  4281. $class = 'bg-healthchecks';
  4282. $image = 'plugins/images/tabs/healthchecks.png';
  4283. if (!$this->config['homepageHealthChecksEnabled']) {
  4284. $class .= ' faded';
  4285. }
  4286. break;
  4287. case 'homepageOrderunifi':
  4288. $class = 'bg-info';
  4289. $image = 'plugins/images/tabs/ubnt.png';
  4290. if (!$this->config['homepageUnifiEnabled']) {
  4291. $class .= ' faded';
  4292. }
  4293. break;
  4294. case 'homepageOrdertautulli':
  4295. $class = 'bg-info';
  4296. $image = 'plugins/images/tabs/tautulli.png';
  4297. if (!$this->config['homepageTautulliEnabled']) {
  4298. $class .= ' faded';
  4299. }
  4300. break;
  4301. case 'homepageOrderPihole':
  4302. $class = 'bg-info';
  4303. $image = 'plugins/images/tabs/pihole.png';
  4304. if (!$this->config['homepagePiholeEnabled']) {
  4305. $class .= ' faded';
  4306. }
  4307. break;
  4308. case 'homepageOrderMonitorr':
  4309. $class = 'bg-info';
  4310. $image = 'plugins/images/tabs/monitorr.png';
  4311. if (!$this->config['homepageMonitorrEnabled']) {
  4312. $class .= ' faded';
  4313. }
  4314. break;
  4315. case 'homepageOrderWeatherAndAir':
  4316. $class = 'bg-success';
  4317. $image = 'plugins/images/tabs/wind.png';
  4318. if (!$this->config['homepageWeatherAndAirEnabled']) {
  4319. $class .= ' faded';
  4320. }
  4321. break;
  4322. case 'homepageOrderSpeedtest':
  4323. $class = 'bg-success';
  4324. $image = 'plugins/images/tabs/speedtest-icon.png';
  4325. if (!$this->config['homepageSpeedtestEnabled']) {
  4326. $class .= ' faded';
  4327. }
  4328. break;
  4329. case 'homepageOrderNetdata':
  4330. $class = 'bg-success';
  4331. $image = 'plugins/images/tabs/netdata.png';
  4332. if (!$this->config['homepageNetdataEnabled']) {
  4333. $class .= ' faded';
  4334. }
  4335. break;
  4336. case 'homepageOrderOctoprint':
  4337. $class = 'bg-success';
  4338. $image = 'plugins/images/tabs/octoprint.png';
  4339. if (!$this->config['homepageOctoprintEnabled']) {
  4340. $class .= ' faded';
  4341. }
  4342. break;
  4343. case 'homepageOrderSonarrQueue':
  4344. $class = 'bg-sonarr';
  4345. $image = 'plugins/images/tabs/sonarr.png';
  4346. if (!$this->config['homepageSonarrQueueEnabled']) {
  4347. $class .= ' faded';
  4348. }
  4349. break;
  4350. case 'homepageOrderRadarrQueue':
  4351. $class = 'bg-radarr';
  4352. $image = 'plugins/images/tabs/radarr.png';
  4353. if (!$this->config['homepageRadarrQueueEnabled']) {
  4354. $class .= ' faded';
  4355. }
  4356. break;
  4357. case 'homepageOrderJackett':
  4358. $class = 'bg-inverse';
  4359. $image = 'plugins/images/tabs/jackett.png';
  4360. if (!$this->config['homepageJackettEnabled']) {
  4361. $class .= ' faded';
  4362. }
  4363. break;
  4364. case 'homepageOrderBookmarks':
  4365. $class = 'bg-bookmarks';
  4366. $image = 'plugins/images/bookmark.png';
  4367. if (!$this->config['homepageBookmarksEnabled']) {
  4368. $class .= ' faded';
  4369. }
  4370. break;
  4371. default:
  4372. $class = 'blue-bg';
  4373. $image = '';
  4374. break;
  4375. }
  4376. $homepageList .= '
  4377. <div class="col-md-3 col-xs-12 sort-homepage m-t-10 hvr-grow clearfix">
  4378. <div class="homepage-drag fc-event ' . $class . ' lazyload" data-src="' . $image . '">
  4379. <span class="ordinal-position text-uppercase badge bg-org homepage-number" data-link="' . $key . '" style="float:left;width: 30px;">' . $val . '</span>
  4380. <span class="homepage-text">&nbsp; ' . strtoupper(substr($key, 13)) . '</span>
  4381. </div>
  4382. </div>
  4383. ';
  4384. $inputList .= '<input type="hidden" name="' . $key . '">';
  4385. }
  4386. $homepageList .= '</div>';
  4387. $inputList .= '</form>';
  4388. return $homepageList . $inputList;
  4389. }
  4390. public function setGroupOptionsVariable()
  4391. {
  4392. $this->groupOptions = $this->groupSelect();
  4393. }
  4394. public function getSettingsHomepageItem($item)
  4395. {
  4396. $items = $this->getSettingsHomepage();
  4397. foreach ($items as $k => $v) {
  4398. if (strtolower($v['name']) === strtolower($item)) {
  4399. $functionName = $v['settingsArray'];
  4400. return $this->$functionName();
  4401. }
  4402. }
  4403. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4404. return null;
  4405. }
  4406. public function getSettingsHomepageItemDebug($service)
  4407. {
  4408. $service = $this->getSettingsHomepageItem($service);
  4409. if ($service) {
  4410. $debug = [];
  4411. foreach ($service['settings'] as $category => $items) {
  4412. if ($category !== 'About' && $category !== 'Test Connection') {
  4413. foreach ($items as $item) {
  4414. if ($item['type'] !== 'html' && $item['type'] !== 'blank' && $item['type'] !== 'button') {
  4415. if ((stripos($item['name'], 'token') !== false) || (stripos($item['name'], 'key') !== false) || (stripos($item['name'], 'password'))) {
  4416. if ($item['value'] !== '') {
  4417. $item['value'] = '***redacted***';
  4418. }
  4419. }
  4420. $debug[$category][$item['name']] = $item['value'];
  4421. }
  4422. }
  4423. }
  4424. }
  4425. return $debug;
  4426. }
  4427. $this->setAPIResponse('error', 'Homepage item was not found', 404);
  4428. return null;
  4429. }
  4430. public function getSettingsHomepage()
  4431. {
  4432. $this->setGroupOptionsVariable();
  4433. return $this->getHomepageSettingsCombined();
  4434. }
  4435. public function isTabNameTaken($name, $id = null)
  4436. {
  4437. if ($id) {
  4438. $response = [
  4439. array(
  4440. 'function' => 'fetchAll',
  4441. 'query' => array(
  4442. 'SELECT * FROM tabs WHERE `name` LIKE ? AND `id` != ?',
  4443. $name,
  4444. $id
  4445. )
  4446. ),
  4447. ];
  4448. } else {
  4449. $response = [
  4450. array(
  4451. 'function' => 'fetchAll',
  4452. 'query' => array(
  4453. 'SELECT * FROM tabs WHERE `name` LIKE ?',
  4454. $name
  4455. )
  4456. ),
  4457. ];
  4458. }
  4459. return $this->processQueries($response);
  4460. }
  4461. public function isCategoryNameTaken($name, $id = null)
  4462. {
  4463. if ($id) {
  4464. $response = [
  4465. array(
  4466. 'function' => 'fetchAll',
  4467. 'query' => array(
  4468. 'SELECT * FROM categories WHERE `category` LIKE ? AND `id` != ?',
  4469. $name,
  4470. $id
  4471. )
  4472. ),
  4473. ];
  4474. } else {
  4475. $response = [
  4476. array(
  4477. 'function' => 'fetchAll',
  4478. 'query' => array(
  4479. 'SELECT * FROM categories WHERE `category` LIKE ?',
  4480. $name
  4481. )
  4482. ),
  4483. ];
  4484. }
  4485. return $this->processQueries($response);
  4486. }
  4487. public function isGroupNameTaken($name, $id = null)
  4488. {
  4489. if ($id) {
  4490. $response = [
  4491. array(
  4492. 'function' => 'fetchAll',
  4493. 'query' => array(
  4494. 'SELECT * FROM groups WHERE `group` LIKE ? AND `id` != ?',
  4495. $name,
  4496. $id
  4497. )
  4498. ),
  4499. ];
  4500. } else {
  4501. $response = [
  4502. array(
  4503. 'function' => 'fetchAll',
  4504. 'query' => array(
  4505. 'SELECT * FROM groups WHERE `group` LIKE ?',
  4506. $name
  4507. )
  4508. ),
  4509. ];
  4510. }
  4511. return $this->processQueries($response);
  4512. }
  4513. public function getTableColumns($table)
  4514. {
  4515. if ($this->config['driver'] == 'sqlite3') {
  4516. $query = 'PRAGMA table_info(?)';
  4517. } else {
  4518. $query = 'DESCRIBE %n';
  4519. }
  4520. $response = [
  4521. array(
  4522. 'function' => 'fetchAll',
  4523. 'query' => [
  4524. $query, $table
  4525. ]
  4526. ),
  4527. ];
  4528. return $this->processQueries($response);
  4529. }
  4530. public function getTableColumnsFormatted($table)
  4531. {
  4532. if ($this->config['driver'] == 'sqlite3') {
  4533. $name = 'name';
  4534. } else {
  4535. $name = 'Field';
  4536. }
  4537. $columns = $this->getTableColumns($table);
  4538. if ($columns) {
  4539. $columnsFormatted = [];
  4540. foreach ($columns as $k => $v) {
  4541. $columnsFormatted[$v[$name]] = $v;
  4542. }
  4543. return $columnsFormatted;
  4544. } else {
  4545. return false;
  4546. }
  4547. }
  4548. public function getTabById($id)
  4549. {
  4550. $response = [
  4551. array(
  4552. 'function' => 'fetch',
  4553. 'query' => array(
  4554. 'SELECT * FROM tabs WHERE `id` = ?',
  4555. $id
  4556. )
  4557. ),
  4558. ];
  4559. return $this->processQueries($response);
  4560. }
  4561. public function getTabGroupByTabName($tab)
  4562. {
  4563. $response = [
  4564. array(
  4565. 'function' => 'fetch',
  4566. 'query' => array(
  4567. 'SELECT group_id FROM tabs WHERE name LIKE %~like~',
  4568. $tab
  4569. )
  4570. ),
  4571. ];
  4572. $query = $this->processQueries($response);
  4573. return $query ? $query['group_id'] : 0;
  4574. }
  4575. public function getCategoryById($id)
  4576. {
  4577. $response = [
  4578. array(
  4579. 'function' => 'fetch',
  4580. 'query' => array(
  4581. 'SELECT * FROM categories WHERE `id` = ?',
  4582. $id
  4583. )
  4584. ),
  4585. ];
  4586. return $this->processQueries($response);
  4587. }
  4588. public function getGroupUserCountById($id)
  4589. {
  4590. $response = [
  4591. array(
  4592. 'function' => 'fetchSingle',
  4593. 'query' => array(
  4594. 'SELECT count(username) AS count FROM groups INNER JOIN users ON users.group_id = groups.group_id AND groups.id = ?',
  4595. $id
  4596. )
  4597. ),
  4598. ];
  4599. return $this->processQueries($response);
  4600. }
  4601. public function getGroupById($id)
  4602. {
  4603. $response = [
  4604. array(
  4605. 'function' => 'fetch',
  4606. 'query' => array(
  4607. 'SELECT * FROM groups WHERE `id` = ?',
  4608. $id
  4609. )
  4610. ),
  4611. ];
  4612. return $this->processQueries($response);
  4613. }
  4614. public function getGroupByGroupId($id)
  4615. {
  4616. $response = [
  4617. array(
  4618. 'function' => 'fetch',
  4619. 'query' => array(
  4620. 'SELECT * FROM groups WHERE `group_id` = ?',
  4621. $id
  4622. )
  4623. ),
  4624. ];
  4625. return $this->processQueries($response);
  4626. }
  4627. public function getDefaultGroup()
  4628. {
  4629. $response = [
  4630. array(
  4631. 'function' => 'fetch',
  4632. 'query' => array(
  4633. 'SELECT * FROM groups WHERE `default` = 1'
  4634. )
  4635. ),
  4636. ];
  4637. return $this->processQueries($response);
  4638. }
  4639. public function getDefaultGroupId()
  4640. {
  4641. $response = [
  4642. array(
  4643. 'function' => 'fetchSingle',
  4644. 'query' => array(
  4645. 'SELECT `group_id` FROM groups WHERE `default` = 1'
  4646. )
  4647. ),
  4648. ];
  4649. return $this->processQueries($response);
  4650. }
  4651. public function getDefaultCategory()
  4652. {
  4653. $response = [
  4654. array(
  4655. 'function' => 'fetch',
  4656. 'query' => array(
  4657. 'SELECT * FROM categories WHERE `default` = 1'
  4658. )
  4659. ),
  4660. ];
  4661. return $this->processQueries($response);
  4662. }
  4663. public function getDefaultCategoryId()
  4664. {
  4665. $response = [
  4666. array(
  4667. 'function' => 'fetchSingle',
  4668. 'query' => array(
  4669. 'SELECT `category_id` FROM categories WHERE `default` = 1'
  4670. )
  4671. ),
  4672. ];
  4673. return $this->processQueries($response);
  4674. }
  4675. public function getNextTabOrder()
  4676. {
  4677. $response = [
  4678. array(
  4679. 'function' => 'fetchSingle',
  4680. 'query' => array(
  4681. 'SELECT `order` from tabs ORDER BY `order` DESC'
  4682. )
  4683. ),
  4684. ];
  4685. return $this->processQueries($response);
  4686. }
  4687. public function getNextCategoryOrder()
  4688. {
  4689. $response = [
  4690. array(
  4691. 'function' => 'fetchSingle',
  4692. 'query' => array(
  4693. 'SELECT `order` from categories ORDER BY `order` DESC'
  4694. )
  4695. ),
  4696. ];
  4697. return $this->processQueries($response);
  4698. }
  4699. public function getNextGroupOrder()
  4700. {
  4701. $response = [
  4702. array(
  4703. 'function' => 'fetchSingle',
  4704. 'query' => array(
  4705. 'SELECT `group_id` from groups WHERE `group_id` != "999" ORDER BY `group_id` DESC'
  4706. )
  4707. ),
  4708. ];
  4709. return $this->processQueries($response);
  4710. }
  4711. public function getNextCategoryId()
  4712. {
  4713. $response = [
  4714. array(
  4715. 'function' => 'fetchSingle',
  4716. 'query' => array(
  4717. 'SELECT `category_id` from categories ORDER BY `category_id` DESC'
  4718. )
  4719. ),
  4720. ];
  4721. return $this->processQueries($response);
  4722. }
  4723. public function clearTabDefault()
  4724. {
  4725. $response = [
  4726. array(
  4727. 'function' => 'query',
  4728. 'query' => array(
  4729. 'UPDATE tabs SET `default` = 0'
  4730. )
  4731. ),
  4732. ];
  4733. return $this->processQueries($response);
  4734. }
  4735. public function clearCategoryDefault()
  4736. {
  4737. $response = [
  4738. array(
  4739. 'function' => 'query',
  4740. 'query' => array(
  4741. 'UPDATE categories SET `default` = 0'
  4742. )
  4743. ),
  4744. ];
  4745. return $this->processQueries($response);
  4746. }
  4747. public function clearGroupDefault()
  4748. {
  4749. $response = [
  4750. array(
  4751. 'function' => 'query',
  4752. 'query' => array(
  4753. 'UPDATE groups SET `default` = 0'
  4754. )
  4755. ),
  4756. ];
  4757. return $this->processQueries($response);
  4758. }
  4759. public function checkKeys($tabInfo, $newData)
  4760. {
  4761. foreach ($newData as $k => $v) {
  4762. if (!array_key_exists($k, $tabInfo)) {
  4763. unset($newData[$k]);
  4764. }
  4765. }
  4766. return $newData;
  4767. }
  4768. public function getTabByIdCheckUser($id)
  4769. {
  4770. $tabInfo = $this->getTabById($id);
  4771. if ($tabInfo) {
  4772. if ($this->qualifyRequest($tabInfo['group_id'], true)) {
  4773. return $tabInfo;
  4774. }
  4775. } else {
  4776. $this->setAPIResponse('error', 'id not found', 404);
  4777. return false;
  4778. }
  4779. }
  4780. public function deleteTab($id)
  4781. {
  4782. $response = [
  4783. array(
  4784. 'function' => 'query',
  4785. 'query' => array(
  4786. 'DELETE FROM tabs WHERE id = ?',
  4787. $id
  4788. )
  4789. ),
  4790. ];
  4791. $tabInfo = $this->getTabById($id);
  4792. if ($tabInfo) {
  4793. $this->setLoggerChannel('Tab Management');
  4794. $this->logger->debug('Deleted Tab [' . $tabInfo['name'] . ']');
  4795. $this->setAPIResponse('success', 'Tab deleted', 204);
  4796. return $this->processQueries($response);
  4797. } else {
  4798. $this->setAPIResponse('error', 'id not found', 404);
  4799. return false;
  4800. }
  4801. }
  4802. public function addTab($array)
  4803. {
  4804. if (!$array) {
  4805. $this->setAPIResponse('error', 'no data was sent', 422);
  4806. return null;
  4807. }
  4808. $array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
  4809. $array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
  4810. $array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
  4811. $array['enabled'] = ($array['enabled']) ?? 0;
  4812. $array['default'] = ($array['default']) ?? 0;
  4813. $array['type'] = ($array['type']) ?? 1;
  4814. $array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
  4815. if (array_key_exists('name', $array)) {
  4816. $array['name'] = $this->sanitizeUserString($array['name']);
  4817. if ($this->isTabNameTaken($array['name'])) {
  4818. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  4819. return false;
  4820. }
  4821. } else {
  4822. $this->setAPIResponse('error', 'Tab name was not supplied', 422);
  4823. return false;
  4824. }
  4825. if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
  4826. $this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
  4827. return false;
  4828. }
  4829. if (!array_key_exists('image', $array)) {
  4830. $this->setAPIResponse('error', 'Tab image was not supplied', 422);
  4831. return false;
  4832. }
  4833. $response = [
  4834. array(
  4835. 'function' => 'query',
  4836. 'query' => array(
  4837. 'INSERT INTO [tabs]',
  4838. $array
  4839. )
  4840. ),
  4841. ];
  4842. $this->setAPIResponse(null, 'Tab added');
  4843. $this->setLoggerChannel('Tab Management');
  4844. $this->logger->debug('Added Tab for [' . $array['name'] . ']');
  4845. return $this->processQueries($response);
  4846. }
  4847. public function updateTab($id, $array)
  4848. {
  4849. if (!$id || $id == '') {
  4850. $this->setAPIResponse('error', 'id was not set', 422);
  4851. return null;
  4852. }
  4853. if (!$array) {
  4854. $this->setAPIResponse('error', 'no data was sent', 422);
  4855. return null;
  4856. }
  4857. $tabInfo = $this->getTabById($id);
  4858. if ($tabInfo) {
  4859. $array = $this->checkKeys($tabInfo, $array);
  4860. } else {
  4861. $this->setAPIResponse('error', 'No tab info found', 404);
  4862. return false;
  4863. }
  4864. if (array_key_exists('name', $array)) {
  4865. $array['name'] = $this->sanitizeUserString($array['name']);
  4866. if ($this->isTabNameTaken($array['name'], $id)) {
  4867. $this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
  4868. return false;
  4869. }
  4870. }
  4871. if (array_key_exists('default', $array)) {
  4872. if ($array['default']) {
  4873. $this->clearTabDefault();
  4874. }
  4875. }
  4876. $response = [
  4877. array(
  4878. 'function' => 'query',
  4879. 'query' => array(
  4880. 'UPDATE tabs SET',
  4881. $array,
  4882. 'WHERE id = ?',
  4883. $id
  4884. )
  4885. ),
  4886. ];
  4887. $this->setAPIResponse(null, 'Tab info updated');
  4888. $this->setLoggerChannel('Tab Management');
  4889. $this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
  4890. return $this->processQueries($response);
  4891. }
  4892. public function updateTabOrder($array)
  4893. {
  4894. if (count($array) >= 1) {
  4895. foreach ($array as $tab) {
  4896. if (count($tab) !== 2) {
  4897. $this->setAPIResponse('error', 'data is malformed', 422);
  4898. break;
  4899. }
  4900. $id = $tab['id'] ?? null;
  4901. $order = $tab['order'] ?? null;
  4902. if ($id && $order) {
  4903. $response = [
  4904. array(
  4905. 'function' => 'query',
  4906. 'query' => array(
  4907. 'UPDATE tabs set `order` = ? WHERE `id` = ?',
  4908. $order,
  4909. $id
  4910. )
  4911. ),
  4912. ];
  4913. $this->processQueries($response);
  4914. $this->setAPIResponse(null, 'Tab Order updated');
  4915. } else {
  4916. $this->setAPIResponse('error', 'data is malformed', 422);
  4917. }
  4918. }
  4919. } else {
  4920. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  4921. return false;
  4922. }
  4923. }
  4924. public function addCategory($array)
  4925. {
  4926. if (!$array) {
  4927. $this->setAPIResponse('error', 'no data was sent', 422);
  4928. return null;
  4929. }
  4930. $array = $this->checkKeys($this->getTableColumnsFormatted('categories'), $array);
  4931. $array['default'] = ($array['default']) ?? 0;
  4932. $array['order'] = ($array['order']) ?? $this->getNextCategoryOrder() + 1;
  4933. $array['category_id'] = ($array['category_id']) ?? $this->getNextCategoryId() + 1;
  4934. if (array_key_exists('category', $array)) {
  4935. $array['category'] = $this->sanitizeUserString($array['category']);
  4936. if ($this->isCategoryNameTaken($array['category'])) {
  4937. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  4938. return false;
  4939. }
  4940. } else {
  4941. $this->setAPIResponse('error', 'Category name was not supplied', 422);
  4942. return false;
  4943. }
  4944. if (!array_key_exists('image', $array)) {
  4945. $this->setAPIResponse('error', 'Category image was not supplied', 422);
  4946. return false;
  4947. } else {
  4948. $array['image'] = $this->sanitizeUserString($array['image']);
  4949. }
  4950. $response = [
  4951. array(
  4952. 'function' => 'query',
  4953. 'query' => array(
  4954. 'INSERT INTO [categories]',
  4955. $array
  4956. )
  4957. ),
  4958. ];
  4959. $this->setAPIResponse(null, 'Category added');
  4960. $this->setLoggerChannel('Category Management');
  4961. $this->logger->debug('Added Category for [' . $array['category'] . ']');
  4962. return $this->processQueries($response);
  4963. }
  4964. public function updateCategory($id, $array)
  4965. {
  4966. if (!$id || $id == '') {
  4967. $this->setAPIResponse('error', 'id was not set', 422);
  4968. return null;
  4969. }
  4970. if (!$array) {
  4971. $this->setAPIResponse('error', 'no data was sent', 422);
  4972. return null;
  4973. }
  4974. $categoryInfo = $this->getCategoryById($id);
  4975. if ($categoryInfo) {
  4976. $array = $this->checkKeys($categoryInfo, $array);
  4977. } else {
  4978. $this->setAPIResponse('error', 'No category info found', 404);
  4979. return false;
  4980. }
  4981. if (array_key_exists('category', $array)) {
  4982. $array['category'] = $this->sanitizeUserString($array['category']);
  4983. if ($this->isCategoryNameTaken($array['category'], $id)) {
  4984. $this->setAPIResponse('error', 'Category name: ' . $array['category'] . ' is already taken', 409);
  4985. return false;
  4986. }
  4987. }
  4988. if (array_key_exists('image', $array)) {
  4989. $array['image'] = $this->sanitizeUserString($array['image']);
  4990. }
  4991. if (array_key_exists('default', $array)) {
  4992. if ($array['default']) {
  4993. $this->clearCategoryDefault();
  4994. }
  4995. }
  4996. $response = [
  4997. array(
  4998. 'function' => 'query',
  4999. 'query' => array(
  5000. 'UPDATE categories SET',
  5001. $array,
  5002. 'WHERE id = ?',
  5003. $id
  5004. )
  5005. ),
  5006. ];
  5007. $this->setAPIResponse(null, 'Category info updated');
  5008. $this->setLoggerChannel('Category Management');
  5009. $this->logger->debug('Edited Category [' . $categoryInfo['category'] . ']');
  5010. return $this->processQueries($response);
  5011. }
  5012. public function updateCategoryOrder($array)
  5013. {
  5014. if (count($array) >= 1) {
  5015. foreach ($array as $category) {
  5016. if (count($category) !== 2) {
  5017. $this->setAPIResponse('error', 'data is malformed', 422);
  5018. break;
  5019. }
  5020. $id = $category['id'] ?? null;
  5021. $order = $category['order'] ?? null;
  5022. if ($id && $order) {
  5023. $response = [
  5024. array(
  5025. 'function' => 'query',
  5026. 'query' => array(
  5027. 'UPDATE categories set `order` = ? WHERE `id` = ?',
  5028. $order,
  5029. $id
  5030. )
  5031. ),
  5032. ];
  5033. $this->processQueries($response);
  5034. $this->setAPIResponse(null, 'Category Order updated');
  5035. } else {
  5036. $this->setAPIResponse('error', 'data is malformed', 422);
  5037. }
  5038. }
  5039. } else {
  5040. $this->setAPIResponse('error', 'data is empty or not in array', 422);
  5041. return false;
  5042. }
  5043. }
  5044. public function deleteCategory($id)
  5045. {
  5046. $response = [
  5047. array(
  5048. 'function' => 'query',
  5049. 'query' => array(
  5050. 'DELETE FROM categories WHERE id = ?',
  5051. $id
  5052. )
  5053. ),
  5054. ];
  5055. $categoryInfo = $this->getCategoryById($id);
  5056. if ($categoryInfo) {
  5057. $this->setLoggerChannel('Category Management');
  5058. $this->logger->debug('Deleted Category [' . $categoryInfo['category'] . ']');
  5059. $this->setAPIResponse('success', 'Category deleted', 204);
  5060. return $this->processQueries($response);
  5061. } else {
  5062. $this->setAPIResponse('error', 'id not found', 404);
  5063. return false;
  5064. }
  5065. }
  5066. public function inconspicuous(): string
  5067. {
  5068. if ($this->hasDB()) {
  5069. if ($this->config['easterEggs']) {
  5070. return '
  5071. <div class="org-rox-trigger">
  5072. <div class="org-rox">
  5073. <div class="hair"></div>
  5074. <div class="head">
  5075. <div class="ear left"></div>
  5076. <div class="ear right"></div>
  5077. <div class="face">
  5078. <div class="eye left"></div>
  5079. <div class="eye right"></div>
  5080. <div class="nose"></div>
  5081. <div class="mouth"></div>
  5082. </div>
  5083. </div>
  5084. </div>
  5085. </div>';
  5086. }
  5087. }
  5088. return '';
  5089. }
  5090. public function marketplaceFileListFormat($files, $folder, $type)
  5091. {
  5092. foreach ($files as $k => $v) {
  5093. $splitFiles = explode('|', $v);
  5094. $prePath = (strlen($k) !== 1) ? $k . '/' : $k;
  5095. foreach ($splitFiles as $file) {
  5096. $filesList[] = array(
  5097. 'fileName' => $file,
  5098. 'path' => $prePath,
  5099. 'githubPath' => 'https://raw.githubusercontent.com/causefx/Organizr/v2-' . $type . '/' . $folder . $prePath . $file
  5100. );
  5101. }
  5102. }
  5103. return $filesList;
  5104. }
  5105. public function removeTheme($theme)
  5106. {
  5107. $this->setLoggerChannel('Theme Marketplace');
  5108. $theme = $this->cleanClassName($theme, '_');
  5109. $array = $this->getThemesMarketplace();
  5110. $arrayLower = array_change_key_case($array);
  5111. if (!$array) {
  5112. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5113. return false;
  5114. }
  5115. if (!isset($arrayLower[$theme])) {
  5116. $this->setAPIResponse('error', 'Theme does not exist in marketplace', 404);
  5117. return false;
  5118. } else {
  5119. $key = array_search($theme, array_keys($arrayLower));
  5120. $theme = array_keys($array)[$key];
  5121. }
  5122. $array = $array[$theme];
  5123. $themeDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5124. $dirExists = file_exists($themeDir);
  5125. if ($dirExists) {
  5126. if (!$this->rrmdir($themeDir)) {
  5127. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5128. return false;
  5129. }
  5130. } else {
  5131. $this->setAPIResponse('error', 'Theme is not installed', 404);
  5132. return false;
  5133. }
  5134. $this->updateInstalledThemes('uninstall', $theme, $array);
  5135. $this->setAPIResponse('success', 'Theme removed', 200, $array);
  5136. return true;
  5137. }
  5138. public function installTheme($theme)
  5139. {
  5140. $this->setLoggerChannel('Theme Marketplace');
  5141. $theme = $this->cleanClassName($theme, '_');
  5142. $array = $this->getThemesMarketplace();
  5143. $arrayLower = array_change_key_case($array);
  5144. if (!$array) {
  5145. $this->setAPIResponse('error', 'Could not access theme marketplace', 409);
  5146. return false;
  5147. }
  5148. if (!isset($arrayLower[$theme])) {
  5149. $this->setAPIResponse('error', 'Theme [' . $theme . '] does not exist in marketplace', 404, $arrayLower);
  5150. return false;
  5151. } else {
  5152. $key = array_search($theme, array_keys($arrayLower));
  5153. $theme = array_keys($array)[$key];
  5154. }
  5155. $array = $array[$theme];
  5156. // Check Version of Organizr against minimum version needed
  5157. $compare = new Composer\Semver\Comparator;
  5158. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5159. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5160. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5161. return true;
  5162. }
  5163. // It is okay to user Plugin function - we should rename it so it is universal
  5164. $files = $this->getPluginFilesFromRepo($theme, $array);
  5165. if ($files) {
  5166. $downloadList = $this->themeFileListFormat($files, $array['project_folder']);
  5167. } else {
  5168. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5169. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5170. return false;
  5171. }
  5172. if (!$downloadList) {
  5173. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5174. $this->setAPIResponse('error', 'Could not get download list for theme', 409);
  5175. return false;
  5176. }
  5177. foreach ($downloadList as $k => $v) {
  5178. $file = array(
  5179. 'from' => $v['githubPath'],
  5180. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5181. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5182. );
  5183. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes');
  5184. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5185. $this->setLoggerChannel('Theme Marketplace');
  5186. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5187. $this->setAPIResponse('error', 'Theme download failed', 500);
  5188. return false;
  5189. }
  5190. }
  5191. $this->updateInstalledThemes('install', $theme, $array);
  5192. $this->setAPIResponse('success', 'Theme installed', 200, $array);
  5193. return true;
  5194. }
  5195. public function themeFileListFormat($files, $folder)
  5196. {
  5197. $filesList = false;
  5198. foreach ($files as $k => $v) {
  5199. if ($v['type'] !== 'dir') {
  5200. $filesList[] = array(
  5201. 'fileName' => $v['name'],
  5202. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5203. 'githubPath' => $v['download_url']
  5204. );
  5205. }
  5206. }
  5207. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $folder);
  5208. return $filesList;
  5209. }
  5210. public function pluginFileListFormat($files, $folder)
  5211. {
  5212. $filesList = false;
  5213. foreach ($files as $k => $v) {
  5214. if ($v['type'] !== 'dir') {
  5215. $filesList[] = array(
  5216. 'fileName' => $v['name'],
  5217. 'path' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . str_replace($v['name'], '', $v['path']),
  5218. 'githubPath' => $v['download_url']
  5219. );
  5220. }
  5221. }
  5222. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $folder);
  5223. return $filesList;
  5224. }
  5225. public function getPluginFilesFromGithub($plugin = 'test')
  5226. {
  5227. $url = 'https://api.github.com/repos/causefx/organizr/contents/' . $plugin . '?ref=v2-plugins';
  5228. $options = array('verify' => false);
  5229. $response = Requests::get($url, array(), $options);
  5230. if ($response->success) {
  5231. return json_decode($response->body, true);
  5232. }
  5233. return false;
  5234. }
  5235. public function getBranchFromGithub($repo)
  5236. {
  5237. $url = 'https://api.github.com/repos/' . $repo;
  5238. $options = array('verify' => false);
  5239. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5240. try {
  5241. if ($response->success) {
  5242. $github = json_decode($response->body, true);
  5243. return $github['default_branch'] ?? null;
  5244. } else {
  5245. $this->setLoggerChannel('Plugins');
  5246. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5247. return false;
  5248. }
  5249. } catch (Requests_Exception $e) {
  5250. $this->logger->error($e);
  5251. $this->setAPIResponse('error', $e->getMessage(), 401);
  5252. return false;
  5253. }
  5254. }
  5255. public function getFilesFromGithub($repo, $branch)
  5256. {
  5257. if (!$repo || !$branch) {
  5258. return false;
  5259. }
  5260. $url = 'https://api.github.com/repos/' . $repo . '/git/trees/' . $branch . '?recursive=1';
  5261. $options = array('verify' => false);
  5262. $response = Requests::get($url, $this->setGithubAccessToken(), $options);
  5263. try {
  5264. if ($response->success) {
  5265. $github = json_decode($response->body, true);
  5266. return is_array($github) ? $github : null;
  5267. } else {
  5268. $this->setLoggerChannel('Plugins');
  5269. $this->logger->warning('Plugin failed to get branch from Github', $this->apiResponseFormatter($response->body));
  5270. return false;
  5271. }
  5272. } catch (Requests_Exception $e) {
  5273. $this->logger->error($e);
  5274. $this->setAPIResponse('error', $e->getMessage(), 401);
  5275. return false;
  5276. }
  5277. }
  5278. public function formatFilesFromGithub($files, $repo, $branch, $folder)
  5279. {
  5280. if (!$files || !$repo || !$branch || !$folder) {
  5281. return false;
  5282. }
  5283. if (isset($files['tree'])) {
  5284. $fileList = [];
  5285. foreach ($files['tree'] as $k => $v) {
  5286. if ($v['type'] !== 'tree') {
  5287. $fileInfo = pathinfo($v['path']);
  5288. $v['name'] = $fileInfo['basename'];
  5289. $v['download_url'] = 'https://raw.githubusercontent.com/' . $repo . '/' . $branch . '/' . $v['path'];
  5290. if ($folder == 'root') {
  5291. $fileList[] = $v;
  5292. } else {
  5293. if (stripos($v['path'], $folder) !== false) {
  5294. $v['path'] = (substr($v['path'], 0, strlen($folder)) == $folder) ? substr($v['path'], (strlen($folder) + 1)) : $v['path'];
  5295. $fileList[] = $v;
  5296. }
  5297. }
  5298. }
  5299. }
  5300. return $fileList;
  5301. }
  5302. return false;
  5303. }
  5304. public function getPluginFilesFromRepo($plugin, $pluginDetails)
  5305. {
  5306. if (stripos($pluginDetails['repo'], 'github.com') !== false) {
  5307. $repo = explode('https://github.com/', $pluginDetails['repo']);
  5308. } else {
  5309. return false;
  5310. }
  5311. $branch = $this->getBranchFromGithub($repo[1]);
  5312. if ($branch) {
  5313. return $this->formatFilesFromGithub($this->getFilesFromGithub($repo[1], $branch), $repo[1], $branch, $pluginDetails['github_folder']);
  5314. }
  5315. return false;
  5316. }
  5317. public function installPlugin($plugin)
  5318. {
  5319. $this->setLoggerChannel('Plugin Marketplace');
  5320. $plugin = $this->reverseCleanClassName($plugin);
  5321. $array = $this->getPluginsMarketplace();
  5322. $arrayLower = array_change_key_case($array);
  5323. if (!$array) {
  5324. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5325. return false;
  5326. }
  5327. if (!$arrayLower[$plugin]) {
  5328. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5329. return false;
  5330. } else {
  5331. $key = array_search($plugin, array_keys($arrayLower));
  5332. $plugin = array_keys($array)[$key];
  5333. }
  5334. $array = $array[$plugin];
  5335. // Check Version of Organizr against minimum version needed
  5336. $compare = new Composer\Semver\Comparator;
  5337. if ($compare->lessThan($this->version, $array['minimum_organizr_version'])) {
  5338. $this->logger->warning('Minimum Organizr version needed: ' . $array['minimum_organizr_version']);
  5339. $this->setResponse(500, 'Minimum Organizr version needed: ' . $array['minimum_organizr_version'] . ' | Current Version: ' . $this->version);
  5340. return true;
  5341. }
  5342. $files = $this->getPluginFilesFromRepo($plugin, $array);
  5343. if ($files) {
  5344. $downloadList = $this->pluginFileListFormat($files, $array['project_folder']);
  5345. } else {
  5346. $this->logger->warning('File list failed for: ' . $array['github_folder']);
  5347. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5348. return false;
  5349. }
  5350. if (!$downloadList) {
  5351. $this->logger->warning('Setting download list failed for: ' . $array['github_folder']);
  5352. $this->setAPIResponse('error', 'Could not get download list for plugin', 409);
  5353. return false;
  5354. }
  5355. foreach ($downloadList as $k => $v) {
  5356. $file = array(
  5357. 'from' => $v['githubPath'],
  5358. 'to' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'] . $v['fileName']),
  5359. 'path' => str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $v['path'])
  5360. );
  5361. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins');
  5362. if (!$this->downloadFileToPath($file['from'], $file['to'], $file['path'])) {
  5363. $this->setLoggerChannel('Plugin Marketplace');
  5364. $this->logger->warning('Downloaded File Failed for: ' . $v['githubPath']);
  5365. $this->setAPIResponse('error', 'Plugin download failed', 500);
  5366. return false;
  5367. }
  5368. }
  5369. $this->updateInstalledPlugins('install', $plugin, $array);
  5370. $this->setAPIResponse('success', 'Plugin installed', 200, $array);
  5371. return true;
  5372. }
  5373. public function removePlugin($plugin)
  5374. {
  5375. $this->setLoggerChannel('Plugin Marketplace');
  5376. $plugin = $this->reverseCleanClassName($plugin);
  5377. $array = $this->getPluginsMarketplace();
  5378. $arrayLower = array_change_key_case($array);
  5379. if (!$array) {
  5380. $this->setAPIResponse('error', 'Could not access plugin marketplace', 409);
  5381. return false;
  5382. }
  5383. if (!$arrayLower[$plugin]) {
  5384. $this->setAPIResponse('error', 'Plugin does not exist in marketplace', 404);
  5385. return false;
  5386. } else {
  5387. $key = array_search($plugin, array_keys($arrayLower));
  5388. $plugin = array_keys($array)[$key];
  5389. }
  5390. $array = $array[$plugin];
  5391. $pluginDir = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $array['project_folder'] . DIRECTORY_SEPARATOR;
  5392. $dirExists = file_exists($pluginDir);
  5393. if ($dirExists) {
  5394. if (!$this->rrmdir($pluginDir)) {
  5395. $this->logger->info('Remove File Failed for: ' . $array['project_folder']);
  5396. return false;
  5397. }
  5398. } else {
  5399. $this->setAPIResponse('error', 'Plugin is not installed', 404);
  5400. return false;
  5401. }
  5402. $this->updateInstalledPlugins('uninstall', $plugin, $array);
  5403. $this->setAPIResponse('success', 'Plugin removed', 200, $array);
  5404. return true;
  5405. }
  5406. public function updateInstalledPlugins($action, $plugin, $pluginDetails)
  5407. {
  5408. if (!$action || !$plugin || !$pluginDetails) {
  5409. return false;
  5410. }
  5411. $config = $this->config['installedPlugins'];
  5412. $config = is_array($config) ? $config : [];
  5413. switch ($action) {
  5414. case 'install':
  5415. case 'update':
  5416. $update[$plugin] = [
  5417. 'name' => $plugin,
  5418. 'version' => $pluginDetails['version'],
  5419. 'repo' => $pluginDetails['repo']
  5420. ];
  5421. $config = array_merge($config, $update);
  5422. break;
  5423. default:
  5424. unset($config[$plugin]);
  5425. break;
  5426. }
  5427. $this->updateConfig(['installedPlugins' => $config]);
  5428. }
  5429. public function updateInstalledThemes($action, $theme, $themeDetails)
  5430. {
  5431. if (!$action || !$theme || !$themeDetails) {
  5432. return false;
  5433. }
  5434. $config = $this->config['installedThemes'];
  5435. $config = is_array($config) ? $config : [];
  5436. switch ($action) {
  5437. case 'install':
  5438. case 'update':
  5439. $update[$theme] = [
  5440. 'name' => $theme,
  5441. 'version' => $themeDetails['version'],
  5442. 'repo' => $themeDetails['repo'],
  5443. 'path' => 'data/themes/' . $themeDetails['project_folder']
  5444. ];
  5445. $config = array_merge($config, $update);
  5446. break;
  5447. default:
  5448. unset($config[$theme]);
  5449. break;
  5450. }
  5451. $this->updateConfig(['installedThemes' => $config]);
  5452. }
  5453. public function getThemesGithub()
  5454. {
  5455. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-themes/themes.json';
  5456. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5457. $response = Requests::get($url, array(), $options);
  5458. if ($response->success) {
  5459. return json_decode($response->body, true);
  5460. }
  5461. return false;
  5462. }
  5463. public function getPluginsGithub()
  5464. {
  5465. $url = 'https://raw.githubusercontent.com/causefx/Organizr/v2-plugins/plugins.json';
  5466. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5467. try {
  5468. $response = Requests::get($url, array(), $options);
  5469. if ($response->success) {
  5470. return json_decode($response->body, true);
  5471. }
  5472. } catch (Requests_Exception $e) {
  5473. return false;
  5474. }
  5475. return false;
  5476. }
  5477. public function getPluginsMarketplace()
  5478. {
  5479. $plugins = $this->getPluginsGithubCombined();
  5480. foreach ($plugins as $pluginName => $pluginDetails) {
  5481. $plugins[$pluginName]['installed'] = (isset($this->config['installedPlugins'][$pluginName]));
  5482. $plugins[$pluginName]['installed_version'] = $this->config['installedPlugins'][$pluginName]['version'] ?? null;
  5483. $plugins[$pluginName]['needs_update'] = ($plugins[$pluginName]['installed'] && ($plugins[$pluginName]['installed_version'] !== $plugins[$pluginName]['version']));
  5484. $plugins[$pluginName]['status'] = $this->getPluginStatus($plugins[$pluginName]);
  5485. }
  5486. return $plugins;
  5487. }
  5488. public function getThemesMarketplace()
  5489. {
  5490. $themes = $this->getThemesGithubCombined();
  5491. foreach ($themes as $themeName => $themeDetails) {
  5492. $themes[$themeName]['installed'] = (isset($this->config['installedThemes'][$themeName]));
  5493. $themes[$themeName]['installed_version'] = $this->config['installedThemes'][$themeName]['version'] ?? null;
  5494. $themes[$themeName]['needs_update'] = ($themes[$themeName]['installed'] && ($themes[$themeName]['installed_version'] !== $themes[$themeName]['version']));
  5495. $themes[$themeName]['status'] = $this->getPluginStatus($themes[$themeName]);
  5496. }
  5497. return $themes;
  5498. }
  5499. public function getThemesGithubCombined()
  5500. {
  5501. // Organizr Repo
  5502. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Themes')];
  5503. foreach (explode(',', $this->config['externalThemeMarketplaceRepos']) as $repo) {
  5504. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5505. }
  5506. $themes = [];
  5507. foreach ($urls as $repo) {
  5508. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5509. try {
  5510. $response = Requests::get($repo, array(), $options);
  5511. if ($response->success) {
  5512. $themes = array_merge($themes, json_decode($response->body, true));
  5513. } else {
  5514. $this->setLoggerChannel('Themes');
  5515. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5516. return false;
  5517. }
  5518. } catch (Requests_Exception $e) {
  5519. //return false;
  5520. }
  5521. }
  5522. return $themes;
  5523. }
  5524. public function getPluginStatus($pluginDetails)
  5525. {
  5526. if ($pluginDetails['needs_update']) {
  5527. return 'Update Available';
  5528. } elseif ($pluginDetails['installed']) {
  5529. return 'Up to date';
  5530. } else {
  5531. return 'Not Installed';
  5532. }
  5533. }
  5534. public function getPluginsGithubCombined()
  5535. {
  5536. // Organizr Repo
  5537. $urls = [$this->getMarketplaceJSONFromRepo('https://github.com/Organizr/Organizr-Plugins')];
  5538. foreach (explode(',', $this->config['externalPluginMarketplaceRepos']) as $repo) {
  5539. $urls[] = $this->getMarketplaceJSONFromRepo($repo);
  5540. }
  5541. $plugins = [];
  5542. foreach ($urls as $repo) {
  5543. $options = ($this->localURL($repo)) ? array('verify' => false) : array();
  5544. try {
  5545. $response = Requests::get($repo, array(), $options);
  5546. if ($response->success) {
  5547. $plugins = array_merge($plugins, json_decode($response->body, true));
  5548. } else {
  5549. $this->setLoggerChannel('Plugins');
  5550. $this->logger->warning('Getting Marketplace items from Github', $this->apiResponseFormatter($response->body));
  5551. return false;
  5552. }
  5553. } catch (Requests_Exception $e) {
  5554. //return false;
  5555. }
  5556. }
  5557. return $plugins;
  5558. }
  5559. public function getMarketplaceJSONFromRepo($url)
  5560. {
  5561. if (stripos($url, '.json') !== false) {
  5562. return $url;
  5563. } elseif (stripos($url, 'github.com') !== false) {
  5564. $repo = explode('https://github.com/', $url);
  5565. $newURL = 'https://api.github.com/repos/' . $repo[1] . '/contents';
  5566. $options = ($this->localURL($newURL)) ? array('verify' => false) : array();
  5567. try {
  5568. $response = Requests::get($newURL, $this->setGithubAccessToken(), $options);
  5569. if ($response->success) {
  5570. $jsonFiles = json_decode($response->body, true);
  5571. foreach ($jsonFiles as $file) {
  5572. if (stripos($file['name'], '.json') !== false) {
  5573. return $file['download_url'];
  5574. }
  5575. }
  5576. return false;
  5577. } else {
  5578. $this->setLoggerChannel('Plugins');
  5579. $this->logger->warning('Getting Marketplace JSON from Github', $this->apiResponseFormatter($response->body));
  5580. return false;
  5581. }
  5582. } catch (Requests_Exception $e) {
  5583. return false;
  5584. }
  5585. }
  5586. return false;
  5587. }
  5588. public function setGithubAccessToken()
  5589. {
  5590. return ($this->config['githubAccessToken'] !== '') ? ['Authorization' => 'token ' . $this->config['githubAccessToken']] : [];
  5591. }
  5592. public function formatGithubAccessToken()
  5593. {
  5594. $accessToken = $this->setGithubAccessToken();
  5595. if (count($accessToken) >= 1) {
  5596. return key($accessToken) . ': ' . $accessToken[key($accessToken)];
  5597. } else {
  5598. return '';
  5599. }
  5600. }
  5601. public function getOpenCollectiveBackers()
  5602. {
  5603. $url = 'https://opencollective.com/organizr/members/users.json?limit=100&offset=0';
  5604. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5605. try {
  5606. $response = Requests::get($url, array(), $options);
  5607. if ($response->success) {
  5608. $api = json_decode($response->body, true);
  5609. foreach ($api as $k => $backer) {
  5610. $api[$k] = array_merge($api[$k], ['sortName' => strtolower($backer['name'])]);
  5611. }
  5612. $this->setAPIResponse('success', '', 200, $api);
  5613. return $api;
  5614. }
  5615. } catch (Requests_Exception $e) {
  5616. $this->setResponse(500, $e->getMessage());
  5617. return false;
  5618. }
  5619. $this->setAPIResponse('error', 'Error connecting to Open Collective', 409);
  5620. return false;
  5621. }
  5622. public function getGithubSponsors()
  5623. {
  5624. $url = 'https://github.com/sponsors/causefx';
  5625. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5626. $response = Requests::get($url, array(), $options);
  5627. if ($response->success) {
  5628. $sponsors = [];
  5629. $dom = new PHPHtmlParser\Dom;
  5630. try {
  5631. $dom->loadStr($response->body);
  5632. $contents = $dom->find('#sponsors .clearfix div');
  5633. foreach ($contents as $content) {
  5634. $html = $content->innerHtml;
  5635. preg_match('/(@[a-zA-Z])\w+/', $html, $username);
  5636. preg_match('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»""\'\']))/', $html, $image);
  5637. if (isset($image[0]) && isset($username[0])) {
  5638. $sponsors[] = [
  5639. 'name' => str_replace('@', '', $username[0]),
  5640. 'sortName' => str_replace('@', '', strtolower($username[0])),
  5641. 'image' => str_replace('s=60', 's=200', $image[0]),
  5642. 'isActive' => true,
  5643. 'type' => 'USER',
  5644. 'role' => 'BACKER'
  5645. ];
  5646. }
  5647. }
  5648. $this->setAPIResponse('success', '', 200, $sponsors);
  5649. return $sponsors;
  5650. } catch (\PHPHtmlParser\Exceptions\ChildNotFoundException | \PHPHtmlParser\Exceptions\CircularException | \PHPHtmlParser\Exceptions\LogicalException | \PHPHtmlParser\Exceptions\StrictException | \PHPHtmlParser\Exceptions\ContentLengthException | \PHPHtmlParser\Exceptions\NotLoadedException $e) {
  5651. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5652. return false;
  5653. }
  5654. }
  5655. $this->setAPIResponse('error', 'Error connecting to Github', 409);
  5656. return false;
  5657. }
  5658. public function getAllSponsors()
  5659. {
  5660. $sponsors = [];
  5661. $list = [
  5662. 'openCollective' => $this->getOpenCollectiveBackers(),
  5663. 'github' => $this->getGithubSponsors()
  5664. ];
  5665. foreach ($list as $k => $sponsor) {
  5666. if ($sponsor) {
  5667. $sponsors = array_merge($sponsor, $sponsors);
  5668. }
  5669. }
  5670. if ($sponsors) {
  5671. usort($sponsors, function ($a, $b) {
  5672. return $a['sortName'] <=> $b['sortName'];
  5673. });
  5674. }
  5675. $this->setAPIResponse('success', '', 200, $sponsors);
  5676. return $sponsors;
  5677. }
  5678. public function getOrganizrSmtpFromAPI()
  5679. {
  5680. $url = 'https://api.organizr.app/?cmd=smtp';
  5681. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  5682. try {
  5683. $response = Requests::get($url, array(), $options);
  5684. if ($response->success) {
  5685. return json_decode($response->body, true);
  5686. }
  5687. } catch (Requests_Exception $e) {
  5688. $this->setResponse(500, $e->getMessage());
  5689. return false;
  5690. }
  5691. return false;
  5692. }
  5693. public function saveOrganizrSmtpFromAPI()
  5694. {
  5695. $api = $this->getOrganizrSmtpFromAPI();
  5696. if ($api) {
  5697. $this->updateConfigItems($api['response']['data']);
  5698. $this->setAPIResponse(null, 'SMTP activated with Organizr SMTP account');
  5699. return true;
  5700. } else {
  5701. return false;
  5702. }
  5703. }
  5704. public function guestHash($start, $end)
  5705. {
  5706. $ip = $this->userIP();
  5707. $ip = md5($ip);
  5708. return substr($ip, $start, $end);
  5709. }
  5710. public function rrmdir($dir)
  5711. {
  5712. ini_set('max_execution_time', 0);
  5713. set_time_limit(0);
  5714. if (is_dir($dir)) {
  5715. $files = scandir($dir);
  5716. foreach ($files as $file) {
  5717. if ($file != "." && $file != "..") {
  5718. $this->rrmdir("$dir/$file");
  5719. }
  5720. }
  5721. rmdir($dir);
  5722. } elseif (file_exists($dir)) {
  5723. unlink($dir);
  5724. }
  5725. return true;
  5726. }
  5727. public function rcopy($src, $dst)
  5728. {
  5729. ini_set('max_execution_time', 0);
  5730. set_time_limit(0);
  5731. $src = $this->cleanPath($src);
  5732. $dst = $this->cleanPath($dst);
  5733. if (is_dir($src)) {
  5734. if (!file_exists($dst)) : mkdir($dst);
  5735. endif;
  5736. $files = scandir($src);
  5737. foreach ($files as $file) {
  5738. if ($file != "." && $file != "..") {
  5739. $this->rcopy("$src/$file", "$dst/$file");
  5740. }
  5741. }
  5742. } elseif (file_exists($src)) {
  5743. copy($src, $dst);
  5744. }
  5745. return true;
  5746. }
  5747. public function unzipFile($zipFile)
  5748. {
  5749. ini_set('max_execution_time', 0);
  5750. set_time_limit(0);
  5751. $zip = new ZipArchive;
  5752. $extractPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade/";
  5753. $this->setLoggerChannel('File Management');
  5754. if ($zip->open($extractPath . $zipFile) != "true") {
  5755. $this->logger->warning('organizr could not unzip upgrade.zip');
  5756. } else {
  5757. $this->logger->debug('organizr unzipped upgrade.zip');
  5758. }
  5759. /* Extract Zip File */
  5760. $zip->extractTo($extractPath);
  5761. $zip->close();
  5762. return true;
  5763. }
  5764. public function downloadFile($url, $path)
  5765. {
  5766. ini_set('max_execution_time', 0);
  5767. set_time_limit(0);
  5768. $folderPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . "upgrade" . DIRECTORY_SEPARATOR;
  5769. $this->setLoggerChannel('File Management');
  5770. if (!file_exists($folderPath)) {
  5771. if (@!mkdir($folderPath)) {
  5772. $this->logger->warning('Folder Creation failed');
  5773. return false;
  5774. }
  5775. }
  5776. $newfname = $folderPath . $path;
  5777. $context = stream_context_create(
  5778. array(
  5779. 'ssl' => array(
  5780. 'verify_peer' => true,
  5781. 'cafile' => $this->getCert()
  5782. )
  5783. )
  5784. );
  5785. $file = fopen($url, 'rb', false, $context);
  5786. if ($file) {
  5787. $newf = fopen($newfname, 'wb');
  5788. if ($newf) {
  5789. while (!feof($file)) {
  5790. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  5791. }
  5792. }
  5793. } else {
  5794. $this->logger->warning('Organizr could not download ' . $url);
  5795. return false;
  5796. }
  5797. if ($file) {
  5798. fclose($file);
  5799. $this->logger->debug('Organizr finished downloading the github zip file');
  5800. } else {
  5801. $this->logger->warning('Organizr could not download the github zip file');
  5802. return false;
  5803. }
  5804. if ($newf) {
  5805. fclose($newf);
  5806. $this->logger->debug('Organizr created upgrade zip file from github zip file');
  5807. } else {
  5808. $this->logger->warning('Organizr could not create upgrade zip file from github zip file');
  5809. return false;
  5810. }
  5811. return true;
  5812. }
  5813. public function downloadFileToPath($from, $to, $path)
  5814. {
  5815. if (((stripos($from, 'api.github.com') !== false) || (stripos($from, 'raw.githubusercontent.com') !== false)) && $this->config['githubAccessToken'] !== '') {
  5816. $context = stream_context_create(
  5817. array(
  5818. 'ssl' => array(
  5819. 'verify_peer' => false,
  5820. 'cafile' => $this->getCert()
  5821. ),
  5822. 'http' => array(
  5823. 'method' => 'GET',
  5824. 'header' => $this->formatGithubAccessToken()
  5825. )
  5826. )
  5827. );
  5828. } else {
  5829. $context = stream_context_create([]);
  5830. }
  5831. ini_set('max_execution_time', 0);
  5832. set_time_limit(0);
  5833. $this->makeDir($path);
  5834. $file = fopen($from, 'rb', false, $context);
  5835. if ($file) {
  5836. $newf = fopen($to, 'wb', false, $context);
  5837. if ($newf) {
  5838. while (!feof($file)) {
  5839. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  5840. }
  5841. }
  5842. } else {
  5843. $this->logger->warning('Organizr could not download file');
  5844. }
  5845. if ($file) {
  5846. fclose($file);
  5847. $this->logger->debug('Organizr finished downloading the file');
  5848. } else {
  5849. $this->logger->warning('Organizr could not download file');
  5850. }
  5851. if ($newf) {
  5852. fclose($newf);
  5853. $this->logger->debug('Organizr saved and/or moved the file');
  5854. } else {
  5855. $this->logger->warning('Organizr could not save and/or move the file');
  5856. }
  5857. return true;
  5858. }
  5859. public function getAllUsers($includeGroups = false)
  5860. {
  5861. $response = [
  5862. array(
  5863. 'function' => 'fetchAll',
  5864. 'query' => array(
  5865. 'SELECT * FROM users'
  5866. ),
  5867. 'key' => 'users'
  5868. ),
  5869. ];
  5870. $groups = array(
  5871. 'function' => 'fetchAll',
  5872. 'query' => array(
  5873. 'SELECT * FROM groups ORDER BY group_id ASC'
  5874. ),
  5875. 'key' => 'groups'
  5876. );
  5877. $addGroups = (isset($_GET['includeGroups']) || $includeGroups) ?? false;
  5878. if ($addGroups) {
  5879. array_push($response, $groups);
  5880. }
  5881. return $this->processQueries($response);
  5882. }
  5883. public function getAllGroups()
  5884. {
  5885. $response = [
  5886. array(
  5887. 'function' => 'fetchAll',
  5888. 'query' => array(
  5889. 'SELECT * FROM groups ORDER BY group_id ASC'
  5890. ),
  5891. 'key' => 'groups'
  5892. ),
  5893. ];
  5894. $users = array(
  5895. 'function' => 'fetchAll',
  5896. 'query' => array(
  5897. 'SELECT * FROM users'
  5898. ),
  5899. 'key' => 'users'
  5900. );
  5901. $addUsers = (isset($_GET['includeUsers'])) ?? false;
  5902. if ($addUsers) {
  5903. array_push($response, $users);
  5904. }
  5905. return $this->processQueries($response);
  5906. }
  5907. public function importUsers($array)
  5908. {
  5909. $imported = 0;
  5910. if ($array) {
  5911. foreach ($array as $user) {
  5912. $password = $this->random_ascii_string(30);
  5913. if ($user['username'] !== '' && $user['email'] !== '' && $password !== '') {
  5914. $newUser = $this->createUser($user['username'], $password, $user['email']);
  5915. if (!$newUser) {
  5916. $this->setLoggerChannel('User Management');
  5917. $this->logger->warning('An error occurred during user import');
  5918. } else {
  5919. $imported++;
  5920. }
  5921. }
  5922. }
  5923. }
  5924. $this->setAPIResponse('success', 'Imported ' . $imported . ' users', 200);
  5925. return true;
  5926. }
  5927. public function importUsersType($type)
  5928. {
  5929. if ($type !== '') {
  5930. switch ($type) {
  5931. case 'plex':
  5932. return $this->importUsers($this->allPlexUsers(true));
  5933. case 'jellyfin':
  5934. return $this->importUsers($this->allJellyfinUsers(true));
  5935. case 'emby':
  5936. return $this->importUsers($this->allEmbyUsers(true));
  5937. default:
  5938. return false;
  5939. }
  5940. }
  5941. return false;
  5942. }
  5943. public function allPlexUsers($newOnly = false, $friendsOnly = false)
  5944. {
  5945. try {
  5946. if (!empty($this->config['plexToken'])) {
  5947. $url = 'https://plex.tv/api/users';
  5948. $headers = array(
  5949. 'X-Plex-Token' => $this->config['plexToken'],
  5950. );
  5951. $response = Requests::get($url, $headers);
  5952. if ($response->success) {
  5953. libxml_use_internal_errors(true);
  5954. $userXML = simplexml_load_string($response->body);
  5955. if (is_array($userXML) || is_object($userXML)) {
  5956. $results = array();
  5957. foreach ($userXML as $child) {
  5958. if (((string)$child['restricted'] == '0')) {
  5959. if ($newOnly) {
  5960. $taken = $this->usernameTaken((string)$child['username'], (string)$child['email']);
  5961. if (!$taken) {
  5962. $results[] = array(
  5963. 'username' => (string)$child['username'],
  5964. 'email' => (string)$child['email'],
  5965. 'id' => (string)$child['id'],
  5966. );
  5967. }
  5968. } elseif ($friendsOnly) {
  5969. $machineMatches = false;
  5970. foreach ($child->Server as $server) {
  5971. if ((string)$server['machineIdentifier'] == $this->config['plexID']) {
  5972. $machineMatches = true;
  5973. $shareId = $server['id'];
  5974. }
  5975. }
  5976. if ($machineMatches) {
  5977. $results[] = array(
  5978. 'username' => (string)$child['username'],
  5979. 'email' => (string)$child['email'],
  5980. 'id' => (string)$child['id'],
  5981. 'shareId' => (string)$shareId
  5982. );
  5983. }
  5984. } else {
  5985. $results[] = array(
  5986. 'username' => (string)$child['username'],
  5987. 'email' => (string)$child['email'],
  5988. 'id' => (string)$child['id'],
  5989. );
  5990. }
  5991. }
  5992. }
  5993. return $results;
  5994. }
  5995. }
  5996. }
  5997. return false;
  5998. } catch (Requests_Exception $e) {
  5999. $this->setLoggerChannel('User Management');
  6000. $this->logger->error($e);
  6001. }
  6002. return false;
  6003. }
  6004. public function allJellyfinUsers($newOnly = false)
  6005. {
  6006. try {
  6007. if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
  6008. $url = $this->qualifyURL($this->config['jellyfinURL']) . '/Users?api_key=' . $this->config['jellyfinToken'];
  6009. $headers = array();
  6010. $response = Requests::get($url, $headers);
  6011. if ($response->success) {
  6012. $users = json_decode($response->body, true);
  6013. if (is_array($users) || is_object($users)) {
  6014. $results = array();
  6015. foreach ($users as $child) {
  6016. // Jellyfin doesn't list emails for some reason
  6017. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6018. if ($newOnly) {
  6019. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6020. if (!$taken) {
  6021. $results[] = array(
  6022. 'username' => (string)$child['Name'],
  6023. 'email' => $email
  6024. );
  6025. }
  6026. } else {
  6027. $results[] = array(
  6028. 'username' => (string)$child['Name'],
  6029. 'email' => $email,
  6030. );
  6031. }
  6032. }
  6033. return $results;
  6034. }
  6035. }
  6036. }
  6037. return false;
  6038. } catch (Requests_Exception $e) {
  6039. $this->setLoggerChannel('User Management');
  6040. $this->logger->error($e);
  6041. }
  6042. return false;
  6043. }
  6044. public function allEmbyUsers($newOnly = false)
  6045. {
  6046. try {
  6047. if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
  6048. $url = $this->qualifyURL($this->config['embyURL']) . '/Users?api_key=' . $this->config['embyToken'];
  6049. $headers = array();
  6050. $response = Requests::get($url, $headers);
  6051. if ($response->success) {
  6052. $users = json_decode($response->body, true);
  6053. if (is_array($users) || is_object($users)) {
  6054. $results = array();
  6055. foreach ($users as $child) {
  6056. // Emby doesn't list emails for some reason
  6057. $email = $this->random_ascii_string(10) . '@placeholder.eml';
  6058. if ($newOnly) {
  6059. $taken = $this->usernameTaken((string)$child['Name'], $email);
  6060. if (!$taken) {
  6061. $results[] = array(
  6062. 'username' => (string)$child['Name'],
  6063. 'email' => $email
  6064. );
  6065. }
  6066. } else {
  6067. $results[] = array(
  6068. 'username' => (string)$child['Name'],
  6069. 'email' => $email,
  6070. );
  6071. }
  6072. }
  6073. return $results;
  6074. }
  6075. }
  6076. }
  6077. return false;
  6078. } catch (Requests_Exception $e) {
  6079. $this->setLoggerChannel('User Management');
  6080. $this->logger->error($e);
  6081. }
  6082. return false;
  6083. }
  6084. public function validateEmail($email)
  6085. {
  6086. return filter_var(trim($email), FILTER_VALIDATE_EMAIL);
  6087. }
  6088. public function sanitizeEmail($email)
  6089. {
  6090. return filter_var(trim($email), FILTER_SANITIZE_EMAIL);
  6091. }
  6092. public function sanitizeUserString($string)
  6093. {
  6094. return htmlspecialchars(trim($string));
  6095. }
  6096. public function updateUser($id, $array)
  6097. {
  6098. if (!$id) {
  6099. $this->setAPIResponse('error', 'Id was not supplied', 422);
  6100. return false;
  6101. }
  6102. if ((int)$id !== $this->user['userID']) {
  6103. if (!$this->qualifyRequest('1', true)) {
  6104. return false;
  6105. }
  6106. }
  6107. $user = $this->getUserById($id);
  6108. if ($user) {
  6109. $array = $this->checkKeys($user, $array);
  6110. } else {
  6111. $this->setAPIResponse('error', 'User was not found', 404);
  6112. return false;
  6113. }
  6114. if ($user['group_id'] == 0 && $this->user['groupID'] !== 0) {
  6115. $this->setAPIResponse('error', 'Cannot update admin unless you are admin', 401);
  6116. return false;
  6117. }
  6118. if (array_key_exists('username', $array)) {
  6119. if ($array['username'] == '') {
  6120. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6121. return false;
  6122. }
  6123. $array['username'] = $this->sanitizeUserString($array['username']);
  6124. if ($this->usernameTaken($array['username'], $array['username'], $id)) {
  6125. $this->setAPIResponse('error', 'Username: ' . $array['username'] . ' is already taken', 409);
  6126. return false;
  6127. }
  6128. }
  6129. if (array_key_exists('email', $array)) {
  6130. if ($array['email'] == '') {
  6131. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6132. return false;
  6133. }
  6134. if ($this->validateEmail($array['email'])) {
  6135. $array['email'] = $this->sanitizeEmail($array['email']);
  6136. } else {
  6137. $this->setResponse(409, 'Email is not a valid email', ['email' => $array['email']]);
  6138. return false;
  6139. }
  6140. if ($this->usernameTaken($array['email'], $array['email'], $id)) {
  6141. $this->setAPIResponse('error', 'Email: ' . $array['email'] . ' is already taken', 409);
  6142. return false;
  6143. }
  6144. }
  6145. if (array_key_exists('group_id', $array)) {
  6146. if ($array['group_id'] == '') {
  6147. $array['group_id'] = 0;
  6148. //$this->setAPIResponse('error', 'group_id was set but empty', 409);
  6149. //return false;
  6150. }
  6151. if (!$this->qualifyRequest('1', false)) {
  6152. $this->setAPIResponse('error', 'Cannot change your own group_id', 401);
  6153. return false;
  6154. }
  6155. if (($id == $this->user['userID']) && $this->user['groupID'] == 0) {
  6156. $array['group_id'] = 0;
  6157. }
  6158. if (($id == $this->user['userID']) && ($array['group_id'] == 0 && $this->user['groupID'] !== 0)) {
  6159. $this->setAPIResponse('error', 'Only admins can make others admins', 401);
  6160. return false;
  6161. }
  6162. $array['group'] = $this->getGroupByGroupId($array['group_id'])['group'];
  6163. if (!$array['group']) {
  6164. $this->setAPIResponse('error', 'group_id does not exist', 404);
  6165. return false;
  6166. }
  6167. }
  6168. if (array_key_exists('locked', $array)) {
  6169. //$this->setAPIResponse('error', 'Cannot use endpoint to unlock or lock user - please use /users/{id}/lock', 409);
  6170. //return false;
  6171. }
  6172. if (array_key_exists('password', $array)) {
  6173. if ($array['password'] == '') {
  6174. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6175. return false;
  6176. }
  6177. $array['password'] = password_hash($array['password'], PASSWORD_BCRYPT);
  6178. }
  6179. if (array_key_exists('image', $array)) {
  6180. $array['image'] = $this->sanitizeUserString($array['image']);
  6181. }
  6182. if (array_key_exists('register_date', $array)) {
  6183. $this->setAPIResponse('error', 'Cannot update register date', 409);
  6184. return false;
  6185. }
  6186. $response = [
  6187. array(
  6188. 'function' => 'query',
  6189. 'query' => array(
  6190. 'UPDATE users SET',
  6191. $array,
  6192. 'WHERE id = ?',
  6193. $id
  6194. )
  6195. ),
  6196. ];
  6197. $this->setAPIResponse(null, 'User info updated');
  6198. $this->setLoggerChannel('User Management');
  6199. $this->logger->info('Updated User Info for [' . $user['username'] . ']');
  6200. return $this->processQueries($response);
  6201. }
  6202. public function deleteUser($id)
  6203. {
  6204. $response = [
  6205. array(
  6206. 'function' => 'query',
  6207. 'query' => array(
  6208. 'DELETE FROM users WHERE id = ?',
  6209. $id
  6210. )
  6211. ),
  6212. ];
  6213. $userInfo = $this->getUserById($id);
  6214. if ($id == $this->user['userID']) {
  6215. $this->setAPIResponse('error', 'Cannot delete your own user', 409);
  6216. return false;
  6217. }
  6218. if ($userInfo) {
  6219. $this->setLoggerChannel('User Management');
  6220. $this->logger->info('Deleted User [' . $userInfo['username'] . ']');
  6221. $this->setAPIResponse('success', 'User deleted', 204);
  6222. return $this->processQueries($response);
  6223. } else {
  6224. $this->setAPIResponse('error', 'id not found', 404);
  6225. return false;
  6226. }
  6227. }
  6228. public function addUser($array)
  6229. {
  6230. $username = $array['username'] ?? null;
  6231. $password = $array['password'] ?? null;
  6232. $email = $array['email'] ?? null;
  6233. if (!$username) {
  6234. $this->setAPIResponse('error', 'Username was not supplied', 409);
  6235. return false;
  6236. }
  6237. if ($username == '') {
  6238. $this->setResponse(409, 'Username was set but empty');
  6239. return false;
  6240. } else {
  6241. $username = $this->sanitizeUserString($username);
  6242. }
  6243. if (!$password) {
  6244. $this->setAPIResponse('error', 'Password was not supplied', 409);
  6245. return false;
  6246. }
  6247. if (!$email) {
  6248. $this->setAPIResponse('error', 'Email was set not supplied', 409);
  6249. return false;
  6250. }
  6251. if ($email == '') {
  6252. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6253. return false;
  6254. }
  6255. if ($this->validateEmail($email)) {
  6256. $email = $this->sanitizeEmail($email);
  6257. } else {
  6258. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6259. return false;
  6260. }
  6261. $this->setLoggerChannel('User Management');
  6262. if ($this->createUser($username, $password, $email)) {
  6263. $this->logger->info('Account created for [' . $username . ']');
  6264. return true;
  6265. } else {
  6266. $this->logger->warning('An error occurred');
  6267. return false;
  6268. }
  6269. }
  6270. public function createUser($username, $password, $email = null)
  6271. {
  6272. $username = $username ?? null;
  6273. $password = $password ?? null;
  6274. $email = ($email) ? $email : $this->random_ascii_string(10) . '@placeholder.eml';
  6275. if (!$username) {
  6276. $this->setAPIResponse('error', 'Username was set but empty', 409);
  6277. return false;
  6278. }
  6279. $username = $this->sanitizeUserString($username);
  6280. if (!$password) {
  6281. $this->setAPIResponse('error', 'Password was set but empty', 409);
  6282. return false;
  6283. }
  6284. if ($email == '') {
  6285. $this->setAPIResponse('error', 'Email was set but empty', 409);
  6286. return false;
  6287. }
  6288. if ($this->validateEmail($email)) {
  6289. $email = $this->sanitizeEmail($email);
  6290. } else {
  6291. $this->setResponse(409, 'Email is not a valid email', ['email' => $email]);
  6292. return false;
  6293. }
  6294. if ($this->usernameTaken($username, $email)) {
  6295. $this->setAPIResponse('error', 'Username: ' . $username . ' or Email: ' . $email . ' is already taken', 409);
  6296. return false;
  6297. }
  6298. $defaults = $this->getDefaultGroup();
  6299. $userInfo = [
  6300. 'username' => $username,
  6301. 'password' => password_hash($password, PASSWORD_BCRYPT),
  6302. 'email' => $email,
  6303. 'group' => $defaults['group'],
  6304. 'group_id' => $defaults['group_id'],
  6305. 'image' => $this->gravatar($email),
  6306. 'register_date' => gmdate('Y-m-d H:i:s'),
  6307. ];
  6308. $response = [
  6309. array(
  6310. 'function' => 'query',
  6311. 'query' => array(
  6312. 'INSERT INTO [users]',
  6313. $userInfo
  6314. )
  6315. ),
  6316. ];
  6317. $this->setAPIResponse('success', 'User created', 200);
  6318. return $this->processQueries($response);
  6319. }
  6320. public function updateGroup($id, $array)
  6321. {
  6322. if (!$id || $id == '') {
  6323. $this->setAPIResponse('error', 'id was not set', 422);
  6324. return null;
  6325. }
  6326. if (!$array) {
  6327. $this->setAPIResponse('error', 'no data was sent', 422);
  6328. return null;
  6329. }
  6330. $groupInfo = $this->getGroupById($id);
  6331. if ($groupInfo) {
  6332. $array = $this->checkKeys($groupInfo, $array);
  6333. } else {
  6334. $this->setAPIResponse('error', 'No category info found', 404);
  6335. return false;
  6336. }
  6337. if (array_key_exists('group_id', $array)) {
  6338. $this->setAPIResponse('error', 'Cannot change group_id', 409);
  6339. return false;
  6340. }
  6341. if (array_key_exists('group', $array)) {
  6342. if ($array['group'] == '') {
  6343. $this->setAPIResponse('error', 'Group was set but empty', 409);
  6344. return false;
  6345. }
  6346. $array['group'] = $this->sanitizeUserString($array['group']);
  6347. if ($this->isGroupNameTaken($array['group'], $id)) {
  6348. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6349. return false;
  6350. }
  6351. }
  6352. if (array_key_exists('image', $array)) {
  6353. if ($array['image'] == '') {
  6354. $this->setAPIResponse('error', 'Image was set but empty', 409);
  6355. return false;
  6356. }
  6357. }
  6358. if (array_key_exists('default', $array)) {
  6359. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6360. $this->setAPIResponse('error', 'Setting ' . $groupInfo['group'] . ' as default group is not allowed', 409);
  6361. return false;
  6362. }
  6363. if ($array['default']) {
  6364. $this->clearGroupDefault();
  6365. $array['default'] = 1;
  6366. }
  6367. }
  6368. $response = [
  6369. array(
  6370. 'function' => 'query',
  6371. 'query' => array(
  6372. 'UPDATE groups SET',
  6373. $array,
  6374. 'WHERE id = ?',
  6375. $id
  6376. )
  6377. ),
  6378. ];
  6379. $this->setAPIResponse(null, 'Group info updated');
  6380. $this->setLoggerChannel('Group Management');
  6381. $this->logger->info('Edited Group Info for [' . $groupInfo['group'] . ']');
  6382. return $this->processQueries($response);
  6383. }
  6384. public function deleteGroup($id)
  6385. {
  6386. $response = [
  6387. array(
  6388. 'function' => 'query',
  6389. 'query' => array(
  6390. 'DELETE FROM groups WHERE id = ?',
  6391. $id
  6392. )
  6393. ),
  6394. ];
  6395. $groupInfo = $this->getGroupById($id);
  6396. if ($groupInfo['group_id'] == 0 || $groupInfo['group_id'] == 999) {
  6397. $this->setAPIResponse('error', 'Cannot delete group: ' . $groupInfo['group'] . ' as it is not allowed', 409);
  6398. return false;
  6399. }
  6400. if ($this->getGroupUserCountById($id) >= 1) {
  6401. $this->setAPIResponse('error', 'Cannot delete group as group still has users assigned to it', 409);
  6402. return false;
  6403. }
  6404. if ($groupInfo) {
  6405. $this->setLoggerChannel('Group Management');
  6406. $this->logger->info('Deleted Group [' . $groupInfo['group'] . ']');
  6407. $this->setAPIResponse('success', 'Group deleted', 204);
  6408. return $this->processQueries($response);
  6409. } else {
  6410. $this->setAPIResponse('error', 'id not found', 404);
  6411. return false;
  6412. }
  6413. }
  6414. public function addGroup($array)
  6415. {
  6416. if (!$array) {
  6417. $this->setAPIResponse('error', 'no data was sent', 422);
  6418. return null;
  6419. }
  6420. $array = $this->checkKeys($this->getTableColumnsFormatted('groups'), $array);
  6421. $array['default'] = ($array['default']) ?? 0;
  6422. $array['group_id'] = $this->getNextGroupOrder() + 1;
  6423. if (array_key_exists('group', $array)) {
  6424. $array['group'] = $this->sanitizeUserString($array['group']);
  6425. if ($this->isGroupNameTaken($array['group'])) {
  6426. $this->setAPIResponse('error', 'Group name: ' . $array['group'] . ' is already taken', 409);
  6427. return false;
  6428. }
  6429. } else {
  6430. $this->setAPIResponse('error', 'Group name was not supplied', 422);
  6431. return false;
  6432. }
  6433. if (array_key_exists('image', $array)) {
  6434. if ($array['image'] == '') {
  6435. $this->setAPIResponse('error', 'Group image cannot be empty', 422);
  6436. return false;
  6437. }
  6438. } else {
  6439. $this->setAPIResponse('error', 'Group image was not supplied', 422);
  6440. return false;
  6441. }
  6442. $response = [
  6443. array(
  6444. 'function' => 'query',
  6445. 'query' => array(
  6446. 'INSERT INTO [groups]',
  6447. $array
  6448. )
  6449. ),
  6450. ];
  6451. $this->setAPIResponse(null, 'Group added');
  6452. $this->setLoggerChannel('Group Management');
  6453. $this->logger->info('Added Group for [' . $array['group'] . ']');
  6454. return $this->processQueries($response);
  6455. }
  6456. public function userList($type = null)
  6457. {
  6458. switch ($type) {
  6459. case 'plex':
  6460. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  6461. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'] . '/shared_servers';
  6462. try {
  6463. $headers = array(
  6464. "Accept" => "application/json",
  6465. "X-Plex-Token" => $this->config['plexToken']
  6466. );
  6467. $response = Requests::get($url, $headers, array());
  6468. libxml_use_internal_errors(true);
  6469. if ($response->success) {
  6470. $libraryList = array();
  6471. $plex = simplexml_load_string($response->body);
  6472. foreach ($plex->SharedServer as $child) {
  6473. if (!empty($child['username'])) {
  6474. $username = (string)strtolower($child['username']);
  6475. $email = (string)strtolower($child['email']);
  6476. $libraryList['users'][$username] = (string)$child['id'];
  6477. $libraryList['emails'][$email] = (string)$child['id'];
  6478. $libraryList['both'][$username] = $email;
  6479. }
  6480. }
  6481. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  6482. return $libraryList;
  6483. }
  6484. } catch (Requests_Exception $e) {
  6485. $this->setLoggerChannel('User Management');
  6486. $this->logger->error($e);
  6487. }
  6488. }
  6489. break;
  6490. default:
  6491. # code...
  6492. break;
  6493. }
  6494. return false;
  6495. }
  6496. public function encrypt($password, $key = null)
  6497. {
  6498. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6499. return openssl_encrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6500. }
  6501. public function decrypt($password, $key = null)
  6502. {
  6503. if (empty($password)) {
  6504. return '';
  6505. }
  6506. $key = ($key) ? $key : ((isset($this->config['organizrHash'])) ? $this->config['organizrHash'] : null);
  6507. return openssl_decrypt($password, 'AES-256-CBC', $key, 0, $this->fillString($key, 16));
  6508. }
  6509. public function checkValidCert($file)
  6510. {
  6511. if (file_exists($file)) {
  6512. return filesize($file) > 0;
  6513. } else {
  6514. return false;
  6515. }
  6516. }
  6517. public function getCert()
  6518. {
  6519. $url = 'http://curl.haxx.se/ca/cacert.pem';
  6520. $file = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  6521. $file2 = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  6522. $useCert = ($this->checkValidCert($file)) ? $file : $file2;
  6523. if ($this->config['selfSignedCert'] !== '') {
  6524. if (file_exists($this->config['selfSignedCert'])) {
  6525. return $this->config['selfSignedCert'];
  6526. }
  6527. }
  6528. $context = stream_context_create(
  6529. array(
  6530. 'ssl' => array(
  6531. 'verify_peer' => true,
  6532. 'cafile' => $useCert
  6533. )
  6534. )
  6535. );
  6536. if (!$this->checkValidCert($file) || (file_exists($file) && time() - 2592000 > filemtime($file))) {
  6537. file_put_contents($file, fopen($url, 'r', false, $context));
  6538. }
  6539. return ($this->checkValidCert($file)) ? $file : $file2;
  6540. }
  6541. public function hasCustomCert()
  6542. {
  6543. return file_exists($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem');
  6544. }
  6545. public function getCustomCert()
  6546. {
  6547. return ($this->hasCustomCert()) ? $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'custom.pem' : false;
  6548. }
  6549. public function uploadCert()
  6550. {
  6551. $filesCheck = array_filter($_FILES);
  6552. if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'cert')) {
  6553. ini_set('upload_max_filesize', '10M');
  6554. ini_set('post_max_size', '10M');
  6555. $tempFile = $_FILES['file']['tmp_name'];
  6556. $targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR;
  6557. $targetFile = $targetPath . 'custom.pem';
  6558. $this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
  6559. $this->makeDir($this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cert');
  6560. return move_uploaded_file($tempFile, $targetFile);
  6561. } else {
  6562. $this->setAPIResponse('error', pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' is not approved to be uploaded', 403);
  6563. return false;
  6564. }
  6565. }
  6566. public function createCronFile()
  6567. {
  6568. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6569. file_put_contents($file, time());
  6570. }
  6571. public function checkCronFile()
  6572. {
  6573. $file = $this->root . DIRECTORY_SEPARATOR . 'Cron.txt';
  6574. return file_exists($file) && time() - 120 < filemtime($file);
  6575. }
  6576. public function plexJoinAPI($array)
  6577. {
  6578. $username = ($array['username']) ?? null;
  6579. $email = ($array['email']) ?? null;
  6580. $password = ($array['password']) ?? null;
  6581. if (!$username) {
  6582. $this->setAPIResponse('error', 'Username not supplied', 409);
  6583. return false;
  6584. }
  6585. if (!$email) {
  6586. $this->setAPIResponse('error', 'Email not supplied', 409);
  6587. return false;
  6588. }
  6589. if (!$password) {
  6590. $this->setAPIResponse('error', 'Password not supplied', 409);
  6591. return false;
  6592. }
  6593. return $this->plexJoin($username, $email, $password);
  6594. }
  6595. public function plexJoin($username, $email, $password)
  6596. {
  6597. try {
  6598. $url = 'https://plex.tv/api/v2/users';
  6599. $headers = array(
  6600. 'Accept' => 'application/json',
  6601. 'Content-Type' => 'application/x-www-form-urlencoded',
  6602. 'X-Plex-Product' => 'Organizr',
  6603. 'X-Plex-Version' => '2.0',
  6604. 'X-Plex-Client-Identifier' => $this->config['uuid'],
  6605. );
  6606. $data = array(
  6607. 'email' => $email,
  6608. 'username' => $username,
  6609. 'password' => $password,
  6610. );
  6611. $response = Requests::post($url, $headers, $data, array());
  6612. $json = json_decode($response->body, true);
  6613. $errors = !empty($json['errors']);
  6614. $success = empty($json['errors']);
  6615. //Use This for later
  6616. $errorMessage = '';
  6617. if ($errors) {
  6618. foreach ($json['errors'] as $error) {
  6619. if (isset($error['message']) && isset($error['field'])) {
  6620. $errorMessage .= "[Plex.tv Error: " . $error['message'] . " for field: (" . $error['field'] . ")]";
  6621. }
  6622. }
  6623. }
  6624. $msg = (!empty($success) && empty($errors)) ? 'User has joined Plex' : $errorMessage;
  6625. $status = (!empty($success) && empty($errors)) ? 'success' : 'error';
  6626. $code = (!empty($success) && empty($errors)) ? 200 : 422;
  6627. $this->setAPIResponse($status, $msg, $code);
  6628. return (!empty($success) && empty($errors));
  6629. } catch (Requests_Exception $e) {
  6630. $this->setLoggerChannel('User Management');
  6631. $this->logger->error($e);
  6632. $this->setAPIResponse('error', 'An Error Occurred', 409);
  6633. return false;
  6634. }
  6635. return false;
  6636. }
  6637. public function lockCurrentUser()
  6638. {
  6639. if ($this->user['userID'] == '999') {
  6640. $this->setAPIResponse('error', 'Locking not allowed on Guest users', 409);
  6641. return false;
  6642. }
  6643. return $this->lockUser($this->user['userID']);
  6644. }
  6645. public function lockUser($id)
  6646. {
  6647. $user = $this->getUserById($id);
  6648. if (!$user) {
  6649. $this->setAPIResponse('error', 'User not found', 404);
  6650. return false;
  6651. }
  6652. $response = [
  6653. array(
  6654. 'function' => 'query',
  6655. 'query' => array(
  6656. 'UPDATE users SET',
  6657. ['locked' => '1'],
  6658. 'WHERE id = ?',
  6659. $id
  6660. )
  6661. ),
  6662. ];
  6663. $this->setLoggerChannel('User Management');
  6664. $this->logger->info('User: ' . $user['username'] . ' account locked');
  6665. $this->setAPIResponse('success', 'User account locked', 200);
  6666. return $this->processQueries($response);
  6667. }
  6668. public function unlockCurrentUser($array)
  6669. {
  6670. if ($array['password'] == '') {
  6671. $this->setAPIResponse('error', 'Password Not Set', 422);
  6672. return false;
  6673. }
  6674. $user = $this->getUserById($this->user['userID']);
  6675. if (!password_verify($array['password'], $user['password'])) {
  6676. $this->setAPIResponse('error', 'Password Incorrect', 401);
  6677. return false;
  6678. }
  6679. return $this->unlockUser($this->user['userID']);
  6680. }
  6681. public function unlockUser($id)
  6682. {
  6683. $user = $this->getUserById($id);
  6684. if (!$user) {
  6685. $this->setAPIResponse('error', 'User not found', 404);
  6686. return false;
  6687. }
  6688. $response = [
  6689. array(
  6690. 'function' => 'query',
  6691. 'query' => array(
  6692. 'UPDATE users SET',
  6693. ['locked' => '0'],
  6694. 'WHERE id = ?',
  6695. $id
  6696. )
  6697. ),
  6698. ];
  6699. $this->setLoggerChannel('User Management');
  6700. $this->logger->info('User: ' . $user['username'] . ' account unlocked');
  6701. $this->setAPIResponse('success', 'User account unlocked', 200);
  6702. return $this->processQueries($response);
  6703. }
  6704. public function youtubeSearch($query)
  6705. {
  6706. if (!$query) {
  6707. $this->setAPIResponse('error', 'No query supplied', 422);
  6708. return false;
  6709. }
  6710. $keys = array(
  6711. 'AIzaSyBsdt8nLJRMTwOq5PY5A5GLZ2q7scgn01w',
  6712. 'AIzaSyD-8SHutB60GCcSM8q_Fle38rJUV7ujd8k',
  6713. 'AIzaSyBzOpVBT6VII-b-8gWD0MOEosGg4hyhCsQ',
  6714. 'AIzaSyBKnRe1P8fpfBHgooJpmT0WOsrdUtZ4cpk'
  6715. );
  6716. $randomKeyIndex = array_rand($keys);
  6717. $key = $keys[$randomKeyIndex];
  6718. $apikey = ($this->config['youtubeAPI'] !== '') ? $this->config['youtubeAPI'] : $key;
  6719. $results = false;
  6720. $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=$query+official+trailer&part=snippet&maxResults=1&type=video&videoDuration=short&key=$apikey";
  6721. $response = Requests::get($url);
  6722. if ($response->success) {
  6723. $results = json_decode($response->body, true);
  6724. $this->setAPIResponse('success', null, 200, $results);
  6725. return $results;
  6726. } else {
  6727. $this->setAPIResponse('error', 'Bad response from YouTube', 500);
  6728. return false;
  6729. }
  6730. }
  6731. public function scrapePage($array)
  6732. {
  6733. try {
  6734. $url = $array['url'] ?? false;
  6735. $type = $array['type'] ?? false;
  6736. if (!$url) {
  6737. $this->setAPIResponse('error', 'URL was not supplied', 422);
  6738. return false;
  6739. }
  6740. $url = $this->qualifyURL($url);
  6741. $data = array(
  6742. 'full_url' => $url,
  6743. 'drill_url' => $this->qualifyURL($url, true)
  6744. );
  6745. $options = array('verify' => false);
  6746. $response = Requests::get($url, array(), $options);
  6747. $data['response_code'] = $response->status_code;
  6748. if ($response->success) {
  6749. $data['result'] = 'Success';
  6750. switch ($type) {
  6751. case 'html':
  6752. $data['data'] = html_entity_decode($response->body);
  6753. break;
  6754. case 'json':
  6755. $data['data'] = json_decode($response->body);
  6756. break;
  6757. default:
  6758. $data['data'] = $response->body;
  6759. }
  6760. $this->setAPIResponse('success', null, 200, $data);
  6761. return $data;
  6762. } else {
  6763. $this->setAPIResponse('error', 'Error getting successful response', 500);
  6764. return false;
  6765. }
  6766. } catch (Requests_Exception $e) {
  6767. $this->setResponse(500, $e->getMessage());
  6768. return false;
  6769. }
  6770. }
  6771. public function chooseInstance($url = null, $token = null, $instance = 0, $type = null)
  6772. {
  6773. if (!$url || !$token) {
  6774. return false;
  6775. }
  6776. $list = $this->csvHomepageUrlToken($url, $token);
  6777. if ($type) {
  6778. $type = strtolower($type);
  6779. switch ($type) {
  6780. case 'url':
  6781. case 'token':
  6782. break;
  6783. default:
  6784. $type = 'url';
  6785. break;
  6786. }
  6787. if (is_numeric($instance)) {
  6788. return $list[$instance][$type];
  6789. } else {
  6790. return $list;
  6791. }
  6792. }
  6793. if (is_numeric($instance)) {
  6794. return $list[$instance];
  6795. } else {
  6796. return $list;
  6797. }
  6798. }
  6799. public function CBPFWTabs()
  6800. {
  6801. return '
  6802. <script>
  6803. /**
  6804. * cbpFWTabs.js v1.0.0
  6805. * http://www.codrops.com
  6806. *
  6807. * Licensed under the MIT license.
  6808. * http://www.opensource.org/licenses/mit-license.php
  6809. *
  6810. * Copyright 2014, Codrops
  6811. * http://www.codrops.com
  6812. */
  6813. ;( function( window ) {
  6814. \'use strict\';
  6815. function extend( a, b ) {
  6816. for( var key in b ) {
  6817. if( b.hasOwnProperty( key ) ) {
  6818. a[key] = b[key];
  6819. }
  6820. }
  6821. return a;
  6822. }
  6823. function CBPFWTabs( el, options ) {
  6824. this.el = el;
  6825. this.options = extend( {}, this.options );
  6826. extend( this.options, options );
  6827. this._init();
  6828. }
  6829. CBPFWTabs.prototype.options = {
  6830. start : 0
  6831. };
  6832. CBPFWTabs.prototype._init = function() {
  6833. // tabs elems
  6834. this.tabs = [].slice.call( this.el.querySelectorAll( \'nav > ul > li\' ) );
  6835. // content items
  6836. this.items = [].slice.call( this.el.querySelectorAll( \'.content-wrap > section\' ) );
  6837. // current index
  6838. this.current = -1;
  6839. // show current content item
  6840. try{
  6841. if(this.tabs[0].innerHTML.indexOf(\'#settings\') >= 0){
  6842. this._show(' . $this->config['defaultSettingsTab'] . ');
  6843. let tabId = $(this.items[' . $this->config['defaultSettingsTab'] . ']).attr("id") + "-anchor";
  6844. $("#" + tabId).click();
  6845. $("#" + tabId + " a").click();
  6846. }else{
  6847. this._show();
  6848. }
  6849. }catch{
  6850. this._show();
  6851. }
  6852. // init events
  6853. this._initEvents();
  6854. };
  6855. CBPFWTabs.prototype._initEvents = function() {
  6856. var self = this;
  6857. this.tabs.forEach( function( tab, idx ) {
  6858. tab.addEventListener( \'click\', function( ev ) {
  6859. ev.preventDefault();
  6860. self._show( idx );
  6861. } );
  6862. } );
  6863. };
  6864. CBPFWTabs.prototype._show = function( idx ) {
  6865. if( this.current >= 0 ) {
  6866. this.tabs[ this.current ].className = this.items[ this.current ].className = \'\';
  6867. }
  6868. // change current
  6869. this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
  6870. this.tabs[ this.current ].className = \'tab-current\';
  6871. this.items[ this.current ].className = \'content-current\';
  6872. };
  6873. // add to global namespace
  6874. window.CBPFWTabs = CBPFWTabs;
  6875. })( window );
  6876. </script>
  6877. ';
  6878. }
  6879. public function socksHeadingHTML($app)
  6880. {
  6881. return '
  6882. <h3 lang="en">' . ucwords($app) . ' SOCKS API Connection</h3>
  6883. <p>Using this feature allows you to access the API without having to reverse proxy it. Just access it from: </p>
  6884. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/socks/' . $app . '/</code>
  6885. <p>If you are using multiple URL\'s (using the csv method) you will have to use the url like these: </p>
  6886. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/1</code>
  6887. <br/>
  6888. <code class="elip hidden-xs">' . $this->getServerPath() . 'api/v2/multiple/socks/' . $app . '/2</code>
  6889. ';
  6890. }
  6891. public function socksListing($app = null)
  6892. {
  6893. switch ($app) {
  6894. case 'sonarr':
  6895. $appDetails = [
  6896. 'url' => 'sonarrURL',
  6897. 'enabled' => 'sonarrSocksEnabled',
  6898. 'auth' => 'sonarrSocksAuth',
  6899. 'header' => 'X-Api-Key'
  6900. ];
  6901. break;
  6902. case 'radarr':
  6903. $appDetails = [
  6904. 'url' => 'radarrURL',
  6905. 'enabled' => 'radarrSocksEnabled',
  6906. 'auth' => 'radarrSocksAuth',
  6907. 'header' => 'X-Api-Key'
  6908. ];
  6909. break;
  6910. case 'lidarr':
  6911. $appDetails = [
  6912. 'url' => 'lidarrURL',
  6913. 'enabled' => 'lidarrSocksEnabled',
  6914. 'auth' => 'lidarrSocksAuth',
  6915. 'header' => 'X-Api-Key'
  6916. ];
  6917. break;
  6918. case 'sabnzbd':
  6919. $appDetails = [
  6920. 'url' => 'sabnzbdURL',
  6921. 'enabled' => 'sabnzbdSocksEnabled',
  6922. 'auth' => 'sabnzbdSocksAuth',
  6923. 'header' => null
  6924. ];
  6925. break;
  6926. case 'nzbget':
  6927. $appDetails = [
  6928. 'url' => 'nzbgetURL',
  6929. 'enabled' => 'nzbgetSocksEnabled',
  6930. 'auth' => 'nzbgetSocksAuth',
  6931. 'header' => 'Authorization'
  6932. ];
  6933. break;
  6934. case 'tautulli':
  6935. $appDetails = [
  6936. 'url' => 'tautulliURL',
  6937. 'enabled' => 'tautulliSocksEnabled',
  6938. 'auth' => 'tautulliSocksAuth',
  6939. 'header' => null
  6940. ];
  6941. break;
  6942. case 'qbittorrent':
  6943. $appDetails = [
  6944. 'url' => 'qBittorrentURL',
  6945. 'enabled' => 'qBittorrentSocksEnabled',
  6946. 'auth' => 'qBittorrentSocksAuth',
  6947. 'header' => null
  6948. ];
  6949. break;
  6950. default:
  6951. $appDetails = null;
  6952. }
  6953. return $appDetails;
  6954. }
  6955. public function socks($appDetails, $requestObject, $multiple = null)
  6956. {
  6957. $url = $appDetails['url'];
  6958. $enabled = $appDetails['enabled'];
  6959. $auth = $appDetails['auth'];
  6960. $header = $appDetails['header'];
  6961. $error = false;
  6962. if (!$this->config[$enabled]) {
  6963. $error = true;
  6964. $this->setAPIResponse('error', 'SOCKS module is not enabled', 409);
  6965. }
  6966. if (!$this->qualifyRequest($this->config[$auth], true)) {
  6967. $error = true;
  6968. }
  6969. if (strpos($this->config[$url], ',') !== false) {
  6970. if (!$multiple) {
  6971. $error = true;
  6972. $this->setAPIResponse('error', 'Multiple URLs found in field, please use /api/v2/multiple/socks endpoint', 409);
  6973. }
  6974. } else {
  6975. if ($multiple) {
  6976. $error = true;
  6977. $this->setAPIResponse('error', 'Multiple endpoint accessed but multiple URLs not found in field, please use /api/v2/socks endpoint', 409);
  6978. }
  6979. }
  6980. if (!$error) {
  6981. if ($multiple) {
  6982. $instance = $multiple - 1;
  6983. $pre = explode('/api/v2/multiple/socks/', $requestObject->getUri()->getPath());
  6984. $pre[1] = $this->replace_first('/' . $multiple . '/', '/', $pre[1]);
  6985. // sent url twice since we arent using tokens
  6986. $list = $this->csvHomepageUrlToken($this->config[$url], $this->config[$url]);
  6987. $appURL = $list[$instance]['url'];
  6988. } else {
  6989. $pre = explode('/api/v2/socks/', $requestObject->getUri()->getPath());
  6990. $appURL = $this->config[$url];
  6991. }
  6992. $endpoint = explode('/', $pre[1]);
  6993. $new = urldecode(preg_replace('/' . $endpoint[0] . '/', '', $pre[1], 1));
  6994. $getParams = ($_GET) ? '?' . http_build_query($_GET) : '';
  6995. $url = $this->qualifyURL($appURL) . $new . $getParams;
  6996. $url = $this->cleanPath($url);
  6997. $options = ($this->localURL($appURL)) ? array('verify' => false, 'timeout' => 120) : array('timeout' => 120);
  6998. $headers = [];
  6999. $apiData = $this->apiData($requestObject, false);
  7000. if ($header) {
  7001. if ($requestObject->hasHeader($header)) {
  7002. $headerKey = $requestObject->getHeaderLine($header);
  7003. $headers[$header] = $headerKey;
  7004. }
  7005. }
  7006. if ($requestObject->hasHeader('Content-Type')) {
  7007. $headerKey = $requestObject->getHeaderLine('Content-Type');
  7008. $headers['Content-Type'] = $headerKey;
  7009. }
  7010. $debugInformation = [
  7011. 'type' => $requestObject->getMethod(),
  7012. 'headerType' => $requestObject->getHeaderLine('Content-Type'),
  7013. 'header' => $header,
  7014. 'headers' => $headers,
  7015. 'url' => $url,
  7016. 'options' => $options,
  7017. 'data' => $apiData,
  7018. ];
  7019. $this->setLoggerChannel('Socks');
  7020. $this->logger->debug('Sending Socks request', $debugInformation);
  7021. try {
  7022. switch ($requestObject->getMethod()) {
  7023. case 'GET':
  7024. $call = Requests::get($url, $headers, $options);
  7025. break;
  7026. case 'POST':
  7027. $call = Requests::post($url, $headers, $apiData, $options);
  7028. break;
  7029. case 'DELETE':
  7030. $call = Requests::delete($url, $headers, $options);
  7031. break;
  7032. case 'PUT':
  7033. $call = Requests::put($url, $headers, $apiData, $options);
  7034. break;
  7035. default:
  7036. $call = Requests::get($url, $headers, $options);
  7037. }
  7038. $this->logger->debug('Socks Response', $this->json_validator($call->body) ? json_decode($call->body, true) : $call->body);
  7039. return $call->body;
  7040. } catch (Requests_Exception $e) {
  7041. $this->setResponse(500, $e->getMessage());
  7042. $this->setLoggerChannel('Socks');
  7043. $this->logger->critical($e, $debugInformation);
  7044. return null;
  7045. }
  7046. } else {
  7047. return null;
  7048. }
  7049. }
  7050. public function getPlexServers()
  7051. {
  7052. if ($this->config['plexToken'] == '') {
  7053. $this->setAPIResponse('error', 'Plex Token cannot be empty', 422);
  7054. return false;
  7055. }
  7056. $ownedOnly = isset($_GET['owned']) ?? false;
  7057. $url = $this->qualifyURL('https://plex.tv/pms/servers');
  7058. $options = ($this->localURL($url)) ? array('verify' => false) : array();
  7059. $headers = [
  7060. 'X-Plex-Product' => 'Organizr',
  7061. 'X-Plex-Version' => '2.0',
  7062. 'X-Plex-Client-Identifier' => '01010101-10101010',
  7063. 'X-Plex-Token' => $this->config['plexToken'],
  7064. ];
  7065. try {
  7066. $response = Requests::get($url, $headers, $options);
  7067. libxml_use_internal_errors(true);
  7068. if ($response->success) {
  7069. $items = array();
  7070. $plex = simplexml_load_string($response->body);
  7071. foreach ($plex as $server) {
  7072. if ($ownedOnly) {
  7073. if ($server['owned'] == 1) {
  7074. $items[] = array(
  7075. 'name' => (string)$server['name'],
  7076. 'address' => (string)$server['address'],
  7077. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7078. 'owned' => (float)$server['owned'],
  7079. );
  7080. }
  7081. } else {
  7082. $items[] = array(
  7083. 'name' => (string)$server['name'],
  7084. 'address' => (string)$server['address'],
  7085. 'machineIdentifier' => (string)$server['machineIdentifier'],
  7086. 'owned' => (float)$server['owned'],
  7087. );
  7088. }
  7089. }
  7090. $this->setAPIResponse('success', null, 200, $items);
  7091. return $items;
  7092. }
  7093. } catch (Requests_Exception $e) {
  7094. $this->setLoggerChannel('Plex Connection');
  7095. $this->logger->error($e);
  7096. $this->setResponse(500, $e->getMessage());
  7097. }
  7098. }
  7099. public function getIcons()
  7100. {
  7101. $term = $_GET['search'] ?? null;
  7102. $page = $_GET['page'] ?? 1;
  7103. $limit = $_GET['limit'] ?? 20;
  7104. $offset = ($page * $limit) - $limit;
  7105. $goodIcons['results'] = [];
  7106. $goodIcons['limit'] = $limit;
  7107. $goodIcons['page'] = $page;
  7108. $goodIcons['term'] = $term;
  7109. $allIcons = file_get_contents($this->root . '/js/icons.json');
  7110. $iconListing = json_decode($allIcons, true);
  7111. foreach ($iconListing as $setKey => $set) {
  7112. foreach ($set['children'] as $k => $v) {
  7113. if (stripos($v['text'], $term) !== false || !$term) {
  7114. $goodIcons['results'][] = $v;
  7115. }
  7116. }
  7117. }
  7118. $total = count($goodIcons['results']);
  7119. $goodIcons['total'] = $total;
  7120. $goodIcons['results'] = array_slice($goodIcons['results'], $offset, $limit);
  7121. $goodIcons['pagination']['more'] = $page < (ceil($total / $limit));
  7122. return $goodIcons;
  7123. }
  7124. public function getJournalMode()
  7125. {
  7126. $response = [
  7127. array(
  7128. 'function' => 'fetch',
  7129. 'query' => 'PRAGMA journal_mode',
  7130. ),
  7131. ];
  7132. $query = $this->processQueries($response);
  7133. if ($query) {
  7134. if ($query['journal_mode']) {
  7135. $this->setResponse(200, null, $query);
  7136. } else {
  7137. $this->setResponse(500, 'Error getting Journal Mode');
  7138. }
  7139. } else {
  7140. $this->setResponse(404, 'Journal Mode not found');
  7141. }
  7142. return $query;
  7143. }
  7144. public function setJournalMode($option = 'WAL')
  7145. {
  7146. $option = strtoupper($option);
  7147. switch ($option) {
  7148. case 'WAL':
  7149. case 'DELETE':
  7150. break;
  7151. default:
  7152. return false;
  7153. }
  7154. $response = [
  7155. array(
  7156. 'function' => 'fetch',
  7157. 'query' => 'PRAGMA journal_mode = \'' . $option . '\';',
  7158. ),
  7159. ];
  7160. $query = $this->processQueries($response);
  7161. if ($query) {
  7162. if ($query['journal_mode']) {
  7163. $this->setResponse(200, 'Journal Mode updated to: ' . $option, $query);
  7164. } else {
  7165. $this->setResponse(500, 'Error getting Journal Mode');
  7166. }
  7167. } else {
  7168. $this->setResponse(404, 'Journal Mode not found');
  7169. }
  7170. return $query;
  7171. }
  7172. public function testCronSchedule($schedule = null)
  7173. {
  7174. if (is_array($schedule)) {
  7175. $schedule = str_replace('_', ' ', array_keys($schedule)[0]);
  7176. }
  7177. if (!$schedule) {
  7178. $this->setResponse(409, 'Schedule was not supplied');
  7179. return false;
  7180. }
  7181. try {
  7182. $schedule = new Cron\CronExpression($schedule);
  7183. $this->setResponse(200, 'Schedule was validated');
  7184. return true;
  7185. } catch (InvalidArgumentException $e) {
  7186. $this->setResponse(500, $e->getMessage());
  7187. return false;
  7188. }
  7189. }
  7190. public function testFolder($folder = null)
  7191. {
  7192. $folder = $folder['folder'] ?? null;
  7193. if (!$folder) {
  7194. $this->setResponse(409, 'Folder was not supplied');
  7195. return false;
  7196. }
  7197. $testFolder = $this->makeDir($folder);
  7198. if ($testFolder) {
  7199. $this->setResponse(200, 'Folder approved for logs');
  7200. return true;
  7201. } else {
  7202. $this->setResponse(409, 'Folder path is not valid or permissions insufficient');
  7203. return false;
  7204. }
  7205. }
  7206. public function replaceStringInDatabase($string)
  7207. {
  7208. $databaseStringList = [
  7209. 'AUTOINCREMENT' => [
  7210. 'sqlite3' => 'AUTOINCREMENT',
  7211. 'mysqli' => 'AUTO_INCREMENT',
  7212. 'postgre' => 'AUTOINCREMENT'
  7213. ],
  7214. 'COLLATE NOCASE' => [
  7215. 'sqlite3' => 'COLLATE NOCASE',
  7216. 'mysqli' => '',
  7217. 'postgre' => ''
  7218. ],
  7219. 'INTEGER PRIMARY KEY AUTOINCREMENT' => [
  7220. 'sqlite3' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7221. 'mysqli' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
  7222. 'postgre' => 'SERIAL PRIMARY KEY'
  7223. ],
  7224. 'DATETIME' => [
  7225. 'sqlite3' => 'DATETIME',
  7226. 'mysqli' => 'DATETIME',
  7227. 'postgre' => 'TIMESTAMP'
  7228. ],
  7229. ];
  7230. if (gettype($string) == 'string') {
  7231. foreach ($databaseStringList as $item => $value) {
  7232. if (stripos($string, $item) !== false) {
  7233. $string = str_ireplace($item, $databaseStringList[$item][$this->config['driver']], $string);
  7234. }
  7235. }
  7236. }
  7237. return $string;
  7238. }
  7239. public function cleanDatabaseQuery($query)
  7240. {
  7241. if (is_array($query)) {
  7242. foreach ($query as $key => $value) {
  7243. $query[$key] = $this->cleanDatabaseQuery($value);
  7244. }
  7245. return $query;
  7246. } else {
  7247. return $this->replaceStringInDatabase($query);
  7248. }
  7249. }
  7250. protected function processQueries(array $request, $migration = false)
  7251. {
  7252. $results = array();
  7253. $firstKey = '';
  7254. if ($this->config['includeDatabaseQueriesInDebug']) {
  7255. $this->setLoggerChannel('Database');
  7256. $this->logger->debug('Query to database', $request);
  7257. }
  7258. foreach ($request as $k => $v) {
  7259. try {
  7260. $v['query'] = $this->cleanDatabaseQuery($v['query']);
  7261. $query = ($migration) ? $this->otherDb->query($v['query']) : $this->db->query($v['query']);
  7262. $keyName = (isset($v['key'])) ? $v['key'] : $k;
  7263. $firstKey = (isset($v['key']) && $k == 0) ? $v['key'] : $k;
  7264. switch ($v['function']) {
  7265. case 'fetchAll':
  7266. $results[$keyName] = $query->fetchAll();
  7267. break;
  7268. case 'fetch':
  7269. // PHP 8 Fix?
  7270. $query->setRowClass(null);
  7271. $results[$keyName] = $query->fetch();
  7272. break;
  7273. case 'getAffectedRows':
  7274. $results[$keyName] = $query->getAffectedRows();
  7275. break;
  7276. case 'getRowCount':
  7277. $results[$keyName] = $query->getRowCount();
  7278. break;
  7279. case 'fetchSingle':
  7280. // PHP 8 Fix?
  7281. $query->setRowClass(null);
  7282. $results[$keyName] = $query->fetchSingle();
  7283. break;
  7284. case 'query':
  7285. $results[$keyName] = $query;
  7286. break;
  7287. default:
  7288. return false;
  7289. }
  7290. } catch (Exception $e) {
  7291. $this->setLoggerChannel('Database');
  7292. $this->logger->critical($e, $v['query']);
  7293. return false;
  7294. }
  7295. }
  7296. if ($this->config['includeDatabaseQueriesInDebug']) {
  7297. $this->logger->debug('Results from database', $results);
  7298. }
  7299. return count($request) > 1 ? $results : $results[$firstKey];
  7300. }
  7301. }