weekly release 5.0dev
[moodle.git] / filter / emailprotect / classes / text_filter.php
blobce7e74b761ea1a7d17256baf2155c77c04674644
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 namespace filter_emailprotect;
19 /**
20 * Basic email protection filter.
22 * This class looks for email addresses in Moodle text and hides them using the Moodle obfuscate_text function.
24 * @package filter_emailprotect
25 * @subpackage emailprotect
26 * @copyright 2004 Mike Churchward
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 class text_filter extends \core_filters\text_filter {
30 #[\Override]
31 public function filter($text, array $options = []) {
32 // Do a quick check using stripos to avoid unnecessary work.
33 if (strpos($text, '@') === false) {
34 return $text;
37 // Regular expression to define a standard email string.
38 $emailregex = '((?:[\w\.\-])+\@(?:(?:[a-zA-Z\d\-])+\.)+(?:[a-zA-Z\d]{2,4}))';
40 // Pattern to find a mailto link with the linked text.
41 $pattern = '|(<a\s+href\s*=\s*[\'"]?mailto:)' . $emailregex . '([\'"]?\s*>)' . '(.*)' . '(</a>)|iU';
42 $text = preg_replace_callback($pattern, [self::class, 'alter_mailto'], $text);
44 // Pattern to find any other email address in the text.
45 $pattern = '/(^|\s+|>)' . $emailregex . '($|\s+|\.\s+|\.$|<)/i';
46 $text = preg_replace_callback($pattern, [self::class, 'alter_email'], $text);
48 return $text;
51 /**
52 * Obfuscate the email address.
54 * @param mixed $matches
55 * @return string
57 private function alter_email($matches) {
58 return $matches[1] . obfuscate_text($matches[2]) . $matches[3];
61 /**
62 * Obfuscate the mailto link.
64 * @param mixed $matches
65 * @return string
67 private function alter_mailto($matches) {
68 return obfuscate_mailto($matches[2], $matches[4]);