Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

rcube_sieve_script.php 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. <?php
  2. /**
  3. * Class for operations on Sieve scripts
  4. *
  5. * Copyright (C) 2008-2011, The Roundcube Dev Team
  6. * Copyright (C) 2011, Kolab Systems AG
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  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.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see http://www.gnu.org/licenses/.
  20. */
  21. class rcube_sieve_script
  22. {
  23. public $content = array(); // script rules array
  24. private $vars = array(); // "global" variables
  25. private $prefix = ''; // script header (comments)
  26. private $supported = array( // Sieve extensions supported by class
  27. 'body', // RFC5173
  28. 'copy', // RFC3894
  29. 'date', // RFC5260
  30. 'enotify', // RFC5435
  31. 'envelope', // RFC5228
  32. 'ereject', // RFC5429
  33. 'fileinto', // RFC5228
  34. 'imapflags', // draft-melnikov-sieve-imapflags-06
  35. 'imap4flags', // RFC5232
  36. 'include', // draft-ietf-sieve-include-12
  37. 'index', // RFC5260
  38. 'notify', // draft-martin-sieve-notify-01,
  39. 'regex', // draft-ietf-sieve-regex-01
  40. 'reject', // RFC5429
  41. 'relational', // RFC3431
  42. 'subaddress', // RFC5233
  43. 'vacation', // RFC5230
  44. 'vacation-seconds', // RFC6131
  45. 'variables', // RFC5229
  46. // @TODO: spamtest+virustest, mailbox
  47. );
  48. /**
  49. * Object constructor
  50. *
  51. * @param string Script's text content
  52. * @param array List of capabilities supported by server
  53. */
  54. public function __construct($script, $capabilities=array())
  55. {
  56. $capabilities = array_map('strtolower', (array) $capabilities);
  57. // disable features by server capabilities
  58. if (!empty($capabilities)) {
  59. foreach ($this->supported as $idx => $ext) {
  60. if (!in_array($ext, $capabilities)) {
  61. unset($this->supported[$idx]);
  62. }
  63. }
  64. }
  65. // Parse text content of the script
  66. $this->_parse_text($script);
  67. }
  68. /**
  69. * Adds rule to the script (at the end)
  70. *
  71. * @param string Rule name
  72. * @param array Rule content (as array)
  73. *
  74. * @return int The index of the new rule
  75. */
  76. public function add_rule($content)
  77. {
  78. // TODO: check this->supported
  79. array_push($this->content, $content);
  80. return sizeof($this->content)-1;
  81. }
  82. public function delete_rule($index)
  83. {
  84. if(isset($this->content[$index])) {
  85. unset($this->content[$index]);
  86. return true;
  87. }
  88. return false;
  89. }
  90. public function size()
  91. {
  92. return sizeof($this->content);
  93. }
  94. public function update_rule($index, $content)
  95. {
  96. // TODO: check this->supported
  97. if ($this->content[$index]) {
  98. $this->content[$index] = $content;
  99. return $index;
  100. }
  101. return false;
  102. }
  103. /**
  104. * Sets "global" variable
  105. *
  106. * @param string $name Variable name
  107. * @param string $value Variable value
  108. * @param array $mods Variable modifiers
  109. */
  110. public function set_var($name, $value, $mods = array())
  111. {
  112. // Check if variable exists
  113. for ($i=0, $len=count($this->vars); $i<$len; $i++) {
  114. if ($this->vars[$i]['name'] == $name) {
  115. break;
  116. }
  117. }
  118. $var = array_merge($mods, array('name' => $name, 'value' => $value));
  119. $this->vars[$i] = $var;
  120. }
  121. /**
  122. * Unsets "global" variable
  123. *
  124. * @param string $name Variable name
  125. */
  126. public function unset_var($name)
  127. {
  128. // Check if variable exists
  129. foreach ($this->vars as $idx => $var) {
  130. if ($var['name'] == $name) {
  131. unset($this->vars[$idx]);
  132. break;
  133. }
  134. }
  135. }
  136. /**
  137. * Gets the value of "global" variable
  138. *
  139. * @param string $name Variable name
  140. *
  141. * @return string Variable value
  142. */
  143. public function get_var($name)
  144. {
  145. // Check if variable exists
  146. for ($i=0, $len=count($this->vars); $i<$len; $i++) {
  147. if ($this->vars[$i]['name'] == $name) {
  148. return $this->vars[$i]['name'];
  149. }
  150. }
  151. }
  152. /**
  153. * Sets script header content
  154. *
  155. * @param string $text Header content
  156. */
  157. public function set_prefix($text)
  158. {
  159. $this->prefix = $text;
  160. }
  161. /**
  162. * Returns script as text
  163. */
  164. public function as_text()
  165. {
  166. $output = '';
  167. $exts = array();
  168. $idx = 0;
  169. if (!empty($this->vars)) {
  170. if (in_array('variables', (array)$this->supported)) {
  171. $has_vars = true;
  172. array_push($exts, 'variables');
  173. }
  174. foreach ($this->vars as $var) {
  175. if (empty($has_vars)) {
  176. // 'variables' extension not supported, put vars in comments
  177. $output .= sprintf("# %s %s\n", $var['name'], $var['value']);
  178. }
  179. else {
  180. $output .= 'set ';
  181. foreach (array_diff(array_keys($var), array('name', 'value')) as $opt) {
  182. $output .= ":$opt ";
  183. }
  184. $output .= self::escape_string($var['name']) . ' ' . self::escape_string($var['value']) . ";\n";
  185. }
  186. }
  187. }
  188. $imapflags = in_array('imap4flags', $this->supported) ? 'imap4flags' : 'imapflags';
  189. $notify = in_array('enotify', $this->supported) ? 'enotify' : 'notify';
  190. // rules
  191. foreach ($this->content as $rule) {
  192. $script = '';
  193. $tests = array();
  194. $i = 0;
  195. // header
  196. if (!empty($rule['name']) && strlen($rule['name'])) {
  197. $script .= '# rule:[' . $rule['name'] . "]\n";
  198. }
  199. // constraints expressions
  200. if (!empty($rule['tests'])) {
  201. foreach ($rule['tests'] as $test) {
  202. $tests[$i] = '';
  203. switch ($test['test']) {
  204. case 'size':
  205. $tests[$i] .= ($test['not'] ? 'not ' : '');
  206. $tests[$i] .= 'size :' . ($test['type']=='under' ? 'under ' : 'over ') . $test['arg'];
  207. break;
  208. case 'true':
  209. $tests[$i] .= ($test['not'] ? 'false' : 'true');
  210. break;
  211. case 'exists':
  212. $tests[$i] .= ($test['not'] ? 'not ' : '');
  213. $tests[$i] .= 'exists ' . self::escape_string($test['arg']);
  214. break;
  215. case 'header':
  216. $tests[$i] .= ($test['not'] ? 'not ' : '');
  217. $tests[$i] .= 'header';
  218. $this->add_index($test, $tests[$i], $exts);
  219. $this->add_operator($test, $tests[$i], $exts);
  220. $tests[$i] .= ' ' . self::escape_string($test['arg1']);
  221. $tests[$i] .= ' ' . self::escape_string($test['arg2']);
  222. break;
  223. case 'address':
  224. case 'envelope':
  225. if ($test['test'] == 'envelope') {
  226. array_push($exts, 'envelope');
  227. }
  228. $tests[$i] .= ($test['not'] ? 'not ' : '');
  229. $tests[$i] .= $test['test'];
  230. if ($test['test'] != 'envelope') {
  231. $this->add_index($test, $tests[$i], $exts);
  232. }
  233. // :all address-part is optional, skip it
  234. if (!empty($test['part']) && $test['part'] != 'all') {
  235. $tests[$i] .= ' :' . $test['part'];
  236. if ($test['part'] == 'user' || $test['part'] == 'detail') {
  237. array_push($exts, 'subaddress');
  238. }
  239. }
  240. $this->add_operator($test, $tests[$i], $exts);
  241. $tests[$i] .= ' ' . self::escape_string($test['arg1']);
  242. $tests[$i] .= ' ' . self::escape_string($test['arg2']);
  243. break;
  244. case 'body':
  245. array_push($exts, 'body');
  246. $tests[$i] .= ($test['not'] ? 'not ' : '') . 'body';
  247. if (!empty($test['part'])) {
  248. $tests[$i] .= ' :' . $test['part'];
  249. if (!empty($test['content']) && $test['part'] == 'content') {
  250. $tests[$i] .= ' ' . self::escape_string($test['content']);
  251. }
  252. }
  253. $this->add_operator($test, $tests[$i], $exts);
  254. $tests[$i] .= ' ' . self::escape_string($test['arg']);
  255. break;
  256. case 'date':
  257. case 'currentdate':
  258. array_push($exts, 'date');
  259. $tests[$i] .= ($test['not'] ? 'not ' : '') . $test['test'];
  260. $this->add_index($test, $tests[$i], $exts);
  261. if (!empty($test['originalzone']) && $test['test'] == 'date') {
  262. $tests[$i] .= ' :originalzone';
  263. }
  264. else if (!empty($test['zone'])) {
  265. $tests[$i] .= ' :zone ' . self::escape_string($test['zone']);
  266. }
  267. $this->add_operator($test, $tests[$i], $exts);
  268. if ($test['test'] == 'date') {
  269. $tests[$i] .= ' ' . self::escape_string($test['header']);
  270. }
  271. $tests[$i] .= ' ' . self::escape_string($test['part']);
  272. $tests[$i] .= ' ' . self::escape_string($test['arg']);
  273. break;
  274. }
  275. $i++;
  276. }
  277. }
  278. // disabled rule: if false #....
  279. if (!empty($tests)) {
  280. $script .= 'if ' . ($rule['disabled'] ? 'false # ' : '');
  281. if (count($tests) > 1) {
  282. $tests_str = implode(', ', $tests);
  283. }
  284. else {
  285. $tests_str = $tests[0];
  286. }
  287. if ($rule['join'] || count($tests) > 1) {
  288. $script .= sprintf('%s (%s)', $rule['join'] ? 'allof' : 'anyof', $tests_str);
  289. }
  290. else {
  291. $script .= $tests_str;
  292. }
  293. $script .= "\n{\n";
  294. }
  295. // action(s)
  296. if (!empty($rule['actions'])) {
  297. foreach ($rule['actions'] as $action) {
  298. $action_script = '';
  299. switch ($action['type']) {
  300. case 'fileinto':
  301. array_push($exts, 'fileinto');
  302. $action_script .= 'fileinto ';
  303. if ($action['copy']) {
  304. $action_script .= ':copy ';
  305. array_push($exts, 'copy');
  306. }
  307. $action_script .= self::escape_string($action['target']);
  308. break;
  309. case 'redirect':
  310. $action_script .= 'redirect ';
  311. if ($action['copy']) {
  312. $action_script .= ':copy ';
  313. array_push($exts, 'copy');
  314. }
  315. $action_script .= self::escape_string($action['target']);
  316. break;
  317. case 'reject':
  318. case 'ereject':
  319. array_push($exts, $action['type']);
  320. $action_script .= $action['type'].' '
  321. . self::escape_string($action['target']);
  322. break;
  323. case 'addflag':
  324. case 'setflag':
  325. case 'removeflag':
  326. array_push($exts, $imapflags);
  327. $action_script .= $action['type'].' '
  328. . self::escape_string($action['target']);
  329. break;
  330. case 'keep':
  331. case 'discard':
  332. case 'stop':
  333. $action_script .= $action['type'];
  334. break;
  335. case 'include':
  336. array_push($exts, 'include');
  337. $action_script .= 'include ';
  338. foreach (array_diff(array_keys($action), array('target', 'type')) as $opt) {
  339. $action_script .= ":$opt ";
  340. }
  341. $action_script .= self::escape_string($action['target']);
  342. break;
  343. case 'set':
  344. array_push($exts, 'variables');
  345. $action_script .= 'set ';
  346. foreach (array_diff(array_keys($action), array('name', 'value', 'type')) as $opt) {
  347. $action_script .= ":$opt ";
  348. }
  349. $action_script .= self::escape_string($action['name']) . ' ' . self::escape_string($action['value']);
  350. break;
  351. case 'notify':
  352. array_push($exts, $notify);
  353. $action_script .= 'notify';
  354. $method = $action['method'];
  355. unset($action['method']);
  356. $action['options'] = (array) $action['options'];
  357. // Here we support draft-martin-sieve-notify-01 used by Cyrus
  358. if ($notify == 'notify') {
  359. switch ($action['importance']) {
  360. case 1: $action_script .= " :high"; break;
  361. //case 2: $action_script .= " :normal"; break;
  362. case 3: $action_script .= " :low"; break;
  363. }
  364. // Old-draft way: :method "mailto" :options "email@address"
  365. if (!empty($method)) {
  366. $parts = explode(':', $method, 2);
  367. $action['method'] = $parts[0];
  368. array_unshift($action['options'], $parts[1]);
  369. }
  370. unset($action['importance']);
  371. unset($action['from']);
  372. unset($method);
  373. }
  374. foreach (array('id', 'importance', 'method', 'options', 'from', 'message') as $n_tag) {
  375. if (!empty($action[$n_tag])) {
  376. $action_script .= " :$n_tag " . self::escape_string($action[$n_tag]);
  377. }
  378. }
  379. if (!empty($method)) {
  380. $action_script .= ' ' . self::escape_string($method);
  381. }
  382. break;
  383. case 'vacation':
  384. array_push($exts, 'vacation');
  385. $action_script .= 'vacation';
  386. if (isset($action['seconds'])) {
  387. array_push($exts, 'vacation-seconds');
  388. $action_script .= " :seconds " . intval($action['seconds']);
  389. }
  390. else if (!empty($action['days'])) {
  391. $action_script .= " :days " . intval($action['days']);
  392. }
  393. if (!empty($action['addresses']))
  394. $action_script .= " :addresses " . self::escape_string($action['addresses']);
  395. if (!empty($action['subject']))
  396. $action_script .= " :subject " . self::escape_string($action['subject']);
  397. if (!empty($action['handle']))
  398. $action_script .= " :handle " . self::escape_string($action['handle']);
  399. if (!empty($action['from']))
  400. $action_script .= " :from " . self::escape_string($action['from']);
  401. if (!empty($action['mime']))
  402. $action_script .= " :mime";
  403. $action_script .= " " . self::escape_string($action['reason']);
  404. break;
  405. }
  406. if ($action_script) {
  407. $script .= !empty($tests) ? "\t" : '';
  408. $script .= $action_script . ";\n";
  409. }
  410. }
  411. }
  412. if ($script) {
  413. $output .= $script . (!empty($tests) ? "}\n" : '');
  414. $idx++;
  415. }
  416. }
  417. // requires
  418. if (!empty($exts)) {
  419. $exts = array_unique($exts);
  420. if (in_array('vacation-seconds', $exts) && ($key = array_search('vacation', $exts)) !== false) {
  421. unset($exts[$key]);
  422. }
  423. sort($exts); // for convenience use always the same order
  424. $output = 'require ["' . implode('","', $exts) . "\"];\n" . $output;
  425. }
  426. if (!empty($this->prefix)) {
  427. $output = $this->prefix . "\n\n" . $output;
  428. }
  429. return $output;
  430. }
  431. /**
  432. * Returns script object
  433. *
  434. */
  435. public function as_array()
  436. {
  437. return $this->content;
  438. }
  439. /**
  440. * Returns array of supported extensions
  441. *
  442. */
  443. public function get_extensions()
  444. {
  445. return array_values($this->supported);
  446. }
  447. /**
  448. * Converts text script to rules array
  449. *
  450. * @param string Text script
  451. */
  452. private function _parse_text($script)
  453. {
  454. $prefix = '';
  455. $options = array();
  456. $position = 0;
  457. $length = strlen($script);
  458. while ($position < $length) {
  459. // skip whitespace chars
  460. $position = self::ltrim_position($script, $position);
  461. $rulename = '';
  462. // Comments
  463. while ($script[$position] === '#') {
  464. $endl = strpos($script, "\n", $position) ?: $length;
  465. $line = substr($script, $position, $endl - $position);
  466. // Roundcube format
  467. if (preg_match('/^# rule:\[(.*)\]/', $line, $matches)) {
  468. $rulename = $matches[1];
  469. }
  470. // KEP:14 variables
  471. else if (preg_match('/^# (EDITOR|EDITOR_VERSION) (.+)$/', $line, $matches)) {
  472. $this->set_var($matches[1], $matches[2]);
  473. }
  474. // Horde-Ingo format
  475. else if (!empty($options['format']) && $options['format'] == 'INGO'
  476. && preg_match('/^# (.*)/', $line, $matches)
  477. ) {
  478. $rulename = $matches[1];
  479. }
  480. else if (empty($options['prefix'])) {
  481. $prefix .= $line . "\n";
  482. }
  483. $position = $endl + 1;
  484. }
  485. // handle script header
  486. if (empty($options['prefix'])) {
  487. $options['prefix'] = true;
  488. if ($prefix && strpos($prefix, 'horde.org/ingo')) {
  489. $options['format'] = 'INGO';
  490. }
  491. }
  492. // Control structures/blocks
  493. if (preg_match('/^(if|else|elsif)/i', substr($script, $position, 5))) {
  494. $rule = $this->_tokenize_rule($script, $position);
  495. if (strlen($rulename) && !empty($rule)) {
  496. $rule['name'] = $rulename;
  497. }
  498. }
  499. // Simple commands
  500. else {
  501. $rule = $this->_parse_actions($script, $position, ';');
  502. if (!empty($rule[0]) && is_array($rule)) {
  503. // set "global" variables
  504. if ($rule[0]['type'] == 'set') {
  505. unset($rule[0]['type']);
  506. $this->vars[] = $rule[0];
  507. unset($rule);
  508. }
  509. else {
  510. $rule = array('actions' => $rule);
  511. }
  512. }
  513. }
  514. if (!empty($rule)) {
  515. $this->content[] = $rule;
  516. }
  517. }
  518. if (!empty($prefix)) {
  519. $this->prefix = trim($prefix);
  520. }
  521. }
  522. /**
  523. * Convert text script fragment to rule object
  524. *
  525. * @param string $content The whole script content
  526. * @param int &$position Start position in the script
  527. *
  528. * @return array Rule data
  529. */
  530. private function _tokenize_rule($content, &$position)
  531. {
  532. $cond = strtolower(self::tokenize($content, 1, $position));
  533. if ($cond != 'if' && $cond != 'elsif' && $cond != 'else') {
  534. return null;
  535. }
  536. $disabled = false;
  537. $join = false;
  538. $join_not = false;
  539. $length = strlen($content);
  540. // disabled rule (false + comment): if false # .....
  541. if (preg_match('/^\s*false\s+#\s*/i', substr($content, $position, 20), $m)) {
  542. $position += strlen($m[0]);
  543. $disabled = true;
  544. }
  545. while ($position < $length) {
  546. $tokens = self::tokenize($content, true, $position);
  547. $separator = array_pop($tokens);
  548. if (!empty($tokens)) {
  549. $token = array_shift($tokens);
  550. }
  551. else {
  552. $token = $separator;
  553. }
  554. $token = strtolower($token);
  555. if ($token == 'not') {
  556. $not = true;
  557. $token = strtolower(array_shift($tokens));
  558. }
  559. else {
  560. $not = false;
  561. }
  562. // we support "not allof" as a negation of allof sub-tests
  563. if ($join_not) {
  564. $not = !$not;
  565. }
  566. switch ($token) {
  567. case 'allof':
  568. $join = true;
  569. $join_not = $not;
  570. break;
  571. case 'anyof':
  572. break;
  573. case 'size':
  574. $test = array('test' => 'size', 'not' => $not);
  575. $test['arg'] = array_pop($tokens);
  576. for ($i=0, $len=count($tokens); $i<$len; $i++) {
  577. if (!is_array($tokens[$i])
  578. && preg_match('/^:(under|over)$/i', $tokens[$i])
  579. ) {
  580. $test['type'] = strtolower(substr($tokens[$i], 1));
  581. }
  582. }
  583. $tests[] = $test;
  584. break;
  585. case 'header':
  586. case 'address':
  587. case 'envelope':
  588. $test = array('test' => $token, 'not' => $not);
  589. $test['arg2'] = array_pop($tokens);
  590. $test['arg1'] = array_pop($tokens);
  591. $test += $this->test_tokens($tokens);
  592. if ($token != 'header' && !empty($tokens)) {
  593. for ($i=0, $len=count($tokens); $i<$len; $i++) {
  594. if (!is_array($tokens[$i]) && preg_match('/^:(localpart|domain|all|user|detail)$/i', $tokens[$i])) {
  595. $test['part'] = strtolower(substr($tokens[$i], 1));
  596. }
  597. }
  598. }
  599. $tests[] = $test;
  600. break;
  601. case 'body':
  602. $test = array('test' => 'body', 'not' => $not);
  603. $test['arg'] = array_pop($tokens);
  604. $test += $this->test_tokens($tokens);
  605. for ($i=0, $len=count($tokens); $i<$len; $i++) {
  606. if (!is_array($tokens[$i]) && preg_match('/^:(raw|content|text)$/i', $tokens[$i])) {
  607. $test['part'] = strtolower(substr($tokens[$i], 1));
  608. if ($test['part'] == 'content') {
  609. $test['content'] = $tokens[++$i];
  610. }
  611. }
  612. }
  613. $tests[] = $test;
  614. break;
  615. case 'date':
  616. case 'currentdate':
  617. $test = array('test' => $token, 'not' => $not);
  618. $test['arg'] = array_pop($tokens);
  619. $test['part'] = array_pop($tokens);
  620. if ($token == 'date') {
  621. $test['header'] = array_pop($tokens);
  622. }
  623. $test += $this->test_tokens($tokens);
  624. for ($i=0, $len=count($tokens); $i<$len; $i++) {
  625. if (!is_array($tokens[$i]) && preg_match('/^:zone$/i', $tokens[$i])) {
  626. $test['zone'] = $tokens[++$i];
  627. }
  628. else if (!is_array($tokens[$i]) && preg_match('/^:originalzone$/i', $tokens[$i])) {
  629. $test['originalzone'] = true;
  630. }
  631. }
  632. $tests[] = $test;
  633. break;
  634. case 'exists':
  635. $tests[] = array('test' => 'exists', 'not' => $not,
  636. 'arg' => array_pop($tokens));
  637. break;
  638. case 'true':
  639. $tests[] = array('test' => 'true', 'not' => $not);
  640. break;
  641. case 'false':
  642. $tests[] = array('test' => 'true', 'not' => !$not);
  643. break;
  644. }
  645. // goto actions...
  646. if ($separator == '{') {
  647. break;
  648. }
  649. }
  650. // ...and actions block
  651. $actions = $this->_parse_actions($content, $position);
  652. if ($tests && $actions) {
  653. $result = array(
  654. 'type' => $cond,
  655. 'tests' => $tests,
  656. 'actions' => $actions,
  657. 'join' => $join,
  658. 'disabled' => $disabled,
  659. );
  660. }
  661. return $result;
  662. }
  663. /**
  664. * Parse body of actions section
  665. *
  666. * @param string $content The whole script content
  667. * @param int &$position Start position in the script
  668. * @param string $end End of text separator
  669. *
  670. * @return array Array of parsed action type/target pairs
  671. */
  672. private function _parse_actions($content, &$position, $end = '}')
  673. {
  674. $result = null;
  675. $length = strlen($content);
  676. while ($position < $length) {
  677. $tokens = self::tokenize($content, true, $position);
  678. $separator = array_pop($tokens);
  679. $token = !empty($tokens) ? array_shift($tokens) : $separator;
  680. switch ($token) {
  681. case 'discard':
  682. case 'keep':
  683. case 'stop':
  684. $result[] = array('type' => $token);
  685. break;
  686. case 'fileinto':
  687. case 'redirect':
  688. $action = array('type' => $token, 'target' => array_pop($tokens));
  689. $args = array('copy');
  690. $action += $this->action_arguments($tokens, $args);
  691. $result[] = $action;
  692. break;
  693. case 'vacation':
  694. $action = array('type' => 'vacation', 'reason' => array_pop($tokens));
  695. $args = array('mime');
  696. $vargs = array('seconds', 'days', 'addresses', 'subject', 'handle', 'from');
  697. $action += $this->action_arguments($tokens, $args, $vargs);
  698. $result[] = $action;
  699. break;
  700. case 'reject':
  701. case 'ereject':
  702. case 'setflag':
  703. case 'addflag':
  704. case 'removeflag':
  705. $result[] = array('type' => $token, 'target' => array_pop($tokens));
  706. break;
  707. case 'include':
  708. $action = array('type' => 'include', 'target' => array_pop($tokens));
  709. $args = array('once', 'optional', 'global', 'personal');
  710. $action += $this->action_arguments($tokens, $args);
  711. $result[] = $action;
  712. break;
  713. case 'set':
  714. $action = array('type' => 'set', 'value' => array_pop($tokens), 'name' => array_pop($tokens));
  715. $args = array('lower', 'upper', 'lowerfirst', 'upperfirst', 'quotewildcard', 'length');
  716. $action += $this->action_arguments($tokens, $args);
  717. $result[] = $action;
  718. break;
  719. case 'require':
  720. // skip, will be build according to used commands
  721. // $result[] = array('type' => 'require', 'target' => array_pop($tokens));
  722. break;
  723. case 'notify':
  724. $action = array('type' => 'notify');
  725. $priorities = array('high' => 1, 'normal' => 2, 'low' => 3);
  726. $vargs = array('from', 'id', 'importance', 'options', 'message', 'method');
  727. $args = array_keys($priorities);
  728. $action += $this->action_arguments($tokens, $args, $vargs);
  729. // Here we'll convert draft-martin-sieve-notify-01 into RFC 5435
  730. if (!isset($action['importance'])) {
  731. foreach ($priorities as $key => $val) {
  732. if (isset($action[$key])) {
  733. $action['importance'] = $val;
  734. unset($action[$key]);
  735. }
  736. }
  737. }
  738. $action['options'] = (array) $action['options'];
  739. // Old-draft way: :method "mailto" :options "email@address"
  740. if (!empty($action['method']) && !empty($action['options'])) {
  741. $action['method'] .= ':' . array_shift($action['options']);
  742. }
  743. // unnamed parameter is a :method in enotify extension
  744. else if (!isset($action['method'])) {
  745. $action['method'] = array_pop($tokens);
  746. }
  747. $result[] = $action;
  748. break;
  749. }
  750. if ($separator == $end)
  751. break;
  752. }
  753. return $result;
  754. }
  755. /**
  756. * Add comparator to the test
  757. */
  758. private function add_comparator($test, &$out, &$exts)
  759. {
  760. if (empty($test['comparator'])) {
  761. return;
  762. }
  763. if ($test['comparator'] == 'i;ascii-numeric') {
  764. array_push($exts, 'relational');
  765. array_push($exts, 'comparator-i;ascii-numeric');
  766. }
  767. else if (!in_array($test['comparator'], array('i;octet', 'i;ascii-casemap'))) {
  768. array_push($exts, 'comparator-' . $test['comparator']);
  769. }
  770. // skip default comparator
  771. if ($test['comparator'] != 'i;ascii-casemap') {
  772. $out .= ' :comparator ' . self::escape_string($test['comparator']);
  773. }
  774. }
  775. /**
  776. * Add index argument to the test
  777. */
  778. private function add_index($test, &$out, &$exts)
  779. {
  780. if (!empty($test['index'])) {
  781. array_push($exts, 'index');
  782. $out .= ' :index ' . intval($test['index']) . ($test['last'] ? ' :last' : '');
  783. }
  784. }
  785. /**
  786. * Add operators to the test
  787. */
  788. private function add_operator($test, &$out, &$exts)
  789. {
  790. if (empty($test['type'])) {
  791. return;
  792. }
  793. // relational operator
  794. if (preg_match('/^(value|count)-([gteqnl]{2})/', $test['type'], $m)) {
  795. array_push($exts, 'relational');
  796. $out .= ' :' . $m[1] . ' "' . $m[2] . '"';
  797. }
  798. else {
  799. if ($test['type'] == 'regex') {
  800. array_push($exts, 'regex');
  801. }
  802. $out .= ' :' . $test['type'];
  803. }
  804. $this->add_comparator($test, $out, $exts);
  805. }
  806. /**
  807. * Extract test tokens
  808. */
  809. private function test_tokens(&$tokens)
  810. {
  811. $test = array();
  812. $result = array();
  813. for ($i=0, $len=count($tokens); $i<$len; $i++) {
  814. if (!is_array($tokens[$i]) && $tokens[$i][0] == ':') {
  815. if (preg_match('/^:comparator$/i', $tokens[$i])) {
  816. $test['comparator'] = $tokens[++$i];
  817. continue;
  818. }
  819. if (preg_match('/^:(count|value)$/i', $tokens[$i])) {
  820. $test['type'] = strtolower(substr($tokens[$i], 1)) . '-' . $tokens[++$i];
  821. continue;
  822. }
  823. if (preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
  824. $test['type'] = strtolower(substr($tokens[$i], 1));
  825. continue;
  826. }
  827. if (preg_match('/^:index$/i', $tokens[$i])) {
  828. $test['index'] = intval($tokens[++$i]);
  829. if ($tokens[$i+1] && preg_match('/^:last$/i', $tokens[$i+1])) {
  830. $test['last'] = true;
  831. $i++;
  832. }
  833. continue;
  834. }
  835. }
  836. $result[] = $tokens[$i];
  837. }
  838. $tokens = $result;
  839. return $test;
  840. }
  841. /**
  842. * Extract action arguments
  843. */
  844. private function action_arguments(&$tokens, $bool_args, $val_args = array())
  845. {
  846. $action = array();
  847. $result = array();
  848. for ($i=0, $len=count($tokens); $i<$len; $i++) {
  849. $tok = $tokens[$i];
  850. if (!is_array($tok) && $tok[0] == ':') {
  851. $tok = strtolower(substr($tok, 1));
  852. if (in_array($tok, $bool_args)) {
  853. $action[$tok] = true;
  854. }
  855. else if (in_array($tok, $val_args)) {
  856. $action[$tok] = $tokens[++$i];
  857. }
  858. else {
  859. $result[] = $tok;
  860. }
  861. }
  862. else {
  863. $result[] = $tok;
  864. }
  865. }
  866. $tokens = $result;
  867. return $action;
  868. }
  869. /**
  870. * Escape special chars into quoted string value or multi-line string
  871. * or list of strings
  872. *
  873. * @param string $str Text or array (list) of strings
  874. *
  875. * @return string Result text
  876. */
  877. static function escape_string($str)
  878. {
  879. if (is_array($str) && count($str) > 1) {
  880. foreach($str as $idx => $val)
  881. $str[$idx] = self::escape_string($val);
  882. return '[' . implode(',', $str) . ']';
  883. }
  884. else if (is_array($str)) {
  885. $str = array_pop($str);
  886. }
  887. // multi-line string
  888. if (preg_match('/[\r\n\0]/', $str) || strlen($str) > 1024) {
  889. return sprintf("text:\n%s\n.\n", self::escape_multiline_string($str));
  890. }
  891. // quoted-string
  892. else {
  893. return '"' . addcslashes($str, '\\"') . '"';
  894. }
  895. }
  896. /**
  897. * Escape special chars in multi-line string value
  898. *
  899. * @param string $str Text
  900. *
  901. * @return string Text
  902. */
  903. static function escape_multiline_string($str)
  904. {
  905. $str = preg_split('/(\r?\n)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
  906. foreach ($str as $idx => $line) {
  907. // dot-stuffing
  908. if (isset($line[0]) && $line[0] == '.') {
  909. $str[$idx] = '.' . $line;
  910. }
  911. }
  912. return implode($str);
  913. }
  914. /**
  915. * Splits script into string tokens
  916. *
  917. * @param string $str The script
  918. * @param mixed $num Number of tokens to return, 0 for all
  919. * or True for all tokens until separator is found.
  920. * Separator will be returned as last token.
  921. * @param int &$position Parsing start position
  922. *
  923. * @return mixed Tokens array or string if $num=1
  924. */
  925. static function tokenize($str, $num = 0, &$position = 0)
  926. {
  927. $result = array();
  928. $length = strlen($str);
  929. $mask = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:_';
  930. // remove spaces from the beginning of the string
  931. while ($position < $length && (!$num || $num === true || count($result) < $num)) {
  932. // skip whitespace chars
  933. $position = self::ltrim_position($str, $position);
  934. switch ($str[$position]) {
  935. // Quoted string
  936. case '"':
  937. for ($pos = $position + 1; $pos < $length; $pos++) {
  938. if ($str[$pos] == '"') {
  939. break;
  940. }
  941. if ($str[$pos] == "\\") {
  942. if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
  943. $pos++;
  944. }
  945. }
  946. }
  947. if ($str[$pos] != '"') {
  948. // error
  949. }
  950. // we need to strip slashes for a quoted string
  951. $result[] = stripslashes(substr($str, $position + 1, $pos - $position - 1));
  952. $position = $pos + 1;
  953. break;
  954. // Parenthesized list
  955. case '[':
  956. $position++;
  957. $result[] = self::tokenize($str, 0, $position);
  958. break;
  959. case ']':
  960. $position++;
  961. return $result;
  962. break;
  963. // list/test separator
  964. case ',':
  965. // command separator
  966. case ';':
  967. // block/tests-list
  968. case '(':
  969. case ')':
  970. case '{':
  971. case '}':
  972. $sep = $str[$position];
  973. $position++;
  974. if ($num === true) {
  975. $result[] = $sep;
  976. break 2;
  977. }
  978. break;
  979. // bracket-comment
  980. case '/':
  981. if ($str[$position + 1] == '*') {
  982. if ($end_pos = strpos($str, '*/', $position + 2)) {
  983. $position = $end_pos + 2;
  984. }
  985. else {
  986. // error
  987. $position = $length;
  988. }
  989. }
  990. break;
  991. // hash-comment
  992. case '#':
  993. if ($lf_pos = strpos($str, "\n", $position)) {
  994. $position = $lf_pos + 1;
  995. break;
  996. }
  997. else {
  998. $position = $length;
  999. }
  1000. // String atom
  1001. default:
  1002. // empty or one character
  1003. if ($position == $length) {
  1004. break 2;
  1005. }
  1006. // tag/identifier/number
  1007. if ($len = strspn($str, $mask, $position)) {
  1008. $atom = substr($str, $position, $len);
  1009. $position += $len;
  1010. if ($atom != 'text:') {
  1011. $result[] = $atom;
  1012. }
  1013. // multiline string
  1014. else {
  1015. // skip whitespace chars (except \r\n)
  1016. $position = self::ltrim_position($str, $position, false);
  1017. // possible hash-comment after "text:"
  1018. if ($str[$position] === '#') {
  1019. $endl = strpos($str, "\n", $position);
  1020. $position = $endl ?: $length;
  1021. }
  1022. // skip \n or \r\n
  1023. if ($str[$position] == "\n") {
  1024. $position++;
  1025. }
  1026. else if ($str[$position] == "\r" && $str[$position] == "\n") {
  1027. $position += 2;
  1028. }
  1029. $text = '';
  1030. // get text until alone dot in a line
  1031. while ($position < $length) {
  1032. $pos = strpos($str, "\n.", $position);
  1033. if ($pos === false) {
  1034. break;
  1035. }
  1036. $text .= substr($str, $position, $pos - $position);
  1037. $position = $pos + 2;
  1038. if ($str[$pos] == "\n"
  1039. || ($str[$pos] == "\r" && $str[$pos + 1] == "\n")
  1040. ) {
  1041. break;
  1042. }
  1043. }
  1044. // remove dot-stuffing
  1045. $text = str_replace("\n..", "\n.", $text);
  1046. $result[] = $text;
  1047. $position++;
  1048. }
  1049. }
  1050. // fallback, skip one character as infinite loop prevention
  1051. else {
  1052. $position++;
  1053. }
  1054. break;
  1055. }
  1056. }
  1057. return $num === 1 ? (isset($result[0]) ? $result[0] : null) : $result;
  1058. }
  1059. /**
  1060. * Skip whitespace characters in a string from specified position.
  1061. */
  1062. static function ltrim_position($content, $position, $br = true)
  1063. {
  1064. $blanks = array("\t", "\0", "\x0B", " ");
  1065. if ($br) {
  1066. $blanks[] = "\r";
  1067. $blanks[] = "\n";
  1068. }
  1069. while (isset($content[$position]) && isset($content[$position + 1])
  1070. && in_array($content[$position], $blanks, true)
  1071. ) {
  1072. $position++;
  1073. }
  1074. return $position;
  1075. }
  1076. }