<?php

# PLUGIN PREVIEW BY TEXTPATTERN.INFO


/*
    adi_link - Enhanced links

    Written by Adi Gilbert

    Released under the GNU Lesser General Public License

    Version history:
        0.5        - new attribute: 'link_span'
                - fixed lack of recognition for https://
                - fixed up parse problem in container mode
                - cater for URLs in "Article link" custom field
                - now fails more subtly if id not found
                - auto-detects external links
                - new 'article_id' attribute
                - TXP 4.6 tag registration
        0.4        - new attribute: 'short_url_text'
                - new attribute: 'url_text_only'
                - fix: coding faux pas when setting ext_class (thanks jakob)
        0.3        - new attribute: 'quiet'
                - new attributes: 'wraptag', 'wraptag_id', 'wraptag_class'
                - new attributes: 'label', 'tail'
                - new attribute: 'title_suffix'
                - new attribute: 'image'
                - new attribute: 'no_wrap'
                - enhancement: support for "Article link" custom field
        0.2        - fixed: no error message if URL missing
                - new attribute: 'suppress_href' (for Phlip)
                - new attribute: 'anchor'
                - new attribute: 'section'
                - new attribute: 'category'
                - new attribute: 'urlvars'
        0.1        - initial release
*/

// TXP 4.6 tag registration
if (class_exists('\Textpattern\Tag\Registry')) {
    
Txp::get('\Textpattern\Tag\Registry')
        ->
register('adi_link')
    ;
}

function 
adi_link($atts$thing='') {
    global 
$prefs,$pretext,$thislink,$thisarticle;

    
extract(lAtts(array(
        
'html_id'        => '',            // HTML ID
        
'class'            => '',            // CSS class
        
'title'            => '',            // Title attribute
        
'ext_link'        => '',            // external link or not
        
'ext_class'        => 'ext_link',    // default external class
        
'rel_name'        => '',            // HTML "rel" attribute
        
'url'            => '',            // the URL
        
'link_text'        => '',            // link text
        
'link_span'        => '0',            // <span>link text</span>
        
'no_wrap'        => '0',            // substitute spaces for &nbsp; to prevent link text wrapping
        
'title_suffix'    => '',            // append to title
        
'pretty_url'    => '1',            // strip "http://" & trailing slash if URL used as link text
        
'escape'        => 'html',        // escape HTML entities
        
'single_url'    => '0',            // force single url mode
        
'url_link_text'    => '0',            // use URL for the link text
        
'short_url_text'    => '0',        // shorten the URL link text (e.g. www.example.com/section/subsection/article -> www.example.com)
        
'id'            => '',            // TXP link ID
        
'article_id'    => '',            // TXP article ID
        
'suppress_href'    => '0',            // suppress output of "href" attribute
        
'url_text_only'    => '0',            // output the URL as text only (i.e. no <a>)
        
'section'        => '',            // section name (if specified & empty then current section)
        
'anchor'        => '',            // page anchor
        
'urlvars'        => '',            // URL variables e.g. 'var1=value1&var2=value2'
        
'category'        => '',            // category name (if specified & empty then current category)
        
'quiet'            => '0',            // don't moan if no URL can be found
        
'wraptag'        => '',            // wrap a tag around link
        
'wraptag_class'    => '',            // class for wraptag
        
'wraptag_id'    => '',            // id for wraptag
        
'label'            => '',            // string to precede link output
        
'tail'            => '',            // string to follow link output
        
'image'            => '0',            // container tag mode only, the image is enclosed (rather than the URL)
    
), $atts));

    
// check if 'section' attribute specified
    
$section_mode array_key_exists('section'$atts);
    if (
$section_mode) {
        if (
$section == '')
            
$url_array['s'] = $pretext['s'];
        else
            
$url_array['s'] = $section;
    }

    
// check if 'category' attribute specified
    
$category_mode array_key_exists('category'$atts);
    if (
$category_mode) {
        if (
$category == '')
            
$url_array['c'] = $pretext['c'];
        else
            
$url_array['c'] = $category;
    }

    
// get section/category URL
    
if (($section_mode) || ($category_mode))
        
$url pagelinkurl($url_array);

    
// all alone at the singles bar?
    
$single_link FALSE;
    if (
$single_url) { // force "single url enclosed"
        
$single_link TRUE;
        
$url trim(parse($thing));
    }

    
// check if we're in a link form
    
if (isset($thislink) && !empty($thislink)) { // assume link form
        
$url $thislink['url'];
        if (
$link_text == ""$link_text $thislink['linkname']; // link_text attribute overrides DB value
    
}

    
// enclosure acts?
    
if (($thing === NULL) || $image// not enclosing tag or image is enclosed, so url is supplied from elsewhere
        
$single_link TRUE;
    else { 
// enclosing tag so parse it & see what it becomes
        
$this_thing parse($thing);
        if (
preg_match('@^http.*://@',trim($this_thing))) { // single url enclosed
            
$url trim($this_thing);
            
$single_link TRUE;
        }
    }

    
// check if we're in an article (either form or body)
    
if ($thisarticle && !isset($atts['id']) && !$url && !isset($atts['article_id'])) {
        
// we're in an article, no URL/link id/article id supplied, so try "Article link" custom field instead
        
if (!empty($thisarticle['article link'])) {
            
$id_list explode(',',$thisarticle['article link']); // comma separated list ready
            
$id $id_list[0]; // but only recognise first item
            
if (!is_numeric($id)) { // not a number, so assume it's a URL
                
$id '';
                
$url trim($thisarticle['article link']);
            }
            
$single_link TRUE;
        }
        else {
            
// must be within article body
        
}
    }

    
// link id supplied?
    
if ($id) {
        
$a safe_row('url,linkname,description','txp_link','id = '.$id);
        if (
$a) { // ID found in database
            
$url $a['url'];
            if (
$link_text == ""// use link name
                
$link_text $a['linkname'];
        }
        else
            
$id ='';
    }

    
// article id supplied?
    
if ($article_id) {
        
$url permlinkurl_id($article_id);
        if (
$url) {
            
$a safe_row('title','textpattern','id='.$article_id);
            
extract($a); // set title
            
$title html_entity_decode($title);
            if (
$link_text == ""// use article title
                
$link_text $title;
        }
    }

    
// fix up some values
    
if ($anchor) { // anchor supplied
        
$anchor '#'.$anchor;
        
// if no URL & no section then use current page
        
if (!$url && !$section_mode) {
            
$url $prefs['siteurl'].$pretext['req']; // make up URL for current page
        
}
    }
    if (
$urlvars// check if there's some URL vars already present
        
strstr($url,'?') !== FALSE ?
            
$urlvars '&'.$urlvars // tack onto end
            
$urlvars '?'.$urlvars// start a new one

    // check if supplied url is missing "http://" or "https://"
    
if (!preg_match('@^http.*://@',$url))
        
$url 'http://'.$url;

    
// auto-detect external links
    
if ($ext_link == '') { // auto detect external links
        
$this_url preg_replace('@^http.*://@','',$url); // strip "http(s)://"
        
if (strpos($this_url,$prefs['siteurl']) === FALSE)
            
$ext_link '1';
    }

    
// class action
    
if ($class == ''// if 'class' not specified, set some defaults
        
$ext_link $class $ext_class $class "";

    
// relatively speaking
    
if ($rel_name == ''// if 'rel' not specified, set some defaults
        
$ext_link $rel_name "external" $rel_name "bookmark";

    
// fix up link text
    
if (($link_text == "") || ($url_link_text)) $link_text $url// default 'link_text' to URL
    
if ($pretty_url) {
        if (
preg_match('@^http.*://@',$link_text)) // strip "http(s)://"
//             $link_text = str_replace('http://', '',$link_text);
            
$link_text preg_replace('@^http.*://@','',$link_text); // strip "http(s)://"
        
if (substr($link_text, -11) == "/"// strip trailing slash
            
$link_text substr($link_text,0,-1);
    }
    if (
$short_url_text) { // shorten the URL link text to required number of '/' separated chunks
        
$loadsachunks explode("/"$link_text);
        for (
$i 1$i <= $short_url_text$i++)
            if (!empty(
$loadsachunks)) $somechunks[] = array_shift($loadsachunks);
        
$link_text implode("/"$somechunks);
    }

    
// title action
    
if ($title == "")
        if (
$id// take title from database
            
$title $a['linkname'];
        else
            
$title $link_text// default 'title' to 'link_text'
    
if ($title_suffix)
        
$title .= $title_suffix;

    
// escape to victory
    
if ($escape == "html") {
        
$url htmlspecialchars($url);
        
$urlvars htmlspecialchars($urlvars);
        
$link_text htmlspecialchars($link_text);
        
$title htmlspecialchars($title);
    }

    
// no rap & less chat
    
if ($no_wrap)
        
$link_text str_replace(' ','&nbsp;',$link_text);

    
// generate markup
    
if ($single_link) { // single link mode
        
if ((($url == 'http://') || ($url == 'https://')) && !($suppress_href)) // note that 'http://' automatically inserted above
            
if ($quiet// don't say nuffin ... don't even get label etc
                
return '';
            else
                return 
'no URL';
        else {
            
$attr '';
            
$url .= $urlvars.$anchor;
            if (!
$suppress_href$attr ' href="'.$url.'"';
            if (
$title$attr .= ' title="'.$title.'"';
            if (
$rel_name$attr .= ' rel="'.$rel_name.'"';
            if (
$image// substitute link text for an image
                
$link_text parse($thing);
            else 
// not an image
                
if ($link_span)
                    
$link_text tag($link_text,'span');
            if (
$url_text_only// look no links!
                
$out $url;
            else
                
$out doTag($link_text,'a',$class,$attr,$html_id);
            
$out $label.$out.$tail;
            if (
$wraptag) { // add wraptag stuff
                
$wrap_attr '';
                if (
$wraptag_id$wrap_attr .= ' id="'.$wraptag_id.'"';
                if (
$wraptag_class$wrap_attr .= ' class="'.$wraptag_class.'"';
                
$out tag($out,$wraptag,$wrap_attr);
            }
            return 
$out;
        }
    }
    else { 
// assume a block of pre-parsed links (from Textile) is enclosed
        
$this_thing parse($thing);
        if (
$class == "")
            
$replace "";
        else
            
$replace 'class="'.$class.'" ';
        
$replace .= 'rel="'.$rel_name.'" href="'.'$1';
        
$out preg_replace('/href="/',$replace,$this_thing); // this assumes all links are external regardless (TODO)!
        
return doTag($out,"");
    }
}