organizr.class.php 256 KB

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