[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/filter/urltolink/ -> filter.php (source)

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Filter converting URLs in the text to HTML links
  20   *
  21   * @package    filter
  22   * @subpackage urltolink
  23   * @copyright  2010 David Mudrak <[email protected]>
  24   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  class filter_urltolink extends moodle_text_filter {
  30  
  31      /**
  32       * @var array global configuration for this filter
  33       *
  34       * This might be eventually moved into parent class if we found it
  35       * useful for other filters, too.
  36       */
  37      protected static $globalconfig;
  38  
  39      /**
  40       * Apply the filter to the text
  41       *
  42       * @see filter_manager::apply_filter_chain()
  43       * @param string $text to be processed by the text
  44       * @param array $options filter options
  45       * @return string text after processing
  46       */
  47      public function filter($text, array $options = array()) {
  48          if (!isset($options['originalformat'])) {
  49              // if the format is not specified, we are probably called by {@see format_string()}
  50              // in that case, it would be dangerous to replace URL with the link because it could
  51              // be stripped. therefore, we do nothing
  52              return $text;
  53          }
  54          if (in_array($options['originalformat'], explode(',', $this->get_global_config('formats')))) {
  55              $this->convert_urls_into_links($text);
  56          }
  57          return $text;
  58      }
  59  
  60      ////////////////////////////////////////////////////////////////////////////
  61      // internal implementation starts here
  62      ////////////////////////////////////////////////////////////////////////////
  63  
  64      /**
  65       * Returns the global filter setting
  66       *
  67       * If the $name is provided, returns single value. Otherwise returns all
  68       * global settings in object. Returns null if the named setting is not
  69       * found.
  70       *
  71       * @param mixed $name optional config variable name, defaults to null for all
  72       * @return string|object|null
  73       */
  74      protected function get_global_config($name=null) {
  75          $this->load_global_config();
  76          if (is_null($name)) {
  77              return self::$globalconfig;
  78  
  79          } elseif (array_key_exists($name, self::$globalconfig)) {
  80              return self::$globalconfig->{$name};
  81  
  82          } else {
  83              return null;
  84          }
  85      }
  86  
  87      /**
  88       * Makes sure that the global config is loaded in $this->globalconfig
  89       *
  90       * @return void
  91       */
  92      protected function load_global_config() {
  93          if (is_null(self::$globalconfig)) {
  94              self::$globalconfig = get_config('filter_urltolink');
  95          }
  96      }
  97  
  98      /**
  99       * Given some text this function converts any URLs it finds into HTML links
 100       *
 101       * @param string $text Passed in by reference. The string to be searched for urls.
 102       */
 103      protected function convert_urls_into_links(&$text) {
 104          //I've added img tags to this list of tags to ignore.
 105          //See MDL-21168 for more info. A better way to ignore tags whether or not
 106          //they are escaped partially or completely would be desirable. For example:
 107          //<a href="blah">
 108          //&lt;a href="blah"&gt;
 109          //&lt;a href="blah">
 110          $filterignoretagsopen  = array('<a\s[^>]+?>');
 111          $filterignoretagsclose = array('</a>');
 112          filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
 113  
 114          // Check if we support unicode modifiers in regular expressions. Cache it.
 115          // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
 116          // chars are going to arrive to URLs officially really soon (2010?)
 117          // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
 118          // Various ideas from: http://alanstorm.com/url_regex_explained
 119          // Unicode check, negative assertion and other bits from Moodle.
 120          static $unicoderegexp;
 121          if (!isset($unicoderegexp)) {
 122              $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
 123          }
 124  
 125          // TODO MDL-21296 - use of unicode modifiers may cause a timeout
 126          $urlstart = '(?:http(s)?://|(?<!://)(www\.))';
 127          $domainsegment = '(?:[\pLl0-9][\pLl0-9-]*[\pLl0-9]|[\pLl0-9])';
 128          $numericip = '(?:(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
 129          $port = '(?::\d*)';
 130          $pathchar = '(?:[\pL0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})';
 131          $path = "(?:/$pathchar*)*";
 132          $querystring = '(?:\?(?:[\pL0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)';
 133          $fragment = '(?:\#(?:[\pL0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)';
 134  
 135          // Lookbehind assertions.
 136          // Is not HTML attribute or CSS URL property. Unfortunately legit text like "url(http://...)" will not be a link.
 137          $lookbehindstart = "(?<!=[\"']|\burl\([\"' ]|\burl\()";
 138          $lookbehindend = "(?<![]),.;])";
 139  
 140          $regex = "$lookbehindstart$urlstart((?:$domainsegment\.)+$domainsegment|$numericip)" .
 141                  "($port?$path$querystring?$fragment?)$lookbehindend";
 142          if ($unicoderegexp) {
 143              $regex = '#' . $regex . '#ui';
 144          } else {
 145              $regex = '#' . preg_replace(array('\pLl', '\PL'), 'a-z', $regex) . '#i';
 146          }
 147  
 148          $text = preg_replace($regex, '<a href="http$1://$2$3$4" class="_blanktarget">$0</a>', $text);
 149  
 150          if (!empty($ignoretags)) {
 151              $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
 152              $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
 153          }
 154  
 155          if ($this->get_global_config('embedimages')) {
 156              // now try to inject the images, this code was originally in the mediapluing filter
 157              // this may be useful only if somebody relies on the fact the links in FORMAT_MOODLE get converted
 158              // to URLs which in turn change to real images
 159              $search = '/<a href="([^"]+\.(jpg|png|gif))" class="_blanktarget">([^>]*)<\/a>/is';
 160              $text = preg_replace_callback($search, 'filter_urltolink_img_callback', $text);
 161          }
 162      }
 163  }
 164  
 165  
 166  /**
 167   * Change links to images into embedded images.
 168   *
 169   * This plugin is intended for automatic conversion of image URLs when FORMAT_MOODLE used.
 170   *
 171   * @param  $link
 172   * @return string
 173   */
 174  function filter_urltolink_img_callback($link) {
 175      if ($link[1] !== $link[3]) {
 176          // this is not a link created by this filter, because the url does not match the text
 177          return $link[0];
 178      }
 179      return '<img class="filter_urltolink_image" alt="" src="'.$link[1].'" />';
 180  }
 181  


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1