organizr.class.php 244 KB

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