Location: PHPKode > projects > Bloggie Lite > includes/function-format.php
<?

// Copyright (C) Bloggie Lite Written by : Sean
// http://www.mywebland.com , http://mybloggie.mywebland.com

// You are requested to retain this copyright notice in order to use
// this software.

//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

if ( !defined('IN_BLOGGIE') )
{
    die("You are not allowed to access this page directly !");
}

function viewsmile($message) {
   global $pref_data;
   include ('smiley-list.php');

   for ($i=1; $i<($smileyno+1); $i++) {
    $message = str_replace($smileydata[$i]['smiley'], "<img src=\"".$pref_data['bloggie_path']."/images/smilies/".$smileydata[$i]['filename']."\" alt=\"".$smileydata[$i]['desc']."\"></img>", $message) ;
   }
   return($message);
}

function viewbbcode($message) {
    $uid = md5(mt_rand());
    $uid = substr($uid, 0, 10);
    $message = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1&#058;", $message);
    $message = " " . $message;
      if (! (strpos($message, "[") && strpos($message, "]")) )
  {
    // Remove padding, return.
    $message = substr($message, 1);
    return $message;
  }

    //$uid = "";
    //$message = str_replace("[br]", "<br />", $message);
    $message = str_replace("[u]", "<u>", $message);
    $message = str_replace("[b]", "<b>", $message);
    $message = str_replace("[/u]", "</u>", $message);
    $message = str_replace("[/b]", "</b>", $message);
    $message = str_replace("[i]", "<i>", $message);
    $message = str_replace("[/i]", "</i>", $message);
    $message = str_replace("[quote]", "<center><div class=\"codequotetitle\"><b>Quote</b> : <div class=\"quote\">", $message);
    $message = str_replace("[/quote]", "</div ></div></center>", $message);
//    $message = str_replace("[code]", "<center><div class=\"codequotetitle\"><b>Code</b> : <div class=\"code\">", $message);
//    $message = str_replace("[/code]", "</div ></div></center>", $message);
    $message = convert_2_code($message);

    // [list] and [list=x] for (un)ordered lists.
    $open_tag = array();
    $open_tag[0] = "[list]";

    // unordered..
    $message = bbencode_first_pass_pda($message, $uid, $open_tag, "[/list]", "[/list:u]", false, 'replace_listitems');

    $open_tag[0] = "[list=1]";
    $open_tag[1] = "[list=a]";

    // ordered.
    $message = bbencode_first_pass_pda($message, $uid, $open_tag, "[/list]", "[/list:o]",  false, 'replace_listitems');

    $bb_tpl['olist_open'] = '<ol type="{LIST_TYPE}">';
    $bb_tpl['olist_open'] = str_replace('{LIST_TYPE}', '\\1', $bb_tpl['olist_open']);

    $message = preg_replace("/\[list=([a1]):$uid\]/si", $bb_tpl['olist_open'], $message);
    $message = str_replace("[list:$uid]", "<ul>", $message);

    // li tags
    $message = str_replace("[*:$uid]", "<li>", $message);
    $message = str_replace("[/list:u:$uid]", "</ul>", $message);
    $message = str_replace("[/list:o:$uid]", "</ol>", $message);

    $bb_tpl['size_open'] = "<span style=\"font-size: {SIZE}px; line-height: normal\">";
    $bb_tpl['size_close']  =  "</span>";
    $bb_tpl['size_open'] = str_replace('{SIZE}', '\\1', $bb_tpl['size_open']);
    // Font size
    $message = preg_replace("/\[size=([1-2]?[0-9])\]/si", $bb_tpl['size_open'] , $message);
    $message = str_replace("[/size]", $bb_tpl['size_close'],  $message);


    // Font colours
    $bb_tpl['color_open']   =  "<span style=\"color: {COLOR_CODE}\">";
    $bb_tpl['color_close']  =  "</span>";
    $bb_tpl['color_open'] = str_replace('{COLOR_CODE}', '\\1', $bb_tpl['color_open']);
    $message = preg_replace("/\[color=(\#[0-9A-F]{6}|[a-z]+)\]/si", $bb_tpl['color_open'], $message);
    $message = str_replace("[/color]", $bb_tpl['color_close'], $message);

    return  substr($message, 1);
}

function autolink($message)
{
    $text = " " . $message;
    $text = preg_replace("#([\n ])([a-z]+?)://([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]+)#i", "\\1<a class='postlink' href=\"\\2://\\3\" target=\"_blank\">\\2://\\3</a>", $text);
    $text = preg_replace("#([\n ])www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]*)?)#i", "\\1<a class='postlink' href=\"http://www.\\2.\\3\\4\" target=\"_blank\">www.\\2.\\3\\4</a>", $text);
    $text = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $text);
    $text = substr($text, 1);
    return($text);
}

function viewlink($message) {

   $bb_tpl['url']='<a target="_blank" class="postlink" href="{URL}">{DESCRIPTION}</a>';
   $bb_tpl['url1'] = str_replace('{URL}', '\\1', $bb_tpl['url']);
   $bb_tpl['url1'] = str_replace('{DESCRIPTION}', '\\1', $bb_tpl['url1']);

   $bb_tpl['url2'] = str_replace('{URL}', 'http://\\1', $bb_tpl['url']);
   $bb_tpl['url2'] = str_replace('{DESCRIPTION}', '\\1', $bb_tpl['url2']);

   $bb_tpl['url3'] = str_replace('{URL}', '\\1', $bb_tpl['url']);
   $bb_tpl['url3'] = str_replace('{DESCRIPTION}', '\\2', $bb_tpl['url3']);

   $bb_tpl['url4'] = str_replace('{URL}', 'http://\\1', $bb_tpl['url']);
   $bb_tpl['url4'] = str_replace('{DESCRIPTION}', '\\3', $bb_tpl['url4']);

   $bb_tpl['img'] = '<div><img src="{URL}" border="0" /></div>';
   $bb_tpl['img'] = str_replace('{URL}', '\\1', $bb_tpl['img']);

   $bb_tpl['imgr'] = '<table cellspacing="0" cellpadding="5" align="right"><tr><td><img src="{URL}" border="0" /></td></tr></table>';
   $bb_tpl['imgr'] = str_replace('{URL}', '\\1', $bb_tpl['imgr']);

   $bb_tpl['imgl'] = '<table cellspacing="0" cellpadding="5" align="left"><tr><td><img src="{URL}" border="0" /></td></tr></table>';
   $bb_tpl['imgl'] = str_replace('{URL}', '\\1', $bb_tpl['imgl']);

   $pattern[] = "#\[url\]([\w]+?://([\w\#$%&~/.\-;:=,?@\]+]+|\[(?!url=))*?)\[/url\]#is";
   $replacement[] = $bb_tpl['url1'];

   $pattern[] = "#\[url\]((www|ftp)\.([\w\#$%&~/.\-;:=,?@\]+]+|\[(?!url=))*?)\[/url\]#is";
   $replacement[] = $bb_tpl['url2'];

   $pattern[] = "#\[url=([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*?)\]([^?\n\r\t].*?)\[/url\]#is";
   $replacement[] = $bb_tpl['url3'];

   $pattern[] = "#\[url=((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*?)\]([^?\n\r\t].*?)\[/url\]#is";
   $replacement[] = $bb_tpl['url4'];

   $message = preg_replace("#\[img\]((http|ftp|https|ftps)://)([^ \?&=\#\"\n\r\t<]*?(\.(jpg|jpeg|gif|png)))\[/img\]#sie", "'[img:]\\1' . str_replace(' ', '%20', '\\3') . '[/img:]'", $message);
   $message = preg_replace("#\[imgl\]((http|ftp|https|ftps)://)([^ \?&=\#\"\n\r\t<]*?(\.(jpg|jpeg|gif|png)))\[/imgl\]#sie", "'[imgl:]\\1' . str_replace(' ', '%20', '\\3') . '[/imgl:]'", $message);
   $message = preg_replace("#\[imgr\]((http|ftp|https|ftps)://)([^ \?&=\#\"\n\r\t<]*?(\.(jpg|jpeg|gif|png)))\[/imgr\]#sie", "'[imgr:]\\1' . str_replace(' ', '%20', '\\3') . '[/imgr:]'", $message);


    $pattern[] = "#\[img:\]([^?](?:[^\[]+|\[(?!url))*?)\[/img:]#i";
    $replacement[] = $bb_tpl['img'];

    $pattern[] = "#\[imgr:\]([^?](?:[^\[]+|\[(?!url))*?)\[/imgr:\]#i";
    $replacement[] = $bb_tpl['imgr'];

    $pattern[] = "#\[imgl:\]([^?](?:[^\[]+|\[(?!url))*?)\[/imgl:\]#i";
    $replacement[] = $bb_tpl['imgl'];

    $message = preg_replace($pattern, $replacement, $message);
    return($message);

    }


function convert_2_code($text)
{
    $code_start = "<center><div class=\"codequotetitle\"><b>Code</b> : <div class=\"code\">";
    $code_end =  "</div ></div></center>";

    // First, do all the 1st-level matches. These need an htmlspecialchars() run,
    // so they have to be handled differently.
    $match_count = preg_match_all("#\[code](.*?)\[/code]#si", $text, $matches);

    for ($i = 0; $i < $match_count; $i++)
    {
        $before_replace = $matches[1][$i];
        $after_replace = $matches[1][$i];

        // Replace 2 spaces with "&nbsp; " so non-tabbed code indents without making huge long lines.
        $after_replace = str_replace("  ", "&nbsp; ", $after_replace);
        // now Replace 2 spaces with " &nbsp;" to catch odd #s of spaces.
        $after_replace = str_replace("  ", " &nbsp;", $after_replace);

        // Replace tabs with "&nbsp; &nbsp;" so tabbed code indents sorta right without making huge long lines.
        $after_replace = str_replace("\t", "&nbsp; &nbsp;", $after_replace);

        // now Replace space occurring at the beginning of a line
        $after_replace = preg_replace("/^ {1}/m", '&nbsp;', $after_replace);
        $str_to_match = "[code]" . $before_replace . "[/code]";

        $replacement = $code_start;
        $replacement .= $after_replace;
        $replacement .= $code_end;

        $text = str_replace($str_to_match, $replacement, $text);
    }

    // Now, do all the non-first-level matches. These are simple.
    $text = str_replace("[code]", $code_start, $text);
    $text = str_replace("[/code]", $code_end, $text);

    return $text;
}



/**
 * $text - The text to operate on.
 * $uid - The UID to add to matching tags.
 * $open_tag - The opening tag to match. Can be an array of opening tags.
 * $close_tag - The closing tag to match.
 * $close_tag_new - The closing tag to replace with.
 * $mark_lowest_level - boolean - should we specially mark the tags that occur
 *                     at the lowest level of nesting? (useful for [code], because
 *                        we need to match these tags first and transform HTML tags
 *                        in their contents..
 * $func - This variable should contain a string that is the name of a function.
 *                That function will be called when a match is found, and passed 2
 *                parameters: ($text, $uid). The function should return a string.
 *                This is used when some transformation needs to be applied to the
 *                text INSIDE a pair of matching tags. If this variable is FALSE or the
 *                empty string, it will not be executed.
 * If open_tag is an array, then the pda will try to match pairs consisting of
 * any element of open_tag followed by close_tag. This allows us to match things
 * like [list=A]...[/list] and [list=1]...[/list] in one pass of the PDA.
 *
 * NOTES:    - this function assumes the first character of $text is a space.
 *                - every opening tag and closing tag must be of the [...] format.
 */
function bbencode_first_pass_pda($text, $uid, $open_tag, $close_tag, $close_tag_new, $mark_lowest_level, $func, $open_regexp_replace = false)
{
    $open_tag_count = 0;

    if (!$close_tag_new || ($close_tag_new == ''))
    {
        $close_tag_new = $close_tag;
    }

    $close_tag_length = strlen($close_tag);
    $close_tag_new_length = strlen($close_tag_new);
    $uid_length = strlen($uid);

    $use_function_pointer = ($func && ($func != ''));

    $stack = array();

    if (is_array($open_tag))
    {
        if (0 == count($open_tag))
        {
            // No opening tags to match, so return.
            return $text;
        }
        $open_tag_count = count($open_tag);
    }
    else
    {
        // only one opening tag. make it into a 1-element array.
        $open_tag_temp = $open_tag;
        $open_tag = array();
        $open_tag[0] = $open_tag_temp;
        $open_tag_count = 1;
    }

    $open_is_regexp = false;

    if ($open_regexp_replace)
    {
        $open_is_regexp = true;
        if (!is_array($open_regexp_replace))
        {
            $open_regexp_temp = $open_regexp_replace;
            $open_regexp_replace = array();
            $open_regexp_replace[0] = $open_regexp_temp;
        }
    }

    if ($mark_lowest_level && $open_is_regexp)
    {
        error("ERROR", "Unsupported operation for bbcode_first_pass_pda().");
    }

    // Start at the 2nd char of the string, looking for opening tags.
    $curr_pos = 1;
    while ($curr_pos && ($curr_pos < strlen($text)))
    {
        $curr_pos = strpos($text, "[", $curr_pos);

        // If not found, $curr_pos will be 0, and the loop will end.
        if ($curr_pos)
        {
            // We found a [. It starts at $curr_pos.
            // check if it's a starting or ending tag.
            $found_start = false;
            $which_start_tag = "";
            $start_tag_index = -1;

            for ($i = 0; $i < $open_tag_count; $i++)
            {
                // Grab everything until the first "]"...
                $possible_start = substr($text, $curr_pos, strpos($text, ']', $curr_pos + 1) - $curr_pos + 1);

                //
                // We're going to try and catch usernames with "[' characters.
                //
                if( preg_match('#\[quote=\\\"#si', $possible_start, $match) && !preg_match('#\[quote=\\\"(.*?)\\\"\]#si', $possible_start) )
                {
                    // OK we are in a quote tag that probably contains a ] bracket.
                    // Grab a bit more of the string to hopefully get all of it..
                    if ($close_pos = strpos($text, '"]', $curr_pos + 9))
                    {
                        if (strpos(substr($text, $curr_pos + 9, $close_pos - ($curr_pos + 9)), '[quote') === false)
                        {
                            $possible_start = substr($text, $curr_pos, $close_pos - $curr_pos + 2);
                        }
                    }
                }

                // Now compare, either using regexp or not.
                if ($open_is_regexp)
                {
                    $match_result = array();
                    if (preg_match($open_tag[$i], $possible_start, $match_result))
                    {
                        $found_start = true;
                        $which_start_tag = $match_result[0];
                        $start_tag_index = $i;
                        break;
                    }
                }
                else
                {
                    // straightforward string comparison.
                    if (0 == strcasecmp($open_tag[$i], $possible_start))
                    {
                        $found_start = true;
                        $which_start_tag = $open_tag[$i];
                        $start_tag_index = $i;
                        break;
                    }
                }
            }

            if ($found_start)
            {
                // We have an opening tag.
                // Push its position, the text we matched, and its index in the open_tag array on to the stack, and then keep going to the right.

                $match = array("pos" => $curr_pos, "tag" => $which_start_tag, "index" => $start_tag_index);
                bbcode_array_push($stack, $match);
                //
                // Rather than just increment $curr_pos
                // Set it to the ending of the tag we just found
                // Keeps error in nested tag from breaking out
                // of table structure..
                //
                $curr_pos += strlen($possible_start);
            }
            else
            {
                // check for a closing tag..
                $possible_end = substr($text, $curr_pos, $close_tag_length);
                if (0 == strcasecmp($close_tag, $possible_end))
                {
                    // We have an ending tag.
                    // Check if we've already found a matching starting tag.
                    if (sizeof($stack) > 0)
                    {
                        // There exists a starting tag.
                        $curr_nesting_depth = sizeof($stack);

                        // We need to do 2 replacements now.
                        $match = bbcode_array_pop($stack);
                        $start_index = $match['pos'];
                        $start_tag = $match['tag'];
                        $start_length = strlen($start_tag);
                        $start_tag_index = $match['index'];

                        if ($open_is_regexp)
                        {
                            $start_tag = preg_replace($open_tag[$start_tag_index], $open_regexp_replace[$start_tag_index], $start_tag);
                        }

                        // everything before the opening tag.
                        $before_start_tag = substr($text, 0, $start_index);

                        // everything after the opening tag, but before the closing tag.
                        $between_tags = substr($text, $start_index + $start_length, $curr_pos - $start_index - $start_length);

                        // Run the given function on the text between the tags..
                        if ($use_function_pointer)
                        {
                            $between_tags = $func($between_tags, $uid);
                        }

                        // everything after the closing tag.
                        $after_end_tag = substr($text, $curr_pos + $close_tag_length);

                        // Mark the lowest nesting level if needed.
                        if ($mark_lowest_level && ($curr_nesting_depth == 1))
                        {
                            if ($open_tag[0] == '[code]')
                            {
                                $code_entities_match = array('#<#', '#>#', '#"#', '#:#', '#\[#', '#\]#', '#\(#', '#\)#', '#\{#', '#\}#');
                                $code_entities_replace = array('&lt;', '&gt;', '&quot;', '&#58;', '&#91;', '&#93;', '&#40;', '&#41;', '&#123;', '&#125;');
                                $between_tags = preg_replace($code_entities_match, $code_entities_replace, $between_tags);
                            }
                            $text = $before_start_tag . substr($start_tag, 0, $start_length - 1) . ":$curr_nesting_depth:$uid]";
                            $text .= $between_tags . substr($close_tag_new, 0, $close_tag_new_length - 1) . ":$curr_nesting_depth:$uid]";
                        }
                        else
                        {
                            if ($open_tag[0] == '[code]')
                            {
                                $text = $before_start_tag . '&#91;code&#93;';
                                $text .= $between_tags . '&#91;/code&#93;';
                            }
                            else
                            {
                                if ($open_is_regexp)
                                {
                                    $text = $before_start_tag . $start_tag;
                                }
                                else
                                {
                                    $text = $before_start_tag . substr($start_tag, 0, $start_length - 1) . ":$uid]";
                                }
                                $text .= $between_tags . substr($close_tag_new, 0, $close_tag_new_length - 1) . ":$uid]";
                            }
                        }

                        $text .= $after_end_tag;

                        // Now.. we've screwed up the indices by changing the length of the string.
                        // So, if there's anything in the stack, we want to resume searching just after it.
                        // otherwise, we go back to the start.

                        if (sizeof($stack) > 0)
                        {
                            $match = bbcode_array_pop($stack);
                            $curr_pos = $match['pos'];
//                            bbcode_array_push($stack, $match);
//                            ++$curr_pos;
                        }
                        else
                        {
                            $curr_pos = 1;
                        }
                    }
                    else
                    {
                        // No matching start tag found. Increment pos, keep going.
                        ++$curr_pos;
                    }
                }
                else
                {
                    // No starting tag or ending tag.. Increment pos, keep looping.,
                    ++$curr_pos;
                }
            }
        }
    } // while

    return $text;

} // bbencode_first_pass_pda()

function bbcode_array_pop(&$stack)
{
   $arrSize = count($stack);
   $x = 1;
      //print_r($stack);
      //echo $arrSize;
   while(list($key, $val) = each($stack))
   {
      if($x < count($stack))
      {
             $tmpArr[] = $val;
      }
      else
      {
             $return_val = $val;
      }
      $x++;
   }
   if (isset($tmpArr)) $stack = $tmpArr;
   else  $stack =array();
   return($return_val);
}

function bbcode_array_push(&$stack, $value)
{
   $stack[] = $value;
   return(sizeof($stack));
}

function replace_listitems($message, $uid)
{
    $message = str_replace("[*]", "[*:$uid]", $message);

    return $message;
}

?>
Return current item: Bloggie Lite