Changeset 646 for branches/1.1dev/lib


Ignore:
Timestamp:
Oct 25, 2018 12:32:47 AM (6 years ago)
Author:
anonymous
Message:

Add hyperlinkTxt function

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/1.1dev/lib/Utilities.inc.php

    r423 r646  
    6666
    6767/**
    68  * Returns text with appropriate html translations. 
     68 * Returns text with appropriate html translations.
    6969 *
    7070 * @param  string $txt              Text to clean.
    71  * @param  bool   $preserve_html    If set to true, oTxt will not translage <, >, ", or ' 
     71 * @param  bool   $preserve_html    If set to true, oTxt will not translage <, >, ", or '
    7272 *                                  characters into HTML entities. This allows HTML to pass
    7373 *                                  through unmunged.
     
    9090        $search['retain_left_angle']       = '/&lt;/';
    9191        $replace['retain_left_angle']      = '<';
    92        
     92
    9393        $search['retain_right_angle']      = '/&gt;/';
    9494        $replace['retain_right_angle']     = '>';
    95        
     95
    9696        $search['retain_single_quote']     = '/&#039;/';
    9797        $replace['retain_single_quote']    = "'";
    98        
     98
    9999        $search['retain_double_quote']     = '/&quot;/';
    100100        $replace['retain_double_quote']    = '"';
     
    109109
    110110/**
    111  * Returns text with stylistic modifications. 
     111 * Returns text with stylistic modifications.
    112112 *
    113113 * @param  string   $txt  Text to clean.
     
    131131    $search['single_quotes']    = '/(^|[^\w=])(?:\'|&#39;|&lsquo;)([^\']+?)(?:\'|&#39;|&rsquo;)([^\w]|$)/';
    132132    $replace['single_quotes']   = '\\1&lsquo;\\2&rsquo;\\3';
    133    
     133
    134134    // em--dashes  become em&mdash;dashes
    135135    $search['em_dash']          = '/(\s*[^!<-])--([^>-]\s*)/';
    136136    $replace['em_dash']         = '\\1&mdash;\\2';
    137    
     137
    138138    // & becomes &amp;
    139139    $search['ampersand']        = '/&((?![\w\d#]{1,10};))/';
     
    141141
    142142    return preg_replace($search, $replace, $txt);
     143}
     144
     145/*
     146* Finds all URLs in text and hyperlinks them.
     147*
     148* @access   public
     149* @param    string  $text   Text to search for URLs.
     150* @param    bool    $strict True to only include URLs starting with a scheme (http:// ftp:// im://), or false to include URLs starting with 'www.'.
     151* @param    mixed   $length Number of characters to truncate URL, or NULL to disable truncating.
     152* @param    string  $delim  Delimiter to append, indicate truncation.
     153* @return   string          Same input text, but URLs hyperlinked.
     154* @author   Quinn Comendant <quinn@strangecode.com>
     155* @version  2.1
     156* @since    22 Mar 2015 23:29:04
     157*/
     158function hyperlinkTxt($text, $strict=false, $length=null, $delim='
')
     159{
     160    // A list of schemes we allow at the beginning of a URL.
     161    $schemes = 'mailto:|tel:|skype:|callto:|facetime:|bitcoin:|geo:|magnet:\?|sip:|sms:|xmpp:|view-source:(?:https?://)?|[\w-]{2,}://';
     162
     163    // Capture the full URL into the first match and only the first X characters into the second match.
     164    // This will match URLs not preceded by " ' or = (URLs inside an attribute) or ` (Markdown quoted) or double-scheme (http://http://www.asdf.com)
     165    // Valid URL characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=
     166    $regex = '@
     167        \b                              # Start with a word-boundary.
     168        (?<!"|\'|=|>|`|\]\(|[:/]/) # Negative look-behind to exclude URLs already in <a> tag, <tags>beween</tags>, `Markdown quoted`, [Markdown](link), and avoid broken:/ and doubled://schemes://
     169        (                               # Begin match 1
     170            (                           # Begin match 2
     171                (?:%s)                  # URL starts with known scheme or www. if strict = false
     172                [^\s/$.?#]+             # Any domain-valid characters
     173                [^\s"`<>]{1,%s}         # Match 2 is limited to a maximum of LENGTH valid URL characters
     174            )
     175            [^\s"`<>]*                  # Match 1 continues with any further valid URL characters
     176            ([^\P{Any}\s
<>«»"—–%s])    # Final character not a space or common end-of-sentence punctuation (.,:;?!, etc). Using double negation set, see http://stackoverflow.com/a/4786560/277303
     177        )
     178        @Suxi
     179    ';
     180    $regex = sprintf($regex,
     181        ($strict ? $schemes : $schemes . '|www\.'), // Strict=false adds "www." to the list of allowed start-of-URL.
     182        ($length ? $length : ''),
     183        ($strict ? '' : '?!.,:;)\'-') // Strict=false excludes some "URL-valid" characters from the last character of URL. (Hyphen must remain last character in this class.)
     184    );
     185
     186    // Use a callback function to decide when to append the delim.
     187    // Also encode special chars with oTxt().
     188    return preg_replace_callback($regex, function ($m) use ($length, $delim) {
     189        $url = $m[1];
     190        $truncated_url = $m[2] . $m[3];
     191        $absolute_url = preg_replace('!^www\.!', 'http://www.', $url);
     192        if (is_null($length) || $url == $truncated_url) {
     193            // If not truncating, or URL was not truncated.
     194            // Remove http schemas, and any single trailing / to make the display URL.
     195            $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], $url);
     196            return sprintf('<a href="%s">%s</a>', oTxt($absolute_url), $display_url);
     197        } else {
     198            // Truncated URL.
     199            // Remove http schemas, and any single trailing / to make the display URL.
     200            $display_url = preg_replace(['!^https?://!', '!^([^/]+)/$!'], ['', '$1'], trim($truncated_url));
     201            return sprintf('<a href="%s">%s%s</a>', oTxt($absolute_url), $display_url, $delim);
     202        }
     203    }, $text);
    143204}
    144205
     
    168229    case 'middle' :
    169230        return preg_replace(array(sprintf('/^(.{%s}).{4,}(.{%s})$/sU', $part1, $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim . '$2', $delim), $str);
    170         break;   
     231        break;
    171232    case 'end' :
    172233        return preg_replace(array(sprintf('/^(.{%s}).{4,}$/sU', $part1 + $part2), '/\s*\.{3,}\s*/sU'), array('$1' . $delim, $delim), $str);
     
    174235    }
    175236}
    176    
     237
    177238/**
    178239 * Generates a hexadecimal html color based on provided word.
     
    264325    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    265326    $ii = count($units) - 1;
    266  
     327
    267328    // Max unit
    268329    $unit = array_search((string) $unit, $units);
     
    270331        $unit = $ii;
    271332    }
    272  
     333
    273334    // Loop
    274335    $i = 0;
     
    277338        $i++;
    278339    }
    279  
     340
    280341    return sprintf($format, $size, $units[$i]);
    281342}
     
    287348 * @param  mixed $var       The variable that is being set.
    288349 * @param  mixed $default   What to set it to if $val is not currently set.
    289  * @return mixed            The resulting value of $var. 
     350 * @return mixed            The resulting value of $var.
    290351 */
    291352function setDefault(&$var, $default='')
     
    332393 */
    333394function urlEncodeArray($data, $prefix='', $_return=true) {
    334    
     395
    335396    // Data is stored in static variable.
    336397    static $args;
    337    
     398
    338399    if (is_array($data)) {
    339400        foreach ($data as $key => $val) {
     
    348409        $args[$prefix] = urlencode($data);
    349410    }
    350    
     411
    351412    if ($_return) {
    352413        // This is not a recursive execution. All recursion is complete.
     
    369430 */
    370431function urlEncodeArrayToString($data, $prefix='') {
    371    
     432
    372433    $array_args = urlEncodeArray($data, $prefix);
    373434    $url_args = '';
     
    381442
    382443/**
    383  * An alternative to "shuffle()" that actually works. 
     444 * An alternative to "shuffle()" that actually works.
    384445 *
    385446 * @param  array $array1   input array
     
    393454        return array();
    394455    }
    395    
     456
    396457    srand((double) microtime() * 10000000);
    397458    $rand = array_rand($array1);
    398    
     459
    399460    $array2[] = $array1[$rand];
    400461    unset ($array1[$rand]);
    401    
     462
    402463    return $array2 + arrayRand($array1, $array2);
    403464}
     
    428489 * Prints the word "checked" if a variable is set, and optionally matches
    429490 * the desired value, otherwise prints nothing,
    430  * used for printing the word "checked" in a checkbox form input. 
     491 * used for printing the word "checked" in a checkbox form input.
    431492 *
    432493 * @param  mixed $var     the variable to compare
     
    454515 * prints the word "selected" if a variable is set, and optionally matches
    455516 * the desired value, otherwise prints nothing,
    456  * otherwise prints nothing, used for printing the word "checked" in a 
    457  * select form input 
     517 * otherwise prints nothing, used for printing the word "checked" in a
     518 * select form input
    458519 *
    459520 * @param  mixed $var     the variable to compare
     
    500561 *
    501562 * @param  array $date     String date to convert.
    502  * @param  array $format   Date format to pass to date(). 
     563 * @param  array $format   Date format to pass to date().
    503564 *                         Default produces MySQL datetime: 0000-00-00 00:00:00.
    504565 *
     
    513574        $sql_date = date($format, strtotime($date));
    514575    }
    515    
     576
    516577    return $sql_date;
    517578}
     
    528589{
    529590    static $magic_quotes_gpc;
    530    
     591
    531592    if (!isset($magic_quotes_gpc)) {
    532593        $magic_quotes_gpc = get_magic_quotes_gpc();
    533594    }
    534    
     595
    535596    if ($magic_quotes_gpc) {
    536597        if (!is_array($var)) {
     
    614675{
    615676    global $CFG;
    616    
     677
    617678    if ('' == $val) {
    618679        logMsg(sprintf('Adding signature to empty string.', null), LOG_NOTICE, __FILE__, __LINE__);
    619680    }
    620    
     681
    621682    if (!isset($key)) {
    622683        $key = $CFG->signing_key;
     
    671732    /**
    672733    * Translates text
    673     * 
     734    *
    674735    * @access public
    675736    * @param string $text the text to be translated
     
    679740        return $text;
    680741    }
    681    
     742
    682743    /**
    683744    * Translates text
    684     * 
     745    *
    685746    * @access public
    686747    * @param string $text the text to be translated
     
    690751        return $text;
    691752    }
    692    
     753
    693754    /**
    694755    * Translates text by domain
    695     * 
     756    *
    696757    * @access public
    697758    * @param string $domain the language to translate the text into
     
    702763        return $text;
    703764    }
    704    
     765
    705766    /**
    706767    * Translates text by domain and category
    707     * 
     768    *
    708769    * @access public
    709770    * @param string $domain the language to translate the text into
     
    715776        return $text;
    716777    }
    717    
     778
    718779    /**
    719780    * Binds the text domain
    720     * 
     781    *
    721782    * @access public
    722783    * @param string $domain the language to translate the text into
    723     * @param string 
     784    * @param string
    724785    * @return string translated text
    725786    */
     
    727788        return $domain;
    728789    }
    729    
     790
    730791    /**
    731792    * Sets the text domain
    732     * 
     793    *
    733794    * @access public
    734795    * @param string $domain the language to translate the text into
     
    742803/**
    743804 * Sends empty output to the browser and flushes the php buffer so the client
    744  * will see data before the page is finished processing. 
     805 * will see data before the page is finished processing.
    745806 */
    746807function flushBuffer() {
Note: See TracChangeset for help on using the changeset viewer.