4 Class for operations on Sieve scripts
6 Author: Aleksander Machniak <alec@alec.pl>
8 $Id: rcube_sieve_script.php 4806 2011-05-24 08:32:01Z alec $
12 class rcube_sieve_script
14 public $content = array(); // script rules array
16 private $supported = array( // extensions supported by class
17 'fileinto', // RFC3028
21 'vacation', // RFC5230
22 'relational', // RFC3431
23 'regex', // draft-ietf-sieve-regex-01
24 'imapflags', // draft-melnikov-sieve-imapflags-06
25 'imap4flags', // RFC5232
29 private $capabilities;
34 * @param string Script's text content
35 * @param array List of disabled extensions
36 * @param array List of capabilities supported by server
38 public function __construct($script, $disabled=null, $capabilities=null)
40 if (!empty($disabled)) {
41 // we're working on lower-cased names
42 $disabled = array_map('strtolower', (array) $disabled);
43 foreach ($disabled as $ext) {
44 if (($idx = array_search($ext, $this->supported)) !== false) {
45 unset($this->supported[$idx]);
50 $this->capabilities = $capabilities;
51 $this->content = $this->_parse_text($script);
55 * Adds script contents as text to the script array (at the end)
57 * @param string Text script contents
59 public function add_text($script)
61 $content = $this->_parse_text($script);
64 // check existsing script rules names
65 foreach ($this->content as $idx => $elem) {
66 $names[$elem['name']] = $idx;
69 foreach ($content as $elem) {
70 if (!isset($names[$elem['name']])) {
71 array_push($this->content, $elem);
80 * Adds rule to the script (at the end)
82 * @param string Rule name
83 * @param array Rule content (as array)
85 public function add_rule($content)
87 // TODO: check this->supported
88 array_push($this->content, $content);
89 return sizeof($this->content)-1;
92 public function delete_rule($index)
94 if(isset($this->content[$index])) {
95 unset($this->content[$index]);
101 public function size()
103 return sizeof($this->content);
106 public function update_rule($index, $content)
108 // TODO: check this->supported
109 if ($this->content[$index]) {
110 $this->content[$index] = $content;
117 * Returns script as text
119 public function as_text()
126 foreach ($this->content as $rule) {
132 $script .= '# rule:[' . $rule['name'] . "]\n";
134 // constraints expressions
135 foreach ($rule['tests'] as $test) {
137 switch ($test['test']) {
139 $tests[$i] .= ($test['not'] ? 'not ' : '');
140 $tests[$i] .= 'size :' . ($test['type']=='under' ? 'under ' : 'over ') . $test['arg'];
143 $tests[$i] .= ($test['not'] ? 'false' : 'true');
146 $tests[$i] .= ($test['not'] ? 'not ' : '');
147 $tests[$i] .= 'exists ' . self::escape_string($test['arg']);
150 $tests[$i] .= ($test['not'] ? 'not ' : '');
152 // relational operator + comparator
153 if (preg_match('/^(value|count)-([gteqnl]{2})/', $test['type'], $m)) {
154 array_push($exts, 'relational');
155 array_push($exts, 'comparator-i;ascii-numeric');
157 $tests[$i] .= 'header :' . $m[1] . ' "' . $m[2] . '" :comparator "i;ascii-numeric"';
160 if ($test['type'] == 'regex') {
161 array_push($exts, 'regex');
164 $tests[$i] .= 'header :' . $test['type'];
167 $tests[$i] .= ' ' . self::escape_string($test['arg1']);
168 $tests[$i] .= ' ' . self::escape_string($test['arg2']);
174 // disabled rule: if false #....
175 $script .= 'if ' . ($rule['disabled'] ? 'false # ' : '');
180 else if (count($tests) > 1) {
181 $tests_str = implode(', ', $tests);
184 $tests_str = $tests[0];
187 if ($rule['join'] || count($tests) > 1) {
188 $script .= sprintf('%s (%s)', $rule['join'] ? 'allof' : 'anyof', $tests_str);
191 $script .= $tests_str;
196 foreach ($rule['actions'] as $action) {
197 switch ($action['type']) {
200 array_push($exts, 'fileinto');
201 $script .= "\tfileinto ";
202 if ($action['copy']) {
204 array_push($exts, 'copy');
206 $script .= self::escape_string($action['target']) . ";\n";
210 $script .= "\tredirect ";
211 if ($action['copy']) {
213 array_push($exts, 'copy');
215 $script .= self::escape_string($action['target']) . ";\n";
220 array_push($exts, $action['type']);
221 $script .= "\t".$action['type']." "
222 . self::escape_string($action['target']) . ";\n";
228 if (is_array($this->capabilities) && in_array('imap4flags', $this->capabilities))
229 array_push($exts, 'imap4flags');
231 array_push($exts, 'imapflags');
233 $script .= "\t".$action['type']." "
234 . self::escape_string($action['target']) . ";\n";
240 $script .= "\t" . $action['type'] .";\n";
244 array_push($exts, 'vacation');
245 $script .= "\tvacation";
246 if (!empty($action['days']))
247 $script .= " :days " . $action['days'];
248 if (!empty($action['addresses']))
249 $script .= " :addresses " . self::escape_string($action['addresses']);
250 if (!empty($action['subject']))
251 $script .= " :subject " . self::escape_string($action['subject']);
252 if (!empty($action['handle']))
253 $script .= " :handle " . self::escape_string($action['handle']);
254 if (!empty($action['from']))
255 $script .= " :from " . self::escape_string($action['from']);
256 if (!empty($action['mime']))
258 $script .= " " . self::escape_string($action['reason']) . ";\n";
269 $script = 'require ["' . implode('","', array_unique($exts)) . "\"];\n" . $script;
275 * Returns script object
278 public function as_array()
280 return $this->content;
284 * Returns array of supported extensions
287 public function get_extensions()
289 return array_values($this->supported);
293 * Converts text script to rules array
295 * @param string Text script
297 private function _parse_text($script)
303 if ($tokens = preg_split('/(# rule:\[.*\])\r?\n/', $script, -1, PREG_SPLIT_DELIM_CAPTURE)) {
304 foreach($tokens as $token) {
305 if (preg_match('/^# rule:\[(.*)\]/', $token, $matches)) {
306 $content[$i]['name'] = $matches[1];
308 else if (isset($content[$i]['name']) && sizeof($content[$i]) == 1) {
309 if ($rule = $this->_tokenize_rule($token)) {
310 $content[$i] = array_merge($content[$i], $rule);
313 else // unknown rule format
323 * Convert text script fragment to rule object
325 * @param string Text rule
327 private function _tokenize_rule($content)
329 $cond = strtolower(self::tokenize($content, 1));
331 if ($cond != 'if' && $cond != 'elsif' && $cond != 'else') {
338 // disabled rule (false + comment): if false # .....
339 if (preg_match('/^\s*false\s+#/i', $content)) {
340 $content = preg_replace('/^\s*false\s+#\s*/i', '', $content);
344 while (strlen($content)) {
345 $tokens = self::tokenize($content, true);
346 $separator = array_pop($tokens);
348 if (!empty($tokens)) {
349 $token = array_shift($tokens);
355 $token = strtolower($token);
357 if ($token == 'not') {
359 $token = strtolower(array_shift($tokens));
373 $size = array('test' => 'size', 'not' => $not);
374 for ($i=0, $len=count($tokens); $i<$len; $i++) {
375 if (!is_array($tokens[$i])
376 && preg_match('/^:(under|over)$/i', $tokens[$i])
378 $size['type'] = strtolower(substr($tokens[$i], 1));
381 $size['arg'] = $tokens[$i];
389 $header = array('test' => 'header', 'not' => $not, 'arg1' => '', 'arg2' => '');
390 for ($i=0, $len=count($tokens); $i<$len; $i++) {
391 if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
394 else if (!is_array($tokens[$i]) && preg_match('/^:(count|value)$/i', $tokens[$i])) {
395 $header['type'] = strtolower(substr($tokens[$i], 1)) . '-' . $tokens[++$i];
397 else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
398 $header['type'] = strtolower(substr($tokens[$i], 1));
401 $header['arg1'] = $header['arg2'];
402 $header['arg2'] = $tokens[$i];
410 $tests[] = array('test' => 'exists', 'not' => $not,
411 'arg' => array_pop($tokens));
415 $tests[] = array('test' => 'true', 'not' => $not);
419 $tests[] = array('test' => 'true', 'not' => !$not);
424 if ($separator == '{') {
429 // ...and actions block
431 $actions = $this->_parse_actions($content);
434 if ($tests && $actions) {
438 'actions' => $actions,
440 'disabled' => $disabled,
448 * Parse body of actions section
450 * @param string Text body
451 * @return array Array of parsed action type/target pairs
453 private function _parse_actions($content)
457 while (strlen($content)) {
458 $tokens = self::tokenize($content, true);
459 $separator = array_pop($tokens);
461 if (!empty($tokens)) {
462 $token = array_shift($tokens);
472 $result[] = array('type' => $token);
480 for ($i=0, $len=count($tokens); $i<$len; $i++) {
481 if (strtolower($tokens[$i]) == ':copy') {
485 $target = $tokens[$i];
489 $result[] = array('type' => $token, 'copy' => $copy,
490 'target' => $target);
495 $result[] = array('type' => $token, 'target' => array_pop($tokens));
499 $vacation = array('type' => 'vacation', 'reason' => array_pop($tokens));
501 for ($i=0, $len=count($tokens); $i<$len; $i++) {
502 $tok = strtolower($tokens[$i]);
503 if ($tok == ':days') {
504 $vacation['days'] = $tokens[++$i];
506 else if ($tok == ':subject') {
507 $vacation['subject'] = $tokens[++$i];
509 else if ($tok == ':addresses') {
510 $vacation['addresses'] = $tokens[++$i];
512 else if ($tok == ':handle') {
513 $vacation['handle'] = $tokens[++$i];
515 else if ($tok == ':from') {
516 $vacation['from'] = $tokens[++$i];
518 else if ($tok == ':mime') {
519 $vacation['mime'] = true;
523 $result[] = $vacation;
529 $result[] = array('type' => $token,
530 // Flags list: last token (skip optional variable)
531 'target' => $tokens[count($tokens)-1]
541 * Escape special chars into quoted string value or multi-line string
544 * @param string $str Text or array (list) of strings
546 * @return string Result text
548 static function escape_string($str)
550 if (is_array($str) && count($str) > 1) {
551 foreach($str as $idx => $val)
552 $str[$idx] = self::escape_string($val);
554 return '[' . implode(',', $str) . ']';
556 else if (is_array($str)) {
557 $str = array_pop($str);
561 if (preg_match('/[\r\n\0]/', $str) || strlen($str) > 1024) {
562 return sprintf("text:\n%s\n.\n", self::escape_multiline_string($str));
566 return '"' . addcslashes($str, '\\"') . '"';
571 * Escape special chars in multi-line string value
573 * @param string $str Text
575 * @return string Text
577 static function escape_multiline_string($str)
579 $str = preg_split('/(\r?\n)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
581 foreach ($str as $idx => $line) {
583 if (isset($line[0]) && $line[0] == '.') {
584 $str[$idx] = '.' . $line;
588 return implode($str);
592 * Splits script into string tokens
594 * @param string &$str The script
595 * @param mixed $num Number of tokens to return, 0 for all
596 * or True for all tokens until separator is found.
597 * Separator will be returned as last token.
598 * @param int $in_list Enable to called recursively inside a list
600 * @return mixed Tokens array or string if $num=1
602 static function tokenize(&$str, $num=0, $in_list=false)
606 // remove spaces from the beginning of the string
607 while (($str = ltrim($str)) !== ''
608 && (!$num || $num === true || count($result) < $num)
616 for ($pos=1; $pos<$len; $pos++) {
617 if ($str[$pos] == '"') {
620 if ($str[$pos] == "\\") {
621 if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
626 if ($str[$pos] != '"') {
629 // we need to strip slashes for a quoted string
630 $result[] = stripslashes(substr($str, 1, $pos - 1));
631 $str = substr($str, $pos + 1);
634 // Parenthesized list
636 $str = substr($str, 1);
637 $result[] = self::tokenize($str, 0, true);
640 $str = substr($str, 1);
644 // list/test separator
654 $str = substr($str, 1);
663 if ($str[1] == '*') {
664 if ($end_pos = strpos($str, '*/')) {
665 $str = substr($str, $end_pos + 2);
676 if ($lf_pos = strpos($str, "\n")) {
677 $str = substr($str, $lf_pos);
686 // empty or one character
690 if (strlen($str) < 2) {
696 // tag/identifier/number
697 if (preg_match('/^([a-z0-9:_]+)/i', $str, $m)) {
698 $str = substr($str, strlen($m[1]));
700 if ($m[1] != 'text:') {
705 // possible hash-comment after "text:"
706 if (preg_match('/^( |\t)*(#[^\n]+)?\n/', $str, $m)) {
707 $str = substr($str, strlen($m[0]));
709 // get text until alone dot in a line
710 if (preg_match('/^(.*)\r?\n\.\r?\n/sU', $str, $m)) {
712 // remove dot-stuffing
713 $text = str_replace("\n..", "\n.", $text);
714 $str = substr($str, strlen($m[0]));
728 return $num === 1 ? (isset($result[0]) ? $result[0] : null) : $result;