您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

app.js 289KB

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