<?
/**
 * Сделать внешние ссылки неиндексируемыми
 *
 * @param string $text
 * @return string
 */
function make_external_links_unfollow($text) {
    global $nc_core;
	$all_domains = $nc_core->catalogue->get_current('Domain').' '.$nc_core->catalogue->get_current('Mirrors');

    $links = get_tags_by_attr('a', 'href', $text);
    if ( count($links['all']) ) {
        foreach ( $links['attr'] as $k => $url ) {
            $scheme = parse_url($url, PHP_URL_SCHEME);
            $domain = parse_url($url, PHP_URL_HOST);
            $domain = str_replace('www.', '', $domain);

			$replace = $links['all'][$k];
			if (
				 ( !empty($scheme) || !empty($domain) ) &&
				 strpos($replace, ' rel=') === false &&
				 !preg_match('/\b'.preg_quote($domain, '/').'\b/i', $all_domains)
			   ) {
                $replace = preg_replace( '/<a/i', '<a rel="nofollow"'.( strpos($replace, ' target=') === false ? ' target="_blank"' : NULL ), $replace );
                $text = str_replace( $links['all'][$k], $replace, $text );
            }
        }
    }

    return $text;
} // end function make_external_links_unfollow



/**
 * Найти теги с нужным атрибутом
 *
 * @param string $tag - имя тега
 * @param string $attr - имя атрибута
 * @param string $xml - (ht|x)ml строка
 * @return array: 'all' - весь тег, 'attr' - значение атрибута, 'cont' - содержимое
 */
function get_tags_by_attr( $tag, $attr, $xml ) {
	if( empty($tag) ) $tag = '\w+';
	else $tag = preg_quote($tag);
	if( empty($attr) ) $attr = '\w+';
	else $attr = preg_quote($attr);

	preg_match_all("|<".$tag."[^>]+".$attr."=['\"]+([^'\"]+)['\"]+[^>]*>(.*?)</".$tag.">|is",
				   $xml,
				   $matches,
				   PREG_PATTERN_ORDER);

    return array(
        'all'  => $matches[0],
        'attr' => $matches[1],
        'cont' => $matches[2]
    );
} // end function get_tags_by_attr
?>
