Kyle Francis
2016-03-30 a9d399155d205ae41015d7d205c6dacd7ecfc0d2
commit | author | age
48e9c1 1 <?php
58c279 2
AM 3 /**
48e9c1 4  +-------------------------------------------------------------------------+
T 5  | User Interface for the Enigma Plugin                                    |
6  |                                                                         |
a99c34 7  | Copyright (C) 2010-2015 The Roundcube Dev Team                          |
48e9c1 8  |                                                                         |
a99c34 9  | Licensed under the GNU General Public License version 3 or              |
AM 10  | any later version with exceptions for skins & plugins.                  |
11  | See the README file for a full license statement.                       |
48e9c1 12  |                                                                         |
T 13  +-------------------------------------------------------------------------+
14  | Author: Aleksander Machniak <alec@alec.pl>                              |
15  +-------------------------------------------------------------------------+
16 */
17
18 class enigma_ui
19 {
20     private $rc;
21     private $enigma;
22     private $home;
0878c8 23     private $css_loaded;
AM 24     private $js_loaded;
48e9c1 25     private $data;
0878c8 26     private $keys_parts  = array();
AM 27     private $keys_bodies = array();
48e9c1 28
T 29
30     function __construct($enigma_plugin, $home='')
31     {
32         $this->enigma = $enigma_plugin;
0878c8 33         $this->rc     = $enigma_plugin->rc;
AM 34         $this->home   = $home; // we cannot use $enigma_plugin->home here
48e9c1 35     }
T 36
37     /**
38      * UI initialization and requests handlers.
39      *
40      * @param string Preferences section
41      */
a99c34 42     function init()
48e9c1 43     {
0878c8 44         $this->add_js();
48e9c1 45
0878c8 46         $action = rcube_utils::get_input_value('_a', rcube_utils::INPUT_GPC);
48e9c1 47
0878c8 48         if ($this->rc->action == 'plugin.enigmakeys') {
48e9c1 49             switch ($action) {
0878c8 50                 case 'delete':
AM 51                     $this->key_delete();
52                     break;
53 /*
54                 case 'edit':
48e9c1 55                     $this->key_edit();
T 56                     break;
0878c8 57 */
AM 58                 case 'import':
48e9c1 59                     $this->key_import();
T 60                     break;
0878c8 61
211929 62                 case 'export':
AM 63                     $this->key_export();
64                     break;
65
a0dfcb 66                 case 'generate':
AM 67                     $this->key_generate();
68                     break;
69
d5501a 70                 case 'create':
AM 71                     $this->key_create();
72                     break;
73
0878c8 74                 case 'search':
AM 75                 case 'list':
48e9c1 76                     $this->key_list();
T 77                     break;
0878c8 78
AM 79                 case 'info':
48e9c1 80                     $this->key_info();
0878c8 81                     break;
48e9c1 82             }
0878c8 83
AM 84             $this->rc->output->add_handlers(array(
85                     'keyslist'     => array($this, 'tpl_keys_list'),
86                     'keyframe'     => array($this, 'tpl_key_frame'),
87                     'countdisplay' => array($this, 'tpl_keys_rowcount'),
88                     'searchform'   => array($this->rc->output, 'search_form'),
89             ));
90
91             $this->rc->output->set_pagetitle($this->enigma->gettext('enigmakeys'));
92             $this->rc->output->send('enigma.keys');
48e9c1 93         }
0878c8 94 /*
AM 95         // Preferences UI
96         else if ($this->rc->action == 'plugin.enigmacerts') {
97             $this->rc->output->add_handlers(array(
98                     'keyslist'     => array($this, 'tpl_certs_list'),
99                     'keyframe'     => array($this, 'tpl_cert_frame'),
100                     'countdisplay' => array($this, 'tpl_certs_rowcount'),
101                     'searchform'   => array($this->rc->output, 'search_form'),
102             ));
103
104             $this->rc->output->set_pagetitle($this->enigma->gettext('enigmacerts'));
105             $this->rc->output->send('enigma.certs'); 
106         }
107 */
48e9c1 108         // Message composing UI
T 109         else if ($this->rc->action == 'compose') {
110             $this->compose_ui();
111         }
112     }
113
0878c8 114     /**
48e9c1 115      * Adds CSS style file to the page header.
T 116      */
117     function add_css()
118     {
119         if ($this->css_loaded)
120             return;
121
30ceb6 122         $skin_path = $this->enigma->local_skin_path();
14ace8 123         if (is_file($this->home . "/$skin_path/enigma.css")) {
AM 124             $this->enigma->include_stylesheet("$skin_path/enigma.css");
125         }
48e9c1 126
0878c8 127         $this->css_loaded = true;
AM 128     }
129
130     /**
131      * Adds javascript file to the page header.
132      */
133     function add_js()
134     {
135         if ($this->js_loaded) {
136             return;
137         }
138
139         $this->enigma->include_script('enigma.js');
140
141         $this->js_loaded = true;
142     }
143
144     /**
145      * Initializes key password prompt
146      *
58c279 147      * @param enigma_error $status Error object with key info
AM 148      * @param array        $params Optional prompt parameters
0878c8 149      */
58c279 150     function password_prompt($status, $params = array())
0878c8 151     {
AM 152         $data = $status->getData('missing');
153
154         if (empty($data)) {
155             $data = $status->getData('bad');
156         }
157
158         $data = array('keyid' => key($data), 'user' => $data[key($data)]);
58c279 159
AM 160         if (!empty($params)) {
161             $data = array_merge($params, $data);
162         }
0878c8 163
a99c34 164         if ($this->rc->action == 'send') {
AM 165             $this->rc->output->command('enigma_password_request', $data);
166         }
167         else {
168             $this->rc->output->set_env('enigma_password_request', $data);
169         }
0878c8 170
AM 171         // add some labels to client
172         $this->rc->output->add_label('enigma.enterkeypasstitle', 'enigma.enterkeypass',
173             'save', 'cancel');
174
175         $this->add_css();
176         $this->add_js();
48e9c1 177     }
T 178
179     /**
180      * Template object for key info/edit frame.
181      *
182      * @param array Object attributes
183      *
184      * @return string HTML output
185      */
186     function tpl_key_frame($attrib)
187     {
188         if (!$attrib['id']) {
189             $attrib['id'] = 'rcmkeysframe';
190         }
191
192         $attrib['name'] = $attrib['id'];
193
194         $this->rc->output->set_env('contentframe', $attrib['name']);
a99c34 195         $this->rc->output->set_env('blankpage', $attrib['src'] ?
cfc27c 196             $this->rc->output->abs_url($attrib['src']) : 'program/resources/blank.gif');
48e9c1 197
789baa 198         return $this->rc->output->frame($attrib);
48e9c1 199     }
T 200
201     /**
202      * Template object for list of keys.
203      *
204      * @param array Object attributes
205      *
206      * @return string HTML content
207      */
208     function tpl_keys_list($attrib)
209     {
210         // add id to message list table if not specified
211         if (!strlen($attrib['id'])) {
212             $attrib['id'] = 'rcmenigmakeyslist';
213         }
214
215         // define list of cols to be displayed
216         $a_show_cols = array('name');
217
218         // create XHTML table
61be82 219         $out = $this->rc->table_output($attrib, array(), $a_show_cols, 'id');
48e9c1 220
T 221         // set client env
222         $this->rc->output->add_gui_object('keyslist', $attrib['id']);
223         $this->rc->output->include_script('list.js');
224
225         // add some labels to client
0878c8 226         $this->rc->output->add_label('enigma.keyremoveconfirm', 'enigma.keyremoving');
48e9c1 227
T 228         return $out;
229     }
230
231     /**
232      * Key listing (and searching) request handler
233      */
234     private function key_list()
235     {
236         $this->enigma->load_engine();
237
238         $pagesize = $this->rc->config->get('pagesize', 100);
61be82 239         $page     = max(intval(rcube_utils::get_input_value('_p', rcube_utils::INPUT_GPC)), 1);
AM 240         $search   = rcube_utils::get_input_value('_q', rcube_utils::INPUT_GPC);
48e9c1 241
T 242         // Get the list
243         $list = $this->enigma->engine->list_keys($search);
244
245         if ($list && ($list instanceof enigma_error))
246             $this->rc->output->show_message('enigma.keylisterror', 'error');
247         else if (empty($list))
248             $this->rc->output->show_message('enigma.nokeysfound', 'notice');
a99c34 249         else if (is_array($list)) {
AM 250             // Save the size
251             $listsize = count($list);
48e9c1 252
a99c34 253             // Sort the list by key (user) name
AM 254             usort($list, array('enigma_key', 'cmp'));
48e9c1 255
a99c34 256             // Slice current page
AM 257             $list = array_slice($list, ($page - 1) * $pagesize, $pagesize);
258             $size = count($list);
48e9c1 259
a99c34 260             // Add rows
AM 261             foreach ($list as $key) {
262                 $this->rc->output->command('enigma_add_list_row',
263                     array('name' => rcube::Q($key->name), 'id' => $key->id));
48e9c1 264             }
T 265         }
266
211929 267         $this->rc->output->set_env('rowcount', $size);
48e9c1 268         $this->rc->output->set_env('search_request', $search);
T 269         $this->rc->output->set_env('pagecount', ceil($listsize/$pagesize));
270         $this->rc->output->set_env('current_page', $page);
271         $this->rc->output->command('set_rowcount',
272             $this->get_rowcount_text($listsize, $size, $page));
273
274         $this->rc->output->send();
275     }
276
277     /**
278      * Template object for list records counter.
279      *
280      * @param array Object attributes
281      *
282      * @return string HTML output
283      */
284     function tpl_keys_rowcount($attrib)
285     {
286         if (!$attrib['id'])
287             $attrib['id'] = 'rcmcountdisplay';
288
289         $this->rc->output->add_gui_object('countdisplay', $attrib['id']);
290
291         return html::span($attrib, $this->get_rowcount_text());
292     }
293
294     /**
295      * Returns text representation of list records counter
296      */
297     private function get_rowcount_text($all=0, $curr_count=0, $page=1)
298     {
a99c34 299         if (!$curr_count) {
48e9c1 300             $out = $this->enigma->gettext('nokeysfound');
a99c34 301         }
48e9c1 302         else {
T 303             $pagesize = $this->rc->config->get('pagesize', 100);
a99c34 304             $first    = ($page - 1) * $pagesize;
48e9c1 305
T 306             $out = $this->enigma->gettext(array(
307                 'name' => 'keysfromto',
308                 'vars' => array(
309                     'from'  => $first + 1,
310                     'to'    => $first + $curr_count,
311                     'count' => $all)
312             ));
313         }
314
315         return $out;
316     }
317
318     /**
319      * Key information page handler
320      */
321     private function key_info()
322     {
323         $this->enigma->load_engine();
0878c8 324
AM 325         $id  = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GET);
48e9c1 326         $res = $this->enigma->engine->get_key($id);
T 327
0878c8 328         if ($res instanceof enigma_key) {
48e9c1 329             $this->data = $res;
0878c8 330         }
48e9c1 331         else { // error
T 332             $this->rc->output->show_message('enigma.keyopenerror', 'error');
333             $this->rc->output->command('parent.enigma_loadframe');
334             $this->rc->output->send('iframe');
335         }
336
337         $this->rc->output->add_handlers(array(
338             'keyname' => array($this, 'tpl_key_name'),
339             'keydata' => array($this, 'tpl_key_data'),
340         ));
341
342         $this->rc->output->set_pagetitle($this->enigma->gettext('keyinfo'));
343         $this->rc->output->send('enigma.keyinfo');
344     }
345
346     /**
347      * Template object for key name
348      */
349     function tpl_key_name($attrib)
350     {
61be82 351         return rcube::Q($this->data->name);
48e9c1 352     }
T 353
354     /**
355      * Template object for key information page content
356      */
357     function tpl_key_data($attrib)
358     {
58c279 359         $out   = '';
13eb9b 360         $table = new html_table(array('cols' => 2));
48e9c1 361
T 362         // Key user ID
363         $table->add('title', $this->enigma->gettext('keyuserid'));
61be82 364         $table->add(null, rcube::Q($this->data->name));
58c279 365
48e9c1 366         // Key ID
T 367         $table->add('title', $this->enigma->gettext('keyid'));
368         $table->add(null, $this->data->subkeys[0]->get_short_id());
58c279 369
48e9c1 370         // Key type
T 371         $keytype = $this->data->get_type();
58c279 372         if ($keytype == enigma_key::TYPE_KEYPAIR) {
48e9c1 373             $type = $this->enigma->gettext('typekeypair');
58c279 374         }
AM 375         else if ($keytype == enigma_key::TYPE_PUBLIC) {
48e9c1 376             $type = $this->enigma->gettext('typepublickey');
58c279 377         }
48e9c1 378         $table->add('title', $this->enigma->gettext('keytype'));
T 379         $table->add(null, $type);
58c279 380
48e9c1 381         // Key fingerprint
T 382         $table->add('title', $this->enigma->gettext('fingerprint'));
383         $table->add(null, $this->data->subkeys[0]->get_fingerprint());
384
385         $out .= html::tag('fieldset', null,
386             html::tag('legend', null,
387                 $this->enigma->gettext('basicinfo')) . $table->show($attrib));
13eb9b 388
48e9c1 389         // Subkeys
13eb9b 390         $table = new html_table(array('cols' => 5, 'id' => 'enigmasubkeytable', 'class' => 'records-table'));
AM 391
392         $table->add_header('id', $this->enigma->gettext('subkeyid'));
393         $table->add_header('algo', $this->enigma->gettext('subkeyalgo'));
394         $table->add_header('created', $this->enigma->gettext('subkeycreated'));
395         $table->add_header('expires', $this->enigma->gettext('subkeyexpires'));
396         $table->add_header('usage', $this->enigma->gettext('subkeyusage'));
397
398         $now         = time();
399         $date_format = $this->rc->config->get('date_format', 'Y-m-d');
400         $usage_map   = array(
c85242 401             enigma_key::CAN_ENCRYPT      => $this->enigma->gettext('typeencrypt'),
AM 402             enigma_key::CAN_SIGN         => $this->enigma->gettext('typesign'),
403             enigma_key::CAN_CERTIFY      => $this->enigma->gettext('typecert'),
404             enigma_key::CAN_AUTHENTICATE => $this->enigma->gettext('typeauth'),
13eb9b 405         );
AM 406
407         foreach ($this->data->subkeys as $subkey) {
408             $algo = $subkey->get_algorithm();
409             if ($algo && $subkey->length) {
410                 $algo .= ' (' . $subkey->length . ')';
411             }
412
413             $usage = array();
414             foreach ($usage_map as $key => $text) {
415                 if ($subkey->usage & $key) {
416                     $usage[] = $text;
417                 }
418             }
419
420             $table->add('id', $subkey->get_short_id());
421             $table->add('algo', $algo);
422             $table->add('created', $subkey->created ? $this->rc->format_date($subkey->created, $date_format, false) : '');
423             $table->add('expires', $subkey->expires ? $this->rc->format_date($subkey->expires, $date_format, false) : $this->enigma->gettext('expiresnever'));
424             $table->add('usage', implode(',', $usage));
425             $table->set_row_attribs($subkey->revoked || ($subkey->expires && $subkey->expires < $now) ? 'deleted' : '');
426         }
48e9c1 427
T 428         $out .= html::tag('fieldset', null,
13eb9b 429             html::tag('legend', null,
AM 430                 $this->enigma->gettext('subkeys')) . $table->show());
48e9c1 431
T 432         // Additional user IDs
13eb9b 433         $table = new html_table(array('cols' => 2, 'id' => 'enigmausertable', 'class' => 'records-table'));
AM 434
435         $table->add_header('id', $this->enigma->gettext('userid'));
436         $table->add_header('valid', $this->enigma->gettext('uservalid'));
437
438         foreach ($this->data->users as $user) {
439             $username = $user->name;
440             if ($user->comment) {
441                 $username .= ' (' . $user->comment . ')';
442             }
443             $username .= ' <' . $user->email . '>';
444
445             $table->add('id', rcube::Q(trim($username)));
446             $table->add('valid', $this->enigma->gettext($user->valid ? 'valid' : 'unknown'));
447             $table->set_row_attribs($user->revoked || !$user->valid ? 'deleted' : '');
448         }
48e9c1 449
T 450         $out .= html::tag('fieldset', null,
13eb9b 451             html::tag('legend', null,
AM 452                 $this->enigma->gettext('userids')) . $table->show());
453
48e9c1 454         return $out;
211929 455     }
AM 456
457     /**
458      * Key(s) export handler
459      */
460     private function key_export()
461     {
4a4088 462         $this->rc->request_security_check(rcube_utils::INPUT_GET);
TB 463
211929 464         $keys   = rcube_utils::get_input_value('_keys', rcube_utils::INPUT_GPC);
AM 465         $engine = $this->enigma->load_engine();
466         $list   = $keys == '*' ? $engine->list_keys() : explode(',', $keys);
467
468         if (is_array($list)) {
469             $filename = 'export.pgp';
470             if (count($list) == 1) {
471                 $filename = (is_object($list[0]) ? $list[0]->id : $list[0]) . '.pgp';
472             }
473
474             // send downlaod headers
475             header('Content-Type: application/pgp-keys');
476             header('Content-Disposition: attachment; filename="' . $filename . '"');
477
478             if ($fp = fopen('php://output', 'w')) {
479                 foreach ($list as $key) {
480                     $engine->export_key(is_object($key) ? $key->id : $key, $fp);
481                 }
482             }
483         }
484
485         exit;
48e9c1 486     }
T 487
488     /**
d5501a 489      * Key import (page) handler
48e9c1 490      */
T 491     private function key_import()
492     {
493         // Import process
d5501a 494         if ($data = rcube_utils::get_input_value('_keys', rcube_utils::INPUT_POST)) {
AM 495             // Import from generation form (ajax request)
496             $this->enigma->load_engine();
497             $result = $this->enigma->engine->import_key($data);
498
499             if (is_array($result)) {
500                 $this->rc->output->command('enigma_key_create_success');
501                 $this->rc->output->show_message('enigma.keygeneratesuccess', 'confirmation');
502             }
503             else {
504                 $this->rc->output->show_message('enigma.keysimportfailed', 'error');
505             }
506
507             $this->rc->output->send();
508         }
509         else if ($_FILES['_file']['tmp_name'] && is_uploaded_file($_FILES['_file']['tmp_name'])) {
48e9c1 510             $this->enigma->load_engine();
T 511             $result = $this->enigma->engine->import_key($_FILES['_file']['tmp_name'], true);
512
513             if (is_array($result)) {
514                 // reload list if any keys has been added
515                 if ($result['imported']) {
516                     $this->rc->output->command('parent.enigma_list', 1);
517                 }
d5501a 518                 else {
48e9c1 519                     $this->rc->output->command('parent.enigma_loadframe');
d5501a 520                 }
48e9c1 521
T 522                 $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation',
523                     array('new' => $result['imported'], 'old' => $result['unchanged']));
524
525                 $this->rc->output->send('iframe');
526             }
0878c8 527             else {
48e9c1 528                 $this->rc->output->show_message('enigma.keysimportfailed', 'error');
0878c8 529             }
48e9c1 530         }
T 531         else if ($err = $_FILES['_file']['error']) {
532             if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
533                 $this->rc->output->show_message('filesizeerror', 'error',
61be82 534                     array('size' => $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize')))));
48e9c1 535             } else {
T 536                 $this->rc->output->show_message('fileuploaderror', 'error');
537             }
538         }
539
540         $this->rc->output->add_handlers(array(
541             'importform' => array($this, 'tpl_key_import_form'),
542         ));
543
544         $this->rc->output->set_pagetitle($this->enigma->gettext('keyimport'));
545         $this->rc->output->send('enigma.keyimport');
546     }
547
548     /**
549      * Template object for key import (upload) form
550      */
551     function tpl_key_import_form($attrib)
552     {
553         $attrib += array('id' => 'rcmKeyImportForm');
554
555         $upload = new html_inputfield(array('type' => 'file', 'name' => '_file',
556             'id' => 'rcmimportfile', 'size' => 30));
557
558         $form = html::p(null,
61be82 559             rcube::Q($this->enigma->gettext('keyimporttext'), 'show')
48e9c1 560             . html::br() . html::br() . $upload->show()
T 561         );
562
563         $this->rc->output->add_label('selectimportfile', 'importwait');
564         $this->rc->output->add_gui_object('importform', $attrib['id']);
565
566         $out = $this->rc->output->form_tag(array(
0878c8 567             'action' => $this->rc->url(array('action' => $this->rc->action, 'a' => 'import')),
48e9c1 568             'method' => 'post',
T 569             'enctype' => 'multipart/form-data') + $attrib,
570             $form);
571
572         return $out;
573     }
574
0878c8 575     /**
a0dfcb 576      * Server-side key pair generation handler
AM 577      */
578     private function key_generate()
579     {
580         $user = rcube_utils::get_input_value('_user', rcube_utils::INPUT_POST, true);
581         $pass = rcube_utils::get_input_value('_password', rcube_utils::INPUT_POST, true);
582         $size = (int) rcube_utils::get_input_value('_size', rcube_utils::INPUT_POST);
583
584         if ($size > 4096) {
585             $size = 4096;
586         }
587
588         $ident = rcube_mime::decode_address_list($user, 1, false);
589
590         if (empty($ident)) {
591             $this->rc->output->show_message('enigma.keygenerateerror', 'error');
592             $this->rc->output->send();
593         }
594
595         $this->enigma->load_engine();
596         $result = $this->enigma->engine->generate_key(array(
597             'user'     => $ident[1]['name'],
598             'email'    => $ident[1]['mailto'],
599             'password' => $pass,
600             'size'     => $size,
601         ));
602
603         if ($result instanceof enigma_key) {
604             $this->rc->output->command('enigma_key_create_success');
605             $this->rc->output->show_message('enigma.keygeneratesuccess', 'confirmation');
606         }
607         else {
608             $this->rc->output->show_message('enigma.keygenerateerror', 'error');
609         }
610
611         $this->rc->output->send();
612     }
613
614     /**
d5501a 615      * Key generation page handler
AM 616      */
617     private function key_create()
618     {
619         $this->enigma->include_script('openpgp.min.js');
620
621         $this->rc->output->add_handlers(array(
622             'keyform' => array($this, 'tpl_key_create_form'),
623         ));
a0dfcb 624
AM 625         $this->rc->output->set_env('enigma_keygen_server', $this->rc->config->get('enigma_keygen_server'));
d5501a 626
AM 627         $this->rc->output->set_pagetitle($this->enigma->gettext('keygenerate'));
628         $this->rc->output->send('enigma.keycreate');
629     }
630
631     /**
632      * Template object for key generation form
633      */
634     function tpl_key_create_form($attrib)
635     {
636         $attrib += array('id' => 'rcmKeyCreateForm');
637         $table  = new html_table(array('cols' => 2));
638
639         // get user's identities
640         $identities = $this->rc->user->list_identities(null, true);
641
642         // Identity
643         $select = new html_select(array('name' => 'identity', 'id' => 'key-ident'));
644         foreach ((array) $identities as $idx => $ident) {
645             $name = empty($ident['name']) ? ('<' . $ident['email'] . '>') : $ident['ident'];
646             $select->add($name, $idx);
647         }
648
649         $table->add('title', html::label('key-name', rcube::Q($this->enigma->gettext('newkeyident'))));
650         $table->add(null, $select->show(0));
651
652         // Key size
653         $select = new html_select(array('name' => 'size', 'id' => 'key-size'));
654         $select->add($this->enigma->gettext('key2048'), '2048');
655         $select->add($this->enigma->gettext('key4096'), '4096');
656
657         $table->add('title', html::label('key-size', rcube::Q($this->enigma->gettext('newkeysize'))));
658         $table->add(null, $select->show());
659
660         // Password and confirm password
661         $table->add('title', html::label('key-pass', rcube::Q($this->enigma->gettext('newkeypass'))));
662         $table->add(null, rcube_output::get_edit_field('password', '',
663             array('id' => 'key-pass', 'size' => $attrib['size'], 'required' => true), 'password'));
664
665         $table->add('title', html::label('key-pass-confirm', rcube::Q($this->enigma->gettext('newkeypassconfirm'))));
666         $table->add(null, rcube_output::get_edit_field('password-confirm', '',
667             array('id' => 'key-pass-confirm', 'size' => $attrib['size'], 'required' => true), 'password'));
668
669         $this->rc->output->add_gui_object('keyform', $attrib['id']);
670         $this->rc->output->add_label('enigma.keygenerating', 'enigma.formerror',
a0dfcb 671             'enigma.passwordsdiffer', 'enigma.keygenerateerror', 'enigma.nonameident',
AM 672             'enigma.keygennosupport');
d5501a 673
AM 674         return $this->rc->output->form_tag(array(), $table->show($attrib));
675     }
676
677     /**
0878c8 678      * Key deleting
AM 679      */
680     private function key_delete()
681     {
211929 682         $keys   = rcube_utils::get_input_value('_keys', rcube_utils::INPUT_POST);
AM 683         $engine = $this->enigma->load_engine();
0878c8 684
AM 685         foreach ((array)$keys as $key) {
211929 686             $res = $engine->delete_key($key);
0878c8 687
AM 688             if ($res !== true) {
689                 $this->rc->output->show_message('enigma.keyremoveerror', 'error');
690                 $this->rc->output->command('enigma_list');
691                 $this->rc->output->send();
692             }
693         }
694
695         $this->rc->output->command('enigma_list');
696         $this->rc->output->show_message('enigma.keyremovesuccess', 'confirmation');
697         $this->rc->output->send();
698     }
699
58c279 700     /**
AM 701      * Init compose UI (add task button and the menu)
702      */
48e9c1 703     private function compose_ui()
T 704     {
0878c8 705         $this->add_css();
AM 706
48e9c1 707         // Options menu button
T 708         $this->enigma->add_button(array(
0878c8 709             'type'     => 'link',
AM 710             'command'  => 'plugin.enigma',
711             'onclick'  => "rcmail.command('menu-open', 'enigmamenu', event.target, event)",
712             'class'    => 'button enigma',
a99c34 713             'title'    => 'encryptionoptions',
AM 714             'label'    => 'encryption',
0878c8 715             'domain'   => $this->enigma->ID,
AM 716             'width'    => 32,
717             'height'   => 32
48e9c1 718             ), 'toolbar');
T 719
a99c34 720         $menu  = new html_table(array('cols' => 2));
48e9c1 721         $chbox = new html_checkbox(array('value' => 1));
T 722
723         $menu->add(null, html::label(array('for' => 'enigmasignopt'),
61be82 724             rcube::Q($this->enigma->gettext('signmsg'))));
a99c34 725         $menu->add(null, $chbox->show($this->rc->config->get('enigma_sign_all') ? 1 : 0,
AM 726             array('name' => '_enigma_sign', 'id' => 'enigmasignopt')));
48e9c1 727
a99c34 728         $menu->add(null, html::label(array('for' => 'enigmaencryptopt'),
61be82 729             rcube::Q($this->enigma->gettext('encryptmsg'))));
a99c34 730         $menu->add(null, $chbox->show($this->rc->config->get('enigma_encrypt_all') ? 1 : 0,
AM 731             array('name' => '_enigma_encrypt', 'id' => 'enigmaencryptopt')));
48e9c1 732
58c279 733         $menu = html::div(array('id' => 'enigmamenu', 'class' => 'popupmenu'), $menu->show());
48e9c1 734
58c279 735         // Options menu contents
AM 736         $this->rc->output->add_footer($menu);
0878c8 737     }
48e9c1 738
0878c8 739     /**
AM 740      * Handler for message_body_prefix hook.
741      * Called for every displayed (content) part of the message.
742      * Adds infobox about signature verification and/or decryption
743      * status above the body.
744      *
745      * @param array Original parameters
746      *
747      * @return array Modified parameters
748      */
749     function status_message($p)
750     {
751         // skip: not a message part
752         if ($p['part'] instanceof rcube_message) {
753             return $p;
754         }
755
756         // skip: message has no signed/encoded content
757         if (!$this->enigma->engine) {
758             return $p;
759         }
760
c1a518 761         $engine  = $this->enigma->engine;
AM 762         $part_id = $p['part']->mime_id;
0878c8 763
AM 764         // Decryption status
c1a518 765         if (($found = $this->find_part_id($part_id, $engine->decryptions)) !== null
AM 766             && ($status = $engine->decryptions[$found])
c9e2ab 767         ) {
0878c8 768             $attach_scripts = true;
AM 769
c9e2ab 770             // show the message only once
c1a518 771             unset($engine->decryptions[$found]);
0878c8 772
AM 773             // display status info
774             $attrib['id'] = 'enigma-message';
775
776             if ($status instanceof enigma_error) {
777                 $attrib['class'] = 'enigmaerror';
778                 $code            = $status->getCode();
779
cffe97 780                 if ($code == enigma_error::KEYNOTFOUND) {
0878c8 781                     $msg = rcube::Q(str_replace('$keyid', enigma_key::format_id($status->getData('id')),
AM 782                         $this->enigma->gettext('decryptnokey')));
783                 }
cffe97 784                 else if ($code == enigma_error::BADPASS) {
5a3065 785                     $missing = $status->getData('missing');
AM 786                     $label   = 'decrypt' . (!empty($missing) ? 'no' : 'bad') . 'pass';
787                     $msg     = rcube::Q($this->enigma->gettext($label));
0878c8 788                     $this->password_prompt($status);
AM 789                 }
790                 else {
791                     $msg = rcube::Q($this->enigma->gettext('decrypterror'));
792                 }
793             }
007c9d 794             else if ($status === enigma_engine::ENCRYPTED_PARTIALLY) {
AM 795                 $attrib['class'] = 'enigmawarning';
796                 $msg = rcube::Q($this->enigma->gettext('decryptpartial'));
797             }
0878c8 798             else {
AM 799                 $attrib['class'] = 'enigmanotice';
800                 $msg = rcube::Q($this->enigma->gettext('decryptok'));
801             }
802
803             $p['prefix'] .= html::div($attrib, $msg);
804         }
805
806         // Signature verification status
8c626e 807         if (($found = $this->find_part_id($part_id, $engine->signatures)) !== null
AM 808             && ($sig = $engine->signatures[$found])
0878c8 809         ) {
AM 810             $attach_scripts = true;
c1a518 811
AM 812             // show the message only once
8c626e 813             unset($engine->signatures[$found]);
0878c8 814
AM 815             // display status info
816             $attrib['id'] = 'enigma-message';
817
818             if ($sig instanceof enigma_signature) {
819                 $sender = ($sig->name ? $sig->name . ' ' : '') . '<' . $sig->email . '>';
820
cffe97 821                 if ($sig->valid === enigma_error::UNVERIFIED) {
0878c8 822                     $attrib['class'] = 'enigmawarning';
AM 823                     $msg = str_replace('$sender', $sender, $this->enigma->gettext('sigunverified'));
824                     $msg = str_replace('$keyid', $sig->id, $msg);
825                     $msg = rcube::Q($msg);
826                 }
827                 else if ($sig->valid) {
007c9d 828                     $attrib['class'] = $sig->partial ? 'enigmawarning' : 'enigmanotice';
AM 829                     $label = 'sigvalid' . ($sig->partial ? 'partial' : '');
830                     $msg = rcube::Q(str_replace('$sender', $sender, $this->enigma->gettext($label)));
0878c8 831                 }
AM 832                 else {
833                     $attrib['class'] = 'enigmawarning';
834                     $msg = rcube::Q(str_replace('$sender', $sender, $this->enigma->gettext('siginvalid')));
835                 }
836             }
cffe97 837             else if ($sig && $sig->getCode() == enigma_error::KEYNOTFOUND) {
0878c8 838                 $attrib['class'] = 'enigmawarning';
AM 839                 $msg = rcube::Q(str_replace('$keyid', enigma_key::format_id($sig->getData('id')),
840                     $this->enigma->gettext('signokey')));
841             }
842             else {
843                 $attrib['class'] = 'enigmaerror';
844                 $msg = rcube::Q($this->enigma->gettext('sigerror'));
845             }
846 /*
847             $msg .= '&nbsp;' . html::a(array('href' => "#sigdetails",
848                 'onclick' => rcmail_output::JS_OBJECT_NAME.".command('enigma-sig-details')"),
849                 rcube::Q($this->enigma->gettext('showdetails')));
850 */
851             // test
852 //            $msg .= '<br /><pre>'.$sig->body.'</pre>';
853
854             $p['prefix'] .= html::div($attrib, $msg);
855         }
856
857         if ($attach_scripts) {
858             // add css and js script
859             $this->add_css();
860             $this->add_js();
861         }
862
863         return $p;
864     }
865
866     /**
867      * Handler for message_load hook.
868      * Check message bodies and attachments for keys/certs.
869      */
870     function message_load($p)
871     {
872         $engine = $this->enigma->load_engine();
873
58c279 874         // handle keys/certs in attachments
0878c8 875         foreach ((array) $p['object']->attachments as $attachment) {
AM 876             if ($engine->is_keys_part($attachment)) {
877                 $this->keys_parts[] = $attachment->mime_id;
878             }
879         }
880
881         // the same with message bodies
882         foreach ((array) $p['object']->parts as $part) {
883             if ($engine->is_keys_part($part)) {
884                 $this->keys_parts[]  = $part->mime_id;
885                 $this->keys_bodies[] = $part->mime_id;
886             }
887         }
888
889         // @TODO: inline PGP keys
890
891         if ($this->keys_parts) {
892             $this->enigma->add_texts('localization');
893         }
894
895         return $p;
896     }
897
898     /**
899      * Handler for template_object_messagebody hook.
900      * This callback function adds a box below the message content
901      * if there is a key/cert attachment available
902      */
903     function message_output($p)
904     {
905         foreach ($this->keys_parts as $part) {
906             // remove part's body
907             if (in_array($part, $this->keys_bodies)) {
908                 $p['content'] = '';
909             }
910
911             // add box below message body
912             $p['content'] .= html::p(array('class' => 'enigmaattachment'),
913                 html::a(array(
914                     'href'    => "#",
915                     'onclick' => "return ".rcmail_output::JS_OBJECT_NAME.".enigma_import_attachment('".rcube::JQ($part)."')",
916                     'title'   => $this->enigma->gettext('keyattimport')),
917                     html::span(null, $this->enigma->gettext('keyattfound'))));
918
919             $attach_scripts = true;
920         }
921
922         if ($attach_scripts) {
923             // add css and js script
924             $this->add_css();
925             $this->add_js();
926         }
927
928         return $p;
48e9c1 929     }
T 930
a99c34 931     /**
a9d399 932      * Handle message_ready hook (encryption/signing/attach public key)
a99c34 933      */
AM 934     function message_ready($p)
935     {
936         $savedraft = !empty($_POST['_draft']) && empty($_GET['_saveonly']);
a9d399 937
KF 938         if (!$savedraft && rcube_utils::get_input_value('_enigma_attachpubkey', rcube_utils::INPUT_POST)) {
939             $p = $this->attach_public($p);
940         }
a99c34 941
AM 942         if (!$savedraft && rcube_utils::get_input_value('_enigma_sign', rcube_utils::INPUT_POST)) {
943             $this->enigma->load_engine();
944             $status = $this->enigma->engine->sign_message($p['message']);
945             $mode   = 'sign';
946         }
947
948         if ((!$status instanceof enigma_error) && rcube_utils::get_input_value('_enigma_encrypt', rcube_utils::INPUT_POST)) {
949             $this->enigma->load_engine();
950             $status = $this->enigma->engine->encrypt_message($p['message'], null, $savedraft);
951             $mode   = 'encrypt';
952         }
953
954         if ($mode && ($status instanceof enigma_error)) {
955             $code = $status->getCode();
956
cffe97 957             if ($code == enigma_error::KEYNOTFOUND) {
a99c34 958                 $vars = array('email' => $status->getData('missing'));
AM 959                 $msg  = 'enigma.' . $mode . 'nokey';
960             }
cffe97 961             else if ($code == enigma_error::BADPASS) {
a99c34 962                 $this->password_prompt($status);
AM 963             }
964             else {
965                 $msg = 'enigma.' . $mode . 'error';
966             }
967
5a3065 968             if ($msg) {
AM 969                 $this->rc->output->show_message($msg, $type ?: 'error', $vars);
970             }
971
a99c34 972             $this->rc->output->send('iframe');
AM 973         }
974
975         return $p;
976     }
977
58c279 978     /**
a9d399 979      * Add sender's public key (PGP).
KF 980      */
981     function attach_public($p)
982     {
983         // get sender's PGP pubkey for attachment
984         $this->enigma->load_engine();
985         $key = $this->enigma->engine->list_keys($p['message']->headers()['From']);
986         $keyID = $key[0]->subkeys[0]->get_short_id();
987         $pubkey_armor = $this->enigma->engine->get_gpg_pubkey_for_attach($p['message']->headers()['From']);
988
989         if(!$pubkey_armor instanceof enigma_error) {
990             $p['message']->addAttachment($pubkey_armor, 'application/pgp-keys', "0x$keyID.asc", false);
991         }
992
993         return $p;
994     }
995
996    /**
58c279 997      * Handler for message_compose_body hook
AM 998      * Display error when the message cannot be encrypted
999      * and provide a way to try again with a password.
1000      */
1001     function message_compose($p)
1002     {
1003         $engine = $this->enigma->load_engine();
1004
1005         // skip: message has no signed/encoded content
1006         if (!$this->enigma->engine) {
1007             return $p;
1008         }
1009
1010         $engine = $this->enigma->engine;
1011
1012         // Decryption status
1013         foreach ($engine->decryptions as $status) {
1014             if ($status instanceof enigma_error) {
1015                 $code = $status->getCode();
1016
cffe97 1017                 if ($code == enigma_error::KEYNOTFOUND) {
58c279 1018                     $msg = rcube::Q(str_replace('$keyid', enigma_key::format_id($status->getData('id')),
AM 1019                         $this->enigma->gettext('decryptnokey')));
1020                 }
cffe97 1021                 else if ($code == enigma_error::BADPASS) {
58c279 1022                     $this->password_prompt($status, array('compose-init' => true));
AM 1023                     return $p;
1024                 }
1025                 else {
1026                     $msg = rcube::Q($this->enigma->gettext('decrypterror'));
1027                 }
1028             }
1029         }
1030
1031         if ($msg) {
1032             $this->rc->output->show_message($msg, 'error');
1033         }
1034
f04b56 1035         // Check sign/ecrypt options for signed/encrypted drafts
AM 1036         $this->rc->output->set_env('enigma_force_encrypt', !empty($engine->decryptions));
1037         $this->rc->output->set_env('enigma_force_sign', !empty($engine->signatures));
1038
58c279 1039         return $p;
AM 1040     }
c1a518 1041
AM 1042     /**
1043      * Check if the part or its parent exists in the array
1044      * of decryptions/signatures. Returns found ID.
1045      */
1046     private function find_part_id($part_id, $data)
1047     {
1048         $ids   = explode('.', $part_id);
1049         $i     = 0;
1050         $count = count($ids);
1051
1052         while ($i < $count && strlen($part = implode('.', array_slice($ids, 0, ++$i)))) {
1053             if (array_key_exists($part, $data)) {
1054                 return $part;
1055             }
1056         }
1057     }
48e9c1 1058 }