organizr.class.php 256 KB

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