organizr.class.php 237 KB

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