4 * Class for operations on Sieve scripts
6 * Copyright (C) 2008-2011, The Roundcube Dev Team
7 * Copyright (C) 2011, Kolab Systems AG
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 * $Id: rcube_sieve_script.php 5452 2011-11-18 14:44:48Z alec $
26 class rcube_sieve_script
28 public $content = array(); // script rules array
30 private $vars = array(); // "global" variables
31 private $prefix = ''; // script header (comments)
32 private $supported = array( // Sieve extensions supported by class
33 'fileinto', // RFC5228
34 'envelope', // RFC5228
38 'vacation', // RFC5230
39 'relational', // RFC3431
40 'regex', // draft-ietf-sieve-regex-01
41 'imapflags', // draft-melnikov-sieve-imapflags-06
42 'imap4flags', // RFC5232
43 'include', // draft-ietf-sieve-include-12
44 'variables', // RFC5229
46 'subaddress', // RFC5233
47 // @TODO: enotify/notify, spamtest+virustest, mailbox, date
53 * @param string Script's text content
54 * @param array List of capabilities supported by server
56 public function __construct($script, $capabilities=array())
58 $capabilities = array_map('strtolower', (array) $capabilities);
60 // disable features by server capabilities
61 if (!empty($capabilities)) {
62 foreach ($this->supported as $idx => $ext) {
63 if (!in_array($ext, $capabilities)) {
64 unset($this->supported[$idx]);
69 // Parse text content of the script
70 $this->_parse_text($script);
74 * Adds rule to the script (at the end)
76 * @param string Rule name
77 * @param array Rule content (as array)
79 * @return int The index of the new rule
81 public function add_rule($content)
83 // TODO: check this->supported
84 array_push($this->content, $content);
85 return sizeof($this->content)-1;
88 public function delete_rule($index)
90 if(isset($this->content[$index])) {
91 unset($this->content[$index]);
97 public function size()
99 return sizeof($this->content);
102 public function update_rule($index, $content)
104 // TODO: check this->supported
105 if ($this->content[$index]) {
106 $this->content[$index] = $content;
113 * Sets "global" variable
115 * @param string $name Variable name
116 * @param string $value Variable value
117 * @param array $mods Variable modifiers
119 public function set_var($name, $value, $mods = array())
121 // Check if variable exists
122 for ($i=0, $len=count($this->vars); $i<$len; $i++) {
123 if ($this->vars[$i]['name'] == $name) {
128 $var = array_merge($mods, array('name' => $name, 'value' => $value));
129 $this->vars[$i] = $var;
133 * Unsets "global" variable
135 * @param string $name Variable name
137 public function unset_var($name)
139 // Check if variable exists
140 foreach ($this->vars as $idx => $var) {
141 if ($var['name'] == $name) {
142 unset($this->vars[$idx]);
149 * Gets the value of "global" variable
151 * @param string $name Variable name
153 * @return string Variable value
155 public function get_var($name)
157 // Check if variable exists
158 for ($i=0, $len=count($this->vars); $i<$len; $i++) {
159 if ($this->vars[$i]['name'] == $name) {
160 return $this->vars[$i]['name'];
166 * Sets script header content
168 * @param string $text Header content
170 public function set_prefix($text)
172 $this->prefix = $text;
176 * Returns script as text
178 public function as_text()
184 if (!empty($this->vars)) {
185 if (in_array('variables', (array)$this->supported)) {
187 array_push($exts, 'variables');
189 foreach ($this->vars as $var) {
190 if (empty($has_vars)) {
191 // 'variables' extension not supported, put vars in comments
192 $output .= sprintf("# %s %s\n", $var['name'], $var['value']);
196 foreach (array_diff(array_keys($var), array('name', 'value')) as $opt) {
199 $output .= self::escape_string($var['name']) . ' ' . self::escape_string($var['value']) . ";\n";
205 foreach ($this->content as $rule) {
212 if (!empty($rule['name']) && strlen($rule['name'])) {
213 $script .= '# rule:[' . $rule['name'] . "]\n";
216 // constraints expressions
217 if (!empty($rule['tests'])) {
218 foreach ($rule['tests'] as $test) {
220 switch ($test['test']) {
222 $tests[$i] .= ($test['not'] ? 'not ' : '');
223 $tests[$i] .= 'size :' . ($test['type']=='under' ? 'under ' : 'over ') . $test['arg'];
227 $tests[$i] .= ($test['not'] ? 'false' : 'true');
231 $tests[$i] .= ($test['not'] ? 'not ' : '');
232 $tests[$i] .= 'exists ' . self::escape_string($test['arg']);
236 $tests[$i] .= ($test['not'] ? 'not ' : '');
237 $tests[$i] .= 'header';
239 if (!empty($test['type'])) {
240 // relational operator + comparator
241 if (preg_match('/^(value|count)-([gteqnl]{2})/', $test['type'], $m)) {
242 array_push($exts, 'relational');
243 array_push($exts, 'comparator-i;ascii-numeric');
245 $tests[$i] .= ' :' . $m[1] . ' "' . $m[2] . '" :comparator "i;ascii-numeric"';
248 $this->add_comparator($test, $tests[$i], $exts);
250 if ($test['type'] == 'regex') {
251 array_push($exts, 'regex');
254 $tests[$i] .= ' :' . $test['type'];
258 $tests[$i] .= ' ' . self::escape_string($test['arg1']);
259 $tests[$i] .= ' ' . self::escape_string($test['arg2']);
264 if ($test['test'] == 'envelope') {
265 array_push($exts, 'envelope');
268 $tests[$i] .= ($test['not'] ? 'not ' : '');
269 $tests[$i] .= $test['test'];
271 if (!empty($test['part'])) {
272 $tests[$i] .= ' :' . $test['part'];
273 if ($test['part'] == 'user' || $test['part'] == 'detail') {
274 array_push($exts, 'subaddress');
278 $this->add_comparator($test, $tests[$i], $exts);
280 if (!empty($test['type'])) {
281 if ($test['type'] == 'regex') {
282 array_push($exts, 'regex');
284 $tests[$i] .= ' :' . $test['type'];
287 $tests[$i] .= ' ' . self::escape_string($test['arg1']);
288 $tests[$i] .= ' ' . self::escape_string($test['arg2']);
292 array_push($exts, 'body');
294 $tests[$i] .= ($test['not'] ? 'not ' : '') . 'body';
296 $this->add_comparator($test, $tests[$i], $exts);
298 if (!empty($test['part'])) {
299 $tests[$i] .= ' :' . $test['part'];
301 if (!empty($test['content']) && $test['part'] == 'content') {
302 $tests[$i] .= ' ' . self::escape_string($test['content']);
306 if (!empty($test['type'])) {
307 if ($test['type'] == 'regex') {
308 array_push($exts, 'regex');
310 $tests[$i] .= ' :' . $test['type'];
313 $tests[$i] .= ' ' . self::escape_string($test['arg']);
320 // disabled rule: if false #....
321 if (!empty($tests)) {
322 $script .= 'if ' . ($rule['disabled'] ? 'false # ' : '');
324 if (count($tests) > 1) {
325 $tests_str = implode(', ', $tests);
328 $tests_str = $tests[0];
331 if ($rule['join'] || count($tests) > 1) {
332 $script .= sprintf('%s (%s)', $rule['join'] ? 'allof' : 'anyof', $tests_str);
335 $script .= $tests_str;
341 if (!empty($rule['actions'])) {
342 foreach ($rule['actions'] as $action) {
345 switch ($action['type']) {
348 array_push($exts, 'fileinto');
349 $action_script .= 'fileinto ';
350 if ($action['copy']) {
351 $action_script .= ':copy ';
352 array_push($exts, 'copy');
354 $action_script .= self::escape_string($action['target']);
358 $action_script .= 'redirect ';
359 if ($action['copy']) {
360 $action_script .= ':copy ';
361 array_push($exts, 'copy');
363 $action_script .= self::escape_string($action['target']);
368 array_push($exts, $action['type']);
369 $action_script .= $action['type'].' '
370 . self::escape_string($action['target']);
376 if (in_array('imap4flags', $this->supported))
377 array_push($exts, 'imap4flags');
379 array_push($exts, 'imapflags');
381 $action_script .= $action['type'].' '
382 . self::escape_string($action['target']);
388 $action_script .= $action['type'];
392 array_push($exts, 'include');
393 $action_script .= 'include ';
394 foreach (array_diff(array_keys($action), array('target', 'type')) as $opt) {
395 $action_script .= ":$opt ";
397 $action_script .= self::escape_string($action['target']);
401 array_push($exts, 'variables');
402 $action_script .= 'set ';
403 foreach (array_diff(array_keys($action), array('name', 'value', 'type')) as $opt) {
404 $action_script .= ":$opt ";
406 $action_script .= self::escape_string($action['name']) . ' ' . self::escape_string($action['value']);
410 array_push($exts, 'vacation');
411 $action_script .= 'vacation';
412 if (!empty($action['days']))
413 $action_script .= " :days " . $action['days'];
414 if (!empty($action['addresses']))
415 $action_script .= " :addresses " . self::escape_string($action['addresses']);
416 if (!empty($action['subject']))
417 $action_script .= " :subject " . self::escape_string($action['subject']);
418 if (!empty($action['handle']))
419 $action_script .= " :handle " . self::escape_string($action['handle']);
420 if (!empty($action['from']))
421 $action_script .= " :from " . self::escape_string($action['from']);
422 if (!empty($action['mime']))
423 $action_script .= " :mime";
424 $action_script .= " " . self::escape_string($action['reason']);
428 if ($action_script) {
429 $script .= !empty($tests) ? "\t" : '';
430 $script .= $action_script . ";\n";
436 $output .= $script . (!empty($tests) ? "}\n" : '');
443 $output = 'require ["' . implode('","', array_unique($exts)) . "\"];\n" . $output;
445 if (!empty($this->prefix)) {
446 $output = $this->prefix . "\n\n" . $output;
453 * Returns script object
456 public function as_array()
458 return $this->content;
462 * Returns array of supported extensions
465 public function get_extensions()
467 return array_values($this->supported);
471 * Converts text script to rules array
473 * @param string Text script
475 private function _parse_text($script)
481 $script = trim($script);
485 while (!empty($script) && $script[0] == '#') {
486 $endl = strpos($script, "\n");
487 $line = $endl ? substr($script, 0, $endl) : $script;
490 if (preg_match('/^# rule:\[(.*)\]/', $line, $matches)) {
491 $rulename = $matches[1];
494 else if (preg_match('/^# (EDITOR|EDITOR_VERSION) (.+)$/', $line, $matches)) {
495 $this->set_var($matches[1], $matches[2]);
498 else if (!empty($options['format']) && $options['format'] == 'INGO'
499 && preg_match('/^# (.*)/', $line, $matches)
501 $rulename = $matches[1];
503 else if (empty($options['prefix'])) {
504 $prefix .= $line . "\n";
507 $script = ltrim(substr($script, strlen($line) + 1));
510 // handle script header
511 if (empty($options['prefix'])) {
512 $options['prefix'] = true;
513 if ($prefix && strpos($prefix, 'horde.org/ingo')) {
514 $options['format'] = 'INGO';
518 // Control structures/blocks
519 if (preg_match('/^(if|else|elsif)/i', $script)) {
520 $rule = $this->_tokenize_rule($script);
521 if (strlen($rulename) && !empty($rule)) {
522 $rule['name'] = $rulename;
527 $rule = $this->_parse_actions($script, ';');
528 if (!empty($rule[0]) && is_array($rule)) {
529 // set "global" variables
530 if ($rule[0]['type'] == 'set') {
531 unset($rule[0]['type']);
532 $this->vars[] = $rule[0];
535 $rule = array('actions' => $rule);
543 $this->content[] = $rule;
547 if (!empty($prefix)) {
548 $this->prefix = trim($prefix);
553 * Convert text script fragment to rule object
555 * @param string Text rule
557 * @return array Rule data
559 private function _tokenize_rule(&$content)
561 $cond = strtolower(self::tokenize($content, 1));
563 if ($cond != 'if' && $cond != 'elsif' && $cond != 'else') {
570 // disabled rule (false + comment): if false # .....
571 if (preg_match('/^\s*false\s+#/i', $content)) {
572 $content = preg_replace('/^\s*false\s+#\s*/i', '', $content);
576 while (strlen($content)) {
577 $tokens = self::tokenize($content, true);
578 $separator = array_pop($tokens);
580 if (!empty($tokens)) {
581 $token = array_shift($tokens);
587 $token = strtolower($token);
589 if ($token == 'not') {
591 $token = strtolower(array_shift($tokens));
605 $size = array('test' => 'size', 'not' => $not);
606 for ($i=0, $len=count($tokens); $i<$len; $i++) {
607 if (!is_array($tokens[$i])
608 && preg_match('/^:(under|over)$/i', $tokens[$i])
610 $size['type'] = strtolower(substr($tokens[$i], 1));
613 $size['arg'] = $tokens[$i];
621 $header = array('test' => 'header', 'not' => $not, 'arg1' => '', 'arg2' => '');
622 for ($i=0, $len=count($tokens); $i<$len; $i++) {
623 if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
624 $header['comparator'] = $tokens[++$i];
626 else if (!is_array($tokens[$i]) && preg_match('/^:(count|value)$/i', $tokens[$i])) {
627 $header['type'] = strtolower(substr($tokens[$i], 1)) . '-' . $tokens[++$i];
629 else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
630 $header['type'] = strtolower(substr($tokens[$i], 1));
633 $header['arg1'] = $header['arg2'];
634 $header['arg2'] = $tokens[$i];
643 $header = array('test' => $token, 'not' => $not, 'arg1' => '', 'arg2' => '');
644 for ($i=0, $len=count($tokens); $i<$len; $i++) {
645 if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
646 $header['comparator'] = $tokens[++$i];
648 else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
649 $header['type'] = strtolower(substr($tokens[$i], 1));
651 else if (!is_array($tokens[$i]) && preg_match('/^:(localpart|domain|all|user|detail)$/i', $tokens[$i])) {
652 $header['part'] = strtolower(substr($tokens[$i], 1));
655 $header['arg1'] = $header['arg2'];
656 $header['arg2'] = $tokens[$i];
664 $header = array('test' => 'body', 'not' => $not, 'arg' => '');
665 for ($i=0, $len=count($tokens); $i<$len; $i++) {
666 if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
667 $header['comparator'] = $tokens[++$i];
669 else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
670 $header['type'] = strtolower(substr($tokens[$i], 1));
672 else if (!is_array($tokens[$i]) && preg_match('/^:(raw|content|text)$/i', $tokens[$i])) {
673 $header['part'] = strtolower(substr($tokens[$i], 1));
675 if ($header['part'] == 'content') {
676 $header['content'] = $tokens[++$i];
680 $header['arg'] = $tokens[$i];
688 $tests[] = array('test' => 'exists', 'not' => $not,
689 'arg' => array_pop($tokens));
693 $tests[] = array('test' => 'true', 'not' => $not);
697 $tests[] = array('test' => 'true', 'not' => !$not);
702 if ($separator == '{') {
707 // ...and actions block
708 $actions = $this->_parse_actions($content);
710 if ($tests && $actions) {
714 'actions' => $actions,
716 'disabled' => $disabled,
724 * Parse body of actions section
726 * @param string $content Text body
727 * @param string $end End of text separator
729 * @return array Array of parsed action type/target pairs
731 private function _parse_actions(&$content, $end = '}')
735 while (strlen($content)) {
736 $tokens = self::tokenize($content, true);
737 $separator = array_pop($tokens);
739 if (!empty($tokens)) {
740 $token = array_shift($tokens);
750 $result[] = array('type' => $token);
758 for ($i=0, $len=count($tokens); $i<$len; $i++) {
759 if (strtolower($tokens[$i]) == ':copy') {
763 $target = $tokens[$i];
767 $result[] = array('type' => $token, 'copy' => $copy,
768 'target' => $target);
773 $result[] = array('type' => $token, 'target' => array_pop($tokens));
777 $vacation = array('type' => 'vacation', 'reason' => array_pop($tokens));
779 for ($i=0, $len=count($tokens); $i<$len; $i++) {
780 $tok = strtolower($tokens[$i]);
781 if ($tok == ':days') {
782 $vacation['days'] = $tokens[++$i];
784 else if ($tok == ':subject') {
785 $vacation['subject'] = $tokens[++$i];
787 else if ($tok == ':addresses') {
788 $vacation['addresses'] = $tokens[++$i];
790 else if ($tok == ':handle') {
791 $vacation['handle'] = $tokens[++$i];
793 else if ($tok == ':from') {
794 $vacation['from'] = $tokens[++$i];
796 else if ($tok == ':mime') {
797 $vacation['mime'] = true;
801 $result[] = $vacation;
807 $result[] = array('type' => $token,
808 // Flags list: last token (skip optional variable)
809 'target' => $tokens[count($tokens)-1]
814 $include = array('type' => 'include', 'target' => array_pop($tokens));
816 // Parameters: :once, :optional, :global, :personal
817 for ($i=0, $len=count($tokens); $i<$len; $i++) {
818 $tok = strtolower($tokens[$i]);
819 if ($tok[0] == ':') {
820 $include[substr($tok, 1)] = true;
824 $result[] = $include;
828 $set = array('type' => 'set', 'value' => array_pop($tokens), 'name' => array_pop($tokens));
830 // Parameters: :lower :upper :lowerfirst :upperfirst :quotewildcard :length
831 for ($i=0, $len=count($tokens); $i<$len; $i++) {
832 $tok = strtolower($tokens[$i]);
833 if ($tok[0] == ':') {
834 $set[substr($tok, 1)] = true;
842 // skip, will be build according to used commands
843 // $result[] = array('type' => 'require', 'target' => $tokens);
848 if ($separator == $end)
858 private function add_comparator($test, &$out, &$exts)
860 if (empty($test['comparator'])) {
864 if ($test['comparator'] == 'i;ascii-numeric') {
865 array_push($exts, 'relational');
866 array_push($exts, 'comparator-i;ascii-numeric');
868 else if (!in_array($test['comparator'], array('i;octet', 'i;ascii-casemap'))) {
869 array_push($exts, 'comparator-' . $test['comparator']);
872 // skip default comparator
873 if ($test['comparator'] != 'i;ascii-casemap') {
874 $out .= ' :comparator ' . self::escape_string($test['comparator']);
879 * Escape special chars into quoted string value or multi-line string
882 * @param string $str Text or array (list) of strings
884 * @return string Result text
886 static function escape_string($str)
888 if (is_array($str) && count($str) > 1) {
889 foreach($str as $idx => $val)
890 $str[$idx] = self::escape_string($val);
892 return '[' . implode(',', $str) . ']';
894 else if (is_array($str)) {
895 $str = array_pop($str);
899 if (preg_match('/[\r\n\0]/', $str) || strlen($str) > 1024) {
900 return sprintf("text:\n%s\n.\n", self::escape_multiline_string($str));
904 return '"' . addcslashes($str, '\\"') . '"';
909 * Escape special chars in multi-line string value
911 * @param string $str Text
913 * @return string Text
915 static function escape_multiline_string($str)
917 $str = preg_split('/(\r?\n)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
919 foreach ($str as $idx => $line) {
921 if (isset($line[0]) && $line[0] == '.') {
922 $str[$idx] = '.' . $line;
926 return implode($str);
930 * Splits script into string tokens
932 * @param string &$str The script
933 * @param mixed $num Number of tokens to return, 0 for all
934 * or True for all tokens until separator is found.
935 * Separator will be returned as last token.
936 * @param int $in_list Enable to call recursively inside a list
938 * @return mixed Tokens array or string if $num=1
940 static function tokenize(&$str, $num=0, $in_list=false)
944 // remove spaces from the beginning of the string
945 while (($str = ltrim($str)) !== ''
946 && (!$num || $num === true || count($result) < $num)
954 for ($pos=1; $pos<$len; $pos++) {
955 if ($str[$pos] == '"') {
958 if ($str[$pos] == "\\") {
959 if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
964 if ($str[$pos] != '"') {
967 // we need to strip slashes for a quoted string
968 $result[] = stripslashes(substr($str, 1, $pos - 1));
969 $str = substr($str, $pos + 1);
972 // Parenthesized list
974 $str = substr($str, 1);
975 $result[] = self::tokenize($str, 0, true);
978 $str = substr($str, 1);
982 // list/test separator
992 $str = substr($str, 1);
1001 if ($str[1] == '*') {
1002 if ($end_pos = strpos($str, '*/')) {
1003 $str = substr($str, $end_pos + 2);
1014 if ($lf_pos = strpos($str, "\n")) {
1015 $str = substr($str, $lf_pos);
1024 // empty or one character
1025 if ($str === '' || $str === null) {
1028 if (strlen($str) < 2) {
1034 // tag/identifier/number
1035 if (preg_match('/^([a-z0-9:_]+)/i', $str, $m)) {
1036 $str = substr($str, strlen($m[1]));
1038 if ($m[1] != 'text:') {
1043 // possible hash-comment after "text:"
1044 if (preg_match('/^( |\t)*(#[^\n]+)?\n/', $str, $m)) {
1045 $str = substr($str, strlen($m[0]));
1047 // get text until alone dot in a line
1048 if (preg_match('/^(.*)\r?\n\.\r?\n/sU', $str, $m)) {
1050 // remove dot-stuffing
1051 $text = str_replace("\n..", "\n.", $text);
1052 $str = substr($str, strlen($m[0]));
1066 return $num === 1 ? (isset($result[0]) ? $result[0] : null) : $result;