app.js 289 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407
  1. /**
  2. * Roundcube Webmail Client Script
  3. *
  4. * This file is part of the Roundcube Webmail client
  5. *
  6. * @licstart The following is the entire license notice for the
  7. * JavaScript code in this file.
  8. *
  9. * Copyright (C) 2005-2015, The Roundcube Dev Team
  10. * Copyright (C) 2011-2015, Kolab Systems AG
  11. *
  12. * The JavaScript code in this page is free software: you can
  13. * redistribute it and/or modify it under the terms of the GNU
  14. * General Public License (GNU GPL) as published by the Free Software
  15. * Foundation, either version 3 of the License, or (at your option)
  16. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  17. * without even the implied warranty of MERCHANTABILITY or FITNESS
  18. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  19. *
  20. * As additional permission under GNU GPL version 3 section 7, you
  21. * may distribute non-source (e.g., minimized or compacted) forms of
  22. * that code without the copy of the GNU GPL normally required by
  23. * section 4, provided you include this license notice and a URL
  24. * through which recipients can access the Corresponding Source.
  25. *
  26. * @licend The above is the entire license notice
  27. * for the JavaScript code in this file.
  28. *
  29. * @author Thomas Bruederli <roundcube@gmail.com>
  30. * @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
  31. * @author Charles McNulty <charles@charlesmcnulty.com>
  32. *
  33. * @requires jquery.js, common.js, list.js
  34. */
  35. function rcube_webmail()
  36. {
  37. this.labels = {};
  38. this.buttons = {};
  39. this.buttons_sel = {};
  40. this.gui_objects = {};
  41. this.gui_containers = {};
  42. this.commands = {};
  43. this.command_handlers = {};
  44. this.onloads = [];
  45. this.messages = {};
  46. this.group2expand = {};
  47. this.http_request_jobs = {};
  48. this.menu_stack = [];
  49. // webmail client settings
  50. this.dblclick_time = 500;
  51. this.message_time = 5000;
  52. this.identifier_expr = /[^0-9a-z_-]/gi;
  53. // environment defaults
  54. this.env = {
  55. request_timeout: 180, // seconds
  56. draft_autosave: 0, // seconds
  57. comm_path: './',
  58. recipients_separator: ',',
  59. recipients_delimiter: ', ',
  60. popup_width: 1150,
  61. popup_width_small: 900
  62. };
  63. // create protected reference to myself
  64. this.ref = 'rcmail';
  65. var ref = this;
  66. // set jQuery ajax options
  67. $.ajaxSetup({
  68. cache: false,
  69. timeout: this.env.request_timeout * 1000,
  70. error: function(request, status, err){ ref.http_error(request, status, err); },
  71. beforeSend: function(xmlhttp){ xmlhttp.setRequestHeader('X-Roundcube-Request', ref.env.request_token); }
  72. });
  73. // unload fix
  74. $(window).on('beforeunload', function() { ref.unload = true; });
  75. // set environment variable(s)
  76. this.set_env = function(p, value)
  77. {
  78. if (p != null && typeof p === 'object' && !value)
  79. for (var n in p)
  80. this.env[n] = p[n];
  81. else
  82. this.env[p] = value;
  83. };
  84. // add a localized label to the client environment
  85. this.add_label = function(p, value)
  86. {
  87. if (typeof p == 'string')
  88. this.labels[p] = value;
  89. else if (typeof p == 'object')
  90. $.extend(this.labels, p);
  91. };
  92. // add a button to the button list
  93. this.register_button = function(command, id, type, act, sel, over)
  94. {
  95. var button_prop = {id:id, type:type};
  96. if (act) button_prop.act = act;
  97. if (sel) button_prop.sel = sel;
  98. if (over) button_prop.over = over;
  99. if (!this.buttons[command])
  100. this.buttons[command] = [];
  101. this.buttons[command].push(button_prop);
  102. if (this.loaded)
  103. init_button(command, button_prop);
  104. };
  105. // register a specific gui object
  106. this.gui_object = function(name, id)
  107. {
  108. this.gui_objects[name] = this.loaded ? rcube_find_object(id) : id;
  109. };
  110. // register a container object
  111. this.gui_container = function(name, id)
  112. {
  113. this.gui_containers[name] = id;
  114. };
  115. // add a GUI element (html node) to a specified container
  116. this.add_element = function(elm, container)
  117. {
  118. if (this.gui_containers[container] && this.gui_containers[container].jquery)
  119. this.gui_containers[container].append(elm);
  120. };
  121. // register an external handler for a certain command
  122. this.register_command = function(command, callback, enable)
  123. {
  124. this.command_handlers[command] = callback;
  125. if (enable)
  126. this.enable_command(command, true);
  127. };
  128. // execute the given script on load
  129. this.add_onload = function(f)
  130. {
  131. this.onloads.push(f);
  132. };
  133. // initialize webmail client
  134. this.init = function()
  135. {
  136. var n;
  137. this.task = this.env.task;
  138. // check browser capabilities (never use version checks here)
  139. if (this.env.server_error != 409 && (!bw.dom || !bw.xmlhttp_test())) {
  140. this.goto_url('error', '_code=0x199');
  141. return;
  142. }
  143. if (!this.env.blankpage)
  144. this.env.blankpage = this.assets_path('program/resources/blank.gif');
  145. // find all registered gui containers
  146. for (n in this.gui_containers)
  147. this.gui_containers[n] = $('#'+this.gui_containers[n]);
  148. // find all registered gui objects
  149. for (n in this.gui_objects)
  150. this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
  151. // clickjacking protection
  152. if (n = this.env.x_frame_options) {
  153. try {
  154. // bust frame if not allowed
  155. if (n.toLowerCase() == 'deny' && top.location.href != self.location.href)
  156. top.location.href = self.location.href;
  157. else if (/^allow-from[\s\t]+(.+)$/i.test(n) && RegExp.$1.indexOf(top.location.origin) != 0)
  158. throw 1;
  159. else if (top.location.hostname != self.location.hostname)
  160. throw 1;
  161. } catch (e) {
  162. // possible clickjacking attack: disable all form elements
  163. $('form').each(function(){ ref.lock_form(this, true); });
  164. this.display_message("Blocked: possible clickjacking attack!", 'error');
  165. return;
  166. }
  167. }
  168. // init registered buttons
  169. this.init_buttons();
  170. // tell parent window that this frame is loaded
  171. if (this.is_framed()) {
  172. parent.rcmail.set_busy(false, null, parent.rcmail.env.frame_lock);
  173. parent.rcmail.env.frame_lock = null;
  174. }
  175. // enable general commands
  176. this.enable_command('close', 'logout', 'mail', 'addressbook', 'settings', 'save-pref',
  177. 'compose', 'undo', 'about', 'switch-task', 'menu-open', 'menu-close', 'menu-save', true);
  178. // set active task button
  179. this.set_button(this.task, 'sel');
  180. if (this.env.permaurl)
  181. this.enable_command('permaurl', 'extwin', true);
  182. switch (this.task) {
  183. case 'mail':
  184. // enable mail commands
  185. this.enable_command('list', 'checkmail', 'add-contact', 'search', 'reset-search', 'collapse-folder', 'import-messages', true);
  186. if (this.gui_objects.messagelist) {
  187. this.env.widescreen_list_template = [
  188. {className: 'threads', cells: ['threads']},
  189. {className: 'subject', cells: ['fromto', 'date', 'status', 'subject']},
  190. {className: 'flags', cells: ['flag', 'attachment']}
  191. ];
  192. this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {
  193. multiselect:true, multiexpand:true, draggable:true, keyboard:true,
  194. column_movable:this.env.col_movable, dblclick_time:this.dblclick_time
  195. });
  196. this.message_list
  197. .addEventListener('initrow', function(o) { ref.init_message_row(o); })
  198. .addEventListener('dblclick', function(o) { ref.msglist_dbl_click(o); })
  199. .addEventListener('click', function(o) { ref.msglist_click(o); })
  200. .addEventListener('keypress', function(o) { ref.msglist_keypress(o); })
  201. .addEventListener('select', function(o) { ref.msglist_select(o); })
  202. .addEventListener('dragstart', function(o) { ref.drag_start(o); })
  203. .addEventListener('dragmove', function(e) { ref.drag_move(e); })
  204. .addEventListener('dragend', function(e) { ref.drag_end(e); })
  205. .addEventListener('expandcollapse', function(o) { ref.msglist_expand(o); })
  206. .addEventListener('column_replace', function(o) { ref.msglist_set_coltypes(o); })
  207. .addEventListener('listupdate', function(o) { ref.triggerEvent('listupdate', o); })
  208. .init();
  209. // TODO: this should go into the list-widget code
  210. $(this.message_list.thead).on('click', 'a.sortcol', function(e){
  211. return ref.command('sort', $(this).attr('rel'), this);
  212. });
  213. this.enable_command('toggle_status', 'toggle_flag', 'sort', true);
  214. this.enable_command('set-listmode', this.env.threads && !this.is_multifolder_listing());
  215. // load messages
  216. this.command('list');
  217. $(this.gui_objects.qsearchbox).val(this.env.search_text).focusin(function() { ref.message_list.blur(); });
  218. }
  219. this.set_button_titles();
  220. this.env.message_commands = ['show', 'reply', 'reply-all', 'reply-list',
  221. 'move', 'copy', 'delete', 'open', 'mark', 'edit', 'viewsource',
  222. 'print', 'load-attachment', 'download-attachment', 'show-headers', 'hide-headers', 'download',
  223. 'forward', 'forward-inline', 'forward-attachment', 'change-format'];
  224. if (this.env.action == 'show' || this.env.action == 'preview') {
  225. this.enable_command(this.env.message_commands, this.env.uid);
  226. this.enable_command('reply-list', this.env.list_post);
  227. if (this.env.action == 'show') {
  228. this.http_request('pagenav', {_uid: this.env.uid, _mbox: this.env.mailbox, _search: this.env.search_request},
  229. this.display_message('', 'loading'));
  230. }
  231. if (this.env.mail_read_time > 0)
  232. setTimeout(function() {
  233. ref.http_post('mark', {_uid: ref.env.uid, _flag: 'read', _mbox: ref.env.mailbox, _quiet: 1});
  234. }, this.env.mail_read_time * 1000);
  235. if (this.env.blockedobjects) {
  236. if (this.gui_objects.remoteobjectsmsg)
  237. this.gui_objects.remoteobjectsmsg.style.display = 'block';
  238. this.enable_command('load-images', 'always-load', true);
  239. }
  240. // make preview/message frame visible
  241. if (this.env.action == 'preview' && this.is_framed()) {
  242. this.enable_command('compose', 'add-contact', false);
  243. parent.rcmail.show_contentframe(true);
  244. }
  245. // initialize drag-n-drop on attachments, so they can e.g.
  246. // be dropped into mail compose attachments in another window
  247. if (this.gui_objects.attachments)
  248. $('li > a', this.gui_objects.attachments).not('.drop').on('dragstart', function(e) {
  249. var n, href = this.href, dt = e.originalEvent.dataTransfer;
  250. if (dt) {
  251. // inject username to the uri
  252. href = href.replace(/^https?:\/\//, function(m) { return m + urlencode(ref.env.username) + '@'});
  253. // cleanup the node to get filename without the size test
  254. n = $(this).clone();
  255. n.children().remove();
  256. dt.setData('roundcube-uri', href);
  257. dt.setData('roundcube-name', $.trim(n.text()));
  258. }
  259. });
  260. }
  261. else if (this.env.action == 'compose') {
  262. this.env.address_group_stack = [];
  263. this.env.compose_commands = ['send-attachment', 'remove-attachment', 'send', 'cancel',
  264. 'toggle-editor', 'list-addresses', 'pushgroup', 'search', 'reset-search', 'extwin',
  265. 'insert-response', 'save-response', 'menu-open', 'menu-close', 'load-attachment',
  266. 'download-attachment', 'open-attachment', 'rename-attachment'];
  267. if (this.env.drafts_mailbox)
  268. this.env.compose_commands.push('savedraft')
  269. this.enable_command(this.env.compose_commands, 'identities', 'responses', true);
  270. // add more commands (not enabled)
  271. $.merge(this.env.compose_commands, ['add-recipient', 'firstpage', 'previouspage', 'nextpage', 'lastpage']);
  272. if (window.googie) {
  273. this.env.editor_config.spellchecker = googie;
  274. this.env.editor_config.spellcheck_observer = function(s) { ref.spellcheck_state(); };
  275. this.env.compose_commands.push('spellcheck')
  276. this.enable_command('spellcheck', true);
  277. }
  278. // initialize HTML editor
  279. this.editor_init(this.env.editor_config, this.env.composebody);
  280. // init canned response functions
  281. if (this.gui_objects.responseslist) {
  282. $('a.insertresponse', this.gui_objects.responseslist)
  283. .attr('unselectable', 'on')
  284. .mousedown(function(e) { return rcube_event.cancel(e); })
  285. .on('mouseup keypress', function(e) {
  286. if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
  287. ref.command('insert-response', $(this).attr('rel'));
  288. $(document.body).trigger('mouseup'); // hides the menu
  289. return rcube_event.cancel(e);
  290. }
  291. });
  292. // avoid textarea loosing focus when hitting the save-response button/link
  293. $.each(this.buttons['save-response'] || [], function (i, v) {
  294. $('#' + v.id).mousedown(function(e){ return rcube_event.cancel(e); })
  295. });
  296. }
  297. // init message compose form
  298. this.init_messageform();
  299. }
  300. else if (this.env.action == 'get') {
  301. this.enable_command('download', true);
  302. // Mozilla's PDF.js viewer does not allow printing from host page (#5125)
  303. // to minimize user confusion we disable the Print button
  304. if (bw.mz && this.env.mimetype == 'application/pdf') {
  305. n = 0; // there will be two onload events, first for the preload page
  306. $(this.gui_objects.messagepartframe).on('load', function() {
  307. if (n++) try { this.contentWindow.document; ref.enable_command('print', true); }
  308. catch (e) {/* ignore */}
  309. });
  310. }
  311. else
  312. this.enable_command('print', true);
  313. if (this.env.is_message) {
  314. this.enable_command('reply', 'reply-all', 'edit', 'viewsource',
  315. 'forward', 'forward-inline', 'forward-attachment', true);
  316. if (this.env.list_post)
  317. this.enable_command('reply-list', true);
  318. }
  319. // center and scale the image in preview frame
  320. if (this.env.mimetype.startsWith('image/'))
  321. $(this.gui_objects.messagepartframe).on('load', function() {
  322. var css = 'img { max-width:100%; max-height:100%; } ' // scale
  323. + 'body { display:flex; align-items:center; justify-content:center; height:100%; margin:0; }'; // align
  324. $(this).contents().find('head').append('<style type="text/css">'+ css + '</style>');
  325. });
  326. }
  327. // show printing dialog
  328. else if (this.env.action == 'print' && this.env.uid
  329. && !this.env.is_pgp_content && !this.env.pgp_mime_part
  330. ) {
  331. this.print_dialog();
  332. }
  333. // get unread count for each mailbox
  334. if (this.gui_objects.mailboxlist) {
  335. this.env.unread_counts = {};
  336. this.gui_objects.folderlist = this.gui_objects.mailboxlist;
  337. this.http_request('getunread', {_page: this.env.current_page});
  338. }
  339. // init address book widget
  340. if (this.gui_objects.contactslist) {
  341. this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
  342. { multiselect:true, draggable:false, keyboard:true });
  343. this.contact_list
  344. .addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
  345. .addEventListener('select', function(o) { ref.compose_recipient_select(o); })
  346. .addEventListener('dblclick', function(o) { ref.compose_add_recipient(); })
  347. .addEventListener('keypress', function(o) {
  348. if (o.key_pressed == o.ENTER_KEY) {
  349. if (!ref.compose_add_recipient()) {
  350. // execute link action on <enter> if not a recipient entry
  351. if (o.last_selected && String(o.last_selected).charAt(0) == 'G') {
  352. $(o.rows[o.last_selected].obj).find('a').first().click();
  353. }
  354. }
  355. }
  356. })
  357. .init();
  358. // remember last focused address field
  359. $('#_to,#_cc,#_bcc').focus(function() { ref.env.focused_field = this; });
  360. }
  361. if (this.gui_objects.addressbookslist) {
  362. this.gui_objects.folderlist = this.gui_objects.addressbookslist;
  363. this.enable_command('list-addresses', true);
  364. }
  365. // ask user to send MDN
  366. if (this.env.mdn_request && this.env.uid) {
  367. var postact = 'sendmdn',
  368. postdata = {_uid: this.env.uid, _mbox: this.env.mailbox};
  369. if (!confirm(this.get_label('mdnrequest'))) {
  370. postdata._flag = 'mdnsent';
  371. postact = 'mark';
  372. }
  373. this.http_post(postact, postdata);
  374. }
  375. this.check_mailvelope(this.env.action);
  376. // detect browser capabilities
  377. if (!this.is_framed() && !this.env.extwin)
  378. this.browser_capabilities_check();
  379. break;
  380. case 'addressbook':
  381. this.env.address_group_stack = [];
  382. if (this.gui_objects.folderlist)
  383. this.env.contactfolders = $.extend($.extend({}, this.env.address_sources), this.env.contactgroups);
  384. this.enable_command('add', 'import', this.env.writable_source);
  385. this.enable_command('list', 'listgroup', 'pushgroup', 'popgroup', 'listsearch', 'search', 'reset-search', 'advanced-search', true);
  386. if (this.gui_objects.contactslist) {
  387. this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
  388. {multiselect:true, draggable:this.gui_objects.folderlist?true:false, keyboard:true});
  389. this.contact_list
  390. .addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
  391. .addEventListener('keypress', function(o) { ref.contactlist_keypress(o); })
  392. .addEventListener('select', function(o) { ref.contactlist_select(o); })
  393. .addEventListener('dragstart', function(o) { ref.drag_start(o); })
  394. .addEventListener('dragmove', function(e) { ref.drag_move(e); })
  395. .addEventListener('dragend', function(e) { ref.drag_end(e); })
  396. .init();
  397. $(this.gui_objects.qsearchbox).focusin(function() { ref.contact_list.blur(); });
  398. this.update_group_commands();
  399. this.command('list');
  400. }
  401. if (this.gui_objects.savedsearchlist) {
  402. this.savedsearchlist = new rcube_treelist_widget(this.gui_objects.savedsearchlist, {
  403. id_prefix: 'rcmli',
  404. id_encode: this.html_identifier_encode,
  405. id_decode: this.html_identifier_decode
  406. });
  407. this.savedsearchlist.addEventListener('select', function(node) {
  408. ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }); });
  409. }
  410. this.set_page_buttons();
  411. if (this.env.cid) {
  412. this.enable_command('show', 'edit', 'qrcode', true);
  413. // register handlers for group assignment via checkboxes
  414. if (this.gui_objects.editform) {
  415. $('input.groupmember').change(function() {
  416. ref.group_member_change(this.checked ? 'add' : 'del', ref.env.cid, ref.env.source, this.value);
  417. });
  418. }
  419. }
  420. if (this.gui_objects.editform) {
  421. this.enable_command('save', true);
  422. if (this.env.action == 'add' || this.env.action == 'edit' || this.env.action == 'search')
  423. this.init_contact_form();
  424. }
  425. else if (this.env.action == 'print') {
  426. this.print_dialog();
  427. }
  428. break;
  429. case 'settings':
  430. this.enable_command('preferences', 'identities', 'responses', 'save', 'folders', true);
  431. if (this.env.action == 'identities') {
  432. this.enable_command('add', this.env.identities_level < 2);
  433. }
  434. else if (this.env.action == 'edit-identity' || this.env.action == 'add-identity') {
  435. this.enable_command('save', 'edit', 'toggle-editor', true);
  436. this.enable_command('delete', this.env.identities_level < 2);
  437. // initialize HTML editor
  438. this.editor_init(this.env.editor_config, 'rcmfd_signature');
  439. }
  440. else if (this.env.action == 'folders') {
  441. this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', true);
  442. }
  443. else if (this.env.action == 'edit-folder' && this.gui_objects.editform) {
  444. this.enable_command('save', 'folder-size', true);
  445. parent.rcmail.env.exists = this.env.messagecount;
  446. parent.rcmail.enable_command('purge', this.env.messagecount);
  447. }
  448. else if (this.env.action == 'responses') {
  449. this.enable_command('add', true);
  450. }
  451. if (this.gui_objects.identitieslist) {
  452. this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist,
  453. {multiselect:false, draggable:false, keyboard:true});
  454. this.identity_list
  455. .addEventListener('select', function(o) { ref.identity_select(o); })
  456. .addEventListener('keypress', function(o) {
  457. if (o.key_pressed == o.ENTER_KEY) {
  458. ref.identity_select(o);
  459. }
  460. })
  461. .init()
  462. .focus();
  463. }
  464. else if (this.gui_objects.sectionslist) {
  465. this.sections_list = new rcube_list_widget(this.gui_objects.sectionslist, {multiselect:false, draggable:false, keyboard:true});
  466. this.sections_list
  467. .addEventListener('select', function(o) { ref.section_select(o); })
  468. .addEventListener('keypress', function(o) { if (o.key_pressed == o.ENTER_KEY) ref.section_select(o); })
  469. .init()
  470. .focus();
  471. }
  472. else if (this.gui_objects.subscriptionlist) {
  473. this.init_subscription_list();
  474. }
  475. else if (this.gui_objects.responseslist) {
  476. this.responses_list = new rcube_list_widget(this.gui_objects.responseslist, {multiselect:false, draggable:false, keyboard:true});
  477. this.responses_list
  478. .addEventListener('select', function(list) {
  479. var win, id = list.get_single_selection();
  480. ref.enable_command('delete', !!id && $.inArray(id, ref.env.readonly_responses) < 0);
  481. if (id && (win = ref.get_frame_window(ref.env.contentframe))) {
  482. ref.set_busy(true);
  483. ref.location_href({ _action:'edit-response', _key:id, _framed:1 }, win);
  484. }
  485. })
  486. .init()
  487. .focus();
  488. }
  489. break;
  490. case 'login':
  491. var tz, tz_name, jstz = window.jstz,
  492. input_user = $('#rcmloginuser'),
  493. input_tz = $('#rcmlogintz');
  494. input_user.keyup(function(e) { return ref.login_user_keyup(e); });
  495. if (input_user.val() == '')
  496. input_user.focus();
  497. else
  498. $('#rcmloginpwd').focus();
  499. // detect client timezone
  500. if (jstz && (tz = jstz.determine()))
  501. tz_name = tz.name();
  502. input_tz.val(tz_name ? tz_name : (new Date().getStdTimezoneOffset() / -60));
  503. // display 'loading' message on form submit, lock submit button
  504. $('form').submit(function () {
  505. $('input[type=submit]', this).prop('disabled', true);
  506. ref.clear_messages();
  507. ref.display_message('', 'loading');
  508. });
  509. this.enable_command('login', true);
  510. break;
  511. }
  512. // select first input field in an edit form
  513. if (this.gui_objects.editform)
  514. $("input,select,textarea", this.gui_objects.editform)
  515. .not(':hidden').not(':disabled').first().select().focus();
  516. // unset contentframe variable if preview_pane is enabled
  517. if (this.env.contentframe && !$('#' + this.env.contentframe).is(':visible'))
  518. this.env.contentframe = null;
  519. // prevent from form submit with Enter key in file input fields
  520. if (bw.ie)
  521. $('input[type=file]').keydown(function(e) { if (e.keyCode == '13') e.preventDefault(); });
  522. // flag object as complete
  523. this.loaded = true;
  524. this.env.lastrefresh = new Date();
  525. // show message
  526. if (this.pending_message)
  527. this.display_message.apply(this, this.pending_message);
  528. // init treelist widget
  529. if (this.gui_objects.folderlist && window.rcube_treelist_widget
  530. // some plugins may load rcube_treelist_widget and there's one case
  531. // when this will cause problems - addressbook widget in compose,
  532. // which already has been initialized using rcube_list_widget
  533. && this.gui_objects.folderlist != this.gui_objects.addressbookslist
  534. ) {
  535. this.treelist = new rcube_treelist_widget(this.gui_objects.folderlist, {
  536. selectable: true,
  537. id_prefix: 'rcmli',
  538. parent_focus: true,
  539. id_encode: this.html_identifier_encode,
  540. id_decode: this.html_identifier_decode,
  541. check_droptarget: function(node) { return !node.virtual && ref.check_droptarget(node.id) }
  542. });
  543. this.treelist
  544. .addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
  545. .addEventListener('expand', function(node) { ref.folder_collapsed(node) })
  546. .addEventListener('beforeselect', function(node) { return !ref.busy; })
  547. .addEventListener('select', function(node) {
  548. ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' });
  549. ref.mark_all_read_state();
  550. });
  551. }
  552. // activate html5 file drop feature (if browser supports it and if configured)
  553. if (this.gui_objects.filedrop && this.env.filedrop && ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData)) {
  554. $(document.body).on('dragover dragleave drop', function(e) { return ref.document_drag_hover(e, e.type == 'dragover'); });
  555. $(this.gui_objects.filedrop).addClass('droptarget')
  556. .on('dragover dragleave', function(e) { return ref.file_drag_hover(e, e.type == 'dragover'); })
  557. .get(0).addEventListener('drop', function(e) { return ref.file_dropped(e); }, false);
  558. }
  559. // catch document (and iframe) mouse clicks
  560. var body_mouseup = function(e) { return ref.doc_mouse_up(e); };
  561. $(document.body)
  562. .mouseup(body_mouseup)
  563. .keydown(function(e) { return ref.doc_keypress(e); });
  564. rcube_webmail.set_iframe_events({mouseup: body_mouseup});
  565. // trigger init event hook
  566. this.triggerEvent('init', { task:this.task, action:this.env.action });
  567. // execute all foreign onload scripts
  568. // @deprecated
  569. for (n in this.onloads) {
  570. if (typeof this.onloads[n] === 'string')
  571. eval(this.onloads[n]);
  572. else if (typeof this.onloads[n] === 'function')
  573. this.onloads[n]();
  574. }
  575. // start keep-alive and refresh intervals
  576. this.start_refresh();
  577. this.start_keepalive();
  578. };
  579. this.log = function(msg)
  580. {
  581. if (this.env.devel_mode && window.console && console.log)
  582. console.log(msg);
  583. };
  584. /*********************************************************/
  585. /********* client command interface *********/
  586. /*********************************************************/
  587. // execute a specific command on the web client
  588. this.command = function(command, props, obj, event)
  589. {
  590. var ret, uid, cid, url, flag, aborted = false;
  591. if (obj && obj.blur && !(event && rcube_event.is_keyboard(event)))
  592. obj.blur();
  593. // do nothing if interface is locked by another command
  594. // with exception for searching reset and menu
  595. if (this.busy && !(command == 'reset-search' && this.last_command == 'search') && !command.match(/^menu-/))
  596. return false;
  597. // let the browser handle this click (shift/ctrl usually opens the link in a new window/tab)
  598. if ((obj && obj.href && String(obj.href).indexOf('#') < 0) && rcube_event.get_modifier(event)) {
  599. return true;
  600. }
  601. // command not supported or allowed
  602. if (!this.commands[command]) {
  603. // pass command to parent window
  604. if (this.is_framed())
  605. parent.rcmail.command(command, props);
  606. return false;
  607. }
  608. // check input before leaving compose step
  609. if (this.task == 'mail' && this.env.action == 'compose' && !this.env.server_error && command != 'save-pref'
  610. && $.inArray(command, this.env.compose_commands) < 0
  611. ) {
  612. if (!this.env.is_sent && this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
  613. return false;
  614. // remove copy from local storage if compose screen is left intentionally
  615. this.remove_compose_data(this.env.compose_id);
  616. this.compose_skip_unsavedcheck = true;
  617. }
  618. this.last_command = command;
  619. // process external commands
  620. if (typeof this.command_handlers[command] === 'function') {
  621. ret = this.command_handlers[command](props, obj, event);
  622. return ret !== undefined ? ret : (obj ? false : true);
  623. }
  624. else if (typeof this.command_handlers[command] === 'string') {
  625. ret = window[this.command_handlers[command]](props, obj, event);
  626. return ret !== undefined ? ret : (obj ? false : true);
  627. }
  628. // trigger plugin hooks
  629. this.triggerEvent('actionbefore', {props:props, action:command, originalEvent:event});
  630. ret = this.triggerEvent('before'+command, props || event);
  631. if (ret !== undefined) {
  632. // abort if one of the handlers returned false
  633. if (ret === false)
  634. return false;
  635. else
  636. props = ret;
  637. }
  638. ret = undefined;
  639. // process internal command
  640. switch (command) {
  641. case 'login':
  642. if (this.gui_objects.loginform)
  643. this.gui_objects.loginform.submit();
  644. break;
  645. // commands to switch task
  646. case 'logout':
  647. case 'mail':
  648. case 'addressbook':
  649. case 'settings':
  650. this.switch_task(command);
  651. break;
  652. case 'about':
  653. this.redirect('?_task=settings&_action=about', false);
  654. break;
  655. case 'permaurl':
  656. if (obj && obj.href && obj.target)
  657. return true;
  658. else if (this.env.permaurl)
  659. parent.location.href = this.env.permaurl;
  660. break;
  661. case 'extwin':
  662. if (this.env.action == 'compose') {
  663. var form = this.gui_objects.messageform,
  664. win = this.open_window('');
  665. if (win) {
  666. this.save_compose_form_local();
  667. this.compose_skip_unsavedcheck = true;
  668. $("input[name='_action']", form).val('compose');
  669. form.action = this.url('mail/compose', { _id: this.env.compose_id, _extwin: 1 });
  670. form.target = win.name;
  671. form.submit();
  672. }
  673. }
  674. else {
  675. this.open_window(this.env.permaurl, true);
  676. }
  677. break;
  678. case 'change-format':
  679. url = this.env.permaurl + '&_format=' + props;
  680. if (this.env.action == 'preview')
  681. url = url.replace(/_action=show/, '_action=preview') + '&_framed=1';
  682. if (this.env.extwin)
  683. url += '&_extwin=1';
  684. location.href = url;
  685. break;
  686. case 'menu-open':
  687. if (props && props.menu == 'attachmentmenu') {
  688. var mimetype = this.env.attachments[props.id];
  689. if (mimetype && mimetype.mimetype) // in compose format is different
  690. mimetype = mimetype.mimetype;
  691. this.enable_command('open-attachment', mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0);
  692. }
  693. this.show_menu(props, props.show || undefined, event);
  694. break;
  695. case 'menu-close':
  696. this.hide_menu(props, event);
  697. break;
  698. case 'menu-save':
  699. this.triggerEvent(command, {props:props, originalEvent:event});
  700. return false;
  701. case 'open':
  702. if (uid = this.get_single_uid()) {
  703. obj.href = this.url('show', this.params_from_uid(uid));
  704. return true;
  705. }
  706. break;
  707. case 'close':
  708. if (this.env.extwin)
  709. window.close();
  710. break;
  711. case 'list':
  712. if (props && props != '') {
  713. this.reset_qsearch(true);
  714. }
  715. if (this.env.action == 'compose' && this.env.extwin) {
  716. window.close();
  717. }
  718. else if (this.task == 'mail') {
  719. this.list_mailbox(props);
  720. this.set_button_titles();
  721. }
  722. else if (this.task == 'addressbook')
  723. this.list_contacts(props);
  724. break;
  725. case 'set-listmode':
  726. this.set_list_options(null, undefined, undefined, props == 'threads' ? 1 : 0);
  727. break;
  728. case 'sort':
  729. var sort_order = this.env.sort_order,
  730. sort_col = !this.env.disabled_sort_col ? props : this.env.sort_col;
  731. if (!this.env.disabled_sort_order)
  732. sort_order = this.env.sort_col == sort_col && sort_order == 'ASC' ? 'DESC' : 'ASC';
  733. // set table header and update env
  734. this.set_list_sorting(sort_col, sort_order);
  735. // reload message list
  736. this.list_mailbox('', '', sort_col+'_'+sort_order);
  737. break;
  738. case 'nextpage':
  739. this.list_page('next');
  740. break;
  741. case 'lastpage':
  742. this.list_page('last');
  743. break;
  744. case 'previouspage':
  745. this.list_page('prev');
  746. break;
  747. case 'firstpage':
  748. this.list_page('first');
  749. break;
  750. case 'expunge':
  751. if (this.env.exists)
  752. this.expunge_mailbox(this.env.mailbox);
  753. break;
  754. case 'purge':
  755. case 'empty-mailbox':
  756. if (this.env.exists)
  757. this.purge_mailbox(this.env.mailbox);
  758. break;
  759. // common commands used in multiple tasks
  760. case 'show':
  761. if (this.task == 'mail') {
  762. uid = this.get_single_uid();
  763. if (uid && (!this.env.uid || uid != this.env.uid)) {
  764. if (this.env.mailbox == this.env.drafts_mailbox)
  765. this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
  766. else
  767. this.show_message(uid);
  768. }
  769. }
  770. else if (this.task == 'addressbook') {
  771. cid = props ? props : this.get_single_cid();
  772. if (cid && !(this.env.action == 'show' && cid == this.env.cid))
  773. this.load_contact(cid, 'show');
  774. }
  775. break;
  776. case 'add':
  777. if (this.task == 'addressbook')
  778. this.load_contact(0, 'add');
  779. else if (this.task == 'settings' && this.env.action == 'responses') {
  780. var frame;
  781. if ((frame = this.get_frame_window(this.env.contentframe))) {
  782. this.set_busy(true);
  783. this.location_href({ _action:'add-response', _framed:1 }, frame);
  784. }
  785. }
  786. else if (this.task == 'settings') {
  787. this.identity_list.clear_selection();
  788. this.load_identity(0, 'add-identity');
  789. }
  790. break;
  791. case 'edit':
  792. if (this.task == 'addressbook' && (cid = this.get_single_cid()))
  793. this.load_contact(cid, 'edit');
  794. else if (this.task == 'settings' && props)
  795. this.load_identity(props, 'edit-identity');
  796. else if (this.task == 'mail' && (uid = this.get_single_uid())) {
  797. url = { _mbox: this.get_message_mailbox(uid) };
  798. url[this.env.mailbox == this.env.drafts_mailbox && props != 'new' ? '_draft_uid' : '_uid'] = uid;
  799. this.open_compose_step(url);
  800. }
  801. break;
  802. case 'save':
  803. var input, form = this.gui_objects.editform;
  804. if (form) {
  805. // adv. search
  806. if (this.env.action == 'search') {
  807. }
  808. // user prefs
  809. else if ((input = $("input[name='_pagesize']", form)) && input.length && isNaN(parseInt(input.val()))) {
  810. alert(this.get_label('nopagesizewarning'));
  811. input.focus();
  812. break;
  813. }
  814. // contacts/identities
  815. else {
  816. // reload form
  817. if (props == 'reload') {
  818. form.action += '&_reload=1';
  819. }
  820. else if (this.task == 'settings' && (this.env.identities_level % 2) == 0 &&
  821. (input = $("input[name='_email']", form)) && input.length && !rcube_check_email(input.val())
  822. ) {
  823. alert(this.get_label('noemailwarning'));
  824. input.focus();
  825. break;
  826. }
  827. }
  828. // add selected source (on the list)
  829. if (parent.rcmail && parent.rcmail.env.source)
  830. form.action = this.add_url(form.action, '_orig_source', parent.rcmail.env.source);
  831. form.submit();
  832. }
  833. break;
  834. case 'delete':
  835. // mail task
  836. if (this.task == 'mail')
  837. this.delete_messages(event);
  838. // addressbook task
  839. else if (this.task == 'addressbook')
  840. this.delete_contacts();
  841. // settings: canned response
  842. else if (this.task == 'settings' && this.env.action == 'responses')
  843. this.delete_response();
  844. // settings: user identities
  845. else if (this.task == 'settings')
  846. this.delete_identity();
  847. break;
  848. // mail task commands
  849. case 'move':
  850. case 'moveto': // deprecated
  851. if (this.task == 'mail')
  852. this.move_messages(props, event);
  853. else if (this.task == 'addressbook')
  854. this.move_contacts(props);
  855. break;
  856. case 'copy':
  857. if (this.task == 'mail')
  858. this.copy_messages(props, event);
  859. else if (this.task == 'addressbook')
  860. this.copy_contacts(props);
  861. break;
  862. case 'mark':
  863. if (props)
  864. this.mark_message(props);
  865. break;
  866. case 'toggle_status':
  867. case 'toggle_flag':
  868. flag = command == 'toggle_flag' ? 'flagged' : 'read';
  869. if (uid = props) {
  870. // toggle flagged/unflagged
  871. if (flag == 'flagged') {
  872. if (this.message_list.rows[uid].flagged)
  873. flag = 'unflagged';
  874. }
  875. // toggle read/unread
  876. else if (this.message_list.rows[uid].deleted)
  877. flag = 'undelete';
  878. else if (!this.message_list.rows[uid].unread)
  879. flag = 'unread';
  880. this.mark_message(flag, uid);
  881. }
  882. break;
  883. case 'always-load':
  884. if (this.env.uid && this.env.sender) {
  885. this.add_contact(this.env.sender);
  886. setTimeout(function(){ ref.command('load-images'); }, 300);
  887. break;
  888. }
  889. case 'load-images':
  890. if (this.env.uid)
  891. this.show_message(this.env.uid, true, this.env.action=='preview');
  892. break;
  893. case 'load-attachment':
  894. case 'open-attachment':
  895. case 'download-attachment':
  896. var params, mimetype = this.env.attachments[props];
  897. if (this.env.action == 'compose') {
  898. params = {_file: props, _id: this.env.compose_id};
  899. mimetype = mimetype ? mimetype.mimetype : '';
  900. }
  901. else {
  902. params = {_mbox: this.env.mailbox, _uid: this.env.uid, _part: props};
  903. }
  904. // open attachment in frame if it's of a supported mimetype
  905. if (command != 'download-attachment' && mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0) {
  906. if (this.open_window(this.url('get', $.extend({_frame: 1}, params))))
  907. break;
  908. }
  909. params._download = 1;
  910. // prevent from page unload warning in compose
  911. this.compose_skip_unsavedcheck = 1;
  912. this.goto_url('get', params, false, true);
  913. this.compose_skip_unsavedcheck = 0;
  914. break;
  915. case 'select-all':
  916. this.select_all_mode = props ? false : true;
  917. this.dummy_select = true; // prevent msg opening if there's only one msg on the list
  918. if (props == 'invert')
  919. this.message_list.invert_selection();
  920. else
  921. this.message_list.select_all(props == 'page' ? '' : props);
  922. this.dummy_select = null;
  923. break;
  924. case 'select-none':
  925. this.select_all_mode = false;
  926. this.message_list.clear_selection();
  927. break;
  928. case 'expand-all':
  929. this.env.autoexpand_threads = 1;
  930. this.message_list.expand_all();
  931. break;
  932. case 'expand-unread':
  933. this.env.autoexpand_threads = 2;
  934. this.message_list.collapse_all();
  935. this.expand_unread();
  936. break;
  937. case 'collapse-all':
  938. this.env.autoexpand_threads = 0;
  939. this.message_list.collapse_all();
  940. break;
  941. case 'nextmessage':
  942. if (this.env.next_uid)
  943. this.show_message(this.env.next_uid, false, this.env.action == 'preview');
  944. break;
  945. case 'lastmessage':
  946. if (this.env.last_uid)
  947. this.show_message(this.env.last_uid);
  948. break;
  949. case 'previousmessage':
  950. if (this.env.prev_uid)
  951. this.show_message(this.env.prev_uid, false, this.env.action == 'preview');
  952. break;
  953. case 'firstmessage':
  954. if (this.env.first_uid)
  955. this.show_message(this.env.first_uid);
  956. break;
  957. case 'compose':
  958. url = {};
  959. if (this.task == 'mail') {
  960. url = {_mbox: this.env.mailbox, _search: this.env.search_request};
  961. if (props)
  962. url._to = props;
  963. }
  964. // modify url if we're in addressbook
  965. else if (this.task == 'addressbook') {
  966. // switch to mail compose step directly
  967. if (props && props.indexOf('@') > 0) {
  968. url._to = props;
  969. }
  970. else {
  971. var a_cids = [];
  972. // use contact id passed as command parameter
  973. if (props)
  974. a_cids.push(props);
  975. // get selected contacts
  976. else if (this.contact_list)
  977. a_cids = this.contact_list.get_selection();
  978. if (a_cids.length)
  979. this.http_post('mailto', { _cid: a_cids.join(','), _source: this.env.source }, true);
  980. else if (this.env.group)
  981. this.http_post('mailto', { _gid: this.env.group, _source: this.env.source }, true);
  982. break;
  983. }
  984. }
  985. else if (props && typeof props == 'string') {
  986. url._to = props;
  987. }
  988. else if (props && typeof props == 'object') {
  989. $.extend(url, props);
  990. }
  991. this.open_compose_step(url);
  992. break;
  993. case 'spellcheck':
  994. if (this.spellcheck_state()) {
  995. this.editor.spellcheck_stop();
  996. }
  997. else {
  998. this.editor.spellcheck_start();
  999. }
  1000. break;
  1001. case 'savedraft':
  1002. // Reset the auto-save timer
  1003. clearTimeout(this.save_timer);
  1004. // compose form did not change (and draft wasn't saved already)
  1005. if (this.env.draft_id && this.cmp_hash == this.compose_field_hash()) {
  1006. this.auto_save_start();
  1007. break;
  1008. }
  1009. this.submit_messageform(true);
  1010. break;
  1011. case 'send':
  1012. if (!props.nocheck && !this.env.is_sent && !this.check_compose_input(command))
  1013. break;
  1014. // Reset the auto-save timer
  1015. clearTimeout(this.save_timer);
  1016. this.submit_messageform();
  1017. break;
  1018. case 'send-attachment':
  1019. // Reset the auto-save timer
  1020. clearTimeout(this.save_timer);
  1021. if (!(flag = this.upload_file(props || this.gui_objects.uploadform, 'upload'))) {
  1022. if (flag !== false)
  1023. alert(this.get_label('selectimportfile'));
  1024. aborted = true;
  1025. }
  1026. break;
  1027. case 'insert-sig':
  1028. this.change_identity($("[name='_from']")[0], true);
  1029. break;
  1030. case 'list-addresses':
  1031. this.list_contacts(props);
  1032. this.enable_command('add-recipient', false);
  1033. break;
  1034. case 'add-recipient':
  1035. this.compose_add_recipient(props);
  1036. break;
  1037. case 'reply-all':
  1038. case 'reply-list':
  1039. case 'reply':
  1040. if (uid = this.get_single_uid()) {
  1041. url = {_reply_uid: uid, _mbox: this.get_message_mailbox(uid), _search: this.env.search_request};
  1042. if (command == 'reply-all')
  1043. // do reply-list, when list is detected and popup menu wasn't used
  1044. url._all = (!props && this.env.reply_all_mode == 1 && this.commands['reply-list'] ? 'list' : 'all');
  1045. else if (command == 'reply-list')
  1046. url._all = 'list';
  1047. this.open_compose_step(url);
  1048. }
  1049. break;
  1050. case 'forward-attachment':
  1051. case 'forward-inline':
  1052. case 'forward':
  1053. var uids = this.env.uid ? [this.env.uid] : (this.message_list ? this.message_list.get_selection() : []);
  1054. if (uids.length) {
  1055. url = { _forward_uid: this.uids_to_list(uids), _mbox: this.env.mailbox, _search: this.env.search_request };
  1056. if (command == 'forward-attachment' || (!props && this.env.forward_attachment) || uids.length > 1)
  1057. url._attachment = 1;
  1058. this.open_compose_step(url);
  1059. }
  1060. break;
  1061. case 'print':
  1062. if (this.task == 'addressbook') {
  1063. if (uid = this.contact_list.get_single_selection()) {
  1064. url = '&_action=print&_cid=' + uid;
  1065. if (this.env.source)
  1066. url += '&_source=' + urlencode(this.env.source);
  1067. this.open_window(this.env.comm_path + url, true, true);
  1068. }
  1069. }
  1070. else if (this.env.action == 'get' && !this.env.is_message) {
  1071. this.gui_objects.messagepartframe.contentWindow.print();
  1072. }
  1073. else if (uid = this.get_single_uid()) {
  1074. url = this.url('print', this.params_from_uid(uid, {_safe: this.env.safemode ? 1 : 0}));
  1075. if (this.open_window(url, true, true)) {
  1076. if (this.env.action != 'show' && this.env.action != 'get')
  1077. this.mark_message('read', uid);
  1078. }
  1079. }
  1080. break;
  1081. case 'viewsource':
  1082. if (uid = this.get_single_uid())
  1083. this.open_window(this.url('viewsource', this.params_from_uid(uid)), true, true);
  1084. break;
  1085. case 'download':
  1086. if (this.env.action == 'get') {
  1087. location.href = this.secure_url(location.href.replace(/_frame=/, '_download='));
  1088. }
  1089. else if (uid = this.get_single_uid()) {
  1090. this.goto_url('viewsource', this.params_from_uid(uid, {_save: 1}), false, true);
  1091. }
  1092. break;
  1093. // quicksearch
  1094. case 'search':
  1095. ret = this.qsearch(props);
  1096. break;
  1097. // reset quicksearch
  1098. case 'reset-search':
  1099. var n, s = this.env.search_request || this.env.qsearch;
  1100. this.reset_qsearch(true);
  1101. if (s && this.env.action == 'compose') {
  1102. if (this.contact_list)
  1103. this.list_contacts_clear();
  1104. }
  1105. else if (s && this.env.mailbox) {
  1106. this.list_mailbox(this.env.mailbox, 1);
  1107. }
  1108. else if (s && this.task == 'addressbook') {
  1109. if (this.env.source == '') {
  1110. for (n in this.env.address_sources) break;
  1111. this.env.source = n;
  1112. this.env.group = '';
  1113. }
  1114. this.list_contacts(this.env.source, this.env.group, 1);
  1115. }
  1116. break;
  1117. case 'pushgroup':
  1118. // add group ID and current search to stack
  1119. var group = {
  1120. id: props.id,
  1121. search_request: this.env.search_request,
  1122. page: this.env.current_page,
  1123. search: this.env.search_request && this.gui_objects.qsearchbox ? this.gui_objects.qsearchbox.value : null
  1124. };
  1125. this.env.address_group_stack.push(group);
  1126. if (obj && event)
  1127. rcube_event.cancel(event);
  1128. case 'listgroup':
  1129. this.reset_qsearch();
  1130. this.list_contacts(props.source, props.id, 1, group);
  1131. break;
  1132. case 'popgroup':
  1133. if (this.env.address_group_stack.length) {
  1134. var old = this.env.address_group_stack.pop();
  1135. this.reset_qsearch();
  1136. if (old.search_request) {
  1137. // this code is executed when going back to the search result
  1138. if (old.search && this.gui_objects.qsearchbox)
  1139. $(this.gui_objects.qsearchbox).val(old.search);
  1140. this.env.search_request = old.search_request;
  1141. this.list_contacts_remote(null, null, this.env.current_page = old.page);
  1142. }
  1143. else
  1144. this.list_contacts(props.source, this.env.address_group_stack[this.env.address_group_stack.length-1].id);
  1145. }
  1146. break;
  1147. case 'import-messages':
  1148. var form = props || this.gui_objects.importform,
  1149. importlock = this.set_busy(true, 'importwait');
  1150. $('input[name="_unlock"]', form).val(importlock);
  1151. if (!(flag = this.upload_file(form, 'import', importlock))) {
  1152. this.set_busy(false, null, importlock);
  1153. if (flag !== false)
  1154. alert(this.get_label('selectimportfile'));
  1155. aborted = true;
  1156. }
  1157. break;
  1158. case 'import':
  1159. if (this.env.action == 'import' && this.gui_objects.importform) {
  1160. var file = document.getElementById('rcmimportfile');
  1161. if (file && !file.value) {
  1162. alert(this.get_label('selectimportfile'));
  1163. aborted = true;
  1164. break;
  1165. }
  1166. this.gui_objects.importform.submit();
  1167. this.set_busy(true, 'importwait');
  1168. this.lock_form(this.gui_objects.importform, true);
  1169. }
  1170. else
  1171. this.goto_url('import', (this.env.source ? '_target='+urlencode(this.env.source)+'&' : ''));
  1172. break;
  1173. case 'export':
  1174. if (this.contact_list.rowcount > 0) {
  1175. this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _search: this.env.search_request }, false, true);
  1176. }
  1177. break;
  1178. case 'export-selected':
  1179. if (this.contact_list.rowcount > 0) {
  1180. this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') }, false, true);
  1181. }
  1182. break;
  1183. case 'upload-photo':
  1184. this.upload_contact_photo(props || this.gui_objects.uploadform);
  1185. break;
  1186. case 'delete-photo':
  1187. this.replace_contact_photo('-del-');
  1188. break;
  1189. // user settings commands
  1190. case 'preferences':
  1191. case 'identities':
  1192. case 'responses':
  1193. case 'folders':
  1194. this.goto_url('settings/' + command);
  1195. break;
  1196. case 'undo':
  1197. this.http_request('undo', '', this.display_message('', 'loading'));
  1198. break;
  1199. // unified command call (command name == function name)
  1200. default:
  1201. var func = command.replace(/-/g, '_');
  1202. if (this[func] && typeof this[func] === 'function') {
  1203. ret = this[func](props, obj, event);
  1204. }
  1205. break;
  1206. }
  1207. if (!aborted && this.triggerEvent('after'+command, props) === false)
  1208. ret = false;
  1209. this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted, ret:ret });
  1210. return ret === false ? false : obj ? false : true;
  1211. };
  1212. // set command(s) enabled or disabled
  1213. this.enable_command = function()
  1214. {
  1215. var i, n, args = Array.prototype.slice.call(arguments),
  1216. enable = args.pop(), cmd;
  1217. for (n=0; n<args.length; n++) {
  1218. cmd = args[n];
  1219. // argument of type array
  1220. if (typeof cmd === 'string') {
  1221. this.commands[cmd] = enable;
  1222. this.set_button(cmd, (enable ? 'act' : 'pas'));
  1223. this.triggerEvent('enable-command', {command: cmd, status: enable});
  1224. }
  1225. // push array elements into commands array
  1226. else {
  1227. for (i in cmd)
  1228. args.push(cmd[i]);
  1229. }
  1230. }
  1231. };
  1232. this.command_enabled = function(cmd)
  1233. {
  1234. return this.commands[cmd];
  1235. };
  1236. // lock/unlock interface
  1237. this.set_busy = function(a, message, id)
  1238. {
  1239. if (a && message) {
  1240. var msg = this.get_label(message);
  1241. if (msg == message)
  1242. msg = 'Loading...';
  1243. id = this.display_message(msg, 'loading');
  1244. }
  1245. else if (!a && id) {
  1246. this.hide_message(id);
  1247. }
  1248. this.busy = a;
  1249. //document.body.style.cursor = a ? 'wait' : 'default';
  1250. if (this.gui_objects.editform)
  1251. this.lock_form(this.gui_objects.editform, a);
  1252. return id;
  1253. };
  1254. // return a localized string
  1255. this.get_label = function(name, domain)
  1256. {
  1257. if (domain && this.labels[domain+'.'+name])
  1258. return this.labels[domain+'.'+name];
  1259. else if (this.labels[name])
  1260. return this.labels[name];
  1261. else
  1262. return name;
  1263. };
  1264. // alias for convenience reasons
  1265. this.gettext = this.get_label;
  1266. // switch to another application task
  1267. this.switch_task = function(task)
  1268. {
  1269. if (this.task === task && task != 'mail')
  1270. return;
  1271. var url = this.get_task_url(task);
  1272. if (task == 'mail')
  1273. url += '&_mbox=INBOX';
  1274. else if (task == 'logout' && !this.env.server_error) {
  1275. url = this.secure_url(url);
  1276. this.clear_compose_data();
  1277. }
  1278. this.redirect(url);
  1279. };
  1280. this.get_task_url = function(task, url)
  1281. {
  1282. if (!url)
  1283. url = this.env.comm_path;
  1284. if (url.match(/[?&]_task=[a-zA-Z0-9_-]+/))
  1285. return url.replace(/_task=[a-zA-Z0-9_-]+/, '_task=' + task);
  1286. else
  1287. return url.replace(/\?.*$/, '') + '?_task=' + task;
  1288. };
  1289. this.reload = function(delay)
  1290. {
  1291. if (this.is_framed())
  1292. parent.rcmail.reload(delay);
  1293. else if (delay)
  1294. setTimeout(function() { ref.reload(); }, delay);
  1295. else if (window.location)
  1296. location.href = this.url('', {_extwin: this.env.extwin});
  1297. };
  1298. // Add variable to GET string, replace old value if exists
  1299. this.add_url = function(url, name, value)
  1300. {
  1301. value = urlencode(value);
  1302. if (/(\?.*)$/.test(url)) {
  1303. var urldata = RegExp.$1,
  1304. datax = RegExp('((\\?|&)'+RegExp.escape(name)+'=[^&]*)');
  1305. if (datax.test(urldata)) {
  1306. urldata = urldata.replace(datax, RegExp.$2 + name + '=' + value);
  1307. }
  1308. else
  1309. urldata += '&' + name + '=' + value
  1310. return url.replace(/(\?.*)$/, urldata);
  1311. }
  1312. return url + '?' + name + '=' + value;
  1313. };
  1314. // append CSRF protection token to the given url
  1315. this.secure_url = function(url)
  1316. {
  1317. return this.add_url(url, '_token', this.env.request_token);
  1318. },
  1319. this.is_framed = function()
  1320. {
  1321. return this.env.framed && parent.rcmail && parent.rcmail != this && typeof parent.rcmail.command == 'function';
  1322. };
  1323. this.save_pref = function(prop)
  1324. {
  1325. var request = {_name: prop.name, _value: prop.value};
  1326. if (prop.session)
  1327. request._session = prop.session;
  1328. if (prop.env)
  1329. this.env[prop.env] = prop.value;
  1330. this.http_post('save-pref', request);
  1331. };
  1332. this.html_identifier = function(str, encode)
  1333. {
  1334. return encode ? this.html_identifier_encode(str) : String(str).replace(this.identifier_expr, '_');
  1335. };
  1336. this.html_identifier_encode = function(str)
  1337. {
  1338. return Base64.encode(String(str)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
  1339. };
  1340. this.html_identifier_decode = function(str)
  1341. {
  1342. str = String(str).replace(/-/g, '+').replace(/_/g, '/');
  1343. while (str.length % 4) str += '=';
  1344. return Base64.decode(str);
  1345. };
  1346. /*********************************************************/
  1347. /********* event handling methods *********/
  1348. /*********************************************************/
  1349. this.drag_menu = function(e, target)
  1350. {
  1351. var modkey = rcube_event.get_modifier(e),
  1352. menu = this.gui_objects.dragmenu;
  1353. if (menu && modkey == SHIFT_KEY && this.commands['copy']) {
  1354. var pos = rcube_event.get_mouse_pos(e);
  1355. this.env.drag_target = target;
  1356. this.show_menu(this.gui_objects.dragmenu.id, true, e);
  1357. $(menu).css({top: (pos.y-10)+'px', left: (pos.x-10)+'px'});
  1358. return true;
  1359. }
  1360. return false;
  1361. };
  1362. this.drag_menu_action = function(action)
  1363. {
  1364. var menu = this.gui_objects.dragmenu;
  1365. if (menu) {
  1366. $(menu).hide();
  1367. }
  1368. this.command(action, this.env.drag_target);
  1369. this.env.drag_target = null;
  1370. };
  1371. this.drag_start = function(list)
  1372. {
  1373. this.drag_active = true;
  1374. if (this.preview_timer)
  1375. clearTimeout(this.preview_timer);
  1376. // prepare treelist widget for dragging interactions
  1377. if (this.treelist)
  1378. this.treelist.drag_start();
  1379. };
  1380. this.drag_end = function(e)
  1381. {
  1382. var list, model;
  1383. if (this.treelist)
  1384. this.treelist.drag_end();
  1385. // execute drag & drop action when mouse was released
  1386. if (list = this.message_list)
  1387. model = this.env.mailboxes;
  1388. else if (list = this.contact_list)
  1389. model = this.env.contactfolders;
  1390. if (this.drag_active && model && this.env.last_folder_target) {
  1391. var target = model[this.env.last_folder_target];
  1392. list.draglayer.hide();
  1393. if (this.contact_list) {
  1394. if (!this.contacts_drag_menu(e, target))
  1395. this.command('move', target);
  1396. }
  1397. else if (!this.drag_menu(e, target))
  1398. this.command('move', target);
  1399. }
  1400. this.drag_active = false;
  1401. this.env.last_folder_target = null;
  1402. };
  1403. this.drag_move = function(e)
  1404. {
  1405. if (this.gui_objects.folderlist) {
  1406. var drag_target, oldclass,
  1407. layerclass = 'draglayernormal',
  1408. mouse = rcube_event.get_mouse_pos(e);
  1409. if (this.contact_list && this.contact_list.draglayer)
  1410. oldclass = this.contact_list.draglayer.attr('class');
  1411. // mouse intersects a valid drop target on the treelist
  1412. if (this.treelist && (drag_target = this.treelist.intersects(mouse, true))) {
  1413. this.env.last_folder_target = drag_target;
  1414. layerclass = 'draglayer' + (this.check_droptarget(drag_target) > 1 ? 'copy' : 'normal');
  1415. }
  1416. else {
  1417. // Clear target, otherwise drag end will trigger move into last valid droptarget
  1418. this.env.last_folder_target = null;
  1419. }
  1420. if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
  1421. this.contact_list.draglayer.attr('class', layerclass);
  1422. }
  1423. };
  1424. this.collapse_folder = function(name)
  1425. {
  1426. if (this.treelist)
  1427. this.treelist.toggle(name);
  1428. };
  1429. this.folder_collapsed = function(node)
  1430. {
  1431. var prefname = this.env.task == 'addressbook' ? 'collapsed_abooks' : 'collapsed_folders',
  1432. old = this.env[prefname];
  1433. if (node.collapsed) {
  1434. this.env[prefname] = this.env[prefname] + '&'+urlencode(node.id)+'&';
  1435. // select the folder if one of its childs is currently selected
  1436. // don't select if it's virtual (#1488346)
  1437. if (!node.virtual && this.env.mailbox && this.env.mailbox.startsWith(node.id + this.env.delimiter))
  1438. this.command('list', node.id);
  1439. }
  1440. else {
  1441. var reg = new RegExp('&'+urlencode(node.id)+'&');
  1442. this.env[prefname] = this.env[prefname].replace(reg, '');
  1443. }
  1444. if (!this.drag_active) {
  1445. if (old !== this.env[prefname])
  1446. this.command('save-pref', { name: prefname, value: this.env[prefname] });
  1447. if (this.env.unread_counts)
  1448. this.set_unread_count_display(node.id, false);
  1449. }
  1450. };
  1451. // global mouse-click handler to cleanup some UI elements
  1452. this.doc_mouse_up = function(e)
  1453. {
  1454. var list, id, target = rcube_event.get_target(e);
  1455. // ignore event if jquery UI dialog is open
  1456. if ($(target).closest('.ui-dialog, .ui-widget-overlay').length)
  1457. return;
  1458. // remove focus from list widgets
  1459. if (window.rcube_list_widget && rcube_list_widget._instances.length) {
  1460. $.each(rcube_list_widget._instances, function(i,list){
  1461. if (list && !rcube_mouse_is_over(e, list.list.parentNode))
  1462. list.blur();
  1463. });
  1464. }
  1465. // reset 'pressed' buttons
  1466. if (this.buttons_sel) {
  1467. for (id in this.buttons_sel)
  1468. if (typeof id !== 'function')
  1469. this.button_out(this.buttons_sel[id], id);
  1470. this.buttons_sel = {};
  1471. }
  1472. // reset popup menus; delayed to have updated menu_stack data
  1473. setTimeout(function(e){
  1474. var obj, skip, config, id, i, parents = $(target).parents();
  1475. for (i = ref.menu_stack.length - 1; i >= 0; i--) {
  1476. id = ref.menu_stack[i];
  1477. obj = $('#' + id);
  1478. if (obj.is(':visible')
  1479. && target != obj.data('opener')
  1480. && target != obj.get(0) // check if scroll bar was clicked (#1489832)
  1481. && !parents.is(obj.data('opener'))
  1482. && id != skip
  1483. && (obj.attr('data-editable') != 'true' || !$(target).parents('#' + id).length)
  1484. && (obj.attr('data-sticky') != 'true' || !rcube_mouse_is_over(e, obj.get(0)))
  1485. ) {
  1486. ref.hide_menu(id, e);
  1487. }
  1488. skip = obj.data('parent');
  1489. }
  1490. }, 10, e);
  1491. };
  1492. // global keypress event handler
  1493. this.doc_keypress = function(e)
  1494. {
  1495. // Helper method to move focus to the next/prev active menu item
  1496. var focus_menu_item = function(dir) {
  1497. var obj, item, mod = dir < 0 ? 'prevAll' : 'nextAll', limit = dir < 0 ? 'last' : 'first';
  1498. if (ref.focused_menu && (obj = $('#'+ref.focused_menu))) {
  1499. item = obj.find(':focus').closest('li')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
  1500. if (!item.length)
  1501. item = obj.find(':focus').closest('ul')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
  1502. return item.focus().length;
  1503. }
  1504. return 0;
  1505. };
  1506. var target = e.target || {},
  1507. keyCode = rcube_event.get_keycode(e);
  1508. if (e.keyCode != 27 && (!this.menu_keyboard_active || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')) {
  1509. return true;
  1510. }
  1511. switch (keyCode) {
  1512. case 38:
  1513. case 40:
  1514. case 63232: // "up", in safari keypress
  1515. case 63233: // "down", in safari keypress
  1516. focus_menu_item(keyCode == 38 || keyCode == 63232 ? -1 : 1);
  1517. return rcube_event.cancel(e);
  1518. case 9: // tab
  1519. if (this.focused_menu) {
  1520. var mod = rcube_event.get_modifier(e);
  1521. if (!focus_menu_item(mod == SHIFT_KEY ? -1 : 1)) {
  1522. this.hide_menu(this.focused_menu, e);
  1523. }
  1524. }
  1525. return rcube_event.cancel(e);
  1526. case 27: // esc
  1527. if (this.menu_stack.length)
  1528. this.hide_menu(this.menu_stack[this.menu_stack.length-1], e);
  1529. break;
  1530. }
  1531. return true;
  1532. }
  1533. this.msglist_select = function(list)
  1534. {
  1535. if (this.preview_timer)
  1536. clearTimeout(this.preview_timer);
  1537. var selected = list.get_single_selection();
  1538. this.enable_command(this.env.message_commands, selected != null);
  1539. if (selected) {
  1540. // Hide certain command buttons when Drafts folder is selected
  1541. if (this.env.mailbox == this.env.drafts_mailbox)
  1542. this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', 'forward-inline', false);
  1543. // Disable reply-list when List-Post header is not set
  1544. else {
  1545. var msg = this.env.messages[selected];
  1546. if (!msg.ml)
  1547. this.enable_command('reply-list', false);
  1548. }
  1549. }
  1550. // Multi-message commands
  1551. this.enable_command('delete', 'move', 'copy', 'mark', 'forward', 'forward-attachment', list.selection.length > 0);
  1552. // reset all-pages-selection
  1553. if (selected || (list.selection.length && list.selection.length != list.rowcount))
  1554. this.select_all_mode = false;
  1555. // start timer for message preview (wait for double click)
  1556. if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
  1557. this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, list.dblclick_time);
  1558. else if (this.env.contentframe)
  1559. this.show_contentframe(false);
  1560. };
  1561. // This allow as to re-select selected message and display it in preview frame
  1562. this.msglist_click = function(list)
  1563. {
  1564. if (list.multi_selecting || !this.env.contentframe)
  1565. return;
  1566. if (list.get_single_selection())
  1567. return;
  1568. var win = this.get_frame_window(this.env.contentframe);
  1569. if (win && win.location.href.indexOf(this.env.blankpage) >= 0) {
  1570. if (this.preview_timer)
  1571. clearTimeout(this.preview_timer);
  1572. this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, list.dblclick_time);
  1573. }
  1574. };
  1575. this.msglist_dbl_click = function(list)
  1576. {
  1577. if (this.preview_timer)
  1578. clearTimeout(this.preview_timer);
  1579. var uid = list.get_single_selection();
  1580. if (uid && (this.env.messages[uid].mbox || this.env.mailbox) == this.env.drafts_mailbox)
  1581. this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
  1582. else if (uid)
  1583. this.show_message(uid, false, false);
  1584. };
  1585. this.msglist_keypress = function(list)
  1586. {
  1587. if (list.modkey == CONTROL_KEY)
  1588. return;
  1589. if (list.key_pressed == list.ENTER_KEY)
  1590. this.command('show');
  1591. else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
  1592. this.command('delete');
  1593. else if (list.key_pressed == 33)
  1594. this.command('previouspage');
  1595. else if (list.key_pressed == 34)
  1596. this.command('nextpage');
  1597. };
  1598. this.msglist_get_preview = function()
  1599. {
  1600. var uid = this.get_single_uid();
  1601. if (uid && this.env.contentframe && !this.drag_active)
  1602. this.show_message(uid, false, true);
  1603. else if (this.env.contentframe)
  1604. this.show_contentframe(false);
  1605. };
  1606. this.msglist_expand = function(row)
  1607. {
  1608. if (this.env.messages[row.uid])
  1609. this.env.messages[row.uid].expanded = row.expanded;
  1610. $(row.obj)[row.expanded?'addClass':'removeClass']('expanded');
  1611. };
  1612. this.msglist_set_coltypes = function(list)
  1613. {
  1614. var i, found, name, cols = list.thead.rows[0].cells;
  1615. this.env.listcols = [];
  1616. for (i=0; i<cols.length; i++)
  1617. if (cols[i].id && cols[i].id.startsWith('rcm')) {
  1618. name = cols[i].id.slice(3);
  1619. this.env.listcols.push(name);
  1620. }
  1621. if ((found = $.inArray('flag', this.env.listcols)) >= 0)
  1622. this.env.flagged_col = found;
  1623. if ((found = $.inArray('subject', this.env.listcols)) >= 0)
  1624. this.env.subject_col = found;
  1625. this.command('save-pref', { name: 'list_cols', value: this.env.listcols, session: 'list_attrib/columns' });
  1626. };
  1627. this.check_droptarget = function(id)
  1628. {
  1629. switch (this.task) {
  1630. case 'mail':
  1631. return (this.env.mailboxes[id]
  1632. && !this.env.mailboxes[id].virtual
  1633. && (this.env.mailboxes[id].id != this.env.mailbox || this.is_multifolder_listing())) ? 1 : 0;
  1634. case 'addressbook':
  1635. var target;
  1636. if (id != this.env.source && (target = this.env.contactfolders[id])) {
  1637. // droptarget is a group
  1638. if (target.type == 'group') {
  1639. if (target.id != this.env.group && !this.env.contactfolders[target.source].readonly) {
  1640. var is_other = this.env.selection_sources.length > 1 || $.inArray(target.source, this.env.selection_sources) == -1;
  1641. return !is_other || this.commands.move ? 1 : 2;
  1642. }
  1643. }
  1644. // droptarget is a (writable) addressbook and it's not the source
  1645. else if (!target.readonly && (this.env.selection_sources.length > 1 || $.inArray(id, this.env.selection_sources) == -1)) {
  1646. return this.commands.move ? 1 : 2;
  1647. }
  1648. }
  1649. }
  1650. return 0;
  1651. };
  1652. // open popup window
  1653. this.open_window = function(url, small, toolbar)
  1654. {
  1655. var wname = 'rcmextwin' + new Date().getTime();
  1656. url += (url.match(/\?/) ? '&' : '?') + '_extwin=1';
  1657. if (this.env.standard_windows)
  1658. var extwin = window.open(url, wname);
  1659. else {
  1660. var win = this.is_framed() ? parent.window : window,
  1661. page = $(win),
  1662. page_width = page.width(),
  1663. page_height = bw.mz ? $('body', win).height() : page.height(),
  1664. w = Math.min(small ? this.env.popup_width_small : this.env.popup_width, page_width),
  1665. h = page_height, // always use same height
  1666. l = (win.screenLeft || win.screenX) + 20,
  1667. t = (win.screenTop || win.screenY) + 20,
  1668. extwin = window.open(url, wname,
  1669. 'width='+w+',height='+h+',top='+t+',left='+l+',resizable=yes,location=no,scrollbars=yes'
  1670. +(toolbar ? ',toolbar=yes,menubar=yes,status=yes' : ',toolbar=no,menubar=no,status=no'));
  1671. }
  1672. // detect popup blocker (#1489618)
  1673. // don't care this might not work with all browsers
  1674. if (!extwin || extwin.closed) {
  1675. this.display_message(this.get_label('windowopenerror'), 'warning');
  1676. return;
  1677. }
  1678. // write loading... message to empty windows
  1679. if (!url && extwin.document) {
  1680. extwin.document.write('<html><body>' + this.get_label('loading') + '</body></html>');
  1681. }
  1682. // allow plugins to grab the window reference (#1489413)
  1683. this.triggerEvent('openwindow', { url:url, handle:extwin });
  1684. // focus window, delayed to bring to front
  1685. setTimeout(function() { extwin && extwin.focus(); }, 10);
  1686. return extwin;
  1687. };
  1688. /*********************************************************/
  1689. /********* (message) list functionality *********/
  1690. /*********************************************************/
  1691. this.init_message_row = function(row)
  1692. {
  1693. var i, fn = {}, uid = row.uid,
  1694. status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.id;
  1695. if (uid && this.env.messages[uid])
  1696. $.extend(row, this.env.messages[uid]);
  1697. // set eventhandler to status icon
  1698. if (row.icon = document.getElementById(status_icon)) {
  1699. fn.icon = function(e) { ref.command('toggle_status', uid); };
  1700. }
  1701. // save message icon position too
  1702. if (this.env.status_col != null)
  1703. row.msgicon = document.getElementById('msgicn'+row.id);
  1704. else
  1705. row.msgicon = row.icon;
  1706. // set eventhandler to flag icon
  1707. if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.id))) {
  1708. fn.flagicon = function(e) { ref.command('toggle_flag', uid); };
  1709. }
  1710. // set event handler to thread expand/collapse icon
  1711. if (!row.depth && row.has_children && (row.expando = document.getElementById('rcmexpando'+row.id))) {
  1712. fn.expando = function(e) { ref.expand_message_row(e, uid); };
  1713. }
  1714. // attach events
  1715. $.each(fn, function(i, f) {
  1716. row[i].onclick = function(e) { f(e); return rcube_event.cancel(e); };
  1717. if (bw.touch && row[i].addEventListener) {
  1718. row[i].addEventListener('touchend', function(e) {
  1719. if (e.changedTouches.length == 1) {
  1720. f(e);
  1721. return rcube_event.cancel(e);
  1722. }
  1723. }, false);
  1724. }
  1725. });
  1726. this.triggerEvent('insertrow', { uid:uid, row:row });
  1727. };
  1728. // create a table row in the message list
  1729. this.add_message_row = function(uid, cols, flags, attop)
  1730. {
  1731. if (!this.gui_objects.messagelist || !this.message_list)
  1732. return false;
  1733. // Prevent from adding messages from different folder (#1487752)
  1734. if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
  1735. return false;
  1736. if (!this.env.messages[uid])
  1737. this.env.messages[uid] = {};
  1738. // merge flags over local message object
  1739. $.extend(this.env.messages[uid], {
  1740. deleted: flags.deleted?1:0,
  1741. replied: flags.answered?1:0,
  1742. unread: !flags.seen?1:0,
  1743. forwarded: flags.forwarded?1:0,
  1744. flagged: flags.flagged?1:0,
  1745. has_children: flags.has_children?1:0,
  1746. depth: flags.depth?flags.depth:0,
  1747. unread_children: flags.unread_children || 0,
  1748. flagged_children: flags.flagged_children || 0,
  1749. parent_uid: flags.parent_uid || 0,
  1750. selected: this.select_all_mode || this.message_list.in_selection(uid),
  1751. ml: flags.ml?1:0,
  1752. ctype: flags.ctype,
  1753. mbox: flags.mbox,
  1754. // flags from plugins
  1755. flags: flags.extra_flags
  1756. });
  1757. var c, n, col, html, css_class, label, status_class = '', status_label = '',
  1758. tree = '', expando = '',
  1759. list = this.message_list,
  1760. rows = list.rows,
  1761. message = this.env.messages[uid],
  1762. msg_id = this.html_identifier(uid,true),
  1763. row_class = 'message'
  1764. + (!flags.seen ? ' unread' : '')
  1765. + (flags.deleted ? ' deleted' : '')
  1766. + (flags.flagged ? ' flagged' : '')
  1767. + (message.selected ? ' selected' : ''),
  1768. row = { cols:[], style:{}, id:'rcmrow'+msg_id, uid:uid };
  1769. // message status icons
  1770. css_class = 'msgicon';
  1771. if (this.env.status_col === null) {
  1772. css_class += ' status';
  1773. if (flags.deleted) {
  1774. status_class += ' deleted';
  1775. status_label += this.get_label('deleted') + ' ';
  1776. }
  1777. else if (!flags.seen) {
  1778. status_class += ' unread';
  1779. status_label += this.get_label('unread') + ' ';
  1780. }
  1781. else if (flags.unread_children > 0) {
  1782. status_class += ' unreadchildren';
  1783. }
  1784. }
  1785. if (flags.answered) {
  1786. status_class += ' replied';
  1787. status_label += this.get_label('replied') + ' ';
  1788. }
  1789. if (flags.forwarded) {
  1790. status_class += ' forwarded';
  1791. status_label += this.get_label('forwarded') + ' ';
  1792. }
  1793. // update selection
  1794. if (message.selected && !list.in_selection(uid))
  1795. list.selection.push(uid);
  1796. // threads
  1797. if (this.env.threading) {
  1798. if (message.depth) {
  1799. // This assumes that div width is hardcoded to 15px,
  1800. tree += '<span id="rcmtab' + msg_id + '" class="branch" style="width:' + (message.depth * 15) + 'px;">&nbsp;&nbsp;</span>';
  1801. if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
  1802. || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
  1803. (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
  1804. ) {
  1805. row.style.display = 'none';
  1806. message.expanded = false;
  1807. }
  1808. else
  1809. message.expanded = true;
  1810. row_class += ' thread expanded';
  1811. }
  1812. else if (message.has_children) {
  1813. if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
  1814. message.expanded = true;
  1815. }
  1816. expando = '<div id="rcmexpando' + row.id + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '">&nbsp;&nbsp;</div>';
  1817. row_class += ' thread' + (message.expanded ? ' expanded' : '');
  1818. }
  1819. if (flags.unread_children && flags.seen && !message.expanded)
  1820. row_class += ' unroot';
  1821. if (flags.flagged_children && !message.expanded)
  1822. row_class += ' flaggedroot';
  1823. }
  1824. tree += '<span id="msgicn'+row.id+'" class="'+css_class+status_class+'" title="'+status_label+'"></span>';
  1825. row.className = row_class;
  1826. // build subject link
  1827. if (cols.subject) {
  1828. var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show',
  1829. uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid',
  1830. query = { _mbox: flags.mbox };
  1831. query[uid_param] = uid;
  1832. cols.subject = '<a href="' + this.url(action, query) + '" onclick="return rcube_event.keyboard_only(event)"' +
  1833. ' onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')" tabindex="-1"><span>'+cols.subject+'</span></a>';
  1834. }
  1835. // add each submitted col
  1836. for (n in this.env.listcols) {
  1837. c = this.env.listcols[n];
  1838. col = {className: String(c).toLowerCase(), events:{}};
  1839. if (this.env.coltypes[c] && this.env.coltypes[c].hidden) {
  1840. col.className += ' hidden';
  1841. }
  1842. if (c == 'flag') {
  1843. css_class = (flags.flagged ? 'flagged' : 'unflagged');
  1844. label = this.get_label(css_class);
  1845. html = '<span id="flagicn'+row.id+'" class="'+css_class+'" title="'+label+'"></span>';
  1846. }
  1847. else if (c == 'attachment') {
  1848. label = this.get_label('withattachment');
  1849. if (flags.attachmentClass)
  1850. html = '<span class="'+flags.attachmentClass+'" title="'+label+'"></span>';
  1851. else if (/application\/|multipart\/(m|signed)/.test(flags.ctype))
  1852. html = '<span class="attachment" title="'+label+'"></span>';
  1853. else if (/multipart\/report/.test(flags.ctype))
  1854. html = '<span class="report"></span>';
  1855. else if (flags.ctype == 'multipart/encrypted' || flags.ctype == 'application/pkcs7-mime')
  1856. html = '<span class="encrypted"></span>';
  1857. else
  1858. html = '&nbsp;';
  1859. }
  1860. else if (c == 'status') {
  1861. label = '';
  1862. if (flags.deleted) {
  1863. css_class = 'deleted';
  1864. label = this.get_label('deleted');
  1865. }
  1866. else if (!flags.seen) {
  1867. css_class = 'unread';
  1868. label = this.get_label('unread');
  1869. }
  1870. else if (flags.unread_children > 0) {
  1871. css_class = 'unreadchildren';
  1872. }
  1873. else
  1874. css_class = 'msgicon';
  1875. html = '<span id="statusicn'+row.id+'" class="'+css_class+status_class+'" title="'+label+'"></span>';
  1876. }
  1877. else if (c == 'threads')
  1878. html = expando;
  1879. else if (c == 'subject') {
  1880. html = tree + cols[c];
  1881. }
  1882. else if (c == 'priority') {
  1883. if (flags.prio > 0 && flags.prio < 6) {
  1884. label = this.get_label('priority') + ' ' + flags.prio;
  1885. html = '<span class="prio'+flags.prio+'" title="'+label+'"></span>';
  1886. }
  1887. else
  1888. html = '&nbsp;';
  1889. }
  1890. else if (c == 'folder') {
  1891. html = '<span onmouseover="rcube_webmail.long_subject_title(this)">' + cols[c] + '<span>';
  1892. }
  1893. else
  1894. html = cols[c];
  1895. col.innerHTML = html;
  1896. row.cols.push(col);
  1897. }
  1898. if (this.env.layout == 'widescreen')
  1899. row = this.widescreen_message_row(row, uid, message);
  1900. list.insert_row(row, attop);
  1901. // remove 'old' row
  1902. if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
  1903. var uid = list.get_last_row();
  1904. list.remove_row(uid);
  1905. list.clear_selection(uid);
  1906. }
  1907. };
  1908. // Converts standard message list record into "widescreen" (3-column) layout
  1909. this.widescreen_message_row = function(row, uid, message)
  1910. {
  1911. var domrow = document.createElement('tr');
  1912. domrow.id = row.id;
  1913. domrow.uid = row.uid;
  1914. domrow.className = row.className;
  1915. if (row.style) $.extend(domrow.style, row.style);
  1916. $.each(this.env.widescreen_list_template, function() {
  1917. if (!ref.env.threading && this.className == 'threads')
  1918. return;
  1919. var i, n, e, col, domcol,
  1920. domcell = document.createElement('td');
  1921. if (this.className) domcell.className = this.className;
  1922. for (i=0; this.cells && i < this.cells.length; i++) {
  1923. for (n=0; row.cols && n < row.cols.length; n++) {
  1924. if (this.cells[i] == row.cols[n].className) {
  1925. col = row.cols[n];
  1926. domcol = document.createElement('span');
  1927. domcol.className = this.cells[i];
  1928. if (this.className == 'subject' && domcol.className != 'subject')
  1929. domcol.className += ' skip-on-drag';
  1930. if (col.innerHTML)
  1931. domcol.innerHTML = col.innerHTML;
  1932. domcell.appendChild(domcol);
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. domrow.appendChild(domcell);
  1938. });
  1939. if (this.env.threading && message.depth) {
  1940. $('td.subject', domrow).attr('style', 'padding-left:' + Math.min(90, message.depth * 15) + 'px !important');
  1941. $('span.branch', domrow).remove();
  1942. }
  1943. return domrow;
  1944. };
  1945. this.set_list_sorting = function(sort_col, sort_order)
  1946. {
  1947. var sort_old = this.env.sort_col == 'arrival' ? 'date' : this.env.sort_col,
  1948. sort_new = sort_col == 'arrival' ? 'date' : sort_col;
  1949. // set table header class
  1950. $('#rcm' + sort_old).removeClass('sorted' + this.env.sort_order.toUpperCase());
  1951. if (sort_new)
  1952. $('#rcm' + sort_new).addClass('sorted' + sort_order);
  1953. // if sorting by 'arrival' is selected, click on date column should not switch to 'date'
  1954. $('#rcmdate > a').prop('rel', sort_col == 'arrival' ? 'arrival' : 'date');
  1955. this.env.sort_col = sort_col;
  1956. this.env.sort_order = sort_order;
  1957. };
  1958. this.set_list_options = function(cols, sort_col, sort_order, threads, layout)
  1959. {
  1960. var update, post_data = {};
  1961. if (sort_col === undefined)
  1962. sort_col = this.env.sort_col;
  1963. if (!sort_order)
  1964. sort_order = this.env.sort_order;
  1965. if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
  1966. update = 1;
  1967. this.set_list_sorting(sort_col, sort_order);
  1968. }
  1969. if (this.env.threading != threads) {
  1970. update = 1;
  1971. post_data._threads = threads;
  1972. }
  1973. if (layout && this.env.layout != layout) {
  1974. this.triggerEvent('layout-change', {old_layout: this.env.layout, new_layout: layout});
  1975. update = 1;
  1976. this.env.layout = post_data._layout = layout;
  1977. }
  1978. if (cols && cols.length) {
  1979. // make sure new columns are added at the end of the list
  1980. var i, idx, name, newcols = [], oldcols = this.env.listcols;
  1981. for (i=0; i<oldcols.length; i++) {
  1982. name = oldcols[i];
  1983. idx = $.inArray(name, cols);
  1984. if (idx != -1) {
  1985. newcols.push(name);
  1986. delete cols[idx];
  1987. }
  1988. }
  1989. for (i=0; i<cols.length; i++)
  1990. if (cols[i])
  1991. newcols.push(cols[i]);
  1992. if (newcols.join() != oldcols.join()) {
  1993. update = 1;
  1994. post_data._cols = newcols.join(',');
  1995. }
  1996. }
  1997. if (update)
  1998. this.list_mailbox('', '', sort_col+'_'+sort_order, post_data);
  1999. };
  2000. // when user double-clicks on a row
  2001. this.show_message = function(id, safe, preview)
  2002. {
  2003. if (!id)
  2004. return;
  2005. var win, target = window,
  2006. url = this.params_from_uid(id, {_caps: this.browser_capabilities()});
  2007. if (preview && (win = this.get_frame_window(this.env.contentframe))) {
  2008. target = win;
  2009. url._framed = 1;
  2010. }
  2011. if (safe)
  2012. url._safe = 1;
  2013. // also send search request to get the right messages
  2014. if (this.env.search_request)
  2015. url._search = this.env.search_request;
  2016. if (this.env.extwin)
  2017. url._extwin = 1;
  2018. url = this.url(preview ? 'preview': 'show', url);
  2019. if (preview && String(target.location.href).indexOf(url) >= 0) {
  2020. this.show_contentframe(true);
  2021. }
  2022. else {
  2023. if (!preview && this.env.message_extwin && !this.env.extwin)
  2024. this.open_window(url, true);
  2025. else
  2026. this.location_href(url, target, true);
  2027. }
  2028. };
  2029. // update message status and unread counter after marking a message as read
  2030. this.set_unread_message = function(id, folder)
  2031. {
  2032. var self = this;
  2033. // find window with messages list
  2034. if (!self.message_list)
  2035. self = self.opener();
  2036. if (!self && window.parent)
  2037. self = parent.rcmail;
  2038. if (!self || !self.message_list)
  2039. return;
  2040. // this may fail in multifolder mode
  2041. if (self.set_message(id, 'unread', false) === false)
  2042. self.set_message(id + '-' + folder, 'unread', false);
  2043. if (self.env.unread_counts[folder] > 0) {
  2044. self.env.unread_counts[folder] -= 1;
  2045. self.set_unread_count(folder, self.env.unread_counts[folder], folder == 'INBOX' && !self.is_multifolder_listing());
  2046. }
  2047. };
  2048. this.show_contentframe = function(show)
  2049. {
  2050. var frame, win, name = this.env.contentframe;
  2051. if (name && (frame = this.get_frame_element(name))) {
  2052. if (!show && (win = this.get_frame_window(name))) {
  2053. if (win.location.href.indexOf(this.env.blankpage) < 0) {
  2054. if (win.stop)
  2055. win.stop();
  2056. else // IE
  2057. win.document.execCommand('Stop');
  2058. win.location.href = this.env.blankpage;
  2059. }
  2060. }
  2061. else if (!bw.safari && !bw.konq)
  2062. $(frame)[show ? 'show' : 'hide']();
  2063. }
  2064. if (!show && this.env.frame_lock)
  2065. this.set_busy(false, null, this.env.frame_lock);
  2066. };
  2067. this.get_frame_element = function(id)
  2068. {
  2069. var frame;
  2070. if (id && (frame = document.getElementById(id)))
  2071. return frame;
  2072. };
  2073. this.get_frame_window = function(id)
  2074. {
  2075. var frame = this.get_frame_element(id);
  2076. if (frame && frame.name && window.frames)
  2077. return window.frames[frame.name];
  2078. };
  2079. this.lock_frame = function()
  2080. {
  2081. if (!this.env.frame_lock)
  2082. (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
  2083. };
  2084. // list a specific page
  2085. this.list_page = function(page)
  2086. {
  2087. if (page == 'next')
  2088. page = this.env.current_page+1;
  2089. else if (page == 'last')
  2090. page = this.env.pagecount;
  2091. else if (page == 'prev' && this.env.current_page > 1)
  2092. page = this.env.current_page-1;
  2093. else if (page == 'first' && this.env.current_page > 1)
  2094. page = 1;
  2095. if (page > 0 && page <= this.env.pagecount) {
  2096. this.env.current_page = page;
  2097. if (this.task == 'addressbook' || this.contact_list)
  2098. this.list_contacts(this.env.source, this.env.group, page);
  2099. else if (this.task == 'mail')
  2100. this.list_mailbox(this.env.mailbox, page);
  2101. }
  2102. };
  2103. // sends request to check for recent messages
  2104. this.checkmail = function()
  2105. {
  2106. var lock = this.set_busy(true, 'checkingmail'),
  2107. params = this.check_recent_params();
  2108. this.http_post('check-recent', params, lock);
  2109. };
  2110. // list messages of a specific mailbox using filter
  2111. this.filter_mailbox = function(filter)
  2112. {
  2113. if (this.filter_disabled)
  2114. return;
  2115. var lock = this.set_busy(true, 'searching');
  2116. this.clear_message_list();
  2117. // reset vars
  2118. this.env.current_page = 1;
  2119. this.env.search_filter = filter;
  2120. this.http_request('search', this.search_params(false, filter), lock);
  2121. };
  2122. // reload the current message listing
  2123. this.refresh_list = function()
  2124. {
  2125. this.list_mailbox(this.env.mailbox, this.env.current_page || 1, null, { _clear:1 }, true);
  2126. if (this.message_list)
  2127. this.message_list.clear_selection();
  2128. };
  2129. // list messages of a specific mailbox
  2130. this.list_mailbox = function(mbox, page, sort, url, update_only)
  2131. {
  2132. var win, target = window;
  2133. if (typeof url != 'object')
  2134. url = {};
  2135. if (!mbox)
  2136. mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
  2137. // add sort to url if set
  2138. if (sort)
  2139. url._sort = sort;
  2140. // folder change, reset page, search scope, etc.
  2141. if (this.env.mailbox != mbox) {
  2142. page = 1;
  2143. this.env.current_page = page;
  2144. this.env.search_scope = 'base';
  2145. this.select_all_mode = false;
  2146. this.reset_search_filter();
  2147. }
  2148. // also send search request to get the right messages
  2149. else if (this.env.search_request)
  2150. url._search = this.env.search_request;
  2151. if (!update_only) {
  2152. // unselect selected messages and clear the list and message data
  2153. this.clear_message_list();
  2154. if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
  2155. url._refresh = 1;
  2156. this.select_folder(mbox, '', true);
  2157. this.unmark_folder(mbox, 'recent', '', true);
  2158. this.env.mailbox = mbox;
  2159. }
  2160. // load message list remotely
  2161. if (this.gui_objects.messagelist) {
  2162. this.list_mailbox_remote(mbox, page, url);
  2163. return;
  2164. }
  2165. if (win = this.get_frame_window(this.env.contentframe)) {
  2166. target = win;
  2167. url._framed = 1;
  2168. }
  2169. if (this.env.uid)
  2170. url._uid = this.env.uid;
  2171. // load message list to target frame/window
  2172. if (mbox) {
  2173. this.set_busy(true, 'loading');
  2174. url._mbox = mbox;
  2175. if (page)
  2176. url._page = page;
  2177. this.location_href(url, target);
  2178. }
  2179. };
  2180. this.clear_message_list = function()
  2181. {
  2182. this.env.messages = {};
  2183. this.show_contentframe(false);
  2184. if (this.message_list)
  2185. this.message_list.clear(true);
  2186. };
  2187. // send remote request to load message list
  2188. this.list_mailbox_remote = function(mbox, page, url)
  2189. {
  2190. var lock = this.set_busy(true, 'loading');
  2191. if (typeof url != 'object')
  2192. url = {};
  2193. url._mbox = mbox;
  2194. if (page)
  2195. url._page = page;
  2196. // disable double-click on the list when preview pane is on
  2197. // this eliminates delay when opening a message in preview pane (#5199)
  2198. if (this.message_list)
  2199. this.message_list.dblclick_time = this.env.layout != 'list' ? 10 : this.dblclick_time;
  2200. this.http_request('list', url, lock);
  2201. this.update_state({ _mbox: mbox, _page: (page && page > 1 ? page : null) });
  2202. };
  2203. // removes messages that doesn't exists from list selection array
  2204. this.update_selection = function()
  2205. {
  2206. var list = this.message_list,
  2207. selected = list.selection,
  2208. rows = list.rows,
  2209. i, selection = [];
  2210. for (i in selected)
  2211. if (rows[selected[i]])
  2212. selection.push(selected[i]);
  2213. list.selection = selection;
  2214. // reset preview frame, if currently previewed message is not selected (has been removed)
  2215. try {
  2216. var win = this.get_frame_window(this.env.contentframe),
  2217. id = win.rcmail.env.uid;
  2218. if (id && !list.in_selection(id))
  2219. this.show_contentframe(false);
  2220. }
  2221. catch (e) {};
  2222. };
  2223. // expand all threads with unread children
  2224. this.expand_unread = function()
  2225. {
  2226. var r, tbody = this.message_list.tbody,
  2227. new_row = tbody.firstChild;
  2228. while (new_row) {
  2229. if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
  2230. this.message_list.expand_all(r);
  2231. this.set_unread_children(r.uid);
  2232. }
  2233. new_row = new_row.nextSibling;
  2234. }
  2235. return false;
  2236. };
  2237. // thread expanding/collapsing handler
  2238. this.expand_message_row = function(e, uid)
  2239. {
  2240. var row = this.message_list.rows[uid];
  2241. // handle unread_children/flagged_children mark
  2242. row.expanded = !row.expanded;
  2243. this.set_unread_children(uid);
  2244. this.set_flagged_children(uid);
  2245. row.expanded = !row.expanded;
  2246. this.message_list.expand_row(e, uid);
  2247. };
  2248. // message list expanding
  2249. this.expand_threads = function()
  2250. {
  2251. if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
  2252. return;
  2253. switch (this.env.autoexpand_threads) {
  2254. case 2: this.expand_unread(); break;
  2255. case 1: this.message_list.expand_all(); break;
  2256. }
  2257. };
  2258. // Initializes threads indicators/expanders after list update
  2259. this.init_threads = function(roots, mbox)
  2260. {
  2261. // #1487752
  2262. if (mbox && mbox != this.env.mailbox)
  2263. return false;
  2264. for (var n=0, len=roots.length; n<len; n++)
  2265. this.add_tree_icons(roots[n]);
  2266. this.expand_threads();
  2267. };
  2268. // adds threads tree icons to the list (or specified thread)
  2269. this.add_tree_icons = function(root)
  2270. {
  2271. var i, l, r, n, len, pos, tmp = [], uid = [],
  2272. row, rows = this.message_list.rows;
  2273. if (root)
  2274. row = rows[root] ? rows[root].obj : null;
  2275. else
  2276. row = this.message_list.tbody.firstChild;
  2277. while (row) {
  2278. if (row.nodeType == 1 && (r = rows[row.uid])) {
  2279. if (r.depth) {
  2280. for (i=tmp.length-1; i>=0; i--) {
  2281. len = tmp[i].length;
  2282. if (len > r.depth) {
  2283. pos = len - r.depth;
  2284. if (!(tmp[i][pos] & 2))
  2285. tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
  2286. }
  2287. else if (len == r.depth) {
  2288. if (!(tmp[i][0] & 2))
  2289. tmp[i][0] += 2;
  2290. }
  2291. if (r.depth > len)
  2292. break;
  2293. }
  2294. tmp.push(new Array(r.depth));
  2295. tmp[tmp.length-1][0] = 1;
  2296. uid.push(r.uid);
  2297. }
  2298. else {
  2299. if (tmp.length) {
  2300. for (i in tmp) {
  2301. this.set_tree_icons(uid[i], tmp[i]);
  2302. }
  2303. tmp = [];
  2304. uid = [];
  2305. }
  2306. if (root && row != rows[root].obj)
  2307. break;
  2308. }
  2309. }
  2310. row = row.nextSibling;
  2311. }
  2312. if (tmp.length) {
  2313. for (i in tmp) {
  2314. this.set_tree_icons(uid[i], tmp[i]);
  2315. }
  2316. }
  2317. };
  2318. // adds tree icons to specified message row
  2319. this.set_tree_icons = function(uid, tree)
  2320. {
  2321. var i, divs = [], html = '', len = tree.length;
  2322. for (i=0; i<len; i++) {
  2323. if (tree[i] > 2)
  2324. divs.push({'class': 'l3', width: 15});
  2325. else if (tree[i] > 1)
  2326. divs.push({'class': 'l2', width: 15});
  2327. else if (tree[i] > 0)
  2328. divs.push({'class': 'l1', width: 15});
  2329. // separator div
  2330. else if (divs.length && !divs[divs.length-1]['class'])
  2331. divs[divs.length-1].width += 15;
  2332. else
  2333. divs.push({'class': null, width: 15});
  2334. }
  2335. for (i=divs.length-1; i>=0; i--) {
  2336. if (divs[i]['class'])
  2337. html += '<div class="tree '+divs[i]['class']+'" />';
  2338. else
  2339. html += '<div style="width:'+divs[i].width+'px" />';
  2340. }
  2341. if (html)
  2342. $('#rcmtab'+this.html_identifier(uid, true)).html(html);
  2343. };
  2344. // update parent in a thread
  2345. this.update_thread_root = function(uid, flag)
  2346. {
  2347. if (!this.env.threading)
  2348. return;
  2349. var root = this.message_list.find_root(uid);
  2350. if (uid == root)
  2351. return;
  2352. var p = this.message_list.rows[root];
  2353. if (flag == 'read' && p.unread_children) {
  2354. p.unread_children--;
  2355. }
  2356. else if (flag == 'unread' && p.has_children) {
  2357. // unread_children may be undefined
  2358. p.unread_children = (p.unread_children || 0) + 1;
  2359. }
  2360. else if (flag == 'unflagged' && p.flagged_children) {
  2361. p.flagged_children--;
  2362. }
  2363. else if (flag == 'flagged' && p.has_children) {
  2364. p.flagged_children = (p.flagged_children || 0) + 1;
  2365. }
  2366. else {
  2367. return;
  2368. }
  2369. this.set_message_icon(root);
  2370. this.set_unread_children(root);
  2371. this.set_flagged_children(root);
  2372. };
  2373. // update thread indicators for all messages in a thread below the specified message
  2374. // return number of removed/added root level messages
  2375. this.update_thread = function (uid)
  2376. {
  2377. if (!this.env.threading)
  2378. return 0;
  2379. var r, parent, count = 0,
  2380. rows = this.message_list.rows,
  2381. row = rows[uid],
  2382. depth = rows[uid].depth,
  2383. roots = [];
  2384. if (!row.depth) // root message: decrease roots count
  2385. count--;
  2386. // update unread_children for thread root
  2387. if (row.depth && row.unread) {
  2388. parent = this.message_list.find_root(uid);
  2389. rows[parent].unread_children--;
  2390. this.set_unread_children(parent);
  2391. }
  2392. // update unread_children for thread root
  2393. if (row.depth && row.flagged) {
  2394. parent = this.message_list.find_root(uid);
  2395. rows[parent].flagged_children--;
  2396. this.set_flagged_children(parent);
  2397. }
  2398. parent = row.parent_uid;
  2399. // childrens
  2400. row = row.obj.nextSibling;
  2401. while (row) {
  2402. if (row.nodeType == 1 && (r = rows[row.uid])) {
  2403. if (!r.depth || r.depth <= depth)
  2404. break;
  2405. r.depth--; // move left
  2406. // reset width and clear the content of a tab, icons will be added later
  2407. $('#rcmtab'+r.id).width(r.depth * 15).html('');
  2408. if (!r.depth) { // a new root
  2409. count++; // increase roots count
  2410. r.parent_uid = 0;
  2411. if (r.has_children) {
  2412. // replace 'leaf' with 'collapsed'
  2413. $('#'+r.id+' .leaf:first')
  2414. .attr('id', 'rcmexpando' + r.id)
  2415. .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
  2416. .mousedown({uid: r.uid}, function(e) {
  2417. return ref.expand_message_row(e, e.data.uid);
  2418. });
  2419. r.unread_children = 0;
  2420. roots.push(r);
  2421. }
  2422. // show if it was hidden
  2423. if (r.obj.style.display == 'none')
  2424. $(r.obj).show();
  2425. }
  2426. else {
  2427. if (r.depth == depth)
  2428. r.parent_uid = parent;
  2429. if (r.unread && roots.length)
  2430. roots[roots.length-1].unread_children++;
  2431. }
  2432. }
  2433. row = row.nextSibling;
  2434. }
  2435. // update unread_children/flagged_children for roots
  2436. for (r=0; r<roots.length; r++) {
  2437. this.set_unread_children(roots[r].uid);
  2438. this.set_flagged_children(roots[r].uid);
  2439. }
  2440. return count;
  2441. };
  2442. this.delete_excessive_thread_rows = function()
  2443. {
  2444. var rows = this.message_list.rows,
  2445. tbody = this.message_list.tbody,
  2446. row = tbody.firstChild,
  2447. cnt = this.env.pagesize + 1;
  2448. while (row) {
  2449. if (row.nodeType == 1 && (r = rows[row.uid])) {
  2450. if (!r.depth && cnt)
  2451. cnt--;
  2452. if (!cnt)
  2453. this.message_list.remove_row(row.uid);
  2454. }
  2455. row = row.nextSibling;
  2456. }
  2457. };
  2458. // set message icon
  2459. this.set_message_icon = function(uid)
  2460. {
  2461. var css_class, label = '',
  2462. row = this.message_list.rows[uid];
  2463. if (!row)
  2464. return false;
  2465. if (row.icon) {
  2466. css_class = 'msgicon';
  2467. if (row.deleted) {
  2468. css_class += ' deleted';
  2469. label += this.get_label('deleted') + ' ';
  2470. }
  2471. else if (row.unread) {
  2472. css_class += ' unread';
  2473. label += this.get_label('unread') + ' ';
  2474. }
  2475. else if (row.unread_children)
  2476. css_class += ' unreadchildren';
  2477. if (row.msgicon == row.icon) {
  2478. if (row.replied) {
  2479. css_class += ' replied';
  2480. label += this.get_label('replied') + ' ';
  2481. }
  2482. if (row.forwarded) {
  2483. css_class += ' forwarded';
  2484. label += this.get_label('forwarded') + ' ';
  2485. }
  2486. css_class += ' status';
  2487. }
  2488. $(row.icon).attr('class', css_class).attr('title', label);
  2489. }
  2490. if (row.msgicon && row.msgicon != row.icon) {
  2491. label = '';
  2492. css_class = 'msgicon';
  2493. if (!row.unread && row.unread_children) {
  2494. css_class += ' unreadchildren';
  2495. }
  2496. if (row.replied) {
  2497. css_class += ' replied';
  2498. label += this.get_label('replied') + ' ';
  2499. }
  2500. if (row.forwarded) {
  2501. css_class += ' forwarded';
  2502. label += this.get_label('forwarded') + ' ';
  2503. }
  2504. $(row.msgicon).attr('class', css_class).attr('title', label);
  2505. }
  2506. if (row.flagicon) {
  2507. css_class = (row.flagged ? 'flagged' : 'unflagged');
  2508. label = this.get_label(css_class);
  2509. $(row.flagicon).attr('class', css_class)
  2510. .attr('aria-label', label)
  2511. .attr('title', label);
  2512. }
  2513. };
  2514. // set message status
  2515. this.set_message_status = function(uid, flag, status)
  2516. {
  2517. var row = this.message_list.rows[uid];
  2518. if (!row)
  2519. return false;
  2520. if (flag == 'unread') {
  2521. if (row.unread != status)
  2522. this.update_thread_root(uid, status ? 'unread' : 'read');
  2523. }
  2524. else if (flag == 'flagged') {
  2525. this.update_thread_root(uid, status ? 'flagged' : 'unflagged');
  2526. }
  2527. if ($.inArray(flag, ['unread', 'deleted', 'replied', 'forwarded', 'flagged']) > -1)
  2528. row[flag] = status;
  2529. };
  2530. // set message row status, class and icon
  2531. this.set_message = function(uid, flag, status)
  2532. {
  2533. var row = this.message_list && this.message_list.rows[uid];
  2534. if (!row)
  2535. return false;
  2536. if (flag)
  2537. this.set_message_status(uid, flag, status);
  2538. if ($.inArray(flag, ['unread', 'deleted', 'flagged']) > -1)
  2539. $(row.obj)[row[flag] ? 'addClass' : 'removeClass'](flag);
  2540. this.set_unread_children(uid);
  2541. this.set_message_icon(uid);
  2542. };
  2543. // sets unroot (unread_children) class of parent row
  2544. this.set_unread_children = function(uid)
  2545. {
  2546. var row = this.message_list.rows[uid];
  2547. if (row.parent_uid)
  2548. return;
  2549. var enable = !row.unread && row.unread_children && !row.expanded;
  2550. $(row.obj)[enable ? 'addClass' : 'removeClass']('unroot');
  2551. };
  2552. // sets flaggedroot (flagged_children) class of parent row
  2553. this.set_flagged_children = function(uid)
  2554. {
  2555. var row = this.message_list.rows[uid];
  2556. if (row.parent_uid)
  2557. return;
  2558. var enable = row.flagged_children && !row.expanded;
  2559. $(row.obj)[enable ? 'addClass' : 'removeClass']('flaggedroot');
  2560. };
  2561. // copy selected messages to the specified mailbox
  2562. this.copy_messages = function(mbox, event)
  2563. {
  2564. if (mbox && typeof mbox === 'object')
  2565. mbox = mbox.id;
  2566. else if (!mbox)
  2567. return this.folder_selector(event, function(folder) { ref.command('copy', folder); });
  2568. // exit if current or no mailbox specified
  2569. if (!mbox || mbox == this.env.mailbox)
  2570. return;
  2571. var post_data = this.selection_post_data({_target_mbox: mbox});
  2572. // exit if selection is empty
  2573. if (!post_data._uid)
  2574. return;
  2575. // send request to server
  2576. this.http_post('copy', post_data, this.display_message(this.get_label('copyingmessage'), 'loading'));
  2577. };
  2578. // move selected messages to the specified mailbox
  2579. this.move_messages = function(mbox, event)
  2580. {
  2581. if (mbox && typeof mbox === 'object')
  2582. mbox = mbox.id;
  2583. else if (!mbox)
  2584. return this.folder_selector(event, function(folder) { ref.command('move', folder); });
  2585. // exit if current or no mailbox specified
  2586. if (!mbox || (mbox == this.env.mailbox && !this.is_multifolder_listing()))
  2587. return;
  2588. var lock = false, post_data = this.selection_post_data({_target_mbox: mbox});
  2589. // exit if selection is empty
  2590. if (!post_data._uid)
  2591. return;
  2592. // show wait message
  2593. if (this.env.action == 'show')
  2594. lock = this.set_busy(true, 'movingmessage');
  2595. else
  2596. this.show_contentframe(false);
  2597. // Hide message command buttons until a message is selected
  2598. this.enable_command(this.env.message_commands, false);
  2599. this.with_selected_messages('move', post_data, lock);
  2600. };
  2601. // delete selected messages from the current mailbox
  2602. this.delete_messages = function(event)
  2603. {
  2604. var list = this.message_list, trash = this.env.trash_mailbox;
  2605. // if config is set to flag for deletion
  2606. if (this.env.flag_for_deletion) {
  2607. this.mark_message('delete');
  2608. return false;
  2609. }
  2610. // if there isn't a defined trash mailbox or we are in it
  2611. else if (!trash || this.env.mailbox == trash)
  2612. this.permanently_remove_messages();
  2613. // we're in Junk folder and delete_junk is enabled
  2614. else if (this.env.delete_junk && this.env.junk_mailbox && this.env.mailbox == this.env.junk_mailbox)
  2615. this.permanently_remove_messages();
  2616. // if there is a trash mailbox defined and we're not currently in it
  2617. else {
  2618. // if shift was pressed delete it immediately
  2619. if ((list && list.modkey == SHIFT_KEY) || (event && rcube_event.get_modifier(event) == SHIFT_KEY)) {
  2620. if (confirm(this.get_label('deletemessagesconfirm')))
  2621. this.permanently_remove_messages();
  2622. }
  2623. else
  2624. this.move_messages(trash);
  2625. }
  2626. return true;
  2627. };
  2628. // delete the selected messages permanently
  2629. this.permanently_remove_messages = function()
  2630. {
  2631. var post_data = this.selection_post_data();
  2632. // exit if selection is empty
  2633. if (!post_data._uid)
  2634. return;
  2635. this.show_contentframe(false);
  2636. this.with_selected_messages('delete', post_data);
  2637. };
  2638. // Send a specific move/delete request with UIDs of all selected messages
  2639. this.with_selected_messages = function(action, post_data, lock, http_action)
  2640. {
  2641. var count = 0, msg,
  2642. remove = (action == 'delete' || !this.is_multifolder_listing());
  2643. // update the list (remove rows, clear selection)
  2644. if (this.message_list) {
  2645. var n, id, root, roots = [],
  2646. selection = this.message_list.get_selection();
  2647. for (n=0, len=selection.length; n<len; n++) {
  2648. id = selection[n];
  2649. if (this.env.threading) {
  2650. count += this.update_thread(id);
  2651. root = this.message_list.find_root(id);
  2652. if (root != id && $.inArray(root, roots) < 0) {
  2653. roots.push(root);
  2654. }
  2655. }
  2656. if (remove)
  2657. this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
  2658. }
  2659. // make sure there are no selected rows
  2660. if (!this.env.display_next && remove)
  2661. this.message_list.clear_selection();
  2662. // update thread tree icons
  2663. for (n=0, len=roots.length; n<len; n++) {
  2664. this.add_tree_icons(roots[n]);
  2665. }
  2666. }
  2667. if (count < 0)
  2668. post_data._count = (count*-1);
  2669. // remove threads from the end of the list
  2670. else if (count > 0 && remove)
  2671. this.delete_excessive_thread_rows();
  2672. if (!remove)
  2673. post_data._refresh = 1;
  2674. if (!lock) {
  2675. msg = action == 'move' ? 'movingmessage' : 'deletingmessage';
  2676. lock = this.display_message(this.get_label(msg), 'loading');
  2677. }
  2678. // send request to server
  2679. this.http_post(http_action || action, post_data, lock);
  2680. };
  2681. // build post data for message delete/move/copy/flag requests
  2682. this.selection_post_data = function(data)
  2683. {
  2684. if (typeof(data) != 'object')
  2685. data = {};
  2686. data._mbox = this.env.mailbox;
  2687. if (!data._uid) {
  2688. var uids = this.env.uid ? [this.env.uid] : this.message_list.get_selection();
  2689. data._uid = this.uids_to_list(uids);
  2690. }
  2691. if (this.env.action)
  2692. data._from = this.env.action;
  2693. // also send search request to get the right messages
  2694. if (this.env.search_request)
  2695. data._search = this.env.search_request;
  2696. if (this.env.display_next && this.env.next_uid)
  2697. data._next_uid = this.env.next_uid;
  2698. return data;
  2699. };
  2700. // set a specific flag to one or more messages
  2701. this.mark_message = function(flag, uid)
  2702. {
  2703. var a_uids = [], r_uids = [], len, n, id,
  2704. list = this.message_list;
  2705. if (uid)
  2706. a_uids[0] = uid;
  2707. else if (this.env.uid)
  2708. a_uids[0] = this.env.uid;
  2709. else if (list)
  2710. a_uids = list.get_selection();
  2711. if (!list)
  2712. r_uids = a_uids;
  2713. else {
  2714. list.focus();
  2715. for (n=0, len=a_uids.length; n<len; n++) {
  2716. id = a_uids[n];
  2717. if ((flag == 'read' && list.rows[id].unread)
  2718. || (flag == 'unread' && !list.rows[id].unread)
  2719. || (flag == 'delete' && !list.rows[id].deleted)
  2720. || (flag == 'undelete' && list.rows[id].deleted)
  2721. || (flag == 'flagged' && !list.rows[id].flagged)
  2722. || (flag == 'unflagged' && list.rows[id].flagged))
  2723. {
  2724. r_uids.push(id);
  2725. }
  2726. }
  2727. }
  2728. // nothing to do
  2729. if (!r_uids.length && !this.select_all_mode)
  2730. return;
  2731. switch (flag) {
  2732. case 'read':
  2733. case 'unread':
  2734. this.toggle_read_status(flag, r_uids);
  2735. break;
  2736. case 'delete':
  2737. case 'undelete':
  2738. this.toggle_delete_status(r_uids);
  2739. break;
  2740. case 'flagged':
  2741. case 'unflagged':
  2742. this.toggle_flagged_status(flag, a_uids);
  2743. break;
  2744. }
  2745. };
  2746. // set class to read/unread
  2747. this.toggle_read_status = function(flag, a_uids)
  2748. {
  2749. var i, len = a_uids.length,
  2750. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
  2751. lock = this.display_message(this.get_label('markingmessage'), 'loading');
  2752. // mark all message rows as read/unread
  2753. for (i=0; i<len; i++)
  2754. this.set_message(a_uids[i], 'unread', (flag == 'unread' ? true : false));
  2755. this.http_post('mark', post_data, lock);
  2756. };
  2757. // set image to flagged or unflagged
  2758. this.toggle_flagged_status = function(flag, a_uids)
  2759. {
  2760. var i, len = a_uids.length,
  2761. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
  2762. lock = this.display_message(this.get_label('markingmessage'), 'loading');
  2763. // mark all message rows as flagged/unflagged
  2764. for (i=0; i<len; i++)
  2765. this.set_message(a_uids[i], 'flagged', (flag == 'flagged' ? true : false));
  2766. this.http_post('mark', post_data, lock);
  2767. };
  2768. // mark all message rows as deleted/undeleted
  2769. this.toggle_delete_status = function(a_uids)
  2770. {
  2771. var len = a_uids.length,
  2772. i, uid, all_deleted = true,
  2773. rows = this.message_list ? this.message_list.rows : {};
  2774. if (len == 1) {
  2775. if (!this.message_list || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
  2776. this.flag_as_deleted(a_uids);
  2777. else
  2778. this.flag_as_undeleted(a_uids);
  2779. return true;
  2780. }
  2781. for (i=0; i<len; i++) {
  2782. uid = a_uids[i];
  2783. if (rows[uid] && !rows[uid].deleted) {
  2784. all_deleted = false;
  2785. break;
  2786. }
  2787. }
  2788. if (all_deleted)
  2789. this.flag_as_undeleted(a_uids);
  2790. else
  2791. this.flag_as_deleted(a_uids);
  2792. return true;
  2793. };
  2794. this.flag_as_undeleted = function(a_uids)
  2795. {
  2796. var i, len = a_uids.length,
  2797. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'undelete'}),
  2798. lock = this.display_message(this.get_label('markingmessage'), 'loading');
  2799. for (i=0; i<len; i++)
  2800. this.set_message(a_uids[i], 'deleted', false);
  2801. this.http_post('mark', post_data, lock);
  2802. };
  2803. this.flag_as_deleted = function(a_uids)
  2804. {
  2805. var r_uids = [],
  2806. post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'delete'}),
  2807. lock = this.display_message(this.get_label('markingmessage'), 'loading'),
  2808. rows = this.message_list ? this.message_list.rows : {},
  2809. count = 0;
  2810. for (var i=0, len=a_uids.length; i<len; i++) {
  2811. uid = a_uids[i];
  2812. if (rows[uid]) {
  2813. if (rows[uid].unread)
  2814. r_uids[r_uids.length] = uid;
  2815. if (this.env.skip_deleted) {
  2816. count += this.update_thread(uid);
  2817. this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
  2818. }
  2819. else
  2820. this.set_message(uid, 'deleted', true);
  2821. }
  2822. }
  2823. // make sure there are no selected rows
  2824. if (this.env.skip_deleted && this.message_list) {
  2825. if (!this.env.display_next)
  2826. this.message_list.clear_selection();
  2827. if (count < 0)
  2828. post_data._count = (count*-1);
  2829. else if (count > 0)
  2830. // remove threads from the end of the list
  2831. this.delete_excessive_thread_rows();
  2832. }
  2833. // set of messages to mark as seen
  2834. if (r_uids.length)
  2835. post_data._ruid = this.uids_to_list(r_uids);
  2836. if (this.env.skip_deleted && this.env.display_next && this.env.next_uid)
  2837. post_data._next_uid = this.env.next_uid;
  2838. this.http_post('mark', post_data, lock);
  2839. };
  2840. // flag as read without mark request (called from backend)
  2841. // argument should be a coma-separated list of uids
  2842. this.flag_deleted_as_read = function(uids)
  2843. {
  2844. var uid, i, len,
  2845. rows = this.message_list ? this.message_list.rows : {};
  2846. if (typeof uids == 'string')
  2847. uids = uids.split(',');
  2848. for (i=0, len=uids.length; i<len; i++) {
  2849. uid = uids[i];
  2850. if (rows[uid])
  2851. this.set_message(uid, 'unread', false);
  2852. }
  2853. };
  2854. // Converts array of message UIDs to comma-separated list for use in URL
  2855. // with select_all mode checking
  2856. this.uids_to_list = function(uids)
  2857. {
  2858. return this.select_all_mode ? '*' : (uids.length <= 1 ? uids.join(',') : uids);
  2859. };
  2860. // Sets title of the delete button
  2861. this.set_button_titles = function()
  2862. {
  2863. var label = 'deletemessage';
  2864. if (!this.env.flag_for_deletion
  2865. && this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox
  2866. && (!this.env.delete_junk || !this.env.junk_mailbox || this.env.mailbox != this.env.junk_mailbox)
  2867. )
  2868. label = 'movemessagetotrash';
  2869. this.set_alttext('delete', label);
  2870. };
  2871. // Initialize input element for list page jump
  2872. this.init_pagejumper = function(element)
  2873. {
  2874. $(element).addClass('rcpagejumper')
  2875. .on('focus', function(e) {
  2876. // create and display popup with page selection
  2877. var i, html = '';
  2878. for (i = 1; i <= ref.env.pagecount; i++)
  2879. html += '<li>' + i + '</li>';
  2880. html = '<ul class="toolbarmenu">' + html + '</ul>';
  2881. if (!ref.pagejump) {
  2882. ref.pagejump = $('<div id="pagejump-selector" class="popupmenu"></div>')
  2883. .appendTo(document.body)
  2884. .on('click', 'li', function() {
  2885. if (!ref.busy)
  2886. $(element).val($(this).text()).change();
  2887. });
  2888. }
  2889. if (ref.pagejump.data('count') != i)
  2890. ref.pagejump.html(html);
  2891. ref.pagejump.attr('rel', '#' + this.id).data('count', i);
  2892. // display page selector
  2893. ref.show_menu('pagejump-selector', true, e);
  2894. $(this).keydown();
  2895. })
  2896. // keyboard navigation
  2897. .on('keydown keyup click', function(e) {
  2898. var current, selector = $('#pagejump-selector'),
  2899. ul = $('ul', selector),
  2900. list = $('li', ul),
  2901. height = ul.height(),
  2902. p = parseInt(this.value);
  2903. if (e.which != 27 && e.which != 9 && e.which != 13 && !selector.is(':visible'))
  2904. return ref.show_menu('pagejump-selector', true, e);
  2905. if (e.type == 'keydown') {
  2906. // arrow-down
  2907. if (e.which == 40) {
  2908. if (list.length > p)
  2909. this.value = (p += 1);
  2910. }
  2911. // arrow-up
  2912. else if (e.which == 38) {
  2913. if (p > 1 && list.length > p - 1)
  2914. this.value = (p -= 1);
  2915. }
  2916. // enter
  2917. else if (e.which == 13) {
  2918. return $(this).change();
  2919. }
  2920. // esc, tab
  2921. else if (e.which == 27 || e.which == 9) {
  2922. return $(element).val(ref.env.current_page);
  2923. }
  2924. }
  2925. $('li.selected', ul).removeClass('selected');
  2926. if ((current = $(list[p - 1])).length) {
  2927. current.addClass('selected');
  2928. $('#pagejump-selector').scrollTop(((ul.height() / list.length) * (p - 1)) - selector.height() / 2);
  2929. }
  2930. })
  2931. .on('change', function(e) {
  2932. // go to specified page
  2933. var p = parseInt(this.value);
  2934. if (p && p != ref.env.current_page && !ref.busy) {
  2935. ref.hide_menu('pagejump-selector');
  2936. ref.list_page(p);
  2937. }
  2938. });
  2939. };
  2940. // Update page-jumper state on list updates
  2941. this.update_pagejumper = function()
  2942. {
  2943. $('input.rcpagejumper').val(this.env.current_page).prop('disabled', this.env.pagecount < 2);
  2944. };
  2945. // check for mailvelope API
  2946. this.check_mailvelope = function(action)
  2947. {
  2948. if (typeof window.mailvelope !== 'undefined') {
  2949. this.mailvelope_load(action);
  2950. }
  2951. else {
  2952. $(window).on('mailvelope', function() {
  2953. ref.mailvelope_load(action);
  2954. });
  2955. }
  2956. };
  2957. // Load Mailvelope functionality (and initialize keyring if needed)
  2958. this.mailvelope_load = function(action)
  2959. {
  2960. if (this.env.browser_capabilities)
  2961. this.env.browser_capabilities['pgpmime'] = 1;
  2962. var keyring = this.env.user_id;
  2963. mailvelope.getKeyring(keyring).then(function(kr) {
  2964. ref.mailvelope_keyring = kr;
  2965. ref.mailvelope_init(action, kr);
  2966. }, function(err) {
  2967. // attempt to create a new keyring for this app/user
  2968. mailvelope.createKeyring(keyring).then(function(kr) {
  2969. ref.mailvelope_keyring = kr;
  2970. ref.mailvelope_init(action, kr);
  2971. }, function(err) {
  2972. console.error(err);
  2973. });
  2974. });
  2975. };
  2976. // Initializes Mailvelope editor or display container
  2977. this.mailvelope_init = function(action, keyring)
  2978. {
  2979. if (!window.mailvelope)
  2980. return;
  2981. if (action == 'show' || action == 'preview' || action == 'print') {
  2982. // decrypt text body
  2983. if (this.env.is_pgp_content) {
  2984. var data = $(this.env.is_pgp_content).text();
  2985. ref.mailvelope_display_container(this.env.is_pgp_content, data, keyring);
  2986. }
  2987. // load pgp/mime message and pass it to the mailvelope display container
  2988. else if (this.env.pgp_mime_part) {
  2989. var msgid = this.display_message(this.get_label('loadingdata'), 'loading'),
  2990. selector = this.env.pgp_mime_container;
  2991. $.ajax({
  2992. type: 'GET',
  2993. url: this.url('get', { '_mbox': this.env.mailbox, '_uid': this.env.uid, '_part': this.env.pgp_mime_part }),
  2994. error: function(o, status, err) {
  2995. ref.http_error(o, status, err, msgid);
  2996. },
  2997. success: function(data) {
  2998. ref.mailvelope_display_container(selector, data, keyring, msgid);
  2999. }
  3000. });
  3001. }
  3002. }
  3003. else if (action == 'compose') {
  3004. this.env.compose_commands.push('compose-encrypted');
  3005. var is_html = $('input[name="_is_html"]').val() > 0;
  3006. if (this.env.pgp_mime_message) {
  3007. // fetch PGP/Mime part and open load into Mailvelope editor
  3008. var lock = this.set_busy(true, this.get_label('loadingdata'));
  3009. $.ajax({
  3010. type: 'GET',
  3011. url: this.url('get', this.env.pgp_mime_message),
  3012. error: function(o, status, err) {
  3013. ref.http_error(o, status, err, lock);
  3014. ref.enable_command('compose-encrypted', !is_html);
  3015. },
  3016. success: function(data) {
  3017. ref.set_busy(false, null, lock);
  3018. if (is_html) {
  3019. ref.command('toggle-editor', {html: false, noconvert: true});
  3020. $('#' + ref.env.composebody).val('');
  3021. }
  3022. ref.compose_encrypted({ quotedMail: data });
  3023. ref.enable_command('compose-encrypted', true);
  3024. }
  3025. });
  3026. }
  3027. else {
  3028. // enable encrypted compose toggle
  3029. this.enable_command('compose-encrypted', !is_html);
  3030. }
  3031. // make sure to disable encryption button after toggling editor into HTML mode
  3032. this.addEventListener('actionafter', function(args) {
  3033. if (args.ret && args.action == 'toggle-editor')
  3034. ref.enable_command('compose-encrypted', !args.props.html);
  3035. });
  3036. }
  3037. };
  3038. // handler for the 'compose-encrypted' command
  3039. this.compose_encrypted = function(props)
  3040. {
  3041. var options, container = $('#' + this.env.composebody).parent();
  3042. // remove Mailvelope editor if active
  3043. if (ref.mailvelope_editor) {
  3044. ref.mailvelope_editor = null;
  3045. ref.compose_skip_unsavedcheck = false;
  3046. ref.set_button('compose-encrypted', 'act');
  3047. container.removeClass('mailvelope')
  3048. .find('iframe:not([aria-hidden=true])').remove();
  3049. $('#' + ref.env.composebody).show();
  3050. $("[name='_pgpmime']").remove();
  3051. // disable commands that operate on the compose body
  3052. ref.enable_command('spellcheck', 'insert-sig', 'toggle-editor', 'insert-response', 'save-response', true);
  3053. ref.triggerEvent('compose-encrypted', { active:false });
  3054. }
  3055. // embed Mailvelope editor container
  3056. else {
  3057. if (this.spellcheck_state())
  3058. this.editor.spellcheck_stop();
  3059. if (props.quotedMail) {
  3060. options = { quotedMail: props.quotedMail, quotedMailIndent: false };
  3061. }
  3062. else {
  3063. options = { predefinedText: $('#' + this.env.composebody).val() };
  3064. }
  3065. if (this.env.compose_mode == 'reply') {
  3066. options.quotedMailIndent = true;
  3067. options.quotedMailHeader = this.env.compose_reply_header;
  3068. }
  3069. mailvelope.createEditorContainer('#' + container.attr('id'), ref.mailvelope_keyring, options).then(function(editor) {
  3070. ref.mailvelope_editor = editor;
  3071. ref.compose_skip_unsavedcheck = true;
  3072. ref.set_button('compose-encrypted', 'sel');
  3073. container.addClass('mailvelope');
  3074. $('#' + ref.env.composebody).hide();
  3075. // disable commands that operate on the compose body
  3076. ref.enable_command('spellcheck', 'insert-sig', 'toggle-editor', 'insert-response', 'save-response', false);
  3077. ref.triggerEvent('compose-encrypted', { active:true });
  3078. // notify user about loosing attachments
  3079. if (ref.env.attachments && !$.isEmptyObject(ref.env.attachments)) {
  3080. alert(ref.get_label('encryptnoattachments'));
  3081. $.each(ref.env.attachments, function(name, attach) {
  3082. ref.remove_from_attachment_list(name);
  3083. });
  3084. }
  3085. }, function(err) {
  3086. console.error(err);
  3087. console.log(options);
  3088. });
  3089. }
  3090. };
  3091. // callback to replace the message body with the full armored
  3092. this.mailvelope_submit_messageform = function(draft, saveonly)
  3093. {
  3094. // get recipients
  3095. var recipients = [];
  3096. $.each(['to', 'cc', 'bcc'], function(i,field) {
  3097. var pos, rcpt, val = $.trim($('[name="_' + field + '"]').val());
  3098. while (val.length && rcube_check_email(val, true)) {
  3099. rcpt = RegExp.$2;
  3100. recipients.push(rcpt);
  3101. val = val.substr(val.indexOf(rcpt) + rcpt.length + 1).replace(/^\s*,\s*/, '');
  3102. }
  3103. });
  3104. // check if we have keys for all recipients
  3105. var isvalid = recipients.length > 0;
  3106. ref.mailvelope_keyring.validKeyForAddress(recipients).then(function(status) {
  3107. var missing_keys = [];
  3108. $.each(status, function(k,v) {
  3109. if (v === false) {
  3110. isvalid = false;
  3111. missing_keys.push(k);
  3112. }
  3113. });
  3114. // list recipients with missing keys
  3115. if (!isvalid && missing_keys.length) {
  3116. // display dialog with missing keys
  3117. ref.simple_dialog(
  3118. ref.get_label('nopubkeyfor').replace('$email', missing_keys.join(', ')) +
  3119. '<p>' + ref.get_label('searchpubkeyservers') + '</p>',
  3120. 'encryptedsendialog',
  3121. function() {
  3122. ref.mailvelope_search_pubkeys(missing_keys, function() {
  3123. return true; // close dialog
  3124. });
  3125. },
  3126. {button: 'search'}
  3127. );
  3128. return false;
  3129. }
  3130. if (!isvalid) {
  3131. if (!recipients.length) {
  3132. alert(ref.get_label('norecipientwarning'));
  3133. $("[name='_to']").focus();
  3134. }
  3135. return false;
  3136. }
  3137. // add sender identity to recipients to be able to decrypt our very own message
  3138. var senders = [], selected_sender = ref.env.identities[$("[name='_from'] option:selected").val()];
  3139. $.each(ref.env.identities, function(k, sender) {
  3140. senders.push(sender.email);
  3141. });
  3142. ref.mailvelope_keyring.validKeyForAddress(senders).then(function(status) {
  3143. valid_sender = null;
  3144. $.each(status, function(k,v) {
  3145. if (v !== false) {
  3146. valid_sender = k;
  3147. if (valid_sender == selected_sender) {
  3148. return false; // break
  3149. }
  3150. }
  3151. });
  3152. if (!valid_sender) {
  3153. if (!confirm(ref.get_label('nopubkeyforsender'))) {
  3154. return false;
  3155. }
  3156. }
  3157. recipients.push(valid_sender);
  3158. ref.mailvelope_editor.encrypt(recipients).then(function(armored) {
  3159. // all checks passed, send message
  3160. var form = ref.gui_objects.messageform,
  3161. hidden = $("[name='_pgpmime']", form),
  3162. msgid = ref.set_busy(true, draft || saveonly ? 'savingmessage' : 'sendingmessage')
  3163. form.target = 'savetarget';
  3164. form._draft.value = draft ? '1' : '';
  3165. form.action = ref.add_url(form.action, '_unlock', msgid);
  3166. form.action = ref.add_url(form.action, '_framed', 1);
  3167. if (saveonly) {
  3168. form.action = ref.add_url(form.action, '_saveonly', 1);
  3169. }
  3170. // send pgp conent via hidden field
  3171. if (!hidden.length) {
  3172. hidden = $('<input type="hidden" name="_pgpmime">').appendTo(form);
  3173. }
  3174. hidden.val(armored);
  3175. form.submit();
  3176. }, function(err) {
  3177. console.log(err);
  3178. }); // mailvelope_editor.encrypt()
  3179. }, function(err) {
  3180. console.error(err);
  3181. }); // mailvelope_keyring.validKeyForAddress(senders)
  3182. }, function(err) {
  3183. console.error(err);
  3184. }); // mailvelope_keyring.validKeyForAddress(recipients)
  3185. return false;
  3186. };
  3187. // wrapper for the mailvelope.createDisplayContainer API call
  3188. this.mailvelope_display_container = function(selector, data, keyring, msgid)
  3189. {
  3190. var error_handler = function(error) {
  3191. // remove mailvelope frame with the error message
  3192. $(selector + ' > iframe').remove();
  3193. ref.hide_message(msgid);
  3194. ref.display_message(error.message, 'error');
  3195. };
  3196. mailvelope.createDisplayContainer(selector, data, keyring, { showExternalContent: this.env.safemode }).then(function(status) {
  3197. if (status.error && status.error.message) {
  3198. return error_handler(status.error);
  3199. }
  3200. ref.hide_message(msgid);
  3201. $(selector).addClass('mailvelope').children().not('iframe').hide();
  3202. // on success we can remove encrypted part from the attachments list
  3203. if (ref.env.pgp_mime_part)
  3204. $('#attach' + ref.env.pgp_mime_part).remove();
  3205. setTimeout(function() { $(window).resize(); }, 10);
  3206. }, error_handler);
  3207. };
  3208. // subroutine to query keyservers for public keys
  3209. this.mailvelope_search_pubkeys = function(emails, resolve, import_handler)
  3210. {
  3211. // query with publickey.js
  3212. var deferreds = [],
  3213. pk = new PublicKey(),
  3214. lock = ref.display_message(ref.get_label('loading'), 'loading');
  3215. $.each(emails, function(i, email) {
  3216. var d = $.Deferred();
  3217. pk.search(email, function(results, errorCode) {
  3218. if (errorCode !== null) {
  3219. // rejecting would make all fail
  3220. // d.reject(email);
  3221. d.resolve([email]);
  3222. }
  3223. else {
  3224. d.resolve([email].concat(results));
  3225. }
  3226. });
  3227. deferreds.push(d);
  3228. });
  3229. $.when.apply($, deferreds).then(function() {
  3230. var missing_keys = [],
  3231. key_selection = [];
  3232. // alanyze results of all queries
  3233. $.each(arguments, function(i, result) {
  3234. var email = result.shift();
  3235. if (!result.length) {
  3236. missing_keys.push(email);
  3237. }
  3238. else {
  3239. key_selection = key_selection.concat(result);
  3240. }
  3241. });
  3242. ref.hide_message(lock);
  3243. resolve(true);
  3244. // show key import dialog
  3245. if (key_selection.length) {
  3246. ref.mailvelope_key_import_dialog(key_selection, import_handler);
  3247. }
  3248. // some keys could not be found
  3249. if (missing_keys.length) {
  3250. ref.display_message(ref.get_label('nopubkeyfor').replace('$email', missing_keys.join(', ')), 'warning');
  3251. }
  3252. }).fail(function() {
  3253. console.error('Pubkey lookup failed with', arguments);
  3254. ref.hide_message(lock);
  3255. ref.display_message('pubkeysearcherror', 'error');
  3256. resolve(false);
  3257. });
  3258. };
  3259. // list the given public keys in a dialog with options to import
  3260. // them into the local Maivelope keyring
  3261. this.mailvelope_key_import_dialog = function(candidates, import_handler)
  3262. {
  3263. var ul = $('<div>').addClass('listing pgpkeyimport');
  3264. $.each(candidates, function(i, keyrec) {
  3265. var li = $('<div>').addClass('key');
  3266. if (keyrec.revoked) li.addClass('revoked');
  3267. if (keyrec.disabled) li.addClass('disabled');
  3268. if (keyrec.expired) li.addClass('expired');
  3269. li.append($('<label>').addClass('keyid').text(ref.get_label('keyid')));
  3270. li.append($('<a>').text(keyrec.keyid.substr(-8).toUpperCase())
  3271. .attr('href', keyrec.info)
  3272. .attr('target', '_blank')
  3273. .attr('tabindex', '-1'));
  3274. li.append($('<label>').addClass('keylen').text(ref.get_label('keylength')));
  3275. li.append($('<span>').text(keyrec.keylen));
  3276. if (keyrec.expirationdate) {
  3277. li.append($('<label>').addClass('keyexpired').text(ref.get_label('keyexpired')));
  3278. li.append($('<span>').text(new Date(keyrec.expirationdate * 1000).toDateString()));
  3279. }
  3280. if (keyrec.revoked) {
  3281. li.append($('<span>').addClass('keyrevoked').text(ref.get_label('keyrevoked')));
  3282. }
  3283. var ul_ = $('<ul>').addClass('uids');
  3284. $.each(keyrec.uids, function(j, uid) {
  3285. var li_ = $('<li>').addClass('uid');
  3286. if (uid.revoked) li_.addClass('revoked');
  3287. if (uid.disabled) li_.addClass('disabled');
  3288. if (uid.expired) li_.addClass('expired');
  3289. ul_.append(li_.text(uid.uid));
  3290. });
  3291. li.append(ul_);
  3292. li.append($('<input>')
  3293. .attr('type', 'button')
  3294. .attr('rel', keyrec.keyid)
  3295. .attr('value', ref.get_label('import'))
  3296. .addClass('button importkey')
  3297. .prop('disabled', keyrec.revoked || keyrec.disabled || keyrec.expired));
  3298. ul.append(li);
  3299. });
  3300. // display dialog with missing keys
  3301. ref.show_popup_dialog(
  3302. $('<div>')
  3303. .append($('<p>').html(ref.get_label('encryptpubkeysfound')))
  3304. .append(ul),
  3305. ref.get_label('importpubkeys'),
  3306. [{
  3307. text: ref.get_label('close'),
  3308. click: function() {
  3309. (ref.is_framed() ? parent.$ : $)(this).dialog('close');
  3310. }
  3311. }]
  3312. );
  3313. // delegate handler for import button clicks
  3314. ul.on('click', 'input.button.importkey', function() {
  3315. var btn = $(this),
  3316. keyid = btn.attr('rel'),
  3317. pk = new PublicKey(),
  3318. lock = ref.display_message(ref.get_label('loading'), 'loading');
  3319. // fetch from keyserver and import to Mailvelope keyring
  3320. pk.get(keyid, function(armored, errorCode) {
  3321. ref.hide_message(lock);
  3322. if (errorCode) {
  3323. ref.display_message(ref.get_label('keyservererror'), 'error');
  3324. return;
  3325. }
  3326. if (import_handler) {
  3327. import_handler(armored);
  3328. return;
  3329. }
  3330. // import to keyring
  3331. ref.mailvelope_keyring.importPublicKey(armored).then(function(status) {
  3332. if (status === 'REJECTED') {
  3333. // alert(ref.get_label('Key import was rejected'));
  3334. }
  3335. else {
  3336. var $key = keyid.substr(-8).toUpperCase();
  3337. btn.closest('.key').fadeOut();
  3338. ref.display_message(ref.get_label('keyimportsuccess').replace('$key', $key), 'confirmation');
  3339. }
  3340. }, function(err) {
  3341. console.log(err);
  3342. });
  3343. });
  3344. });
  3345. };
  3346. /*********************************************************/
  3347. /********* mailbox folders methods *********/
  3348. /*********************************************************/
  3349. this.expunge_mailbox = function(mbox)
  3350. {
  3351. var lock, post_data = {_mbox: mbox};
  3352. // lock interface if it's the active mailbox
  3353. if (mbox == this.env.mailbox) {
  3354. lock = this.set_busy(true, 'loading');
  3355. post_data._reload = 1;
  3356. if (this.env.search_request)
  3357. post_data._search = this.env.search_request;
  3358. }
  3359. // send request to server
  3360. this.http_post('expunge', post_data, lock);
  3361. };
  3362. this.purge_mailbox = function(mbox)
  3363. {
  3364. var lock, post_data = {_mbox: mbox};
  3365. if (!confirm(this.get_label('purgefolderconfirm')))
  3366. return false;
  3367. // lock interface if it's the active mailbox
  3368. if (mbox == this.env.mailbox) {
  3369. lock = this.set_busy(true, 'loading');
  3370. post_data._reload = 1;
  3371. }
  3372. // send request to server
  3373. this.http_post('purge', post_data, lock);
  3374. };
  3375. // test if purge command is allowed
  3376. this.purge_mailbox_test = function()
  3377. {
  3378. return (this.env.exists && (
  3379. this.env.mailbox == this.env.trash_mailbox
  3380. || this.env.mailbox == this.env.junk_mailbox
  3381. || this.env.mailbox.startsWith(this.env.trash_mailbox + this.env.delimiter)
  3382. || this.env.mailbox.startsWith(this.env.junk_mailbox + this.env.delimiter)
  3383. ));
  3384. };
  3385. // Mark all messages as read in:
  3386. // - selected folder (mode=cur)
  3387. // - selected folder and its subfolders (mode=sub)
  3388. // - all folders (mode=all)
  3389. this.mark_all_read = function(mbox, mode)
  3390. {
  3391. var state, content, nodes = [],
  3392. list = this.message_list,
  3393. folder = mbox || this.env.mailbox,
  3394. post_data = {_uid: '*', _flag: 'read', _mbox: folder, _folders: mode};
  3395. if (typeof mode != 'string') {
  3396. state = this.mark_all_read_state(folder);
  3397. if (!state)
  3398. return;
  3399. if (state > 1) {
  3400. // build content of the dialog
  3401. $.each({cur: 1, sub: 2, all: 4}, function(i, v) {
  3402. var label = $('<label>').attr('style', 'display:block; line-height:22px'),
  3403. text = $('<span>').text(ref.get_label('folders-' + i)),
  3404. input = $('<input>').attr({type: 'radio', value: i, name: 'mode'});
  3405. if (!(state & v)) {
  3406. label.attr('class', 'disabled');
  3407. input.attr('disabled', true);
  3408. }
  3409. nodes.push(label.append(input).append(text));
  3410. });
  3411. content = $('<div>').append(nodes);
  3412. $('input:not([disabled]):first', content).attr('checked', true);
  3413. this.show_popup_dialog(content, this.get_label('markallread'),
  3414. [{
  3415. 'class': 'mainaction',
  3416. text: this.get_label('mark'),
  3417. click: function() {
  3418. ref.mark_all_read(folder, $('input:checked', this).val());
  3419. $(this).dialog('close');
  3420. }
  3421. },
  3422. {
  3423. text: this.get_label('cancel'),
  3424. click: function() {
  3425. $(this).dialog('close');
  3426. }
  3427. }]
  3428. );
  3429. return;
  3430. }
  3431. post_data._folders = 'cur'; // only current folder has unread messages
  3432. }
  3433. // mark messages on the list
  3434. $.each(list ? list.rows : [], function(uid, row) {
  3435. if (!row.unread)
  3436. return;
  3437. var mbox = ref.env.messages[uid].mbox;
  3438. if (mode == 'all' || mbox == ref.env.mailbox
  3439. || (mode == 'sub' && mbox.startsWith(ref.env.mailbox + ref.env.delimiter))
  3440. ) {
  3441. ref.set_message(uid, 'unread', false);
  3442. }
  3443. });
  3444. // send the request
  3445. this.http_post('mark', post_data, this.display_message(this.get_label('markingmessage'), 'loading'));
  3446. };
  3447. // Enable/disable mark-all-read action depending on folders state
  3448. this.mark_all_read_state = function(mbox)
  3449. {
  3450. var state = 0,
  3451. li = this.treelist.get_item(mbox || this.env.mailbox),
  3452. folder_item = $(li).is('.unread') ? 1 : 0,
  3453. subfolder_items = $('li.unread', li).length,
  3454. all_items = $('li.unread', ref.gui_objects.folderlist).length;
  3455. state += folder_item;
  3456. state += subfolder_items ? 2 : 0;
  3457. state += all_items > folder_item + subfolder_items ? 4 : 0;
  3458. this.enable_command('mark-all-read', state > 0);
  3459. return state;
  3460. };
  3461. /*********************************************************/
  3462. /********* login form methods *********/
  3463. /*********************************************************/
  3464. // handler for keyboard events on the _user field
  3465. this.login_user_keyup = function(e)
  3466. {
  3467. var key = rcube_event.get_keycode(e),
  3468. passwd = $('#rcmloginpwd');
  3469. // enter
  3470. if (key == 13 && passwd.length && !passwd.val()) {
  3471. passwd.focus();
  3472. return rcube_event.cancel(e);
  3473. }
  3474. return true;
  3475. };
  3476. /*********************************************************/
  3477. /********* message compose methods *********/
  3478. /*********************************************************/
  3479. this.open_compose_step = function(p)
  3480. {
  3481. var url = this.url('mail/compose', p);
  3482. // open new compose window
  3483. if (this.env.compose_extwin && !this.env.extwin) {
  3484. this.open_window(url);
  3485. }
  3486. else {
  3487. this.redirect(url);
  3488. if (this.env.extwin)
  3489. window.resizeTo(Math.max(this.env.popup_width, $(window).width()), $(window).height() + 24);
  3490. }
  3491. };
  3492. // init message compose form: set focus and eventhandlers
  3493. this.init_messageform = function()
  3494. {
  3495. if (!this.gui_objects.messageform)
  3496. return false;
  3497. var i, elem, pos, input_from = $("[name='_from']"),
  3498. input_to = $("[name='_to']"),
  3499. input_subject = $("input[name='_subject']"),
  3500. input_message = $("[name='_message']").get(0),
  3501. html_mode = $("input[name='_is_html']").val() == '1',
  3502. ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
  3503. ac_props, opener_rc = this.opener();
  3504. // close compose step in opener
  3505. if (opener_rc && opener_rc.env.action == 'compose') {
  3506. setTimeout(function(){
  3507. if (opener.history.length > 1)
  3508. opener.history.back();
  3509. else
  3510. opener_rc.redirect(opener_rc.get_task_url('mail'));
  3511. }, 100);
  3512. this.env.opened_extwin = true;
  3513. }
  3514. // configure parallel autocompletion
  3515. if (this.env.autocomplete_threads > 0) {
  3516. ac_props = {
  3517. threads: this.env.autocomplete_threads,
  3518. sources: this.env.autocomplete_sources
  3519. };
  3520. }
  3521. // init live search events
  3522. this.init_address_input_events(input_to, ac_props);
  3523. for (i in ac_fields) {
  3524. this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
  3525. }
  3526. if (!html_mode) {
  3527. pos = this.env.top_posting && this.env.compose_mode ? 0 : input_message.value.length;
  3528. // add signature according to selected identity
  3529. // if we have HTML editor, signature is added in a callback
  3530. if (input_from.prop('type') == 'select-one') {
  3531. this.change_identity(input_from[0]);
  3532. }
  3533. // set initial cursor position
  3534. this.set_caret_pos(input_message, pos);
  3535. // scroll to the bottom of the textarea (#1490114)
  3536. if (pos) {
  3537. $(input_message).scrollTop(input_message.scrollHeight);
  3538. }
  3539. }
  3540. // check for locally stored compose data
  3541. if (this.env.save_localstorage)
  3542. this.compose_restore_dialog(0, html_mode)
  3543. if (input_to.val() == '')
  3544. elem = input_to;
  3545. else if (input_subject.val() == '')
  3546. elem = input_subject;
  3547. else if (input_message)
  3548. elem = input_message;
  3549. // focus first empty element (need to be visible on IE8)
  3550. $(elem).filter(':visible').focus();
  3551. this.env.compose_focus_elem = document.activeElement;
  3552. // get summary of all field values
  3553. this.compose_field_hash(true);
  3554. // start the auto-save timer
  3555. this.auto_save_start();
  3556. };
  3557. this.compose_restore_dialog = function(j, html_mode)
  3558. {
  3559. var i, key, formdata, index = this.local_storage_get_item('compose.index', []);
  3560. var show_next = function(i) {
  3561. if (++i < index.length)
  3562. ref.compose_restore_dialog(i, html_mode)
  3563. }
  3564. for (i = j || 0; i < index.length; i++) {
  3565. key = index[i];
  3566. formdata = this.local_storage_get_item('compose.' + key, null, true);
  3567. if (!formdata) {
  3568. continue;
  3569. }
  3570. // restore saved copy of current compose_id
  3571. if (formdata.changed && key == this.env.compose_id) {
  3572. this.restore_compose_form(key, html_mode);
  3573. break;
  3574. }
  3575. // skip records from 'other' drafts
  3576. if (this.env.draft_id && formdata.draft_id && formdata.draft_id != this.env.draft_id) {
  3577. continue;
  3578. }
  3579. // skip records on reply
  3580. if (this.env.reply_msgid && formdata.reply_msgid != this.env.reply_msgid) {
  3581. continue;
  3582. }
  3583. // show dialog asking to restore the message
  3584. if (formdata.changed && formdata.session != this.env.session_id) {
  3585. this.show_popup_dialog(
  3586. this.get_label('restoresavedcomposedata')
  3587. .replace('$date', new Date(formdata.changed).toLocaleString())
  3588. .replace('$subject', formdata._subject)
  3589. .replace(/\n/g, '<br/>'),
  3590. this.get_label('restoremessage'),
  3591. [{
  3592. text: this.get_label('restore'),
  3593. 'class': 'mainaction',
  3594. click: function(){
  3595. ref.restore_compose_form(key, html_mode);
  3596. ref.remove_compose_data(key); // remove old copy
  3597. ref.save_compose_form_local(); // save under current compose_id
  3598. $(this).dialog('close');
  3599. }
  3600. },
  3601. {
  3602. text: this.get_label('delete'),
  3603. 'class': 'delete',
  3604. click: function(){
  3605. ref.remove_compose_data(key);
  3606. $(this).dialog('close');
  3607. show_next(i);
  3608. }
  3609. },
  3610. {
  3611. text: this.get_label('ignore'),
  3612. click: function(){
  3613. $(this).dialog('close');
  3614. show_next(i);
  3615. }
  3616. }]
  3617. );
  3618. break;
  3619. }
  3620. }
  3621. }
  3622. this.init_address_input_events = function(obj, props)
  3623. {
  3624. this.env.recipients_delimiter = this.env.recipients_separator + ' ';
  3625. obj.keydown(function(e) { return ref.ksearch_keydown(e, this, props); })
  3626. .attr({ 'autocomplete': 'off', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'role': 'combobox' });
  3627. };
  3628. this.submit_messageform = function(draft, saveonly)
  3629. {
  3630. var form = this.gui_objects.messageform;
  3631. if (!form)
  3632. return;
  3633. // the message has been sent but not saved, ask the user what to do
  3634. if (!saveonly && this.env.is_sent) {
  3635. return this.simple_dialog(this.get_label('messageissent'), '',
  3636. function() {
  3637. ref.submit_messageform(false, true);
  3638. return true;
  3639. }
  3640. );
  3641. }
  3642. // delegate sending to Mailvelope routine
  3643. if (this.mailvelope_editor) {
  3644. return this.mailvelope_submit_messageform(draft, saveonly);
  3645. }
  3646. // all checks passed, send message
  3647. var msgid = this.set_busy(true, draft || saveonly ? 'savingmessage' : 'sendingmessage'),
  3648. lang = this.spellcheck_lang(),
  3649. files = [];
  3650. // send files list
  3651. $('li', this.gui_objects.attachmentlist).each(function() { files.push(this.id.replace(/^rcmfile/, '')); });
  3652. $('input[name="_attachments"]', form).val(files.join());
  3653. form.target = 'savetarget';
  3654. form._draft.value = draft ? '1' : '';
  3655. form.action = this.add_url(form.action, '_unlock', msgid);
  3656. form.action = this.add_url(form.action, '_lang', lang);
  3657. form.action = this.add_url(form.action, '_framed', 1);
  3658. if (saveonly) {
  3659. form.action = this.add_url(form.action, '_saveonly', 1);
  3660. }
  3661. // register timer to notify about connection timeout
  3662. this.submit_timer = setTimeout(function(){
  3663. ref.set_busy(false, null, msgid);
  3664. ref.display_message(ref.get_label('requesttimedout'), 'error');
  3665. }, this.env.request_timeout * 1000);
  3666. form.submit();
  3667. };
  3668. this.compose_recipient_select = function(list)
  3669. {
  3670. var id, n, recipients = 0;
  3671. for (n=0; n < list.selection.length; n++) {
  3672. id = list.selection[n];
  3673. if (this.env.contactdata[id])
  3674. recipients++;
  3675. }
  3676. this.enable_command('add-recipient', recipients);
  3677. };
  3678. this.compose_add_recipient = function(field)
  3679. {
  3680. // find last focused field name
  3681. if (!field) {
  3682. field = $(this.env.focused_field).filter(':visible');
  3683. field = field.length ? field.attr('id').replace('_', '') : 'to';
  3684. }
  3685. var recipients = [], input = $('#_'+field), delim = this.env.recipients_delimiter;
  3686. if (this.contact_list && this.contact_list.selection.length) {
  3687. for (var id, n=0; n < this.contact_list.selection.length; n++) {
  3688. id = this.contact_list.selection[n];
  3689. if (id && this.env.contactdata[id]) {
  3690. recipients.push(this.env.contactdata[id]);
  3691. // group is added, expand it
  3692. if (id.charAt(0) == 'E' && this.env.contactdata[id].indexOf('@') < 0 && input.length) {
  3693. var gid = id.substr(1);
  3694. this.group2expand[gid] = { name:this.env.contactdata[id], input:input.get(0) };
  3695. this.http_request('group-expand', {_source: this.env.source, _gid: gid}, false);
  3696. }
  3697. }
  3698. }
  3699. }
  3700. if (recipients.length && input.length) {
  3701. var oldval = input.val(), rx = new RegExp(RegExp.escape(delim) + '\\s*$');
  3702. if (oldval && !rx.test(oldval))
  3703. oldval += delim + ' ';
  3704. input.val(oldval + recipients.join(delim + ' ') + delim + ' ').change();
  3705. this.triggerEvent('add-recipient', { field:field, recipients:recipients });
  3706. }
  3707. return recipients.length;
  3708. };
  3709. // checks the input fields before sending a message
  3710. this.check_compose_input = function(cmd, skip_recipients_checks)
  3711. {
  3712. // check input fields
  3713. var key, recipients, dialog,
  3714. limit = this.env.max_disclosed_recipients,
  3715. input_to = $("[name='_to']"),
  3716. input_cc = $("[name='_cc']"),
  3717. input_bcc = $("[name='_bcc']"),
  3718. input_from = $("[name='_from']"),
  3719. input_subject = $("[name='_subject']"),
  3720. get_recipients = function(fields) {
  3721. fields = $.map(fields, function(v) {
  3722. v = $.trim(v.val());
  3723. return v.length ? v : null;
  3724. });
  3725. return fields.join(',').replace(/^[\s,;]+/, '').replace(/[\s,;]+$/, '');
  3726. };
  3727. // check sender (if have no identities)
  3728. if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
  3729. alert(this.get_label('nosenderwarning'));
  3730. input_from.focus();
  3731. return false;
  3732. }
  3733. // check for empty recipient
  3734. recipients = get_recipients([input_to, input_cc, input_bcc]);
  3735. if (!skip_recipients_checks && !rcube_check_email(recipients, true)) {
  3736. alert(this.get_label('norecipientwarning'));
  3737. input_to.focus();
  3738. return false;
  3739. }
  3740. // check if all files has been uploaded
  3741. for (key in this.env.attachments) {
  3742. if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
  3743. alert(this.get_label('notuploadedwarning'));
  3744. return false;
  3745. }
  3746. }
  3747. // check disclosed recipients limit
  3748. if (limit && !skip_recipients_checks && !this.env.disclosed_recipients_warned
  3749. && rcube_check_email(recipients = get_recipients([input_to, input_cc]), true, true) > limit
  3750. ) {
  3751. var save_func = function(move_to_bcc) {
  3752. if (move_to_bcc) {
  3753. var bcc = input_bcc.val();
  3754. input_bcc.val((bcc ? (bcc + ', ') : '') + recipients).change();
  3755. input_to.val('').change();
  3756. input_cc.val('').change();
  3757. }
  3758. dialog.dialog('close');
  3759. ref.check_compose_input(cmd, true);
  3760. };
  3761. dialog = this.show_popup_dialog(
  3762. this.get_label('disclosedrecipwarning'),
  3763. this.get_label('disclosedreciptitle'),
  3764. [{
  3765. text: this.get_label('sendmessage'),
  3766. click: function() { save_func(false); },
  3767. 'class': 'mainaction'
  3768. }, {
  3769. text: this.get_label('bccinstead'),
  3770. click: function() { save_func(true); }
  3771. }, {
  3772. text: this.get_label('cancel'),
  3773. click: function() { dialog.dialog('close'); }
  3774. }],
  3775. {dialogClass: 'warning'}
  3776. );
  3777. this.env.disclosed_recipients_warned = true;
  3778. return false;
  3779. }
  3780. // display localized warning for missing subject
  3781. if (!this.env.nosubject_warned && input_subject.val() == '') {
  3782. var prompt_value = $('<input>').attr({type: 'text', size: 40}),
  3783. myprompt = $('<div class="prompt">')
  3784. .append($('<div class="message">').text(this.get_label('nosubjectwarning')))
  3785. .append(prompt_value),
  3786. save_func = function() {
  3787. input_subject.val(prompt_value.val());
  3788. dialog.dialog('close');
  3789. ref.command(cmd, { nocheck:true }); // repeat command which triggered this
  3790. };
  3791. dialog = this.show_popup_dialog(
  3792. myprompt,
  3793. this.get_label('nosubjecttitle'),
  3794. [{
  3795. text: this.get_label('sendmessage'),
  3796. click: function() { save_func(); },
  3797. 'class': 'mainaction'
  3798. }, {
  3799. text: this.get_label('cancel'),
  3800. click: function() {
  3801. input_subject.focus();
  3802. dialog.dialog('close');
  3803. }
  3804. }],
  3805. {dialogClass: 'warning'}
  3806. );
  3807. prompt_value.select().keydown(function(e) {
  3808. if (e.which == 13) save_func();
  3809. });
  3810. this.env.nosubject_warned = true;
  3811. return false;
  3812. }
  3813. // check for empty body (only possible if not mailvelope encrypted)
  3814. if (!this.mailvelope_editor && !this.editor.get_content() && !confirm(this.get_label('nobodywarning'))) {
  3815. this.editor.focus();
  3816. return false;
  3817. }
  3818. // move body from html editor to textarea (just to be sure, #1485860)
  3819. this.editor.save();
  3820. return true;
  3821. };
  3822. this.toggle_editor = function(props, obj, e)
  3823. {
  3824. // @todo: this should work also with many editors on page
  3825. var result = this.editor.toggle(props.html, props.noconvert || false);
  3826. // satisfy the expectations of aftertoggle-editor event subscribers
  3827. props.mode = props.html ? 'html' : 'plain';
  3828. if (!result && e) {
  3829. // fix selector value if operation failed
  3830. props.mode = props.html ? 'plain' : 'html';
  3831. $(e.target).filter('select').val(props.mode);
  3832. }
  3833. if (result) {
  3834. // update internal format flag
  3835. $("input[name='_is_html']").val(props.html ? 1 : 0);
  3836. }
  3837. return result;
  3838. };
  3839. // Inserts a predefined response to the compose editor
  3840. this.insert_response = function(key)
  3841. {
  3842. return this.editor.replace(this.env.textresponses[key]);
  3843. };
  3844. /**
  3845. * Open the dialog to save a new canned response
  3846. */
  3847. this.save_response = function()
  3848. {
  3849. // show dialog to enter a name and to modify the text to be saved
  3850. var buttons = {}, text = this.editor.get_content({selection: true, format: 'text', nosig: true}),
  3851. html = '<form class="propform">' +
  3852. '<div class="prop block"><label>' + this.get_label('responsename') + '</label>' +
  3853. '<input type="text" name="name" id="ffresponsename" size="40" /></div>' +
  3854. '<div class="prop block"><label>' + this.get_label('responsetext') + '</label>' +
  3855. '<textarea name="text" id="ffresponsetext" cols="40" rows="8"></textarea></div>' +
  3856. '</form>';
  3857. buttons[this.get_label('save')] = function(e) {
  3858. var name = $('#ffresponsename').val(),
  3859. text = $('#ffresponsetext').val();
  3860. if (!text) {
  3861. $('#ffresponsetext').select();
  3862. return false;
  3863. }
  3864. if (!name)
  3865. name = text.substring(0,40);
  3866. var lock = ref.display_message(ref.get_label('savingresponse'), 'loading');
  3867. ref.http_post('settings/responses', { _insert:1, _name:name, _text:text }, lock);
  3868. $(this).dialog('close');
  3869. };
  3870. buttons[this.get_label('cancel')] = function() {
  3871. $(this).dialog('close');
  3872. };
  3873. this.show_popup_dialog(html, this.get_label('newresponse'), buttons, {button_classes: ['mainaction']});
  3874. $('#ffresponsetext').val(text);
  3875. $('#ffresponsename').select();
  3876. };
  3877. this.add_response_item = function(response)
  3878. {
  3879. var key = response.key;
  3880. this.env.textresponses[key] = response;
  3881. // append to responses list
  3882. if (this.gui_objects.responseslist) {
  3883. var li = $('<li>').appendTo(this.gui_objects.responseslist);
  3884. $('<a>').addClass('insertresponse active')
  3885. .attr('href', '#')
  3886. .attr('rel', key)
  3887. .attr('tabindex', '0')
  3888. .html(this.quote_html(response.name))
  3889. .appendTo(li)
  3890. .mousedown(function(e) {
  3891. return rcube_event.cancel(e);
  3892. })
  3893. .on('mouseup keypress', function(e) {
  3894. if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
  3895. ref.command('insert-response', $(this).attr('rel'));
  3896. $(document.body).trigger('mouseup'); // hides the menu
  3897. return rcube_event.cancel(e);
  3898. }
  3899. });
  3900. }
  3901. };
  3902. this.edit_responses = function()
  3903. {
  3904. // TODO: implement inline editing of responses
  3905. };
  3906. this.delete_response = function(key)
  3907. {
  3908. if (!key && this.responses_list) {
  3909. var selection = this.responses_list.get_selection();
  3910. key = selection[0];
  3911. }
  3912. // submit delete request
  3913. if (key && confirm(this.get_label('deleteresponseconfirm'))) {
  3914. this.http_post('settings/delete-response', { _key: key }, false);
  3915. }
  3916. };
  3917. // updates spellchecker buttons on state change
  3918. this.spellcheck_state = function()
  3919. {
  3920. var active = this.editor.spellcheck_state();
  3921. $.each(this.buttons.spellcheck || [], function(i, v) {
  3922. $('#' + v.id)[active ? 'addClass' : 'removeClass']('selected');
  3923. });
  3924. return active;
  3925. };
  3926. // get selected language
  3927. this.spellcheck_lang = function()
  3928. {
  3929. return this.editor.get_language();
  3930. };
  3931. this.spellcheck_lang_set = function(lang)
  3932. {
  3933. this.editor.set_language(lang);
  3934. };
  3935. // resume spellchecking, highlight provided mispellings without new ajax request
  3936. this.spellcheck_resume = function(data)
  3937. {
  3938. this.editor.spellcheck_resume(data);
  3939. };
  3940. this.set_draft_id = function(id)
  3941. {
  3942. if (id && id != this.env.draft_id) {
  3943. var filter = {task: 'mail', action: ''},
  3944. rc = this.opener(false, filter) || this.opener(true, filter);
  3945. // refresh the drafts folder in the opener window
  3946. if (rc && rc.env.mailbox == this.env.drafts_mailbox)
  3947. rc.command('checkmail');
  3948. this.env.draft_id = id;
  3949. $("input[name='_draft_saveid']").val(id);
  3950. // reset history of hidden iframe used for saving draft (#1489643)
  3951. // but don't do this on timer-triggered draft-autosaving (#1489789)
  3952. if (window.frames['savetarget'] && window.frames['savetarget'].history && !this.draft_autosave_submit && !this.mailvelope_editor) {
  3953. window.frames['savetarget'].history.back();
  3954. }
  3955. this.draft_autosave_submit = false;
  3956. }
  3957. // always remove local copy upon saving as draft
  3958. this.remove_compose_data(this.env.compose_id);
  3959. this.compose_skip_unsavedcheck = false;
  3960. };
  3961. this.auto_save_start = function()
  3962. {
  3963. if (this.env.draft_autosave) {
  3964. this.draft_autosave_submit = false;
  3965. this.save_timer = setTimeout(function(){
  3966. ref.draft_autosave_submit = true; // set auto-saved flag (#1489789)
  3967. ref.command("savedraft");
  3968. }, this.env.draft_autosave * 1000);
  3969. }
  3970. // save compose form content to local storage every 5 seconds
  3971. if (!this.local_save_timer && window.localStorage && this.env.save_localstorage) {
  3972. // track typing activity and only save on changes
  3973. this.compose_type_activity = this.compose_type_activity_last = 0;
  3974. $(document).keypress(function(e) { ref.compose_type_activity++; });
  3975. this.local_save_timer = setInterval(function(){
  3976. if (ref.compose_type_activity > ref.compose_type_activity_last) {
  3977. ref.save_compose_form_local();
  3978. ref.compose_type_activity_last = ref.compose_type_activity;
  3979. }
  3980. }, 5000);
  3981. $(window).on('unload', function() {
  3982. // remove copy from local storage if compose screen is left after warning
  3983. if (!ref.env.server_error)
  3984. ref.remove_compose_data(ref.env.compose_id);
  3985. });
  3986. }
  3987. // check for unsaved changes before leaving the compose page
  3988. if (!window.onbeforeunload) {
  3989. window.onbeforeunload = function() {
  3990. if (!ref.compose_skip_unsavedcheck && ref.cmp_hash != ref.compose_field_hash()) {
  3991. return ref.get_label('notsentwarning');
  3992. }
  3993. };
  3994. }
  3995. // Unlock interface now that saving is complete
  3996. this.busy = false;
  3997. };
  3998. this.compose_field_hash = function(save)
  3999. {
  4000. // check input fields
  4001. var i, id, val, str = '', hash_fields = ['to', 'cc', 'bcc', 'subject'];
  4002. for (i=0; i<hash_fields.length; i++)
  4003. if (val = $('[name="_' + hash_fields[i] + '"]').val())
  4004. str += val + ':';
  4005. str += this.editor.get_content({refresh: false});
  4006. if (this.env.attachments)
  4007. for (id in this.env.attachments)
  4008. str += id;
  4009. // we can't detect changes in the Mailvelope editor so assume it changed
  4010. if (this.mailvelope_editor) {
  4011. str += ';' + new Date().getTime();
  4012. }
  4013. if (save)
  4014. this.cmp_hash = str;
  4015. return str;
  4016. };
  4017. // store the contents of the compose form to localstorage
  4018. this.save_compose_form_local = function()
  4019. {
  4020. // feature is disabled
  4021. if (!this.env.save_localstorage)
  4022. return;
  4023. var formdata = { session:this.env.session_id, changed:new Date().getTime() },
  4024. ed, empty = true;
  4025. // get fresh content from editor
  4026. this.editor.save();
  4027. if (this.env.draft_id) {
  4028. formdata.draft_id = this.env.draft_id;
  4029. }
  4030. if (this.env.reply_msgid) {
  4031. formdata.reply_msgid = this.env.reply_msgid;
  4032. }
  4033. $('input, select, textarea', this.gui_objects.messageform).each(function(i, elem) {
  4034. switch (elem.tagName.toLowerCase()) {
  4035. case 'input':
  4036. if (elem.type == 'button' || elem.type == 'submit' || (elem.type == 'hidden' && elem.name != '_is_html')) {
  4037. break;
  4038. }
  4039. formdata[elem.name] = elem.type != 'checkbox' || elem.checked ? $(elem).val() : '';
  4040. if (formdata[elem.name] != '' && elem.type != 'hidden')
  4041. empty = false;
  4042. break;
  4043. case 'select':
  4044. formdata[elem.name] = $('option:checked', elem).val();
  4045. break;
  4046. default:
  4047. formdata[elem.name] = $(elem).val();
  4048. if (formdata[elem.name] != '')
  4049. empty = false;
  4050. }
  4051. });
  4052. if (!empty) {
  4053. var index = this.local_storage_get_item('compose.index', []),
  4054. key = this.env.compose_id;
  4055. if ($.inArray(key, index) < 0) {
  4056. index.push(key);
  4057. }
  4058. this.local_storage_set_item('compose.' + key, formdata, true);
  4059. this.local_storage_set_item('compose.index', index);
  4060. }
  4061. };
  4062. // write stored compose data back to form
  4063. this.restore_compose_form = function(key, html_mode)
  4064. {
  4065. var ed, formdata = this.local_storage_get_item('compose.' + key, true);
  4066. if (formdata && typeof formdata == 'object') {
  4067. $.each(formdata, function(k, value) {
  4068. if (k[0] == '_') {
  4069. var elem = $("*[name='"+k+"']");
  4070. if (elem[0] && elem[0].type == 'checkbox') {
  4071. elem.prop('checked', value != '');
  4072. }
  4073. else {
  4074. elem.val(value);
  4075. }
  4076. }
  4077. });
  4078. // initialize HTML editor
  4079. if ((formdata._is_html == '1' && !html_mode) || (formdata._is_html != '1' && html_mode)) {
  4080. this.command('toggle-editor', {id: this.env.composebody, html: !html_mode, noconvert: true});
  4081. }
  4082. }
  4083. };
  4084. // remove stored compose data from localStorage
  4085. this.remove_compose_data = function(key)
  4086. {
  4087. var index = this.local_storage_get_item('compose.index', []);
  4088. if ($.inArray(key, index) >= 0) {
  4089. this.local_storage_remove_item('compose.' + key);
  4090. this.local_storage_set_item('compose.index', $.grep(index, function(val,i) { return val != key; }));
  4091. }
  4092. };
  4093. // clear all stored compose data of this user
  4094. this.clear_compose_data = function()
  4095. {
  4096. var i, index = this.local_storage_get_item('compose.index', []);
  4097. for (i=0; i < index.length; i++) {
  4098. this.local_storage_remove_item('compose.' + index[i]);
  4099. }
  4100. this.local_storage_remove_item('compose.index');
  4101. };
  4102. this.change_identity = function(obj, show_sig)
  4103. {
  4104. if (!obj || !obj.options)
  4105. return false;
  4106. if (!show_sig)
  4107. show_sig = this.env.show_sig;
  4108. var id = obj.options[obj.selectedIndex].value,
  4109. sig = this.env.identity,
  4110. delim = this.env.recipients_separator,
  4111. rx_delim = RegExp.escape(delim);
  4112. // enable manual signature insert
  4113. if (this.env.signatures && this.env.signatures[id]) {
  4114. this.enable_command('insert-sig', true);
  4115. this.env.compose_commands.push('insert-sig');
  4116. }
  4117. else
  4118. this.enable_command('insert-sig', false);
  4119. // first function execution
  4120. if (!this.env.identities_initialized) {
  4121. this.env.identities_initialized = true;
  4122. if (this.env.show_sig_later)
  4123. this.env.show_sig = true;
  4124. if (this.env.opened_extwin)
  4125. return;
  4126. }
  4127. // update reply-to/bcc fields with addresses defined in identities
  4128. $.each(['replyto', 'bcc'], function() {
  4129. var rx, key = this,
  4130. old_val = sig && ref.env.identities[sig] ? ref.env.identities[sig][key] : '',
  4131. new_val = id && ref.env.identities[id] ? ref.env.identities[id][key] : '',
  4132. input = $('[name="_'+key+'"]'), input_val = input.val();
  4133. // remove old address(es)
  4134. if (old_val && input_val) {
  4135. rx = new RegExp('\\s*' + RegExp.escape(old_val) + '\\s*');
  4136. input_val = input_val.replace(rx, '');
  4137. }
  4138. // cleanup
  4139. rx = new RegExp(rx_delim + '\\s*' + rx_delim, 'g');
  4140. input_val = String(input_val).replace(rx, delim);
  4141. rx = new RegExp('^[\\s' + rx_delim + ']+');
  4142. input_val = input_val.replace(rx, '');
  4143. // add new address(es)
  4144. if (new_val && input_val.indexOf(new_val) == -1 && input_val.indexOf(new_val.replace(/"/g, '')) == -1) {
  4145. if (input_val) {
  4146. rx = new RegExp('[' + rx_delim + '\\s]+$')
  4147. input_val = input_val.replace(rx, '') + delim + ' ';
  4148. }
  4149. input_val += new_val + delim + ' ';
  4150. }
  4151. if (old_val || new_val)
  4152. input.val(input_val).change();
  4153. });
  4154. this.editor.change_signature(id, show_sig);
  4155. this.env.identity = id;
  4156. this.triggerEvent('change_identity');
  4157. return true;
  4158. };
  4159. // Open file selection dialog for defined upload form
  4160. // Works only on click and only with smart-upload forms
  4161. this.upload_input = function(name)
  4162. {
  4163. $('#' + name + ' input[type="file"]').click();
  4164. };
  4165. // upload (attachment) file
  4166. this.upload_file = function(form, action, lock)
  4167. {
  4168. if (!form)
  4169. return;
  4170. // count files and size on capable browser
  4171. var size = 0, numfiles = 0;
  4172. $.each($(form).get(0).elements || [], function() {
  4173. if (this.type != 'file')
  4174. return;
  4175. var i, files = this.files ? this.files.length : (this.value ? 1 : 0);
  4176. // check file size
  4177. if (this.files) {
  4178. for (i=0; i < files; i++)
  4179. size += this.files[i].size;
  4180. }
  4181. numfiles += files;
  4182. });
  4183. // create hidden iframe and post upload form
  4184. if (numfiles) {
  4185. if (this.env.max_filesize && this.env.filesizeerror && size > this.env.max_filesize) {
  4186. this.display_message(this.env.filesizeerror, 'error');
  4187. return false;
  4188. }
  4189. if (this.env.max_filecount && this.env.filecounterror && numfiles > this.env.max_filecount) {
  4190. this.display_message(this.env.filecounterror, 'error');
  4191. return false;
  4192. }
  4193. var frame_name = this.async_upload_form(form, action || 'upload', function(e) {
  4194. var d, content = '';
  4195. try {
  4196. if (this.contentDocument) {
  4197. d = this.contentDocument;
  4198. } else if (this.contentWindow) {
  4199. d = this.contentWindow.document;
  4200. }
  4201. content = d.childNodes[1].innerHTML;
  4202. } catch (err) {}
  4203. if (!content.match(/add2attachment/) && (!bw.opera || (ref.env.uploadframe && ref.env.uploadframe == e.data.ts))) {
  4204. if (!content.match(/display_message/))
  4205. ref.display_message(ref.get_label('fileuploaderror'), 'error');
  4206. ref.remove_from_attachment_list(e.data.ts);
  4207. if (lock)
  4208. ref.set_busy(false, null, lock);
  4209. }
  4210. // Opera hack: handle double onload
  4211. if (bw.opera)
  4212. ref.env.uploadframe = e.data.ts;
  4213. });
  4214. // display upload indicator and cancel button
  4215. var content = '<span>' + this.get_label('uploading' + (numfiles > 1 ? 'many' : '')) + '</span>',
  4216. ts = frame_name.replace(/^rcmupload/, '');
  4217. this.add2attachment_list(ts, { name:'', html:content, classname:'uploading', frame:frame_name, complete:false });
  4218. // upload progress support
  4219. if (this.env.upload_progress_time) {
  4220. this.upload_progress_start('upload', ts);
  4221. }
  4222. // set reference to the form object
  4223. this.gui_objects.attachmentform = form;
  4224. return true;
  4225. }
  4226. };
  4227. // add file name to attachment list
  4228. // called from upload page
  4229. this.add2attachment_list = function(name, att, upload_id)
  4230. {
  4231. if (upload_id)
  4232. this.triggerEvent('fileuploaded', {name: name, attachment: att, id: upload_id});
  4233. if (!this.env.attachments)
  4234. this.env.attachments = {};
  4235. if (upload_id && this.env.attachments[upload_id])
  4236. delete this.env.attachments[upload_id];
  4237. this.env.attachments[name] = att;
  4238. if (!this.gui_objects.attachmentlist)
  4239. return false;
  4240. if (!att.complete && this.env.loadingicon)
  4241. att.html = '<img src="'+this.env.loadingicon+'" alt="" class="uploading" />' + att.html;
  4242. if (!att.complete && att.frame)
  4243. att.html = '<a title="'+this.get_label('cancel')+'" onclick="return rcmail.cancel_attachment_upload(\''+name+'\', \''+att.frame+'\');" href="#cancelupload" class="cancelupload">'
  4244. + (this.env.cancelicon ? '<img src="'+this.env.cancelicon+'" alt="'+this.get_label('cancel')+'" />' : this.get_label('cancel')) + '</a>' + att.html;
  4245. var indicator, li = $('<li>');
  4246. li.attr('id', name)
  4247. .addClass(att.classname)
  4248. .html(att.html)
  4249. .on('mouseover', function() { rcube_webmail.long_subject_title_ex(this); });
  4250. // replace indicator's li
  4251. if (upload_id && (indicator = document.getElementById(upload_id))) {
  4252. li.replaceAll(indicator);
  4253. }
  4254. else { // add new li
  4255. li.appendTo(this.gui_objects.attachmentlist);
  4256. }
  4257. // set tabindex attribute
  4258. var tabindex = $(this.gui_objects.attachmentlist).attr('data-tabindex') || '0';
  4259. li.find('a').attr('tabindex', tabindex);
  4260. this.triggerEvent('fileappended', {name: name, attachment: att, id: upload_id, item: li});
  4261. return true;
  4262. };
  4263. this.remove_from_attachment_list = function(name)
  4264. {
  4265. if (this.env.attachments) {
  4266. delete this.env.attachments[name];
  4267. $('#'+name).remove();
  4268. }
  4269. };
  4270. this.remove_attachment = function(name)
  4271. {
  4272. if (name && this.env.attachments[name])
  4273. this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
  4274. return false;
  4275. };
  4276. this.cancel_attachment_upload = function(name, frame_name)
  4277. {
  4278. if (!name || !frame_name)
  4279. return false;
  4280. this.remove_from_attachment_list(name);
  4281. $("iframe[name='"+frame_name+"']").remove();
  4282. return false;
  4283. };
  4284. this.upload_progress_start = function(action, name)
  4285. {
  4286. setTimeout(function() { ref.http_request(action, {_progress: name}); },
  4287. this.env.upload_progress_time * 1000);
  4288. };
  4289. this.upload_progress_update = function(param)
  4290. {
  4291. var elem = $('#'+param.name + ' > span');
  4292. if (!elem.length || !param.text)
  4293. return;
  4294. elem.text(param.text);
  4295. if (!param.done)
  4296. this.upload_progress_start(param.action, param.name);
  4297. };
  4298. // rename uploaded attachment (in compose)
  4299. this.rename_attachment = function(id)
  4300. {
  4301. var attachment = this.env.attachments ? this.env.attachments[id] : null;
  4302. if (!attachment)
  4303. return;
  4304. var input = $('<input>').attr({type: 'text', size: 50}).val(attachment.name),
  4305. content = $('<label>').text(this.get_label('namex')).append(input);
  4306. this.simple_dialog(content, 'attachmentrename', function() {
  4307. var name;
  4308. if ((name = input.val()) && name != attachment.name) {
  4309. ref.http_post('rename-attachment', {_id: ref.env.compose_id, _file: id, _name: name},
  4310. ref.set_busy(true, 'loading'));
  4311. return true;
  4312. }
  4313. },
  4314. {open: function() { input.select(); }}
  4315. );
  4316. };
  4317. // update attachments list with the new name
  4318. this.rename_attachment_handler = function(id, name)
  4319. {
  4320. var attachment = this.env.attachments ? this.env.attachments[id] : null,
  4321. item = $('#' + id + ' > a.filename'),
  4322. link = $('<a>');
  4323. if (!attachment || !name)
  4324. return;
  4325. attachment.name = name;
  4326. // update attachments list
  4327. if (item.length == 1) {
  4328. // create a new element with new attachment name and cloned size
  4329. link.text(name).append($('span', item).clone());
  4330. // update attachment name element
  4331. item.html(link.html());
  4332. // reset parent's title which may contain the old name
  4333. item.parent().attr('title', '');
  4334. }
  4335. };
  4336. // send remote request to add a new contact
  4337. this.add_contact = function(value)
  4338. {
  4339. if (value)
  4340. this.http_post('addcontact', {_address: value});
  4341. return true;
  4342. };
  4343. // send remote request to search mail or contacts
  4344. this.qsearch = function(value)
  4345. {
  4346. if (value || $(this.gui_objects.qsearchbox).val() || $(this.gui_objects.search_interval).val()) {
  4347. var r, lock = this.set_busy(true, 'searching'),
  4348. url = this.search_params(value),
  4349. action = this.env.action == 'compose' && this.contact_list ? 'search-contacts' : 'search';
  4350. if (this.message_list)
  4351. this.clear_message_list();
  4352. else if (this.contact_list)
  4353. this.list_contacts_clear();
  4354. if (this.env.source)
  4355. url._source = this.env.source;
  4356. if (this.env.group)
  4357. url._gid = this.env.group;
  4358. // reset vars
  4359. this.env.current_page = 1;
  4360. r = this.http_request(action, url, lock);
  4361. this.env.qsearch = {lock: lock, request: r};
  4362. this.enable_command('set-listmode', this.env.threads && (this.env.search_scope || 'base') == 'base');
  4363. return true;
  4364. }
  4365. return false;
  4366. };
  4367. this.continue_search = function(request_id)
  4368. {
  4369. var lock = this.set_busy(true, 'stillsearching');
  4370. setTimeout(function() {
  4371. var url = ref.search_params();
  4372. url._continue = request_id;
  4373. ref.env.qsearch = { lock: lock, request: ref.http_request('search', url, lock) };
  4374. }, 100);
  4375. };
  4376. // build URL params for search
  4377. this.search_params = function(search, filter)
  4378. {
  4379. var n, url = {}, mods_arr = [],
  4380. mods = this.env.search_mods,
  4381. scope = this.env.search_scope || 'base',
  4382. mbox = scope == 'all' ? '*' : this.env.mailbox;
  4383. if (!filter && this.gui_objects.search_filter)
  4384. filter = this.gui_objects.search_filter.value;
  4385. if (!search && this.gui_objects.qsearchbox)
  4386. search = this.gui_objects.qsearchbox.value;
  4387. if (filter)
  4388. url._filter = filter;
  4389. if (this.gui_objects.search_interval)
  4390. url._interval = $(this.gui_objects.search_interval).val();
  4391. if (search) {
  4392. url._q = search;
  4393. if (mods && this.message_list)
  4394. mods = mods[mbox] || mods['*'];
  4395. if (mods) {
  4396. for (n in mods)
  4397. mods_arr.push(n);
  4398. url._headers = mods_arr.join(',');
  4399. }
  4400. }
  4401. if (scope)
  4402. url._scope = scope;
  4403. if (mbox && scope != 'all')
  4404. url._mbox = mbox;
  4405. return url;
  4406. };
  4407. // reset search filter
  4408. this.reset_search_filter = function()
  4409. {
  4410. this.filter_disabled = true;
  4411. if (this.gui_objects.search_filter)
  4412. $(this.gui_objects.search_filter).val('ALL').change();
  4413. this.filter_disabled = false;
  4414. };
  4415. // reset quick-search form
  4416. this.reset_qsearch = function(all)
  4417. {
  4418. if (this.gui_objects.qsearchbox)
  4419. this.gui_objects.qsearchbox.value = '';
  4420. if (this.gui_objects.search_interval)
  4421. $(this.gui_objects.search_interval).val('');
  4422. if (this.env.qsearch)
  4423. this.abort_request(this.env.qsearch);
  4424. if (all) {
  4425. this.env.search_scope = 'base';
  4426. this.reset_search_filter();
  4427. }
  4428. this.env.qsearch = null;
  4429. this.env.search_request = null;
  4430. this.env.search_id = null;
  4431. this.select_all_mode = false;
  4432. this.enable_command('set-listmode', this.env.threads);
  4433. };
  4434. this.set_searchscope = function(scope)
  4435. {
  4436. var old = this.env.search_scope;
  4437. this.env.search_scope = scope;
  4438. // re-send search query with new scope
  4439. if (scope != old && this.env.search_request) {
  4440. if (!this.qsearch(this.gui_objects.qsearchbox.value) && this.env.search_filter && this.env.search_filter != 'ALL')
  4441. this.filter_mailbox(this.env.search_filter);
  4442. if (scope != 'all')
  4443. this.select_folder(this.env.mailbox, '', true);
  4444. }
  4445. };
  4446. this.set_searchinterval = function(interval)
  4447. {
  4448. var old = this.env.search_interval;
  4449. this.env.search_interval = interval;
  4450. // re-send search query with new interval
  4451. if (interval != old && this.env.search_request) {
  4452. if (!this.qsearch(this.gui_objects.qsearchbox.value) && this.env.search_filter && this.env.search_filter != 'ALL')
  4453. this.filter_mailbox(this.env.search_filter);
  4454. if (interval)
  4455. this.select_folder(this.env.mailbox, '', true);
  4456. }
  4457. };
  4458. this.set_searchmods = function(mods)
  4459. {
  4460. var mbox = this.env.mailbox,
  4461. scope = this.env.search_scope || 'base';
  4462. if (scope == 'all')
  4463. mbox = '*';
  4464. if (!this.env.search_mods)
  4465. this.env.search_mods = {};
  4466. if (mbox)
  4467. this.env.search_mods[mbox] = mods;
  4468. };
  4469. this.is_multifolder_listing = function()
  4470. {
  4471. return this.env.multifolder_listing !== undefined ? this.env.multifolder_listing :
  4472. (this.env.search_request && (this.env.search_scope || 'base') != 'base');
  4473. };
  4474. // action executed after mail is sent
  4475. this.sent_successfully = function(type, msg, folders, save_error)
  4476. {
  4477. this.display_message(msg, type);
  4478. this.compose_skip_unsavedcheck = true;
  4479. if (this.env.extwin) {
  4480. if (!save_error)
  4481. this.lock_form(this.gui_objects.messageform);
  4482. var filter = {task: 'mail', action: ''},
  4483. rc = this.opener(false, filter) || this.opener(true, filter);
  4484. if (rc) {
  4485. rc.display_message(msg, type);
  4486. // refresh the folder where sent message was saved or replied message comes from
  4487. if (folders && $.inArray(rc.env.mailbox, folders) >= 0) {
  4488. rc.command('checkmail');
  4489. }
  4490. }
  4491. if (!save_error)
  4492. setTimeout(function() { window.close(); }, 1000);
  4493. }
  4494. else if (!save_error) {
  4495. // before redirect we need to wait some time for Chrome (#1486177)
  4496. setTimeout(function() { ref.list_mailbox(); }, 500);
  4497. }
  4498. if (save_error)
  4499. this.env.is_sent = true;
  4500. };
  4501. /*********************************************************/
  4502. /********* keyboard live-search methods *********/
  4503. /*********************************************************/
  4504. // handler for keyboard events on address-fields
  4505. this.ksearch_keydown = function(e, obj, props)
  4506. {
  4507. if (this.ksearch_timer)
  4508. clearTimeout(this.ksearch_timer);
  4509. var key = rcube_event.get_keycode(e),
  4510. mod = rcube_event.get_modifier(e);
  4511. switch (key) {
  4512. case 38: // arrow up
  4513. case 40: // arrow down
  4514. if (!this.ksearch_visible())
  4515. return;
  4516. var dir = key == 38 ? 1 : 0,
  4517. highlight = document.getElementById('rcmkSearchItem' + this.ksearch_selected);
  4518. if (!highlight)
  4519. highlight = this.ksearch_pane.__ul.firstChild;
  4520. if (highlight)
  4521. this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
  4522. return rcube_event.cancel(e);
  4523. case 9: // tab
  4524. if (mod == SHIFT_KEY || !this.ksearch_visible()) {
  4525. this.ksearch_hide();
  4526. return;
  4527. }
  4528. case 13: // enter
  4529. if (!this.ksearch_visible())
  4530. return false;
  4531. // insert selected address and hide ksearch pane
  4532. this.insert_recipient(this.ksearch_selected);
  4533. this.ksearch_hide();
  4534. return rcube_event.cancel(e);
  4535. case 27: // escape
  4536. this.ksearch_hide();
  4537. return;
  4538. case 37: // left
  4539. case 39: // right
  4540. return;
  4541. }
  4542. // start timer
  4543. this.ksearch_timer = setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
  4544. this.ksearch_input = obj;
  4545. return true;
  4546. };
  4547. this.ksearch_visible = function()
  4548. {
  4549. return this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value;
  4550. };
  4551. this.ksearch_select = function(node)
  4552. {
  4553. if (this.ksearch_pane && node) {
  4554. this.ksearch_pane.find('li.selected').removeClass('selected').removeAttr('aria-selected');
  4555. }
  4556. if (node) {
  4557. $(node).addClass('selected').attr('aria-selected', 'true');
  4558. this.ksearch_selected = node._rcm_id;
  4559. $(this.ksearch_input).attr('aria-activedescendant', 'rcmkSearchItem' + this.ksearch_selected);
  4560. }
  4561. };
  4562. this.insert_recipient = function(id)
  4563. {
  4564. if (id === null || !this.env.contacts[id] || !this.ksearch_input)
  4565. return;
  4566. // get cursor pos
  4567. var inp_value = this.ksearch_input.value,
  4568. cpos = this.get_caret_pos(this.ksearch_input),
  4569. p = inp_value.lastIndexOf(this.ksearch_value, cpos),
  4570. trigger = false,
  4571. insert = '',
  4572. // replace search string with full address
  4573. pre = inp_value.substring(0, p),
  4574. end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
  4575. this.ksearch_destroy();
  4576. // insert all members of a group
  4577. if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].type == 'group' && !this.env.contacts[id].email) {
  4578. insert += this.env.contacts[id].name + this.env.recipients_delimiter;
  4579. this.group2expand[this.env.contacts[id].id] = $.extend({ input: this.ksearch_input }, this.env.contacts[id]);
  4580. this.http_request('mail/group-expand', {_source: this.env.contacts[id].source, _gid: this.env.contacts[id].id}, false);
  4581. }
  4582. else if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].name) {
  4583. insert = this.env.contacts[id].name + this.env.recipients_delimiter;
  4584. trigger = true;
  4585. }
  4586. else if (typeof this.env.contacts[id] === 'string') {
  4587. insert = this.env.contacts[id] + this.env.recipients_delimiter;
  4588. trigger = true;
  4589. }
  4590. this.ksearch_input.value = pre + insert + end;
  4591. // set caret to insert pos
  4592. this.set_caret_pos(this.ksearch_input, p + insert.length);
  4593. if (trigger) {
  4594. this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert, data:this.env.contacts[id], search:this.ksearch_value_last, result_type:'person' });
  4595. this.ksearch_value_last = null;
  4596. this.compose_type_activity++;
  4597. }
  4598. };
  4599. this.replace_group_recipients = function(id, recipients)
  4600. {
  4601. if (this.group2expand[id]) {
  4602. this.group2expand[id].input.value = this.group2expand[id].input.value.replace(this.group2expand[id].name, recipients);
  4603. this.triggerEvent('autocomplete_insert', { field:this.group2expand[id].input, insert:recipients, data:this.group2expand[id], search:this.ksearch_value_last, result_type:'group' });
  4604. this.ksearch_value_last = null;
  4605. this.group2expand[id] = null;
  4606. this.compose_type_activity++;
  4607. }
  4608. };
  4609. // address search processor
  4610. this.ksearch_get_results = function(props)
  4611. {
  4612. var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
  4613. if (inp_value === null)
  4614. return;
  4615. if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
  4616. this.ksearch_pane.hide();
  4617. // get string from current cursor pos to last comma
  4618. var cpos = this.get_caret_pos(this.ksearch_input),
  4619. p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
  4620. q = inp_value.substring(p+1, cpos),
  4621. min = this.env.autocomplete_min_length,
  4622. data = this.ksearch_data;
  4623. // trim query string
  4624. q = $.trim(q);
  4625. // Don't (re-)search if the last results are still active
  4626. if (q == this.ksearch_value)
  4627. return;
  4628. this.ksearch_destroy();
  4629. if (q.length && q.length < min) {
  4630. if (!this.ksearch_info) {
  4631. this.ksearch_info = this.display_message(
  4632. this.get_label('autocompletechars').replace('$min', min));
  4633. }
  4634. return;
  4635. }
  4636. var old_value = this.ksearch_value;
  4637. this.ksearch_value = q;
  4638. this.ksearch_value_last = q; // Group expansion clears ksearch_value before calling autocomplete_insert trigger, therefore store it in separate variable for later consumption.
  4639. // ...string is empty
  4640. if (!q.length)
  4641. return;
  4642. // ...new search value contains old one and previous search was not finished or its result was empty
  4643. if (old_value && old_value.length && q.startsWith(old_value) && (!data || data.num <= 0) && this.env.contacts && !this.env.contacts.length)
  4644. return;
  4645. var sources = props && props.sources ? props.sources : [''];
  4646. var reqid = this.multi_thread_http_request({
  4647. items: sources,
  4648. threads: props && props.threads ? props.threads : 1,
  4649. action: props && props.action ? props.action : 'mail/autocomplete',
  4650. postdata: { _search:q, _source:'%s' },
  4651. lock: this.display_message(this.get_label('searching'), 'loading')
  4652. });
  4653. this.ksearch_data = { id:reqid, sources:sources.slice(), num:sources.length };
  4654. };
  4655. this.ksearch_query_results = function(results, search, reqid)
  4656. {
  4657. // trigger multi-thread http response callback
  4658. this.multi_thread_http_response(results, reqid);
  4659. // search stopped in meantime?
  4660. if (!this.ksearch_value)
  4661. return;
  4662. // ignore this outdated search response
  4663. if (this.ksearch_input && search != this.ksearch_value)
  4664. return;
  4665. // display search results
  4666. var i, id, len, ul, text, type, init,
  4667. value = this.ksearch_value,
  4668. maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
  4669. // create results pane if not present
  4670. if (!this.ksearch_pane) {
  4671. ul = $('<ul>');
  4672. this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane').attr('role', 'listbox')
  4673. .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
  4674. this.ksearch_pane.__ul = ul[0];
  4675. }
  4676. ul = this.ksearch_pane.__ul;
  4677. // remove all search results or add to existing list if parallel search
  4678. if (reqid && this.ksearch_pane.data('reqid') == reqid) {
  4679. maxlen -= ul.childNodes.length;
  4680. }
  4681. else {
  4682. this.ksearch_pane.data('reqid', reqid);
  4683. init = 1;
  4684. // reset content
  4685. ul.innerHTML = '';
  4686. this.env.contacts = [];
  4687. // move the results pane right under the input box
  4688. var pos = $(this.ksearch_input).offset();
  4689. this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
  4690. }
  4691. // add each result line to list
  4692. if (results && (len = results.length)) {
  4693. for (i=0; i < len && maxlen > 0; i++) {
  4694. text = typeof results[i] === 'object' ? (results[i].display || results[i].name) : results[i];
  4695. type = typeof results[i] === 'object' ? results[i].type : '';
  4696. id = i + this.env.contacts.length;
  4697. $('<li>').attr('id', 'rcmkSearchItem' + id)
  4698. .attr('role', 'option')
  4699. .html('<i class="icon"></i>' + this.quote_html(text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%')).replace(/##([^%]+)%%/g, '<b>$1</b>'))
  4700. .addClass(type || '')
  4701. .appendTo(ul)
  4702. .mouseover(function() { ref.ksearch_select(this); })
  4703. .mouseup(function() { ref.ksearch_click(this); })
  4704. .get(0)._rcm_id = id;
  4705. maxlen -= 1;
  4706. }
  4707. }
  4708. if (ul.childNodes.length) {
  4709. // set the right aria-* attributes to the input field
  4710. $(this.ksearch_input)
  4711. .attr('aria-haspopup', 'true')
  4712. .attr('aria-expanded', 'true')
  4713. .attr('aria-owns', 'rcmKSearchpane');
  4714. this.ksearch_pane.show();
  4715. // select the first
  4716. if (!this.env.contacts.length) {
  4717. this.ksearch_select($('li:first', ul).get(0));
  4718. }
  4719. }
  4720. if (len)
  4721. this.env.contacts = this.env.contacts.concat(results);
  4722. if (this.ksearch_data.id == reqid)
  4723. this.ksearch_data.num--;
  4724. };
  4725. this.ksearch_click = function(node)
  4726. {
  4727. if (this.ksearch_input)
  4728. this.ksearch_input.focus();
  4729. this.insert_recipient(node._rcm_id);
  4730. this.ksearch_hide();
  4731. };
  4732. this.ksearch_blur = function()
  4733. {
  4734. if (this.ksearch_timer)
  4735. clearTimeout(this.ksearch_timer);
  4736. this.ksearch_input = null;
  4737. this.ksearch_hide();
  4738. };
  4739. this.ksearch_hide = function()
  4740. {
  4741. this.ksearch_selected = null;
  4742. this.ksearch_value = '';
  4743. if (this.ksearch_pane)
  4744. this.ksearch_pane.hide();
  4745. $(this.ksearch_input)
  4746. .attr('aria-haspopup', 'false')
  4747. .attr('aria-expanded', 'false')
  4748. .removeAttr('aria-activedescendant')
  4749. .removeAttr('aria-owns');
  4750. this.ksearch_destroy();
  4751. };
  4752. // Clears autocomplete data/requests
  4753. this.ksearch_destroy = function()
  4754. {
  4755. if (this.ksearch_data)
  4756. this.multi_thread_request_abort(this.ksearch_data.id);
  4757. if (this.ksearch_info)
  4758. this.hide_message(this.ksearch_info);
  4759. if (this.ksearch_msg)
  4760. this.hide_message(this.ksearch_msg);
  4761. this.ksearch_data = null;
  4762. this.ksearch_info = null;
  4763. this.ksearch_msg = null;
  4764. };
  4765. /*********************************************************/
  4766. /********* address book methods *********/
  4767. /*********************************************************/
  4768. this.contactlist_keypress = function(list)
  4769. {
  4770. if (list.key_pressed == list.DELETE_KEY)
  4771. this.command('delete');
  4772. };
  4773. this.contactlist_select = function(list)
  4774. {
  4775. if (this.preview_timer)
  4776. clearTimeout(this.preview_timer);
  4777. var n, id, sid, contact, writable = false,
  4778. selected = list.selection.length,
  4779. source = this.env.source ? this.env.address_sources[this.env.source] : null;
  4780. // we don't have dblclick handler here, so use 50 instead of this.dblclick_time
  4781. if (this.env.contentframe && (id = list.get_single_selection()))
  4782. this.preview_timer = setTimeout(function(){ ref.load_contact(id, 'show'); }, 50);
  4783. else if (this.env.contentframe)
  4784. this.show_contentframe(false);
  4785. if (selected) {
  4786. list.draggable = false;
  4787. // no source = search result, we'll need to detect if any of
  4788. // selected contacts are in writable addressbook to enable edit/delete
  4789. // we'll also need to know sources used in selection for copy
  4790. // and group-addmember operations (drag&drop)
  4791. this.env.selection_sources = [];
  4792. if (source) {
  4793. this.env.selection_sources.push(this.env.source);
  4794. }
  4795. for (n in list.selection) {
  4796. contact = list.data[list.selection[n]];
  4797. if (!source) {
  4798. sid = String(list.selection[n]).replace(/^[^-]+-/, '');
  4799. if (sid && this.env.address_sources[sid]) {
  4800. writable = writable || (!this.env.address_sources[sid].readonly && !contact.readonly);
  4801. this.env.selection_sources.push(sid);
  4802. }
  4803. }
  4804. else {
  4805. writable = writable || (!source.readonly && !contact.readonly);
  4806. }
  4807. if (contact._type != 'group')
  4808. list.draggable = true;
  4809. }
  4810. this.env.selection_sources = $.unique(this.env.selection_sources);
  4811. }
  4812. // if a group is currently selected, and there is at least one contact selected
  4813. // thend we can enable the group-remove-selected command
  4814. this.enable_command('group-remove-selected', this.env.group && selected && writable);
  4815. this.enable_command('compose', this.env.group || selected);
  4816. this.enable_command('print', selected == 1);
  4817. this.enable_command('export-selected', 'copy', selected > 0);
  4818. this.enable_command('edit', id && writable);
  4819. this.enable_command('delete', 'move', selected && writable);
  4820. return false;
  4821. };
  4822. this.list_contacts = function(src, group, page, search)
  4823. {
  4824. var win, folder, index = -1, url = {},
  4825. refresh = src === undefined && group === undefined && page === undefined,
  4826. target = window;
  4827. if (!src)
  4828. src = this.env.source;
  4829. if (refresh)
  4830. group = this.env.group;
  4831. if (src != this.env.source) {
  4832. page = this.env.current_page = 1;
  4833. this.reset_qsearch();
  4834. }
  4835. else if (!refresh && group != this.env.group)
  4836. page = this.env.current_page = 1;
  4837. if (this.env.search_id)
  4838. folder = 'S'+this.env.search_id;
  4839. else if (!this.env.search_request)
  4840. folder = group ? 'G'+src+group : src;
  4841. this.env.source = src;
  4842. this.env.group = group;
  4843. // truncate groups listing stack
  4844. $.each(this.env.address_group_stack, function(i, v) {
  4845. if (ref.env.group == v.id) {
  4846. index = i;
  4847. return false;
  4848. }
  4849. });
  4850. this.env.address_group_stack = index < 0 ? [] : this.env.address_group_stack.slice(0, index);
  4851. // make sure the current group is on top of the stack
  4852. if (this.env.group) {
  4853. if (!search) search = {};
  4854. search.id = this.env.group;
  4855. this.env.address_group_stack.push(search);
  4856. // mark the first group on the stack as selected in the directory list
  4857. folder = 'G'+src+this.env.address_group_stack[0].id;
  4858. }
  4859. else if (this.gui_objects.addresslist_title) {
  4860. $(this.gui_objects.addresslist_title).text(this.get_label('contacts'));
  4861. }
  4862. if (!this.env.search_id)
  4863. this.select_folder(folder, '', true);
  4864. // load contacts remotely
  4865. if (this.gui_objects.contactslist) {
  4866. this.list_contacts_remote(src, group, page);
  4867. return;
  4868. }
  4869. if (win = this.get_frame_window(this.env.contentframe)) {
  4870. target = win;
  4871. url._framed = 1;
  4872. }
  4873. if (group)
  4874. url._gid = group;
  4875. if (page)
  4876. url._page = page;
  4877. if (src)
  4878. url._source = src;
  4879. // also send search request to get the correct listing
  4880. if (this.env.search_request)
  4881. url._search = this.env.search_request;
  4882. this.set_busy(true, 'loading');
  4883. this.location_href(url, target);
  4884. };
  4885. // send remote request to load contacts list
  4886. this.list_contacts_remote = function(src, group, page)
  4887. {
  4888. // clear message list first
  4889. this.list_contacts_clear();
  4890. // send request to server
  4891. var url = {}, lock = this.set_busy(true, 'loading');
  4892. if (src)
  4893. url._source = src;
  4894. if (page)
  4895. url._page = page;
  4896. if (group)
  4897. url._gid = group;
  4898. this.env.source = src;
  4899. this.env.group = group;
  4900. // also send search request to get the right records
  4901. if (this.env.search_request)
  4902. url._search = this.env.search_request;
  4903. this.http_request(this.env.task == 'mail' ? 'list-contacts' : 'list', url, lock);
  4904. if (this.env.task != 'mail')
  4905. this.update_state({_source: src, _page: page && page > 1 ? page : null, _gid: group});
  4906. };
  4907. this.list_contacts_clear = function()
  4908. {
  4909. this.contact_list.data = {};
  4910. this.contact_list.clear(true);
  4911. this.show_contentframe(false);
  4912. this.enable_command('delete', 'move', 'copy', 'print', false);
  4913. this.enable_command('compose', this.env.group);
  4914. };
  4915. this.set_group_prop = function(prop)
  4916. {
  4917. if (this.gui_objects.addresslist_title) {
  4918. var boxtitle = $(this.gui_objects.addresslist_title).html(''); // clear contents
  4919. // add link to pop back to parent group
  4920. if (this.env.address_group_stack.length > 1
  4921. || (this.env.address_group_stack.length == 1 && this.env.address_group_stack[0].search_request)
  4922. ) {
  4923. $('<a href="#list">...</a>')
  4924. .attr('title', this.get_label('uponelevel'))
  4925. .addClass('poplink')
  4926. .appendTo(boxtitle)
  4927. .click(function(e){ return ref.command('popgroup','',this); });
  4928. boxtitle.append('&nbsp;&raquo;&nbsp;');
  4929. }
  4930. boxtitle.append($('<span>').text(prop ? prop.name : this.get_label('contacts')));
  4931. }
  4932. if (prop)
  4933. this.triggerEvent('groupupdate', prop);
  4934. };
  4935. // load contact record
  4936. this.load_contact = function(cid, action, framed)
  4937. {
  4938. var win, url = {}, target = window,
  4939. rec = this.contact_list ? this.contact_list.data[cid] : null;
  4940. if (win = this.get_frame_window(this.env.contentframe)) {
  4941. url._framed = 1;
  4942. target = win;
  4943. this.show_contentframe(true);
  4944. // load dummy content, unselect selected row(s)
  4945. if (!cid)
  4946. this.contact_list.clear_selection();
  4947. this.enable_command('compose', rec && rec.email);
  4948. this.enable_command('export-selected', 'print', rec && rec._type != 'group');
  4949. }
  4950. else if (framed)
  4951. return false;
  4952. if (action && (cid || action == 'add') && !this.drag_active) {
  4953. if (this.env.group)
  4954. url._gid = this.env.group;
  4955. if (this.env.search_request)
  4956. url._search = this.env.search_request;
  4957. url._action = action;
  4958. url._source = this.env.source;
  4959. url._cid = cid;
  4960. this.location_href(url, target, true);
  4961. }
  4962. return true;
  4963. };
  4964. // add/delete member to/from the group
  4965. this.group_member_change = function(what, cid, source, gid)
  4966. {
  4967. if (what != 'add')
  4968. what = 'del';
  4969. var label = this.get_label(what == 'add' ? 'addingmember' : 'removingmember'),
  4970. lock = this.display_message(label, 'loading'),
  4971. post_data = {_cid: cid, _source: source, _gid: gid};
  4972. this.http_post('group-'+what+'members', post_data, lock);
  4973. };
  4974. this.contacts_drag_menu = function(e, to)
  4975. {
  4976. var dest = to.type == 'group' ? to.source : to.id,
  4977. source = this.env.source;
  4978. if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
  4979. return true;
  4980. // search result may contain contacts from many sources, but if there is only one...
  4981. if (source == '' && this.env.selection_sources.length == 1)
  4982. source = this.env.selection_sources[0];
  4983. if (to.type == 'group' && dest == source) {
  4984. var cid = this.contact_list.get_selection().join(',');
  4985. this.group_member_change('add', cid, dest, to.id);
  4986. return true;
  4987. }
  4988. // move action is not possible, "redirect" to copy if menu wasn't requested
  4989. else if (!this.commands.move && rcube_event.get_modifier(e) != SHIFT_KEY) {
  4990. this.copy_contacts(to);
  4991. return true;
  4992. }
  4993. return this.drag_menu(e, to);
  4994. };
  4995. // copy contact(s) to the specified target (group or directory)
  4996. this.copy_contacts = function(to)
  4997. {
  4998. var dest = to.type == 'group' ? to.source : to.id,
  4999. source = this.env.source,
  5000. group = this.env.group ? this.env.group : '',
  5001. cid = this.contact_list.get_selection().join(',');
  5002. if (!cid || !this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
  5003. return;
  5004. // search result may contain contacts from many sources, but if there is only one...
  5005. if (source == '' && this.env.selection_sources.length == 1)
  5006. source = this.env.selection_sources[0];
  5007. // tagret is a group
  5008. if (to.type == 'group') {
  5009. if (dest == source)
  5010. return;
  5011. var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
  5012. post_data = {_cid: cid, _source: this.env.source, _to: dest, _togid: to.id, _gid: group};
  5013. this.http_post('copy', post_data, lock);
  5014. }
  5015. // target is an addressbook
  5016. else if (to.id != source) {
  5017. var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
  5018. post_data = {_cid: cid, _source: this.env.source, _to: to.id, _gid: group};
  5019. this.http_post('copy', post_data, lock);
  5020. }
  5021. };
  5022. // move contact(s) to the specified target (group or directory)
  5023. this.move_contacts = function(to)
  5024. {
  5025. var dest = to.type == 'group' ? to.source : to.id,
  5026. source = this.env.source,
  5027. group = this.env.group ? this.env.group : '';
  5028. if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
  5029. return;
  5030. // search result may contain contacts from many sources, but if there is only one...
  5031. if (source == '' && this.env.selection_sources.length == 1)
  5032. source = this.env.selection_sources[0];
  5033. if (to.type == 'group') {
  5034. if (dest == source)
  5035. return;
  5036. this._with_selected_contacts('move', {_to: dest, _togid: to.id});
  5037. }
  5038. // target is an addressbook
  5039. else if (to.id != source)
  5040. this._with_selected_contacts('move', {_to: to.id});
  5041. };
  5042. // delete contact(s)
  5043. this.delete_contacts = function()
  5044. {
  5045. var undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
  5046. if (!undelete && !confirm(this.get_label('deletecontactconfirm')))
  5047. return;
  5048. return this._with_selected_contacts('delete');
  5049. };
  5050. this._with_selected_contacts = function(action, post_data)
  5051. {
  5052. var selection = this.contact_list ? this.contact_list.get_selection() : [];
  5053. // exit if no contact specified or if selection is empty
  5054. if (!selection.length && !this.env.cid)
  5055. return;
  5056. var n, a_cids = [],
  5057. label = action == 'delete' ? 'contactdeleting' : 'movingcontact',
  5058. lock = this.display_message(this.get_label(label), 'loading');
  5059. if (this.env.cid)
  5060. a_cids.push(this.env.cid);
  5061. else {
  5062. for (n=0; n<selection.length; n++) {
  5063. id = selection[n];
  5064. a_cids.push(id);
  5065. this.contact_list.remove_row(id, (n == selection.length-1));
  5066. }
  5067. // hide content frame if we delete the currently displayed contact
  5068. if (selection.length == 1)
  5069. this.show_contentframe(false);
  5070. }
  5071. if (!post_data)
  5072. post_data = {};
  5073. post_data._source = this.env.source;
  5074. post_data._from = this.env.action;
  5075. post_data._cid = a_cids.join(',');
  5076. if (this.env.group)
  5077. post_data._gid = this.env.group;
  5078. // also send search request to get the right records from the next page
  5079. if (this.env.search_request)
  5080. post_data._search = this.env.search_request;
  5081. // send request to server
  5082. this.http_post(action, post_data, lock)
  5083. return true;
  5084. };
  5085. // update a contact record in the list
  5086. this.update_contact_row = function(cid, cols_arr, newcid, source, data)
  5087. {
  5088. var list = this.contact_list;
  5089. cid = this.html_identifier(cid);
  5090. // when in searching mode, concat cid with the source name
  5091. if (!list.rows[cid]) {
  5092. cid = cid + '-' + source;
  5093. if (newcid)
  5094. newcid = newcid + '-' + source;
  5095. }
  5096. list.update_row(cid, cols_arr, newcid, true);
  5097. list.data[cid] = data;
  5098. };
  5099. // add row to contacts list
  5100. this.add_contact_row = function(cid, cols, classes, data)
  5101. {
  5102. if (!this.gui_objects.contactslist)
  5103. return false;
  5104. var c, col, list = this.contact_list,
  5105. row = { cols:[] };
  5106. row.id = 'rcmrow' + this.html_identifier(cid);
  5107. row.className = 'contact ' + (classes || '');
  5108. if (list.in_selection(cid))
  5109. row.className += ' selected';
  5110. // add each submitted col
  5111. for (c in cols) {
  5112. col = {};
  5113. col.className = String(c).toLowerCase();
  5114. col.innerHTML = cols[c];
  5115. row.cols.push(col);
  5116. }
  5117. // store data in list member
  5118. list.data[cid] = data;
  5119. list.insert_row(row);
  5120. this.enable_command('export', list.rowcount > 0);
  5121. };
  5122. this.init_contact_form = function()
  5123. {
  5124. var col;
  5125. if (this.env.coltypes) {
  5126. this.set_photo_actions($('#ff_photo').val());
  5127. for (col in this.env.coltypes)
  5128. this.init_edit_field(col, null);
  5129. }
  5130. $('.contactfieldgroup .row a.deletebutton').click(function() {
  5131. ref.delete_edit_field(this);
  5132. return false;
  5133. });
  5134. $('select.addfieldmenu').change(function() {
  5135. ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
  5136. this.selectedIndex = 0;
  5137. });
  5138. // enable date pickers on date fields
  5139. if ($.datepicker && this.env.date_format) {
  5140. $.datepicker.setDefaults({
  5141. dateFormat: this.env.date_format,
  5142. changeMonth: true,
  5143. changeYear: true,
  5144. yearRange: '-120:+10',
  5145. showOtherMonths: true,
  5146. selectOtherMonths: true
  5147. // onSelect: function(dateText) { $(this).focus().val(dateText); }
  5148. });
  5149. $('input.datepicker').datepicker();
  5150. }
  5151. // Submit search form on Enter
  5152. if (this.env.action == 'search')
  5153. $(this.gui_objects.editform).append($('<input type="submit">').hide())
  5154. .submit(function() { $('input.mainaction').click(); return false; });
  5155. };
  5156. // group creation dialog
  5157. this.group_create = function()
  5158. {
  5159. var input = $('<input>').attr('type', 'text'),
  5160. content = $('<label>').text(this.get_label('namex')).append(input);
  5161. this.simple_dialog(content, 'newgroup',
  5162. function() {
  5163. var name;
  5164. if (name = input.val()) {
  5165. ref.http_post('group-create', {_source: ref.env.source, _name: name},
  5166. ref.set_busy(true, 'loading'));
  5167. return true;
  5168. }
  5169. });
  5170. };
  5171. // group rename dialog
  5172. this.group_rename = function()
  5173. {
  5174. if (!this.env.group)
  5175. return;
  5176. var group_name = this.env.contactgroups['G' + this.env.source + this.env.group].name,
  5177. input = $('<input>').attr('type', 'text').val(group_name),
  5178. content = $('<label>').text(this.get_label('namex')).append(input);
  5179. this.simple_dialog(content, 'grouprename',
  5180. function() {
  5181. var name;
  5182. if ((name = input.val()) && name != group_name) {
  5183. ref.http_post('group-rename', {_source: ref.env.source, _gid: ref.env.group, _name: name},
  5184. ref.set_busy(true, 'loading'));
  5185. return true;
  5186. }
  5187. },
  5188. {open: function() { input.select(); }}
  5189. );
  5190. };
  5191. this.group_delete = function()
  5192. {
  5193. if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
  5194. var lock = this.set_busy(true, 'groupdeleting');
  5195. this.http_post('group-delete', {_source: this.env.source, _gid: this.env.group}, lock);
  5196. }
  5197. };
  5198. // callback from server upon group-delete command
  5199. this.remove_group_item = function(prop)
  5200. {
  5201. var key = 'G'+prop.source+prop.id;
  5202. if (this.treelist.remove(key)) {
  5203. this.triggerEvent('group_delete', { source:prop.source, id:prop.id });
  5204. delete this.env.contactfolders[key];
  5205. delete this.env.contactgroups[key];
  5206. }
  5207. this.list_contacts(prop.source, 0);
  5208. };
  5209. //remove selected contacts from current active group
  5210. this.group_remove_selected = function()
  5211. {
  5212. this.http_post('group-delmembers', {_cid: this.contact_list.selection,
  5213. _source: this.env.source, _gid: this.env.group});
  5214. };
  5215. //callback after deleting contact(s) from current group
  5216. this.remove_group_contacts = function(props)
  5217. {
  5218. if (this.env.group !== undefined && (this.env.group === props.gid)) {
  5219. var n, selection = this.contact_list.get_selection();
  5220. for (n=0; n<selection.length; n++) {
  5221. id = selection[n];
  5222. this.contact_list.remove_row(id, (n == selection.length-1));
  5223. }
  5224. }
  5225. };
  5226. // callback for creating a new contact group
  5227. this.insert_contact_group = function(prop)
  5228. {
  5229. prop.type = 'group';
  5230. var key = 'G'+prop.source+prop.id,
  5231. link = $('<a>').attr('href', '#')
  5232. .attr('rel', prop.source+':'+prop.id)
  5233. .click(function() { return ref.command('listgroup', prop, this); })
  5234. .html(prop.name);
  5235. this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
  5236. this.treelist.insert({ id:key, html:link, classes:['contactgroup'] }, prop.source, 'contactgroup');
  5237. this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key) });
  5238. };
  5239. // callback for renaming a contact group
  5240. this.update_contact_group = function(prop)
  5241. {
  5242. var key = 'G'+prop.source+prop.id,
  5243. newnode = {};
  5244. // group ID has changed, replace link node and identifiers
  5245. if (prop.newid) {
  5246. var newkey = 'G'+prop.source+prop.newid,
  5247. newprop = $.extend({}, prop);
  5248. this.env.contactfolders[newkey] = this.env.contactfolders[key];
  5249. this.env.contactfolders[newkey].id = prop.newid;
  5250. this.env.group = prop.newid;
  5251. delete this.env.contactfolders[key];
  5252. delete this.env.contactgroups[key];
  5253. newprop.id = prop.newid;
  5254. newprop.type = 'group';
  5255. newnode.id = newkey;
  5256. newnode.html = $('<a>').attr('href', '#')
  5257. .attr('rel', prop.source+':'+prop.newid)
  5258. .click(function() { return ref.command('listgroup', newprop, this); })
  5259. .html(prop.name);
  5260. }
  5261. // update displayed group name
  5262. else {
  5263. $(this.treelist.get_item(key)).children().first().html(prop.name);
  5264. this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
  5265. }
  5266. // update list node and re-sort it
  5267. this.treelist.update(key, newnode, true);
  5268. this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key), newid:prop.newid });
  5269. };
  5270. this.update_group_commands = function()
  5271. {
  5272. var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null,
  5273. supported = source && source.groups && !source.readonly;
  5274. this.enable_command('group-create', supported);
  5275. this.enable_command('group-rename', 'group-delete', supported && this.env.group);
  5276. };
  5277. this.init_edit_field = function(col, elem)
  5278. {
  5279. var label = this.env.coltypes[col].label;
  5280. if (!elem)
  5281. elem = $('.ff_' + col);
  5282. if (label)
  5283. elem.placeholder(label);
  5284. };
  5285. this.insert_edit_field = function(col, section, menu)
  5286. {
  5287. // just make pre-defined input field visible
  5288. var elem = $('#ff_'+col);
  5289. if (elem.length) {
  5290. elem.show().focus();
  5291. $(menu).children('option[value="'+col+'"]').prop('disabled', true);
  5292. }
  5293. else {
  5294. var lastelem = $('.ff_'+col),
  5295. appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
  5296. if (!appendcontainer.length) {
  5297. var sect = $('#contactsection'+section),
  5298. lastgroup = $('.contactfieldgroup', sect).last();
  5299. appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col);
  5300. if (lastgroup.length)
  5301. appendcontainer.insertAfter(lastgroup);
  5302. else
  5303. sect.prepend(appendcontainer);
  5304. }
  5305. if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
  5306. var input, colprop = this.env.coltypes[col],
  5307. input_id = 'ff_' + col + (colprop.count || 0),
  5308. row = $('<div>').addClass('row'),
  5309. cell = $('<div>').addClass('contactfieldcontent data'),
  5310. label = $('<div>').addClass('contactfieldlabel label');
  5311. if (colprop.subtypes_select)
  5312. label.html(colprop.subtypes_select);
  5313. else
  5314. label.html('<label for="' + input_id + '">' + colprop.label + '</label>');
  5315. var name_suffix = colprop.limit != 1 ? '[]' : '';
  5316. if (colprop.type == 'text' || colprop.type == 'date') {
  5317. input = $('<input>')
  5318. .addClass('ff_'+col)
  5319. .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size, id: input_id})
  5320. .appendTo(cell);
  5321. this.init_edit_field(col, input);
  5322. if (colprop.type == 'date' && $.datepicker)
  5323. input.datepicker();
  5324. }
  5325. else if (colprop.type == 'textarea') {
  5326. input = $('<textarea>')
  5327. .addClass('ff_'+col)
  5328. .attr({ name: '_'+col+name_suffix, cols:colprop.size, rows:colprop.rows, id: input_id })
  5329. .appendTo(cell);
  5330. this.init_edit_field(col, input);
  5331. }
  5332. else if (colprop.type == 'composite') {
  5333. var i, childcol, cp, first, templ, cols = [], suffices = [];
  5334. // read template for composite field order
  5335. if ((templ = this.env[col+'_template'])) {
  5336. for (i=0; i < templ.length; i++) {
  5337. cols.push(templ[i][1]);
  5338. suffices.push(templ[i][2]);
  5339. }
  5340. }
  5341. else { // list fields according to appearance in colprop
  5342. for (childcol in colprop.childs)
  5343. cols.push(childcol);
  5344. }
  5345. for (i=0; i < cols.length; i++) {
  5346. childcol = cols[i];
  5347. cp = colprop.childs[childcol];
  5348. input = $('<input>')
  5349. .addClass('ff_'+childcol)
  5350. .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
  5351. .appendTo(cell);
  5352. cell.append(suffices[i] || " ");
  5353. this.init_edit_field(childcol, input);
  5354. if (!first) first = input;
  5355. }
  5356. input = first; // set focus to the first of this composite fields
  5357. }
  5358. else if (colprop.type == 'select') {
  5359. input = $('<select>')
  5360. .addClass('ff_'+col)
  5361. .attr({ 'name': '_'+col+name_suffix, id: input_id })
  5362. .appendTo(cell);
  5363. var options = input.attr('options');
  5364. options[options.length] = new Option('---', '');
  5365. if (colprop.options)
  5366. $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
  5367. }
  5368. if (input) {
  5369. var delbutton = $('<a href="#del"></a>')
  5370. .addClass('contactfieldbutton deletebutton')
  5371. .attr({title: this.get_label('delete'), rel: col})
  5372. .html(this.env.delbutton)
  5373. .click(function(){ ref.delete_edit_field(this); return false })
  5374. .appendTo(cell);
  5375. row.append(label).append(cell).appendTo(appendcontainer.show());
  5376. input.first().focus();
  5377. // disable option if limit reached
  5378. if (!colprop.count) colprop.count = 0;
  5379. if (++colprop.count == colprop.limit && colprop.limit)
  5380. $(menu).children('option[value="'+col+'"]').prop('disabled', true);
  5381. }
  5382. }
  5383. }
  5384. };
  5385. this.delete_edit_field = function(elem)
  5386. {
  5387. var col = $(elem).attr('rel'),
  5388. colprop = this.env.coltypes[col],
  5389. fieldset = $(elem).parents('fieldset.contactfieldgroup'),
  5390. addmenu = fieldset.parent().find('select.addfieldmenu');
  5391. // just clear input but don't hide the last field
  5392. if (--colprop.count <= 0 && colprop.visible)
  5393. $(elem).parent().children('input').val('').blur();
  5394. else {
  5395. $(elem).parents('div.row').remove();
  5396. // hide entire fieldset if no more rows
  5397. if (!fieldset.children('div.row').length)
  5398. fieldset.hide();
  5399. }
  5400. // enable option in add-field selector or insert it if necessary
  5401. if (addmenu.length) {
  5402. var option = addmenu.children('option[value="'+col+'"]');
  5403. if (option.length)
  5404. option.prop('disabled', false);
  5405. else
  5406. option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
  5407. addmenu.show();
  5408. }
  5409. };
  5410. this.upload_contact_photo = function(form)
  5411. {
  5412. if (form && form.elements._photo.value) {
  5413. this.async_upload_form(form, 'upload-photo', function(e) {
  5414. ref.set_busy(false, null, ref.file_upload_id);
  5415. });
  5416. // display upload indicator
  5417. this.file_upload_id = this.set_busy(true, 'uploading');
  5418. }
  5419. };
  5420. this.replace_contact_photo = function(id)
  5421. {
  5422. var img_src = id == '-del-' ? this.env.photo_placeholder :
  5423. this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + (this.env.cid || 0) + '&_photo=' + id;
  5424. this.set_photo_actions(id);
  5425. $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
  5426. };
  5427. this.photo_upload_end = function()
  5428. {
  5429. this.set_busy(false, null, this.file_upload_id);
  5430. delete this.file_upload_id;
  5431. };
  5432. this.set_photo_actions = function(id)
  5433. {
  5434. var n, buttons = this.buttons['upload-photo'];
  5435. for (n=0; buttons && n < buttons.length; n++)
  5436. $('a#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
  5437. $('#ff_photo').val(id);
  5438. this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
  5439. this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
  5440. };
  5441. // load advanced search page
  5442. this.advanced_search = function()
  5443. {
  5444. var win, url = {_form: 1, _action: 'search'}, target = window;
  5445. if (win = this.get_frame_window(this.env.contentframe)) {
  5446. url._framed = 1;
  5447. target = win;
  5448. this.contact_list.clear_selection();
  5449. }
  5450. this.location_href(url, target, true);
  5451. return true;
  5452. };
  5453. // unselect directory/group
  5454. this.unselect_directory = function()
  5455. {
  5456. this.select_folder('');
  5457. this.enable_command('search-delete', false);
  5458. };
  5459. // callback for creating a new saved search record
  5460. this.insert_saved_search = function(name, id)
  5461. {
  5462. var key = 'S'+id,
  5463. link = $('<a>').attr('href', '#')
  5464. .attr('rel', id)
  5465. .click(function() { return ref.command('listsearch', id, this); })
  5466. .html(name),
  5467. prop = { name:name, id:id };
  5468. this.savedsearchlist.insert({ id:key, html:link, classes:['contactsearch'] }, null, 'contactsearch');
  5469. this.select_folder(key,'',true);
  5470. this.enable_command('search-delete', true);
  5471. this.env.search_id = id;
  5472. this.triggerEvent('abook_search_insert', prop);
  5473. };
  5474. // creates a dialog for saved search
  5475. this.search_create = function()
  5476. {
  5477. var input = $('<input>').attr('type', 'text'),
  5478. content = $('<label>').text(this.get_label('namex')).append(input);
  5479. this.simple_dialog(content, 'searchsave',
  5480. function() {
  5481. var name;
  5482. if (name = input.val()) {
  5483. ref.http_post('search-create', {_search: ref.env.search_request, _name: name},
  5484. ref.set_busy(true, 'loading'));
  5485. return true;
  5486. }
  5487. }
  5488. );
  5489. };
  5490. this.search_delete = function()
  5491. {
  5492. if (this.env.search_request) {
  5493. var lock = this.set_busy(true, 'savedsearchdeleting');
  5494. this.http_post('search-delete', {_sid: this.env.search_id}, lock);
  5495. }
  5496. };
  5497. // callback from server upon search-delete command
  5498. this.remove_search_item = function(id)
  5499. {
  5500. var li, key = 'S'+id;
  5501. if (this.savedsearchlist.remove(key)) {
  5502. this.triggerEvent('search_delete', { id:id, li:li });
  5503. }
  5504. this.env.search_id = null;
  5505. this.env.search_request = null;
  5506. this.list_contacts_clear();
  5507. this.reset_qsearch();
  5508. this.enable_command('search-delete', 'search-create', false);
  5509. };
  5510. this.listsearch = function(id)
  5511. {
  5512. var lock = this.set_busy(true, 'searching');
  5513. if (this.contact_list) {
  5514. this.list_contacts_clear();
  5515. }
  5516. this.reset_qsearch();
  5517. if (this.savedsearchlist) {
  5518. this.treelist.select('');
  5519. this.savedsearchlist.select('S'+id);
  5520. }
  5521. else
  5522. this.select_folder('S'+id, '', true);
  5523. // reset vars
  5524. this.env.current_page = 1;
  5525. this.http_request('search', {_sid: id}, lock);
  5526. };
  5527. // display a dialog with QR code image
  5528. this.qrcode = function()
  5529. {
  5530. var title = this.get_label('qrcode'),
  5531. buttons = [{
  5532. text: this.get_label('close'),
  5533. 'class': 'mainaction',
  5534. click: function() {
  5535. (ref.is_framed() ? parent.$ : $)(this).dialog('destroy');
  5536. }
  5537. }],
  5538. img = new Image(300, 300);
  5539. img.src = this.url('addressbook/qrcode', {_source: this.env.source, _cid: this.env.cid});
  5540. return this.show_popup_dialog(img, title, buttons, {width: 310, height: 410});
  5541. };
  5542. /*********************************************************/
  5543. /********* user settings methods *********/
  5544. /*********************************************************/
  5545. // preferences section select and load options frame
  5546. this.section_select = function(list)
  5547. {
  5548. var win, id = list.get_single_selection(), target = window,
  5549. url = {_action: 'edit-prefs', _section: id};
  5550. if (id) {
  5551. if (win = this.get_frame_window(this.env.contentframe)) {
  5552. url._framed = 1;
  5553. target = win;
  5554. }
  5555. this.location_href(url, target, true);
  5556. }
  5557. return true;
  5558. };
  5559. this.identity_select = function(list)
  5560. {
  5561. var id;
  5562. if (id = list.get_single_selection()) {
  5563. this.enable_command('delete', list.rowcount > 1 && this.env.identities_level < 2);
  5564. this.load_identity(id, 'edit-identity');
  5565. }
  5566. };
  5567. // load identity record
  5568. this.load_identity = function(id, action)
  5569. {
  5570. if (action == 'edit-identity' && (!id || id == this.env.iid))
  5571. return false;
  5572. var win, target = window,
  5573. url = {_action: action, _iid: id};
  5574. if (win = this.get_frame_window(this.env.contentframe)) {
  5575. url._framed = 1;
  5576. target = win;
  5577. }
  5578. if (id || action == 'add-identity') {
  5579. this.location_href(url, target, true);
  5580. }
  5581. return true;
  5582. };
  5583. this.delete_identity = function(id)
  5584. {
  5585. // exit if no identity is specified or if selection is empty
  5586. var selection = this.identity_list.get_selection();
  5587. if (!(selection.length || this.env.iid))
  5588. return;
  5589. if (!id)
  5590. id = this.env.iid ? this.env.iid : selection[0];
  5591. // submit request with appended token
  5592. if (id && confirm(this.get_label('deleteidentityconfirm')))
  5593. this.http_post('settings/delete-identity', { _iid: id }, true);
  5594. };
  5595. this.update_identity_row = function(id, name, add)
  5596. {
  5597. var list = this.identity_list,
  5598. rid = this.html_identifier(id);
  5599. if (add) {
  5600. list.insert_row({ id:'rcmrow'+rid, cols:[ { className:'mail', innerHTML:name } ] });
  5601. list.select(rid);
  5602. }
  5603. else {
  5604. list.update_row(rid, [ name ]);
  5605. }
  5606. };
  5607. this.update_response_row = function(response, oldkey)
  5608. {
  5609. var list = this.responses_list;
  5610. if (list && oldkey) {
  5611. list.update_row(oldkey, [ response.name ], response.key, true);
  5612. }
  5613. else if (list) {
  5614. list.insert_row({ id:'rcmrow'+response.key, cols:[ { className:'name', innerHTML:response.name } ] });
  5615. list.select(response.key);
  5616. }
  5617. };
  5618. this.remove_response = function(key)
  5619. {
  5620. var frame;
  5621. if (this.env.textresponses) {
  5622. delete this.env.textresponses[key];
  5623. }
  5624. if (this.responses_list) {
  5625. this.responses_list.remove_row(key);
  5626. if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
  5627. frame.location.href = this.env.blankpage;
  5628. }
  5629. }
  5630. this.enable_command('delete', false);
  5631. };
  5632. this.remove_identity = function(id)
  5633. {
  5634. var frame, list = this.identity_list,
  5635. rid = this.html_identifier(id);
  5636. if (list && id) {
  5637. list.remove_row(rid);
  5638. if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
  5639. frame.location.href = this.env.blankpage;
  5640. }
  5641. }
  5642. this.enable_command('delete', false);
  5643. };
  5644. /*********************************************************/
  5645. /********* folder manager methods *********/
  5646. /*********************************************************/
  5647. this.init_subscription_list = function()
  5648. {
  5649. var delim = RegExp.escape(this.env.delimiter);
  5650. this.last_sub_rx = RegExp('['+delim+']?[^'+delim+']+$');
  5651. this.subscription_list = new rcube_treelist_widget(this.gui_objects.subscriptionlist, {
  5652. selectable: true,
  5653. tabexit: false,
  5654. parent_focus: true,
  5655. id_prefix: 'rcmli',
  5656. id_encode: this.html_identifier_encode,
  5657. id_decode: this.html_identifier_decode,
  5658. searchbox: '#foldersearch'
  5659. });
  5660. this.subscription_list
  5661. .addEventListener('select', function(node) { ref.subscription_select(node.id); })
  5662. .addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
  5663. .addEventListener('expand', function(node) { ref.folder_collapsed(node) })
  5664. .addEventListener('search', function(p) { if (p.query) ref.subscription_select(); })
  5665. .draggable({cancel: 'li.mailbox.root'})
  5666. .droppable({
  5667. // @todo: find better way, accept callback is executed for every folder
  5668. // on the list when dragging starts (and stops), this is slow, but
  5669. // I didn't find a method to check droptarget on over event
  5670. accept: function(node) {
  5671. if (!$(node).is('.mailbox'))
  5672. return false;
  5673. var source_folder = ref.folder_id2name($(node).attr('id')),
  5674. dest_folder = ref.folder_id2name(this.id),
  5675. source = ref.env.subscriptionrows[source_folder],
  5676. dest = ref.env.subscriptionrows[dest_folder];
  5677. return source && !source[2]
  5678. && dest_folder != source_folder.replace(ref.last_sub_rx, '')
  5679. && !dest_folder.startsWith(source_folder + ref.env.delimiter);
  5680. },
  5681. drop: function(e, ui) {
  5682. var source = ref.folder_id2name(ui.draggable.attr('id')),
  5683. dest = ref.folder_id2name(this.id);
  5684. ref.subscription_move_folder(source, dest);
  5685. }
  5686. });
  5687. };
  5688. this.folder_id2name = function(id)
  5689. {
  5690. return id ? ref.html_identifier_decode(id.replace(/^rcmli/, '')) : null;
  5691. };
  5692. this.subscription_select = function(id)
  5693. {
  5694. var folder;
  5695. if (id && id != '*' && (folder = this.env.subscriptionrows[id])) {
  5696. this.env.mailbox = id;
  5697. this.show_folder(id);
  5698. this.enable_command('delete-folder', !folder[2]);
  5699. }
  5700. else {
  5701. this.env.mailbox = null;
  5702. this.show_contentframe(false);
  5703. this.enable_command('delete-folder', 'purge', false);
  5704. }
  5705. };
  5706. this.subscription_move_folder = function(from, to)
  5707. {
  5708. if (from && to !== null && from != to && to != from.replace(this.last_sub_rx, '')) {
  5709. var path = from.split(this.env.delimiter),
  5710. basename = path.pop(),
  5711. newname = to === '' || to === '*' ? basename : to + this.env.delimiter + basename;
  5712. if (newname != from) {
  5713. this.http_post('rename-folder', {_folder_oldname: from, _folder_newname: newname},
  5714. this.set_busy(true, 'foldermoving'));
  5715. }
  5716. }
  5717. };
  5718. // tell server to create and subscribe a new mailbox
  5719. this.create_folder = function()
  5720. {
  5721. this.show_folder('', this.env.mailbox);
  5722. };
  5723. // delete a specific mailbox with all its messages
  5724. this.delete_folder = function(name)
  5725. {
  5726. if (!name)
  5727. name = this.env.mailbox;
  5728. if (name && confirm(this.get_label('deletefolderconfirm'))) {
  5729. this.http_post('delete-folder', {_mbox: name}, this.set_busy(true, 'folderdeleting'));
  5730. }
  5731. };
  5732. // Add folder row to the table and initialize it
  5733. this.add_folder_row = function (id, name, display_name, is_protected, subscribed, class_name, refrow, subfolders)
  5734. {
  5735. if (!this.gui_objects.subscriptionlist)
  5736. return false;
  5737. // reset searching
  5738. if (this.subscription_list.is_search()) {
  5739. this.subscription_select();
  5740. this.subscription_list.reset_search();
  5741. }
  5742. // disable drag-n-drop temporarily
  5743. this.subscription_list.draggable('destroy').droppable('destroy');
  5744. var row, n, tmp, tmp_name, rowid, collator, pos, p, parent = '',
  5745. folders = [], list = [], slist = [],
  5746. list_element = $(this.gui_objects.subscriptionlist);
  5747. row = refrow ? refrow : $($('li', list_element).get(1)).clone(true);
  5748. if (!row.length) {
  5749. // Refresh page if we don't have a table row to clone
  5750. this.goto_url('folders');
  5751. return false;
  5752. }
  5753. // set ID, reset css class
  5754. row.attr({id: 'rcmli' + this.html_identifier_encode(id), 'class': class_name});
  5755. if (!refrow || !refrow.length) {
  5756. // remove old data, subfolders and toggle
  5757. $('ul,div.treetoggle', row).remove();
  5758. row.removeData('filtered');
  5759. }
  5760. // set folder name
  5761. $('a:first', row).text(display_name);
  5762. // update subscription checkbox
  5763. $('input[name="_subscribed[]"]:first', row).val(id)
  5764. .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
  5765. // add to folder/row-ID map
  5766. this.env.subscriptionrows[id] = [name, display_name, false];
  5767. // copy folders data to an array for sorting
  5768. $.each(this.env.subscriptionrows, function(k, v) { v[3] = k; folders.push(v); });
  5769. try {
  5770. // use collator if supported (FF29, IE11, Opera15, Chrome24)
  5771. collator = new Intl.Collator(this.env.locale.replace('_', '-'));
  5772. }
  5773. catch (e) {};
  5774. // sort folders
  5775. folders.sort(function(a, b) {
  5776. var i, f1, f2,
  5777. path1 = a[0].split(ref.env.delimiter),
  5778. path2 = b[0].split(ref.env.delimiter),
  5779. len = path1.length;
  5780. for (i=0; i<len; i++) {
  5781. f1 = path1[i];
  5782. f2 = path2[i];
  5783. if (f1 !== f2) {
  5784. if (f2 === undefined)
  5785. return 1;
  5786. if (collator)
  5787. return collator.compare(f1, f2);
  5788. else
  5789. return f1 < f2 ? -1 : 1;
  5790. }
  5791. else if (i == len-1) {
  5792. return -1
  5793. }
  5794. }
  5795. });
  5796. for (n in folders) {
  5797. p = folders[n][3];
  5798. // protected folder
  5799. if (folders[n][2]) {
  5800. tmp_name = p + this.env.delimiter;
  5801. // prefix namespace cannot have subfolders (#1488349)
  5802. if (tmp_name == this.env.prefix_ns)
  5803. continue;
  5804. slist.push(p);
  5805. tmp = tmp_name;
  5806. }
  5807. // protected folder's child
  5808. else if (tmp && p.startsWith(tmp))
  5809. slist.push(p);
  5810. // other
  5811. else {
  5812. list.push(p);
  5813. tmp = null;
  5814. }
  5815. }
  5816. // check if subfolder of a protected folder
  5817. for (n=0; n<slist.length; n++) {
  5818. if (id.startsWith(slist[n] + this.env.delimiter))
  5819. rowid = slist[n];
  5820. }
  5821. // find folder position after sorting
  5822. for (n=0; !rowid && n<list.length; n++) {
  5823. if (n && list[n] == id)
  5824. rowid = list[n-1];
  5825. }
  5826. // add row to the table
  5827. if (rowid && (n = this.subscription_list.get_item(rowid, true))) {
  5828. // find parent folder
  5829. if (pos = id.lastIndexOf(this.env.delimiter)) {
  5830. parent = id.substring(0, pos);
  5831. parent = this.subscription_list.get_item(parent, true);
  5832. // add required tree elements to the parent if not already there
  5833. if (!$('div.treetoggle', parent).length) {
  5834. $('<div>&nbsp;</div>').addClass('treetoggle collapsed').appendTo(parent);
  5835. }
  5836. if (!$('ul', parent).length) {
  5837. $('<ul>').css('display', 'none').appendTo(parent);
  5838. }
  5839. }
  5840. if (parent && n == parent) {
  5841. $('ul:first', parent).append(row);
  5842. }
  5843. else {
  5844. while (p = $(n).parent().parent().get(0)) {
  5845. if (parent && p == parent)
  5846. break;
  5847. if (!$(p).is('li.mailbox'))
  5848. break;
  5849. n = p;
  5850. }
  5851. $(n).after(row);
  5852. }
  5853. }
  5854. else {
  5855. list_element.append(row);
  5856. }
  5857. // add subfolders
  5858. $.extend(this.env.subscriptionrows, subfolders || {});
  5859. // update list widget
  5860. this.subscription_list.reset(true);
  5861. this.subscription_select();
  5862. // expand parent
  5863. if (parent) {
  5864. this.subscription_list.expand(this.folder_id2name(parent.id));
  5865. }
  5866. row = row.show().get(0);
  5867. if (row.scrollIntoView)
  5868. row.scrollIntoView();
  5869. return row;
  5870. };
  5871. // replace an existing table row with a new folder line (with subfolders)
  5872. this.replace_folder_row = function(oldid, id, name, display_name, is_protected, class_name)
  5873. {
  5874. if (!this.gui_objects.subscriptionlist) {
  5875. if (this.is_framed()) {
  5876. // @FIXME: for some reason this 'parent' variable need to be prefixed with 'window.'
  5877. return window.parent.rcmail.replace_folder_row(oldid, id, name, display_name, is_protected, class_name);
  5878. }
  5879. return false;
  5880. }
  5881. // reset searching
  5882. if (this.subscription_list.is_search()) {
  5883. this.subscription_select();
  5884. this.subscription_list.reset_search();
  5885. }
  5886. var subfolders = {},
  5887. row = this.subscription_list.get_item(oldid, true),
  5888. parent = $(row).parent(),
  5889. old_folder = this.env.subscriptionrows[oldid],
  5890. prefix_len_id = oldid.length,
  5891. prefix_len_name = old_folder[0].length,
  5892. subscribed = $('input[name="_subscribed[]"]:first', row).prop('checked');
  5893. // no renaming, only update class_name
  5894. if (oldid == id) {
  5895. $(row).attr('class', class_name || '');
  5896. return;
  5897. }
  5898. // update subfolders
  5899. $('li', row).each(function() {
  5900. var fname = ref.folder_id2name(this.id),
  5901. folder = ref.env.subscriptionrows[fname],
  5902. newid = id + fname.slice(prefix_len_id);
  5903. this.id = 'rcmli' + ref.html_identifier_encode(newid);
  5904. $('input[name="_subscribed[]"]:first', this).val(newid);
  5905. folder[0] = name + folder[0].slice(prefix_len_name);
  5906. subfolders[newid] = folder;
  5907. delete ref.env.subscriptionrows[fname];
  5908. });
  5909. // get row off the list
  5910. row = $(row).detach();
  5911. delete this.env.subscriptionrows[oldid];
  5912. // remove parent list/toggle elements if not needed
  5913. if (parent.get(0) != this.gui_objects.subscriptionlist && !$('li', parent).length) {
  5914. $('ul,div.treetoggle', parent.parent()).remove();
  5915. }
  5916. // move the existing table row
  5917. this.add_folder_row(id, name, display_name, is_protected, subscribed, class_name, row, subfolders);
  5918. };
  5919. // remove the table row of a specific mailbox from the table
  5920. this.remove_folder_row = function(folder)
  5921. {
  5922. // reset searching
  5923. if (this.subscription_list.is_search()) {
  5924. this.subscription_select();
  5925. this.subscription_list.reset_search();
  5926. }
  5927. var list = [], row = this.subscription_list.get_item(folder, true);
  5928. // get subfolders if any
  5929. $('li', row).each(function() { list.push(ref.folder_id2name(this.id)); });
  5930. // remove folder row (and subfolders)
  5931. this.subscription_list.remove(folder);
  5932. // update local list variable
  5933. list.push(folder);
  5934. $.each(list, function(i, v) { delete ref.env.subscriptionrows[v]; });
  5935. };
  5936. this.subscribe = function(folder)
  5937. {
  5938. if (folder) {
  5939. var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
  5940. this.http_post('subscribe', {_mbox: folder}, lock);
  5941. }
  5942. };
  5943. this.unsubscribe = function(folder)
  5944. {
  5945. if (folder) {
  5946. var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
  5947. this.http_post('unsubscribe', {_mbox: folder}, lock);
  5948. }
  5949. };
  5950. // when user select a folder in manager
  5951. this.show_folder = function(folder, path, force)
  5952. {
  5953. var win, target = window,
  5954. url = '&_action=edit-folder&_mbox='+urlencode(folder);
  5955. if (path)
  5956. url += '&_path='+urlencode(path);
  5957. if (win = this.get_frame_window(this.env.contentframe)) {
  5958. target = win;
  5959. url += '&_framed=1';
  5960. }
  5961. if (String(target.location.href).indexOf(url) >= 0 && !force)
  5962. this.show_contentframe(true);
  5963. else
  5964. this.location_href(this.env.comm_path+url, target, true);
  5965. };
  5966. // disables subscription checkbox (for protected folder)
  5967. this.disable_subscription = function(folder)
  5968. {
  5969. var row = this.subscription_list.get_item(folder, true);
  5970. if (row)
  5971. $('input[name="_subscribed[]"]:first', row).prop('disabled', true);
  5972. };
  5973. // resets state of subscription checkbox (e.g. on error)
  5974. this.reset_subscription = function(folder, state)
  5975. {
  5976. var row = this.subscription_list.get_item(folder, true);
  5977. if (row)
  5978. $('input[name="_subscribed[]"]:first', row).prop('checked', state);
  5979. };
  5980. this.folder_size = function(folder)
  5981. {
  5982. var lock = this.set_busy(true, 'loading');
  5983. this.http_post('folder-size', {_mbox: folder}, lock);
  5984. };
  5985. this.folder_size_update = function(size)
  5986. {
  5987. $('#folder-size').replaceWith(size);
  5988. };
  5989. // filter folders by namespace
  5990. this.folder_filter = function(prefix)
  5991. {
  5992. this.subscription_list.reset_search();
  5993. this.subscription_list.container.children('li').each(function() {
  5994. var i, folder = ref.folder_id2name(this.id);
  5995. // show all folders
  5996. if (prefix == '---') {
  5997. }
  5998. // got namespace prefix
  5999. else if (prefix) {
  6000. if (folder !== prefix) {
  6001. $(this).data('filtered', true).hide();
  6002. return
  6003. }
  6004. }
  6005. // no namespace prefix, filter out all other namespaces
  6006. else {
  6007. // first get all namespace roots
  6008. for (i in ref.env.ns_roots) {
  6009. if (folder === ref.env.ns_roots[i]) {
  6010. $(this).data('filtered', true).hide();
  6011. return;
  6012. }
  6013. }
  6014. }
  6015. $(this).removeData('filtered').show();
  6016. });
  6017. };
  6018. /*********************************************************/
  6019. /********* GUI functionality *********/
  6020. /*********************************************************/
  6021. var init_button = function(cmd, prop)
  6022. {
  6023. var elm = document.getElementById(prop.id);
  6024. if (!elm)
  6025. return;
  6026. var preload = false;
  6027. if (prop.type == 'image') {
  6028. elm = elm.parentNode;
  6029. preload = true;
  6030. }
  6031. elm._command = cmd;
  6032. elm._id = prop.id;
  6033. if (prop.sel) {
  6034. elm.onmousedown = function(e) { return ref.button_sel(this._command, this._id); };
  6035. elm.onmouseup = function(e) { return ref.button_out(this._command, this._id); };
  6036. if (preload)
  6037. new Image().src = prop.sel;
  6038. }
  6039. if (prop.over) {
  6040. elm.onmouseover = function(e) { return ref.button_over(this._command, this._id); };
  6041. elm.onmouseout = function(e) { return ref.button_out(this._command, this._id); };
  6042. if (preload)
  6043. new Image().src = prop.over;
  6044. }
  6045. };
  6046. // set event handlers on registered buttons
  6047. this.init_buttons = function()
  6048. {
  6049. for (var cmd in this.buttons) {
  6050. if (typeof cmd !== 'string')
  6051. continue;
  6052. for (var i=0; i<this.buttons[cmd].length; i++) {
  6053. init_button(cmd, this.buttons[cmd][i]);
  6054. }
  6055. }
  6056. };
  6057. // set button to a specific state
  6058. this.set_button = function(command, state)
  6059. {
  6060. var n, button, obj, $obj, a_buttons = this.buttons[command],
  6061. len = a_buttons ? a_buttons.length : 0;
  6062. for (n=0; n<len; n++) {
  6063. button = a_buttons[n];
  6064. obj = document.getElementById(button.id);
  6065. if (!obj || button.status === state)
  6066. continue;
  6067. // get default/passive setting of the button
  6068. if (button.type == 'image' && !button.status) {
  6069. button.pas = obj._original_src ? obj._original_src : obj.src;
  6070. // respect PNG fix on IE browsers
  6071. if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
  6072. button.pas = RegExp.$1;
  6073. }
  6074. else if (!button.status)
  6075. button.pas = String(obj.className);
  6076. button.status = state;
  6077. // set image according to button state
  6078. if (button.type == 'image' && button[state]) {
  6079. obj.src = button[state];
  6080. }
  6081. // set class name according to button state
  6082. else if (button[state] !== undefined) {
  6083. obj.className = button[state];
  6084. }
  6085. // disable/enable input buttons
  6086. if (button.type == 'input') {
  6087. obj.disabled = state == 'pas';
  6088. }
  6089. else if (button.type == 'uibutton') {
  6090. button.status = state;
  6091. $(obj).button('option', 'disabled', state == 'pas');
  6092. }
  6093. else {
  6094. $obj = $(obj);
  6095. $obj
  6096. .attr('tabindex', state == 'pas' || state == 'sel' ? '-1' : ($obj.attr('data-tabindex') || '0'))
  6097. .attr('aria-disabled', state == 'pas' || state == 'sel' ? 'true' : 'false');
  6098. }
  6099. }
  6100. };
  6101. // display a specific alttext
  6102. this.set_alttext = function(command, label)
  6103. {
  6104. var n, button, obj, link, a_buttons = this.buttons[command],
  6105. len = a_buttons ? a_buttons.length : 0;
  6106. for (n=0; n<len; n++) {
  6107. button = a_buttons[n];
  6108. obj = document.getElementById(button.id);
  6109. if (button.type == 'image' && obj) {
  6110. obj.setAttribute('alt', this.get_label(label));
  6111. if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
  6112. link.setAttribute('title', this.get_label(label));
  6113. }
  6114. else if (obj)
  6115. obj.setAttribute('title', this.get_label(label));
  6116. }
  6117. };
  6118. // mouse over button
  6119. this.button_over = function(command, id)
  6120. {
  6121. this.button_event(command, id, 'over');
  6122. };
  6123. // mouse down on button
  6124. this.button_sel = function(command, id)
  6125. {
  6126. this.button_event(command, id, 'sel');
  6127. };
  6128. // mouse out of button
  6129. this.button_out = function(command, id)
  6130. {
  6131. this.button_event(command, id, 'act');
  6132. };
  6133. // event of button
  6134. this.button_event = function(command, id, event)
  6135. {
  6136. var n, button, obj, a_buttons = this.buttons[command],
  6137. len = a_buttons ? a_buttons.length : 0;
  6138. for (n=0; n<len; n++) {
  6139. button = a_buttons[n];
  6140. if (button.id == id && button.status == 'act') {
  6141. if (button[event] && (obj = document.getElementById(button.id))) {
  6142. obj[button.type == 'image' ? 'src' : 'className'] = button[event];
  6143. }
  6144. if (event == 'sel') {
  6145. this.buttons_sel[id] = command;
  6146. }
  6147. }
  6148. }
  6149. };
  6150. // write to the document/window title
  6151. this.set_pagetitle = function(title)
  6152. {
  6153. if (title && document.title)
  6154. document.title = title;
  6155. };
  6156. // display a system message, list of types in common.css (below #message definition)
  6157. this.display_message = function(msg, type, timeout, key)
  6158. {
  6159. // pass command to parent window
  6160. if (this.is_framed())
  6161. return parent.rcmail.display_message(msg, type, timeout);
  6162. if (!this.gui_objects.message) {
  6163. // save message in order to display after page loaded
  6164. if (type != 'loading')
  6165. this.pending_message = [msg, type, timeout, key];
  6166. return 1;
  6167. }
  6168. if (!type)
  6169. type = 'notice';
  6170. if (!key)
  6171. key = this.html_identifier(msg);
  6172. var date = new Date(),
  6173. id = type + date.getTime();
  6174. if (!timeout) {
  6175. switch (type) {
  6176. case 'error':
  6177. case 'warning':
  6178. timeout = this.message_time * 2;
  6179. break;
  6180. case 'uploading':
  6181. timeout = 0;
  6182. break;
  6183. default:
  6184. timeout = this.message_time;
  6185. }
  6186. }
  6187. if (type == 'loading') {
  6188. key = 'loading';
  6189. timeout = this.env.request_timeout * 1000;
  6190. if (!msg)
  6191. msg = this.get_label('loading');
  6192. }
  6193. // The same message is already displayed
  6194. if (this.messages[key]) {
  6195. // replace label
  6196. if (this.messages[key].obj)
  6197. this.messages[key].obj.html(msg);
  6198. // store label in stack
  6199. if (type == 'loading') {
  6200. this.messages[key].labels.push({'id': id, 'msg': msg});
  6201. }
  6202. // add element and set timeout
  6203. this.messages[key].elements.push(id);
  6204. setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
  6205. return id;
  6206. }
  6207. // create DOM object and display it
  6208. var obj = $('<div>').addClass(type).html(msg).data('key', key),
  6209. cont = $(this.gui_objects.message).append(obj).show();
  6210. this.messages[key] = {'obj': obj, 'elements': [id]};
  6211. if (type == 'loading') {
  6212. this.messages[key].labels = [{'id': id, 'msg': msg}];
  6213. }
  6214. else if (type != 'uploading') {
  6215. obj.click(function() { return ref.hide_message(obj); })
  6216. .attr('role', 'alert');
  6217. }
  6218. this.triggerEvent('message', { message:msg, type:type, timeout:timeout, object:obj });
  6219. if (timeout > 0)
  6220. setTimeout(function() { ref.hide_message(id, type != 'loading'); }, timeout);
  6221. return id;
  6222. };
  6223. // make a message to disapear
  6224. this.hide_message = function(obj, fade)
  6225. {
  6226. // pass command to parent window
  6227. if (this.is_framed())
  6228. return parent.rcmail.hide_message(obj, fade);
  6229. if (!this.gui_objects.message)
  6230. return;
  6231. var k, n, i, o, m = this.messages;
  6232. // Hide message by object, don't use for 'loading'!
  6233. if (typeof obj === 'object') {
  6234. o = $(obj);
  6235. k = o.data('key');
  6236. this.hide_message_object(o, fade);
  6237. if (m[k])
  6238. delete m[k];
  6239. }
  6240. // Hide message by id
  6241. else {
  6242. for (k in m) {
  6243. for (n in m[k].elements) {
  6244. if (m[k] && m[k].elements[n] == obj) {
  6245. m[k].elements.splice(n, 1);
  6246. // hide DOM element if last instance is removed
  6247. if (!m[k].elements.length) {
  6248. this.hide_message_object(m[k].obj, fade);
  6249. delete m[k];
  6250. }
  6251. // set pending action label for 'loading' message
  6252. else if (k == 'loading') {
  6253. for (i in m[k].labels) {
  6254. if (m[k].labels[i].id == obj) {
  6255. delete m[k].labels[i];
  6256. }
  6257. else {
  6258. o = m[k].labels[i].msg;
  6259. m[k].obj.html(o);
  6260. }
  6261. }
  6262. }
  6263. }
  6264. }
  6265. }
  6266. }
  6267. };
  6268. // hide message object and remove from the DOM
  6269. this.hide_message_object = function(o, fade)
  6270. {
  6271. if (fade)
  6272. o.fadeOut(600, function() {$(this).remove(); });
  6273. else
  6274. o.hide().remove();
  6275. };
  6276. // remove all messages immediately
  6277. this.clear_messages = function()
  6278. {
  6279. // pass command to parent window
  6280. if (this.is_framed())
  6281. return parent.rcmail.clear_messages();
  6282. var k, n, m = this.messages;
  6283. for (k in m)
  6284. for (n in m[k].elements)
  6285. if (m[k].obj)
  6286. this.hide_message_object(m[k].obj);
  6287. this.messages = {};
  6288. };
  6289. // display uploading message with progress indicator
  6290. // data should contain: name, total, current, percent, text
  6291. this.display_progress = function(data)
  6292. {
  6293. if (!data || !data.name)
  6294. return;
  6295. var msg = this.messages['progress' + data.name];
  6296. if (!data.label)
  6297. data.label = this.get_label('uploadingmany');
  6298. if (!msg) {
  6299. if (!data.percent || data.percent < 100)
  6300. this.display_message(data.label, 'uploading', 0, 'progress' + data.name);
  6301. return;
  6302. }
  6303. if (!data.total || data.percent >= 100) {
  6304. this.hide_message(msg.obj);
  6305. return;
  6306. }
  6307. if (data.text)
  6308. data.label += ' ' + data.text;
  6309. msg.obj.text(data.label);
  6310. };
  6311. // open a jquery UI dialog with the given content
  6312. this.show_popup_dialog = function(content, title, buttons, options)
  6313. {
  6314. // forward call to parent window
  6315. if (this.is_framed()) {
  6316. return parent.rcmail.show_popup_dialog(content, title, buttons, options);
  6317. }
  6318. var popup = $('<div class="popup">');
  6319. if (typeof content == 'object')
  6320. popup.append(content);
  6321. else
  6322. popup.html(content);
  6323. options = $.extend({
  6324. title: title,
  6325. buttons: buttons,
  6326. modal: true,
  6327. resizable: true,
  6328. width: 500,
  6329. close: function(event, ui) { $(this).remove(); }
  6330. }, options || {});
  6331. popup.dialog(options);
  6332. // resize and center popup
  6333. var win = $(window), w = win.width(), h = win.height(),
  6334. width = popup.width(), height = popup.height();
  6335. popup.dialog('option', {
  6336. height: Math.min(h - 40, height + 75 + (buttons ? 50 : 0)),
  6337. width: Math.min(w - 20, width + 36)
  6338. });
  6339. // assign special classes to dialog buttons
  6340. $.each(options.button_classes || [], function(i, v) {
  6341. if (v) $($('.ui-dialog-buttonpane button.ui-button', popup.parent()).get(i)).addClass(v);
  6342. });
  6343. return popup;
  6344. };
  6345. // show_popup_dialog() wrapper for simple dialogs with Save and Cancel buttons
  6346. this.simple_dialog = function(content, title, button_func, options)
  6347. {
  6348. var title = this.get_label(title),
  6349. buttons = [{
  6350. text: this.get_label((options || {}).button || 'save'),
  6351. 'class': 'mainaction',
  6352. click: function() {
  6353. if (button_func())
  6354. $(this).dialog('close');
  6355. }
  6356. },
  6357. {
  6358. text: ref.get_label('cancel'),
  6359. click: function() {
  6360. $(this).dialog('close');
  6361. }
  6362. }];
  6363. return this.show_popup_dialog(content, title, buttons, options);
  6364. };
  6365. // enable/disable buttons for page shifting
  6366. this.set_page_buttons = function()
  6367. {
  6368. this.enable_command('nextpage', 'lastpage', this.env.pagecount > this.env.current_page);
  6369. this.enable_command('previouspage', 'firstpage', this.env.current_page > 1);
  6370. this.update_pagejumper();
  6371. };
  6372. // mark a mailbox as selected and set environment variable
  6373. this.select_folder = function(name, prefix, encode)
  6374. {
  6375. if (this.savedsearchlist) {
  6376. this.savedsearchlist.select('');
  6377. }
  6378. if (this.treelist) {
  6379. this.treelist.select(name);
  6380. }
  6381. else if (this.gui_objects.folderlist) {
  6382. $('li.selected', this.gui_objects.folderlist).removeClass('selected');
  6383. $(this.get_folder_li(name, prefix, encode)).addClass('selected');
  6384. // trigger event hook
  6385. this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
  6386. }
  6387. };
  6388. // adds a class to selected folder
  6389. this.mark_folder = function(name, class_name, prefix, encode)
  6390. {
  6391. $(this.get_folder_li(name, prefix, encode)).addClass(class_name);
  6392. this.triggerEvent('markfolder', {folder: name, mark: class_name, status: true});
  6393. };
  6394. // adds a class to selected folder
  6395. this.unmark_folder = function(name, class_name, prefix, encode)
  6396. {
  6397. $(this.get_folder_li(name, prefix, encode)).removeClass(class_name);
  6398. this.triggerEvent('markfolder', {folder: name, mark: class_name, status: false});
  6399. };
  6400. // helper method to find a folder list item
  6401. this.get_folder_li = function(name, prefix, encode)
  6402. {
  6403. if (!prefix)
  6404. prefix = 'rcmli';
  6405. if (this.gui_objects.folderlist) {
  6406. name = this.html_identifier(name, encode);
  6407. return document.getElementById(prefix+name);
  6408. }
  6409. };
  6410. // for reordering column array (Konqueror workaround)
  6411. // and for setting some message list global variables
  6412. this.set_message_coltypes = function(listcols, repl, smart_col)
  6413. {
  6414. var list = this.message_list,
  6415. thead = list ? list.thead : null,
  6416. repl, cell, col, n, len, tr;
  6417. this.env.listcols = listcols;
  6418. if (!this.env.coltypes)
  6419. this.env.coltypes = {};
  6420. // replace old column headers
  6421. if (thead) {
  6422. if (repl) {
  6423. thead.innerHTML = '';
  6424. tr = document.createElement('tr');
  6425. for (c=0, len=repl.length; c < len; c++) {
  6426. cell = document.createElement('th');
  6427. cell.innerHTML = repl[c].html || '';
  6428. if (repl[c].id) cell.id = repl[c].id;
  6429. if (repl[c].className) cell.className = repl[c].className;
  6430. tr.appendChild(cell);
  6431. }
  6432. thead.appendChild(tr);
  6433. }
  6434. for (n=0, len=this.env.listcols.length; n<len; n++) {
  6435. col = this.env.listcols[n];
  6436. if ((cell = thead.rows[0].cells[n]) && (col == 'from' || col == 'to' || col == 'fromto')) {
  6437. $(cell).attr('rel', col).find('span,a').text(this.get_label(col == 'fromto' ? smart_col : col));
  6438. }
  6439. }
  6440. }
  6441. this.env.subject_col = null;
  6442. this.env.flagged_col = null;
  6443. this.env.status_col = null;
  6444. if (this.env.coltypes.folder)
  6445. this.env.coltypes.folder.hidden = !(this.env.search_request || this.env.search_id) || this.env.search_scope == 'base';
  6446. if ((n = $.inArray('subject', this.env.listcols)) >= 0) {
  6447. this.env.subject_col = n;
  6448. if (list)
  6449. list.subject_col = n;
  6450. }
  6451. if ((n = $.inArray('flag', this.env.listcols)) >= 0)
  6452. this.env.flagged_col = n;
  6453. if ((n = $.inArray('status', this.env.listcols)) >= 0)
  6454. this.env.status_col = n;
  6455. if (list) {
  6456. list.hide_column('folder', (this.env.coltypes.folder && this.env.coltypes.folder.hidden) || $.inArray('folder', this.env.listcols) < 0);
  6457. list.init_header();
  6458. }
  6459. };
  6460. // replace content of row count display
  6461. this.set_rowcount = function(text, mbox)
  6462. {
  6463. // #1487752
  6464. if (mbox && mbox != this.env.mailbox)
  6465. return false;
  6466. $(this.gui_objects.countdisplay).html(text);
  6467. // update page navigation buttons
  6468. this.set_page_buttons();
  6469. };
  6470. // replace content of mailboxname display
  6471. this.set_mailboxname = function(content)
  6472. {
  6473. if (this.gui_objects.mailboxname && content)
  6474. this.gui_objects.mailboxname.innerHTML = content;
  6475. };
  6476. // replace content of quota display
  6477. this.set_quota = function(content)
  6478. {
  6479. if (this.gui_objects.quotadisplay && content && content.type == 'text')
  6480. $(this.gui_objects.quotadisplay).text((content.percent||0) + '%').attr('title', content.title);
  6481. this.triggerEvent('setquota', content);
  6482. this.env.quota_content = content;
  6483. };
  6484. // update trash folder state
  6485. this.set_trash_count = function(count)
  6486. {
  6487. this[(count ? 'un' : '') + 'mark_folder'](this.env.trash_mailbox, 'empty', '', true);
  6488. };
  6489. // update the mailboxlist
  6490. this.set_unread_count = function(mbox, count, set_title, mark)
  6491. {
  6492. if (!this.gui_objects.mailboxlist)
  6493. return false;
  6494. this.env.unread_counts[mbox] = count;
  6495. this.set_unread_count_display(mbox, set_title);
  6496. if (mark)
  6497. this.mark_folder(mbox, mark, '', true);
  6498. else if (!count)
  6499. this.unmark_folder(mbox, 'recent', '', true);
  6500. this.mark_all_read_state();
  6501. };
  6502. // update the mailbox count display
  6503. this.set_unread_count_display = function(mbox, set_title)
  6504. {
  6505. var reg, link, text_obj, item, mycount, childcount, div;
  6506. if (item = this.get_folder_li(mbox, '', true)) {
  6507. mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
  6508. link = $(item).children('a').eq(0);
  6509. text_obj = link.children('span.unreadcount');
  6510. if (!text_obj.length && mycount)
  6511. text_obj = $('<span>').addClass('unreadcount').appendTo(link);
  6512. reg = /\s+\([0-9]+\)$/i;
  6513. childcount = 0;
  6514. if ((div = item.getElementsByTagName('div')[0]) &&
  6515. div.className.match(/collapsed/)) {
  6516. // add children's counters
  6517. for (var k in this.env.unread_counts)
  6518. if (k.startsWith(mbox + this.env.delimiter))
  6519. childcount += this.env.unread_counts[k];
  6520. }
  6521. if (mycount && text_obj.length)
  6522. text_obj.html(this.env.unreadwrap.replace(/%[sd]/, mycount));
  6523. else if (text_obj.length)
  6524. text_obj.remove();
  6525. // set parent's display
  6526. reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
  6527. if (mbox.match(reg))
  6528. this.set_unread_count_display(mbox.replace(reg, ''), false);
  6529. // set the right classes
  6530. if ((mycount+childcount)>0)
  6531. $(item).addClass('unread');
  6532. else
  6533. $(item).removeClass('unread');
  6534. }
  6535. // set unread count to window title
  6536. reg = /^\([0-9]+\)\s+/i;
  6537. if (set_title && document.title) {
  6538. var new_title = '',
  6539. doc_title = String(document.title);
  6540. if (mycount && doc_title.match(reg))
  6541. new_title = doc_title.replace(reg, '('+mycount+') ');
  6542. else if (mycount)
  6543. new_title = '('+mycount+') '+doc_title;
  6544. else
  6545. new_title = doc_title.replace(reg, '');
  6546. this.set_pagetitle(new_title);
  6547. }
  6548. };
  6549. // display fetched raw headers
  6550. this.set_headers = function(content)
  6551. {
  6552. if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
  6553. $(this.gui_objects.all_headers_box).html(content).show();
  6554. };
  6555. // display all-headers row and fetch raw message headers
  6556. this.show_headers = function(props, elem)
  6557. {
  6558. if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
  6559. return;
  6560. $(elem).removeClass('show-headers').addClass('hide-headers');
  6561. $(this.gui_objects.all_headers_row).show();
  6562. elem.onclick = function() { ref.command('hide-headers', '', elem); };
  6563. // fetch headers only once
  6564. if (!this.gui_objects.all_headers_box.innerHTML) {
  6565. this.http_post('headers', {_uid: this.env.uid, _mbox: this.env.mailbox},
  6566. this.display_message(this.get_label('loading'), 'loading')
  6567. );
  6568. }
  6569. };
  6570. // hide all-headers row
  6571. this.hide_headers = function(props, elem)
  6572. {
  6573. if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
  6574. return;
  6575. $(elem).removeClass('hide-headers').addClass('show-headers');
  6576. $(this.gui_objects.all_headers_row).hide();
  6577. elem.onclick = function() { ref.command('show-headers', '', elem); };
  6578. };
  6579. // create folder selector popup, position and display it
  6580. this.folder_selector = function(event, callback)
  6581. {
  6582. var container = this.folder_selector_element;
  6583. if (!container) {
  6584. var rows = [],
  6585. delim = this.env.delimiter,
  6586. ul = $('<ul class="toolbarmenu">'),
  6587. link = document.createElement('a');
  6588. container = $('<div id="folder-selector" class="popupmenu"></div>');
  6589. link.href = '#';
  6590. link.className = 'icon';
  6591. // loop over sorted folders list
  6592. $.each(this.env.mailboxes_list, function() {
  6593. var n = 0, s = 0,
  6594. folder = ref.env.mailboxes[this],
  6595. id = folder.id,
  6596. a = $(link.cloneNode(false)),
  6597. row = $('<li>');
  6598. if (folder.virtual)
  6599. a.addClass('virtual').attr('aria-disabled', 'true').attr('tabindex', '-1');
  6600. else
  6601. a.addClass('active').data('id', folder.id);
  6602. if (folder['class'])
  6603. a.addClass(folder['class']);
  6604. // calculate/set indentation level
  6605. while ((s = id.indexOf(delim, s)) >= 0) {
  6606. n++; s++;
  6607. }
  6608. a.css('padding-left', n ? (n * 16) + 'px' : 0);
  6609. // add folder name element
  6610. a.append($('<span>').text(folder.name));
  6611. row.append(a);
  6612. rows.push(row);
  6613. });
  6614. ul.append(rows).appendTo(container);
  6615. // temporarily show element to calculate its size
  6616. container.css({left: '-1000px', top: '-1000px'})
  6617. .appendTo($('body')).show();
  6618. // set max-height if the list is long
  6619. if (rows.length > 10)
  6620. container.css('max-height', $('li', container)[0].offsetHeight * 10 + 9);
  6621. // register delegate event handler for folder item clicks
  6622. container.on('click', 'a.active', function(e){
  6623. container.data('callback')($(this).data('id'));
  6624. return false;
  6625. });
  6626. this.folder_selector_element = container;
  6627. }
  6628. container.data('callback', callback);
  6629. // position menu on the screen
  6630. this.show_menu('folder-selector', true, event);
  6631. };
  6632. /***********************************************/
  6633. /********* popup menu functions *********/
  6634. /***********************************************/
  6635. // Show/hide a specific popup menu
  6636. this.show_menu = function(prop, show, event)
  6637. {
  6638. var name = typeof prop == 'object' ? prop.menu : prop,
  6639. obj = $('#'+name),
  6640. ref = event && event.target ? $(event.target) : $(obj.attr('rel') || '#'+name+'link'),
  6641. keyboard = rcube_event.is_keyboard(event),
  6642. align = obj.attr('data-align') || '',
  6643. stack = false;
  6644. // find "real" button element
  6645. if (ref.get(0).tagName != 'A' && ref.closest('a').length)
  6646. ref = ref.closest('a');
  6647. if (typeof prop == 'string')
  6648. prop = { menu:name };
  6649. // let plugins or skins provide the menu element
  6650. if (!obj.length) {
  6651. obj = this.triggerEvent('menu-get', { name:name, props:prop, originalEvent:event });
  6652. }
  6653. if (!obj || !obj.length) {
  6654. // just delegate the action to subscribers
  6655. return this.triggerEvent(show === false ? 'menu-close' : 'menu-open', { name:name, props:prop, originalEvent:event });
  6656. }
  6657. // move element to top for proper absolute positioning
  6658. obj.appendTo(document.body);
  6659. if (typeof show == 'undefined')
  6660. show = obj.is(':visible') ? false : true;
  6661. if (show && ref.length) {
  6662. var win = $(window),
  6663. pos = ref.offset(),
  6664. above = align.indexOf('bottom') >= 0;
  6665. stack = ref.attr('role') == 'menuitem' || ref.closest('[role=menuitem]').length > 0;
  6666. ref.offsetWidth = ref.outerWidth();
  6667. ref.offsetHeight = ref.outerHeight();
  6668. if (!above && pos.top + ref.offsetHeight + obj.height() > win.height()) {
  6669. above = true;
  6670. }
  6671. if (align.indexOf('right') >= 0) {
  6672. pos.left = pos.left + ref.outerWidth() - obj.width();
  6673. }
  6674. else if (stack) {
  6675. pos.left = pos.left + ref.offsetWidth - 5;
  6676. pos.top -= ref.offsetHeight;
  6677. }
  6678. if (pos.left + obj.width() > win.width()) {
  6679. pos.left = win.width() - obj.width() - 12;
  6680. }
  6681. pos.top = Math.max(0, pos.top + (above ? -obj.height() : ref.offsetHeight));
  6682. obj.css({ left:pos.left+'px', top:pos.top+'px' });
  6683. }
  6684. // add menu to stack
  6685. if (show) {
  6686. // truncate stack down to the one containing the ref link
  6687. for (var i = this.menu_stack.length - 1; stack && i >= 0; i--) {
  6688. if (!$(ref).parents('#'+this.menu_stack[i]).length && $(event.target).parent().attr('role') != 'menuitem')
  6689. this.hide_menu(this.menu_stack[i], event);
  6690. }
  6691. if (stack && this.menu_stack.length) {
  6692. obj.data('parent', $.last(this.menu_stack));
  6693. obj.css('z-index', ($('#'+$.last(this.menu_stack)).css('z-index') || 0) + 1);
  6694. }
  6695. else if (!stack && this.menu_stack.length) {
  6696. this.hide_menu(this.menu_stack[0], event);
  6697. }
  6698. obj.show().attr('aria-hidden', 'false').data('opener', ref.attr('aria-expanded', 'true').get(0));
  6699. this.triggerEvent('menu-open', { name:name, obj:obj, props:prop, originalEvent:event });
  6700. this.menu_stack.push(name);
  6701. this.menu_keyboard_active = show && keyboard;
  6702. if (this.menu_keyboard_active) {
  6703. this.focused_menu = name;
  6704. obj.find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
  6705. }
  6706. }
  6707. else { // close menu
  6708. this.hide_menu(name, event);
  6709. }
  6710. return show;
  6711. };
  6712. // hide the given popup menu (and it's childs)
  6713. this.hide_menu = function(name, event)
  6714. {
  6715. if (!this.menu_stack.length) {
  6716. // delegate to subscribers
  6717. this.triggerEvent('menu-close', { name:name, props:{ menu:name }, originalEvent:event });
  6718. return;
  6719. }
  6720. var obj, keyboard = rcube_event.is_keyboard(event);
  6721. for (var j=this.menu_stack.length-1; j >= 0; j--) {
  6722. obj = $('#' + this.menu_stack[j]).hide().attr('aria-hidden', 'true').data('parent', false);
  6723. this.triggerEvent('menu-close', { name:this.menu_stack[j], obj:obj, props:{ menu:this.menu_stack[j] }, originalEvent:event });
  6724. if (this.menu_stack[j] == name) {
  6725. j = -1; // stop loop
  6726. if (obj.data('opener')) {
  6727. $(obj.data('opener')).attr('aria-expanded', 'false');
  6728. if (keyboard)
  6729. obj.data('opener').focus();
  6730. }
  6731. }
  6732. this.menu_stack.pop();
  6733. }
  6734. // focus previous menu in stack
  6735. if (this.menu_stack.length && keyboard) {
  6736. this.menu_keyboard_active = true;
  6737. this.focused_menu = $.last(this.menu_stack);
  6738. if (!obj || !obj.data('opener'))
  6739. $('#'+this.focused_menu).find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
  6740. }
  6741. else {
  6742. this.focused_menu = null;
  6743. this.menu_keyboard_active = false;
  6744. }
  6745. }
  6746. // position a menu element on the screen in relation to other object
  6747. this.element_position = function(element, obj)
  6748. {
  6749. var obj = $(obj), win = $(window),
  6750. width = obj.outerWidth(),
  6751. height = obj.outerHeight(),
  6752. menu_pos = obj.data('menu-pos'),
  6753. win_height = win.height(),
  6754. elem_height = $(element).height(),
  6755. elem_width = $(element).width(),
  6756. pos = obj.offset(),
  6757. top = pos.top,
  6758. left = pos.left + width;
  6759. if (menu_pos == 'bottom') {
  6760. top += height;
  6761. left -= width;
  6762. }
  6763. else
  6764. left -= 5;
  6765. if (top + elem_height > win_height) {
  6766. top -= elem_height - height;
  6767. if (top < 0)
  6768. top = Math.max(0, (win_height - elem_height) / 2);
  6769. }
  6770. if (left + elem_width > win.width())
  6771. left -= elem_width + width;
  6772. element.css({left: left + 'px', top: top + 'px'});
  6773. };
  6774. // initialize HTML editor
  6775. this.editor_init = function(config, id)
  6776. {
  6777. this.editor = new rcube_text_editor(config, id);
  6778. };
  6779. /********************************************************/
  6780. /********* html to text conversion functions *********/
  6781. /********************************************************/
  6782. this.html2plain = function(html, func)
  6783. {
  6784. return this.format_converter(html, 'html', func);
  6785. };
  6786. this.plain2html = function(plain, func)
  6787. {
  6788. return this.format_converter(plain, 'plain', func);
  6789. };
  6790. this.format_converter = function(text, format, func)
  6791. {
  6792. // warn the user (if converted content is not empty)
  6793. if (!text
  6794. || (format == 'html' && !(text.replace(/<[^>]+>|&nbsp;|\xC2\xA0|\s/g, '')).length)
  6795. || (format != 'html' && !(text.replace(/\xC2\xA0|\s/g, '')).length)
  6796. ) {
  6797. // without setTimeout() here, textarea is filled with initial (onload) content
  6798. if (func)
  6799. setTimeout(function() { func(''); }, 50);
  6800. return true;
  6801. }
  6802. var confirmed = this.env.editor_warned || confirm(this.get_label('editorwarning'));
  6803. this.env.editor_warned = true;
  6804. if (!confirmed)
  6805. return false;
  6806. var url = '?_task=utils&_action=' + (format == 'html' ? 'html2text' : 'text2html'),
  6807. lock = this.set_busy(true, 'converting');
  6808. $.ajax({ type: 'POST', url: url, data: text, contentType: 'application/octet-stream',
  6809. error: function(o, status, err) { ref.http_error(o, status, err, lock); },
  6810. success: function(data) {
  6811. ref.set_busy(false, null, lock);
  6812. if (func) func(data);
  6813. }
  6814. });
  6815. return true;
  6816. };
  6817. /********************************************************/
  6818. /********* remote request methods *********/
  6819. /********************************************************/
  6820. // compose a valid url with the given parameters
  6821. this.url = function(action, query)
  6822. {
  6823. var querystring = typeof query === 'string' ? query : '';
  6824. if (typeof action !== 'string')
  6825. query = action;
  6826. else if (!query || typeof query !== 'object')
  6827. query = {};
  6828. if (action)
  6829. query._action = action;
  6830. else if (this.env.action)
  6831. query._action = this.env.action;
  6832. var url = this.env.comm_path, k, param = {};
  6833. // overwrite task name
  6834. if (action && action.match(/([a-z0-9_-]+)\/([a-z0-9-_.]+)/)) {
  6835. query._action = RegExp.$2;
  6836. url = url.replace(/\_task=[a-z0-9_-]+/, '_task=' + RegExp.$1);
  6837. }
  6838. // remove undefined values
  6839. for (k in query) {
  6840. if (query[k] !== undefined && query[k] !== null)
  6841. param[k] = query[k];
  6842. }
  6843. if (param = $.param(param))
  6844. url += (url.indexOf('?') > -1 ? '&' : '?') + param;
  6845. if (querystring)
  6846. url += (url.indexOf('?') > -1 ? '&' : '?') + querystring;
  6847. return url;
  6848. };
  6849. this.redirect = function(url, lock)
  6850. {
  6851. if (lock || lock === null)
  6852. this.set_busy(true);
  6853. if (this.is_framed()) {
  6854. parent.rcmail.redirect(url, lock);
  6855. }
  6856. else {
  6857. if (this.env.extwin) {
  6858. if (typeof url == 'string')
  6859. url += (url.indexOf('?') < 0 ? '?' : '&') + '_extwin=1';
  6860. else
  6861. url._extwin = 1;
  6862. }
  6863. this.location_href(url, window);
  6864. }
  6865. };
  6866. this.goto_url = function(action, query, lock, secure)
  6867. {
  6868. var url = this.url(action, query)
  6869. if (secure) url = this.secure_url(url);
  6870. this.redirect(url, lock);
  6871. };
  6872. this.location_href = function(url, target, frame)
  6873. {
  6874. if (frame)
  6875. this.lock_frame();
  6876. if (typeof url == 'object')
  6877. url = this.env.comm_path + '&' + $.param(url);
  6878. // simulate real link click to force IE to send referer header
  6879. if (bw.ie && target == window)
  6880. $('<a>').attr('href', url).appendTo(document.body).get(0).click();
  6881. else
  6882. target.location.href = url;
  6883. // reset keep-alive interval
  6884. this.start_keepalive();
  6885. };
  6886. // update browser location to remember current view
  6887. this.update_state = function(query)
  6888. {
  6889. if (window.history.replaceState)
  6890. try {
  6891. // This may throw security exception in Firefox (#5400)
  6892. window.history.replaceState({}, document.title, rcmail.url('', query));
  6893. }
  6894. catch(e) { /* ignore */ };
  6895. };
  6896. // send a http request to the server
  6897. this.http_request = function(action, data, lock, type)
  6898. {
  6899. if (type != 'POST')
  6900. type = 'GET';
  6901. if (typeof data !== 'object')
  6902. data = rcube_parse_query(data);
  6903. data._remote = 1;
  6904. data._unlock = lock ? lock : 0;
  6905. // trigger plugin hook
  6906. var result = this.triggerEvent('request' + action, data);
  6907. // abort if one of the handlers returned false
  6908. if (result === false) {
  6909. if (data._unlock)
  6910. this.set_busy(false, null, data._unlock);
  6911. return false;
  6912. }
  6913. else if (result !== undefined) {
  6914. data = result;
  6915. if (data._action) {
  6916. action = data._action;
  6917. delete data._action;
  6918. }
  6919. }
  6920. var url = this.url(action);
  6921. // reset keep-alive interval
  6922. this.start_keepalive();
  6923. // send request
  6924. return $.ajax({
  6925. type: type, url: url, data: data, dataType: 'json',
  6926. success: function(data) { ref.http_response(data); },
  6927. error: function(o, status, err) { ref.http_error(o, status, err, lock, action); }
  6928. });
  6929. };
  6930. // send a http GET request to the server
  6931. this.http_get = this.http_request;
  6932. // send a http POST request to the server
  6933. this.http_post = function(action, data, lock)
  6934. {
  6935. return this.http_request(action, data, lock, 'POST');
  6936. };
  6937. // aborts ajax request
  6938. this.abort_request = function(r)
  6939. {
  6940. if (r.request)
  6941. r.request.abort();
  6942. if (r.lock)
  6943. this.set_busy(false, null, r.lock);
  6944. };
  6945. // handle HTTP response
  6946. this.http_response = function(response)
  6947. {
  6948. if (!response)
  6949. return;
  6950. if (response.unlock)
  6951. this.set_busy(false);
  6952. this.triggerEvent('responsebefore', {response: response});
  6953. this.triggerEvent('responsebefore'+response.action, {response: response});
  6954. // set env vars
  6955. if (response.env)
  6956. this.set_env(response.env);
  6957. var i;
  6958. // we have labels to add
  6959. if (typeof response.texts === 'object') {
  6960. for (i in response.texts)
  6961. if (typeof response.texts[i] === 'string')
  6962. this.add_label(i, response.texts[i]);
  6963. }
  6964. // if we get javascript code from server -> execute it
  6965. if (response.exec) {
  6966. eval(response.exec);
  6967. }
  6968. // execute callback functions of plugins
  6969. if (response.callbacks && response.callbacks.length) {
  6970. for (i=0; i < response.callbacks.length; i++)
  6971. this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
  6972. }
  6973. // process the response data according to the sent action
  6974. switch (response.action) {
  6975. case 'mark':
  6976. // Mark the message as Seen also in the opener/parent
  6977. if ((this.env.action == 'show' || this.env.action == 'preview') && this.env.last_flag == 'SEEN')
  6978. this.set_unread_message(this.env.uid, this.env.mailbox);
  6979. break;
  6980. case 'delete':
  6981. if (this.task == 'addressbook') {
  6982. var sid, uid = this.contact_list.get_selection(), writable = false;
  6983. if (uid && this.contact_list.rows[uid]) {
  6984. // search results, get source ID from record ID
  6985. if (this.env.source == '') {
  6986. sid = String(uid).replace(/^[^-]+-/, '');
  6987. writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
  6988. }
  6989. else {
  6990. writable = !this.env.address_sources[this.env.source].readonly;
  6991. }
  6992. }
  6993. this.enable_command('compose', (uid && this.contact_list.rows[uid]));
  6994. this.enable_command('delete', 'edit', writable);
  6995. this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
  6996. this.enable_command('export-selected', 'print', false);
  6997. }
  6998. case 'move':
  6999. if (this.env.action == 'show') {
  7000. // re-enable commands on move/delete error
  7001. this.enable_command(this.env.message_commands, true);
  7002. if (!this.env.list_post)
  7003. this.enable_command('reply-list', false);
  7004. }
  7005. else if (this.task == 'addressbook') {
  7006. this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
  7007. }
  7008. case 'purge':
  7009. case 'expunge':
  7010. if (this.task == 'mail') {
  7011. if (!this.env.exists) {
  7012. // clear preview pane content
  7013. if (this.env.contentframe)
  7014. this.show_contentframe(false);
  7015. // disable commands useless when mailbox is empty
  7016. this.enable_command(this.env.message_commands, 'purge', 'expunge',
  7017. 'select-all', 'select-none', 'expand-all', 'expand-unread', 'collapse-all', false);
  7018. }
  7019. if (this.message_list)
  7020. this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
  7021. }
  7022. break;
  7023. case 'refresh':
  7024. case 'check-recent':
  7025. // update message flags
  7026. $.each(this.env.recent_flags || {}, function(uid, flags) {
  7027. ref.set_message(uid, 'deleted', flags.deleted);
  7028. ref.set_message(uid, 'replied', flags.answered);
  7029. ref.set_message(uid, 'unread', !flags.seen);
  7030. ref.set_message(uid, 'forwarded', flags.forwarded);
  7031. ref.set_message(uid, 'flagged', flags.flagged);
  7032. });
  7033. delete this.env.recent_flags;
  7034. case 'getunread':
  7035. case 'search':
  7036. this.env.qsearch = null;
  7037. case 'list':
  7038. if (this.task == 'mail') {
  7039. var is_multifolder = this.is_multifolder_listing(),
  7040. list = this.message_list,
  7041. uid = this.env.list_uid;
  7042. this.enable_command('show', 'select-all', 'select-none', this.env.messagecount > 0);
  7043. this.enable_command('expunge', this.env.exists && !is_multifolder);
  7044. this.enable_command('purge', this.purge_mailbox_test() && !is_multifolder);
  7045. this.enable_command('import-messages', !is_multifolder);
  7046. this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount && !is_multifolder);
  7047. if (list) {
  7048. if (response.action == 'list' || response.action == 'search') {
  7049. // highlight message row when we're back from message page
  7050. if (uid) {
  7051. if (!list.rows[uid])
  7052. uid += '-' + this.env.mailbox;
  7053. if (list.rows[uid]) {
  7054. list.select(uid);
  7055. }
  7056. delete this.env.list_uid;
  7057. }
  7058. this.enable_command('set-listmode', this.env.threads && !is_multifolder);
  7059. if (list.rowcount > 0 && !$(document.activeElement).is('input,textarea'))
  7060. list.focus();
  7061. // trigger 'select' so all dependent actions update its state
  7062. // e.g. plugins use this event to activate buttons (#1490647)
  7063. list.triggerEvent('select');
  7064. }
  7065. if (response.action != 'getunread')
  7066. this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:list.rowcount });
  7067. }
  7068. }
  7069. else if (this.task == 'addressbook') {
  7070. this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
  7071. if (response.action == 'list' || response.action == 'search') {
  7072. this.enable_command('search-create', this.env.source == '');
  7073. this.enable_command('search-delete', this.env.search_id);
  7074. this.update_group_commands();
  7075. if (this.contact_list.rowcount > 0 && !$(document.activeElement).is('input,textarea'))
  7076. this.contact_list.focus();
  7077. this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
  7078. }
  7079. }
  7080. break;
  7081. case 'list-contacts':
  7082. case 'search-contacts':
  7083. if (this.contact_list && this.contact_list.rowcount > 0)
  7084. this.contact_list.focus();
  7085. break;
  7086. }
  7087. if (response.unlock)
  7088. this.hide_message(response.unlock);
  7089. this.triggerEvent('responseafter', {response: response});
  7090. this.triggerEvent('responseafter'+response.action, {response: response});
  7091. // reset keep-alive interval
  7092. this.start_keepalive();
  7093. };
  7094. // handle HTTP request errors
  7095. this.http_error = function(request, status, err, lock, action)
  7096. {
  7097. var errmsg = request.statusText;
  7098. this.set_busy(false, null, lock);
  7099. request.abort();
  7100. // don't display error message on page unload (#1488547)
  7101. if (this.unload)
  7102. return;
  7103. if (request.status && errmsg)
  7104. this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
  7105. else if (status == 'timeout')
  7106. this.display_message(this.get_label('requesttimedout'), 'error');
  7107. else if (request.status == 0 && status != 'abort')
  7108. this.display_message(this.get_label('connerror'), 'error');
  7109. // redirect to url specified in location header if not empty
  7110. var location_url = request.getResponseHeader("Location");
  7111. if (location_url && this.env.action != 'compose') // don't redirect on compose screen, contents might get lost (#1488926)
  7112. this.redirect(location_url);
  7113. // 403 Forbidden response (CSRF prevention) - reload the page.
  7114. // In case there's a new valid session it will be used, otherwise
  7115. // login form will be presented (#1488960).
  7116. if (request.status == 403) {
  7117. (this.is_framed() ? parent : window).location.reload();
  7118. return;
  7119. }
  7120. // re-send keep-alive requests after 30 seconds
  7121. if (action == 'keep-alive')
  7122. setTimeout(function(){ ref.keep_alive(); ref.start_keepalive(); }, 30000);
  7123. };
  7124. // handler for session errors detected on the server
  7125. this.session_error = function(redirect_url)
  7126. {
  7127. this.env.server_error = 401;
  7128. // save message in local storage and do not redirect
  7129. if (this.env.action == 'compose') {
  7130. this.save_compose_form_local();
  7131. this.compose_skip_unsavedcheck = true;
  7132. // stop keep-alive and refresh processes
  7133. this.env.session_lifetime = 0;
  7134. if (this._keepalive)
  7135. clearInterval(this._keepalive);
  7136. if (this._refresh)
  7137. clearInterval(this._refresh);
  7138. }
  7139. else if (redirect_url) {
  7140. setTimeout(function(){ ref.redirect(redirect_url, true); }, 2000);
  7141. }
  7142. };
  7143. // callback when an iframe finished loading
  7144. this.iframe_loaded = function(unlock)
  7145. {
  7146. this.set_busy(false, null, unlock);
  7147. if (this.submit_timer)
  7148. clearTimeout(this.submit_timer);
  7149. };
  7150. /**
  7151. Send multi-threaded parallel HTTP requests to the server for a list if items.
  7152. The string '%' in either a GET query or POST parameters will be replaced with the respective item value.
  7153. This is the argument object expected: {
  7154. items: ['foo','bar','gna'], // list of items to send requests for
  7155. action: 'task/some-action', // Roudncube action to call
  7156. query: { q:'%s' }, // GET query parameters
  7157. postdata: { source:'%s' }, // POST data (sends a POST request if present)
  7158. threads: 3, // max. number of concurrent requests
  7159. onresponse: function(data){ }, // Callback function called for every response received from server
  7160. whendone: function(alldata){ } // Callback function called when all requests have been sent
  7161. }
  7162. */
  7163. this.multi_thread_http_request = function(prop)
  7164. {
  7165. var i, item, reqid = new Date().getTime(),
  7166. threads = prop.threads || 1;
  7167. prop.reqid = reqid;
  7168. prop.running = 0;
  7169. prop.requests = [];
  7170. prop.result = [];
  7171. prop._items = $.extend([], prop.items); // copy items
  7172. if (!prop.lock)
  7173. prop.lock = this.display_message(this.get_label('loading'), 'loading');
  7174. // add the request arguments to the jobs pool
  7175. this.http_request_jobs[reqid] = prop;
  7176. // start n threads
  7177. for (i=0; i < threads; i++) {
  7178. item = prop._items.shift();
  7179. if (item === undefined)
  7180. break;
  7181. prop.running++;
  7182. prop.requests.push(this.multi_thread_send_request(prop, item));
  7183. }
  7184. return reqid;
  7185. };
  7186. // helper method to send an HTTP request with the given iterator value
  7187. this.multi_thread_send_request = function(prop, item)
  7188. {
  7189. var k, postdata, query;
  7190. // replace %s in post data
  7191. if (prop.postdata) {
  7192. postdata = {};
  7193. for (k in prop.postdata) {
  7194. postdata[k] = String(prop.postdata[k]).replace('%s', item);
  7195. }
  7196. postdata._reqid = prop.reqid;
  7197. }
  7198. // replace %s in query
  7199. else if (typeof prop.query == 'string') {
  7200. query = prop.query.replace('%s', item);
  7201. query += '&_reqid=' + prop.reqid;
  7202. }
  7203. else if (typeof prop.query == 'object' && prop.query) {
  7204. query = {};
  7205. for (k in prop.query) {
  7206. query[k] = String(prop.query[k]).replace('%s', item);
  7207. }
  7208. query._reqid = prop.reqid;
  7209. }
  7210. // send HTTP GET or POST request
  7211. return postdata ? this.http_post(prop.action, postdata) : this.http_request(prop.action, query);
  7212. };
  7213. // callback function for multi-threaded http responses
  7214. this.multi_thread_http_response = function(data, reqid)
  7215. {
  7216. var prop = this.http_request_jobs[reqid];
  7217. if (!prop || prop.running <= 0 || prop.cancelled)
  7218. return;
  7219. prop.running--;
  7220. // trigger response callback
  7221. if (prop.onresponse && typeof prop.onresponse == 'function') {
  7222. prop.onresponse(data);
  7223. }
  7224. prop.result = $.extend(prop.result, data);
  7225. // send next request if prop.items is not yet empty
  7226. var item = prop._items.shift();
  7227. if (item !== undefined) {
  7228. prop.running++;
  7229. prop.requests.push(this.multi_thread_send_request(prop, item));
  7230. }
  7231. // trigger whendone callback and mark this request as done
  7232. else if (prop.running == 0) {
  7233. if (prop.whendone && typeof prop.whendone == 'function') {
  7234. prop.whendone(prop.result);
  7235. }
  7236. this.set_busy(false, '', prop.lock);
  7237. // remove from this.http_request_jobs pool
  7238. delete this.http_request_jobs[reqid];
  7239. }
  7240. };
  7241. // abort a running multi-thread request with the given identifier
  7242. this.multi_thread_request_abort = function(reqid)
  7243. {
  7244. var prop = this.http_request_jobs[reqid];
  7245. if (prop) {
  7246. for (var i=0; prop.running > 0 && i < prop.requests.length; i++) {
  7247. if (prop.requests[i].abort)
  7248. prop.requests[i].abort();
  7249. }
  7250. prop.running = 0;
  7251. prop.cancelled = true;
  7252. this.set_busy(false, '', prop.lock);
  7253. }
  7254. };
  7255. // post the given form to a hidden iframe
  7256. this.async_upload_form = function(form, action, onload)
  7257. {
  7258. // create hidden iframe
  7259. var ts = new Date().getTime(),
  7260. frame_name = 'rcmupload' + ts,
  7261. frame = this.async_upload_form_frame(frame_name);
  7262. // upload progress support
  7263. if (this.env.upload_progress_name) {
  7264. var fname = this.env.upload_progress_name,
  7265. field = $('input[name='+fname+']', form);
  7266. if (!field.length) {
  7267. field = $('<input>').attr({type: 'hidden', name: fname});
  7268. field.prependTo(form);
  7269. }
  7270. field.val(ts);
  7271. }
  7272. // handle upload errors by parsing iframe content in onload
  7273. frame.on('load', {ts:ts}, onload);
  7274. $(form).attr({
  7275. target: frame_name,
  7276. action: this.url(action, {_id: this.env.compose_id || '', _uploadid: ts, _from: this.env.action}),
  7277. method: 'POST'})
  7278. .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
  7279. .submit();
  7280. return frame_name;
  7281. };
  7282. // create iframe element for files upload
  7283. this.async_upload_form_frame = function(name)
  7284. {
  7285. return $('<iframe>').attr({name: name, style: 'border: none; width: 0; height: 0; visibility: hidden'})
  7286. .appendTo(document.body);
  7287. };
  7288. // html5 file-drop API
  7289. this.document_drag_hover = function(e, over)
  7290. {
  7291. // don't e.preventDefault() here to not block text dragging on the page (#1490619)
  7292. $(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('active');
  7293. };
  7294. this.file_drag_hover = function(e, over)
  7295. {
  7296. e.preventDefault();
  7297. e.stopPropagation();
  7298. $(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('hover');
  7299. };
  7300. // handler when files are dropped to a designated area.
  7301. // compose a multipart form data and submit it to the server
  7302. this.file_dropped = function(e)
  7303. {
  7304. // abort event and reset UI
  7305. this.file_drag_hover(e, false);
  7306. // prepare multipart form data composition
  7307. var uri, files = e.target.files || e.dataTransfer.files,
  7308. formdata = window.FormData ? new FormData() : null,
  7309. fieldname = (this.env.filedrop.fieldname || '_file') + (this.env.filedrop.single ? '' : '[]'),
  7310. boundary = '------multipartformboundary' + (new Date).getTime(),
  7311. dashdash = '--', crlf = '\r\n',
  7312. multipart = dashdash + boundary + crlf,
  7313. args = {_id: this.env.compose_id || this.env.cid || '', _remote: 1, _from: this.env.action};
  7314. if (!files || !files.length) {
  7315. // Roundcube attachment, pass its uri to the backend and attach
  7316. if (uri = e.dataTransfer.getData('roundcube-uri')) {
  7317. var ts = new Date().getTime(),
  7318. // jQuery way to escape filename (#1490530)
  7319. content = $('<span>').text(e.dataTransfer.getData('roundcube-name') || this.get_label('attaching')).html();
  7320. args._uri = uri;
  7321. args._uploadid = ts;
  7322. // add to attachments list
  7323. if (!this.add2attachment_list(ts, {name: '', html: content, classname: 'uploading', complete: false}))
  7324. this.file_upload_id = this.set_busy(true, 'attaching');
  7325. this.http_post(this.env.filedrop.action || 'upload', args);
  7326. }
  7327. return;
  7328. }
  7329. // inline function to submit the files to the server
  7330. var submit_data = function() {
  7331. var multiple = files.length > 1,
  7332. ts = new Date().getTime(),
  7333. // jQuery way to escape filename (#1490530)
  7334. content = $('<span>').text(multiple ? ref.get_label('uploadingmany') : files[0].name).html();
  7335. // add to attachments list
  7336. if (!ref.add2attachment_list(ts, { name:'', html:content, classname:'uploading', complete:false }))
  7337. ref.file_upload_id = ref.set_busy(true, 'uploading');
  7338. // complete multipart content and post request
  7339. multipart += dashdash + boundary + dashdash + crlf;
  7340. args._uploadid = ts;
  7341. $.ajax({
  7342. type: 'POST',
  7343. dataType: 'json',
  7344. url: ref.url(ref.env.filedrop.action || 'upload', args),
  7345. contentType: formdata ? false : 'multipart/form-data; boundary=' + boundary,
  7346. processData: false,
  7347. timeout: 0, // disable default timeout set in ajaxSetup()
  7348. data: formdata || multipart,
  7349. headers: {'X-Roundcube-Request': ref.env.request_token},
  7350. xhr: function() { var xhr = jQuery.ajaxSettings.xhr(); if (!formdata && xhr.sendAsBinary) xhr.send = xhr.sendAsBinary; return xhr; },
  7351. success: function(data){ ref.http_response(data); },
  7352. error: function(o, status, err) { ref.http_error(o, status, err, null, 'attachment'); }
  7353. });
  7354. };
  7355. // get contents of all dropped files
  7356. var last = this.env.filedrop.single ? 0 : files.length - 1;
  7357. for (var j=0, i=0, f; j <= last && (f = files[i]); i++) {
  7358. if (!f.name) f.name = f.fileName;
  7359. if (!f.size) f.size = f.fileSize;
  7360. if (!f.type) f.type = 'application/octet-stream';
  7361. // file name contains non-ASCII characters, do UTF8-binary string conversion.
  7362. if (!formdata && /[^\x20-\x7E]/.test(f.name))
  7363. f.name_bin = unescape(encodeURIComponent(f.name));
  7364. // filter by file type if requested
  7365. if (this.env.filedrop.filter && !f.type.match(new RegExp(this.env.filedrop.filter))) {
  7366. // TODO: show message to user
  7367. continue;
  7368. }
  7369. // do it the easy way with FormData (FF 4+, Chrome 5+, Safari 5+)
  7370. if (formdata) {
  7371. formdata.append(fieldname, f);
  7372. if (j == last)
  7373. return submit_data();
  7374. }
  7375. // use FileReader supporetd by Firefox 3.6
  7376. else if (window.FileReader) {
  7377. var reader = new FileReader();
  7378. // closure to pass file properties to async callback function
  7379. reader.onload = (function(file, j) {
  7380. return function(e) {
  7381. multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
  7382. multipart += '; filename="' + (f.name_bin || file.name) + '"' + crlf;
  7383. multipart += 'Content-Length: ' + file.size + crlf;
  7384. multipart += 'Content-Type: ' + file.type + crlf + crlf;
  7385. multipart += reader.result + crlf;
  7386. multipart += dashdash + boundary + crlf;
  7387. if (j == last) // we're done, submit the data
  7388. return submit_data();
  7389. }
  7390. })(f,j);
  7391. reader.readAsBinaryString(f);
  7392. }
  7393. // Firefox 3
  7394. else if (f.getAsBinary) {
  7395. multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
  7396. multipart += '; filename="' + (f.name_bin || f.name) + '"' + crlf;
  7397. multipart += 'Content-Length: ' + f.size + crlf;
  7398. multipart += 'Content-Type: ' + f.type + crlf + crlf;
  7399. multipart += f.getAsBinary() + crlf;
  7400. multipart += dashdash + boundary +crlf;
  7401. if (j == last)
  7402. return submit_data();
  7403. }
  7404. j++;
  7405. }
  7406. };
  7407. // starts interval for keep-alive signal
  7408. this.start_keepalive = function()
  7409. {
  7410. if (!this.env.session_lifetime || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
  7411. return;
  7412. if (this._keepalive)
  7413. clearInterval(this._keepalive);
  7414. // use Math to prevent from an integer overflow (#5273)
  7415. // maximum interval is 15 minutes, minimum is 30 seconds
  7416. var interval = Math.min(1800, this.env.session_lifetime) * 0.5 * 1000;
  7417. this._keepalive = setInterval(function() { ref.keep_alive(); }, interval < 30000 ? 30000 : interval);
  7418. };
  7419. // starts interval for refresh signal
  7420. this.start_refresh = function()
  7421. {
  7422. if (!this.env.refresh_interval || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
  7423. return;
  7424. if (this._refresh)
  7425. clearInterval(this._refresh);
  7426. this._refresh = setInterval(function(){ ref.refresh(); }, this.env.refresh_interval * 1000);
  7427. };
  7428. // sends keep-alive signal
  7429. this.keep_alive = function()
  7430. {
  7431. if (!this.busy)
  7432. this.http_request('keep-alive');
  7433. };
  7434. // sends refresh signal
  7435. this.refresh = function()
  7436. {
  7437. if (this.busy) {
  7438. // try again after 10 seconds
  7439. setTimeout(function(){ ref.refresh(); ref.start_refresh(); }, 10000);
  7440. return;
  7441. }
  7442. var params = {}, lock = this.set_busy(true, 'refreshing');
  7443. if (this.task == 'mail' && this.gui_objects.mailboxlist)
  7444. params = this.check_recent_params();
  7445. params._last = Math.floor(this.env.lastrefresh.getTime() / 1000);
  7446. this.env.lastrefresh = new Date();
  7447. // plugins should bind to 'requestrefresh' event to add own params
  7448. this.http_post('refresh', params, lock);
  7449. };
  7450. // returns check-recent request parameters
  7451. this.check_recent_params = function()
  7452. {
  7453. var params = {_mbox: this.env.mailbox};
  7454. if (this.gui_objects.mailboxlist)
  7455. params._folderlist = 1;
  7456. if (this.gui_objects.quotadisplay)
  7457. params._quota = 1;
  7458. if (this.env.search_request)
  7459. params._search = this.env.search_request;
  7460. if (this.gui_objects.messagelist) {
  7461. params._list = 1;
  7462. // message uids for flag updates check
  7463. params._uids = $.map(this.message_list.rows, function(row, uid) { return uid; }).join(',');
  7464. }
  7465. return params;
  7466. };
  7467. /********************************************************/
  7468. /********* helper methods *********/
  7469. /********************************************************/
  7470. /**
  7471. * Quote html entities
  7472. */
  7473. this.quote_html = function(str)
  7474. {
  7475. return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  7476. };
  7477. // get window.opener.rcmail if available
  7478. this.opener = function(deep, filter)
  7479. {
  7480. var i, win = window.opener;
  7481. // catch Error: Permission denied to access property rcmail
  7482. try {
  7483. if (win && !win.closed) {
  7484. // try parent of the opener window, e.g. preview frame
  7485. if (deep && (!win.rcmail || win.rcmail.env.framed) && win.parent && win.parent.rcmail)
  7486. win = win.parent;
  7487. if (win.rcmail && filter)
  7488. for (i in filter)
  7489. if (win.rcmail.env[i] != filter[i])
  7490. return;
  7491. return win.rcmail;
  7492. }
  7493. }
  7494. catch (e) {}
  7495. };
  7496. // check if we're in show mode or if we have a unique selection
  7497. // and return the message uid
  7498. this.get_single_uid = function()
  7499. {
  7500. var uid = this.env.uid || (this.message_list ? this.message_list.get_single_selection() : null);
  7501. var result = ref.triggerEvent('get_single_uid', { uid: uid });
  7502. return result || uid;
  7503. };
  7504. // same as above but for contacts
  7505. this.get_single_cid = function()
  7506. {
  7507. var cid = this.env.cid || (this.contact_list ? this.contact_list.get_single_selection() : null);
  7508. var result = ref.triggerEvent('get_single_cid', { cid: cid });
  7509. return result || cid;
  7510. };
  7511. // get the IMP mailbox of the message with the given UID
  7512. this.get_message_mailbox = function(uid)
  7513. {
  7514. var msg = (this.env.messages && uid ? this.env.messages[uid] : null) || {};
  7515. return msg.mbox || this.env.mailbox;
  7516. };
  7517. // build request parameters from single message id (maybe with mailbox name)
  7518. this.params_from_uid = function(uid, params)
  7519. {
  7520. if (!params)
  7521. params = {};
  7522. params._uid = String(uid).split('-')[0];
  7523. params._mbox = this.get_message_mailbox(uid);
  7524. return params;
  7525. };
  7526. // gets cursor position
  7527. this.get_caret_pos = function(obj)
  7528. {
  7529. if (obj.selectionEnd !== undefined)
  7530. return obj.selectionEnd;
  7531. return obj.value.length;
  7532. };
  7533. // moves cursor to specified position
  7534. this.set_caret_pos = function(obj, pos)
  7535. {
  7536. try {
  7537. if (obj.setSelectionRange)
  7538. obj.setSelectionRange(pos, pos);
  7539. }
  7540. catch(e) {} // catch Firefox exception if obj is hidden
  7541. };
  7542. // get selected text from an input field
  7543. this.get_input_selection = function(obj)
  7544. {
  7545. var start = 0, end = 0, normalizedValue = '';
  7546. if (typeof obj.selectionStart == "number" && typeof obj.selectionEnd == "number") {
  7547. normalizedValue = obj.value;
  7548. start = obj.selectionStart;
  7549. end = obj.selectionEnd;
  7550. }
  7551. return {start: start, end: end, text: normalizedValue.substr(start, end-start)};
  7552. };
  7553. // disable/enable all fields of a form
  7554. this.lock_form = function(form, lock)
  7555. {
  7556. if (!form || !form.elements)
  7557. return;
  7558. var n, len, elm;
  7559. if (lock)
  7560. this.disabled_form_elements = [];
  7561. for (n=0, len=form.elements.length; n<len; n++) {
  7562. elm = form.elements[n];
  7563. if (elm.type == 'hidden')
  7564. continue;
  7565. // remember which elem was disabled before lock
  7566. if (lock && elm.disabled)
  7567. this.disabled_form_elements.push(elm);
  7568. else if (lock || $.inArray(elm, this.disabled_form_elements) < 0)
  7569. elm.disabled = lock;
  7570. }
  7571. };
  7572. this.mailto_handler_uri = function()
  7573. {
  7574. return location.href.split('?')[0] + '?_task=mail&_action=compose&_to=%s';
  7575. };
  7576. this.register_protocol_handler = function(name)
  7577. {
  7578. try {
  7579. window.navigator.registerProtocolHandler('mailto', this.mailto_handler_uri(), name);
  7580. }
  7581. catch(e) {
  7582. this.display_message(String(e), 'error');
  7583. }
  7584. };
  7585. this.check_protocol_handler = function(name, elem)
  7586. {
  7587. var nav = window.navigator;
  7588. if (!nav || (typeof nav.registerProtocolHandler != 'function')) {
  7589. $(elem).addClass('disabled').click(function(){ return false; });
  7590. }
  7591. else if (typeof nav.isProtocolHandlerRegistered == 'function') {
  7592. var status = nav.isProtocolHandlerRegistered('mailto', this.mailto_handler_uri());
  7593. if (status)
  7594. $(elem).parent().find('.mailtoprotohandler-status').html(status);
  7595. }
  7596. else {
  7597. $(elem).click(function() { ref.register_protocol_handler(name); return false; });
  7598. }
  7599. };
  7600. // Checks browser capabilities eg. PDF support, TIF support
  7601. this.browser_capabilities_check = function()
  7602. {
  7603. if (!this.env.browser_capabilities)
  7604. this.env.browser_capabilities = {};
  7605. $.each(['pdf', 'flash', 'tiff', 'webp'], function() {
  7606. if (ref.env.browser_capabilities[this] === undefined)
  7607. ref.env.browser_capabilities[this] = ref[this + '_support_check']();
  7608. });
  7609. };
  7610. // Returns browser capabilities string
  7611. this.browser_capabilities = function()
  7612. {
  7613. if (!this.env.browser_capabilities)
  7614. return '';
  7615. var n, ret = [];
  7616. for (n in this.env.browser_capabilities)
  7617. ret.push(n + '=' + this.env.browser_capabilities[n]);
  7618. return ret.join();
  7619. };
  7620. this.tiff_support_check = function()
  7621. {
  7622. this.image_support_check('tiff');
  7623. return 0;
  7624. };
  7625. this.webp_support_check = function()
  7626. {
  7627. this.image_support_check('webp');
  7628. return 0;
  7629. };
  7630. this.image_support_check = function(type)
  7631. {
  7632. window.setTimeout(function() {
  7633. var img = new Image();
  7634. img.onload = function() { ref.env.browser_capabilities[type] = 1; };
  7635. img.onerror = function() { ref.env.browser_capabilities[type] = 0; };
  7636. img.src = ref.assets_path('program/resources/blank.' + type);
  7637. }, 10);
  7638. };
  7639. this.pdf_support_check = function()
  7640. {
  7641. var i, plugin = navigator.mimeTypes ? navigator.mimeTypes["application/pdf"] : {},
  7642. plugins = navigator.plugins,
  7643. len = plugins.length,
  7644. regex = /Adobe Reader|PDF|Acrobat/i;
  7645. if (plugin && plugin.enabledPlugin)
  7646. return 1;
  7647. if ('ActiveXObject' in window) {
  7648. try {
  7649. if (plugin = new ActiveXObject("AcroPDF.PDF"))
  7650. return 1;
  7651. }
  7652. catch (e) {}
  7653. try {
  7654. if (plugin = new ActiveXObject("PDF.PdfCtrl"))
  7655. return 1;
  7656. }
  7657. catch (e) {}
  7658. }
  7659. for (i=0; i<len; i++) {
  7660. plugin = plugins[i];
  7661. if (typeof plugin === 'String') {
  7662. if (regex.test(plugin))
  7663. return 1;
  7664. }
  7665. else if (plugin.name && regex.test(plugin.name))
  7666. return 1;
  7667. }
  7668. window.setTimeout(function() {
  7669. $('<object>').attr({
  7670. data: ref.assets_path('program/resources/dummy.pdf'),
  7671. type: 'application/pdf',
  7672. style: 'position: "absolute"; top: -1000px; height: 1px'
  7673. })
  7674. .on('load error', function(e) {
  7675. ref.env.browser_capabilities.pdf = e.type == 'load' ? 1 : 0;
  7676. $(this).remove();
  7677. })
  7678. .appendTo($('body'));
  7679. }, 10);
  7680. return 0;
  7681. };
  7682. this.flash_support_check = function()
  7683. {
  7684. var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/x-shockwave-flash"] : {};
  7685. if (plugin && plugin.enabledPlugin)
  7686. return 1;
  7687. if ('ActiveXObject' in window) {
  7688. try {
  7689. if (plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))
  7690. return 1;
  7691. }
  7692. catch (e) {}
  7693. }
  7694. return 0;
  7695. };
  7696. this.assets_path = function(path)
  7697. {
  7698. if (this.env.assets_path && !path.startsWith(this.env.assets_path)) {
  7699. path = this.env.assets_path + path;
  7700. }
  7701. return path;
  7702. };
  7703. // Cookie setter
  7704. this.set_cookie = function(name, value, expires)
  7705. {
  7706. setCookie(name, value, expires, this.env.cookie_path, this.env.cookie_domain, this.env.cookie_secure);
  7707. };
  7708. this.get_local_storage_prefix = function()
  7709. {
  7710. if (!this.local_storage_prefix)
  7711. this.local_storage_prefix = 'roundcube.' + (this.env.user_id || 'anonymous') + '.';
  7712. return this.local_storage_prefix;
  7713. };
  7714. // wrapper for localStorage.getItem(key)
  7715. this.local_storage_get_item = function(key, deflt, encrypted)
  7716. {
  7717. var item, result;
  7718. // TODO: add encryption
  7719. try {
  7720. item = localStorage.getItem(this.get_local_storage_prefix() + key);
  7721. result = JSON.parse(item);
  7722. }
  7723. catch (e) { }
  7724. return result || deflt || null;
  7725. };
  7726. // wrapper for localStorage.setItem(key, data)
  7727. this.local_storage_set_item = function(key, data, encrypted)
  7728. {
  7729. // try/catch to handle no localStorage support, but also error
  7730. // in Safari-in-private-browsing-mode where localStorage exists
  7731. // but can't be used (#1489996)
  7732. try {
  7733. // TODO: add encryption
  7734. localStorage.setItem(this.get_local_storage_prefix() + key, JSON.stringify(data));
  7735. return true;
  7736. }
  7737. catch (e) {
  7738. return false;
  7739. }
  7740. };
  7741. // wrapper for localStorage.removeItem(key)
  7742. this.local_storage_remove_item = function(key)
  7743. {
  7744. try {
  7745. localStorage.removeItem(this.get_local_storage_prefix() + key);
  7746. return true;
  7747. }
  7748. catch (e) {
  7749. return false;
  7750. }
  7751. };
  7752. this.print_dialog = function()
  7753. {
  7754. if (bw.safari)
  7755. setTimeout('window.print()', 10);
  7756. else
  7757. window.print();
  7758. };
  7759. } // end object rcube_webmail
  7760. // some static methods
  7761. rcube_webmail.long_subject_title = function(elem, indent)
  7762. {
  7763. if (!elem.title) {
  7764. var $elem = $(elem);
  7765. if ($elem.width() + (indent || 0) * 15 > $elem.parent().width())
  7766. elem.title = rcube_webmail.subject_text(elem);
  7767. }
  7768. };
  7769. rcube_webmail.long_subject_title_ex = function(elem)
  7770. {
  7771. if (!elem.title) {
  7772. var $elem = $(elem),
  7773. txt = $.trim($elem.text()),
  7774. tmp = $('<span>').text(txt)
  7775. .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
  7776. 'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
  7777. .appendTo($('body')),
  7778. w = tmp.width();
  7779. tmp.remove();
  7780. if (w + $('span.branch', $elem).width() * 15 > $elem.width())
  7781. elem.title = rcube_webmail.subject_text(elem);
  7782. }
  7783. };
  7784. rcube_webmail.subject_text = function(elem)
  7785. {
  7786. var t = $(elem).clone();
  7787. t.find('.skip-on-drag,.skip-content,.voice').remove();
  7788. return t.text();
  7789. };
  7790. // set event handlers on all iframe elements (and their contents)
  7791. rcube_webmail.set_iframe_events = function(events)
  7792. {
  7793. $('iframe').each(function() {
  7794. var frame = $(this);
  7795. $.each(events, function(event_name, event_handler) {
  7796. frame.on('load', function(e) {
  7797. try { $(this).contents().on(event_name, event_handler); }
  7798. catch (e) {/* catch possible permission error in IE */ }
  7799. });
  7800. try { frame.contents().on(event_name, event_handler); }
  7801. catch (e) {/* catch possible permission error in IE */ }
  7802. });
  7803. });
  7804. };
  7805. rcube_webmail.prototype.get_cookie = getCookie;
  7806. // copy event engine prototype
  7807. rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
  7808. rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
  7809. rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;