Re: PHPBB3 : Resize Width and Height of Image BBCode

Micro things in Macro World

PHPBB3 : Resize Width and Height of Image BBCode

Postby Admin » Tue Sep 22, 2009 4:36 pm

I recently found that, PHPBB3 doesn't allow specifying width and height of images in Post. However since we require to modify the width and height in some cases, I have tried to understand the working of the underlying code for BBCodes so that I could edit the files to make this option available for users. I found one or two good ways to do it.

1) Easy Way - New Custom BBCode Through Admin Control Panel (ACP)
You can add a custom BBCode Tag in your ACP. Follow the steps as below

a) Go to ACP -> Posting -> BBCodes -> Add a new BBCode.
b) In BBCode usage, type
Code: Select all
[rimg width={NUMBER1} height={NUMBER2}]{URL}[/rimg] 
or
Code: Select all
[rimg=({NUMBER1},{NUMBER2}]{URL}[/rimg] 
It depends on how you want the bbcode to be.
c) In HTML replacement, type
Code: Select all
<img src='{URL}' width='{NUMBER1}' height='{NUMBER2}' /> 

d) Type whatever you want in Help Line.
e) If needed Enable "Display on Posting Page" option and give submit.

However, I feel that above method has two disadvantages. One is, we need to have a separate BBCode for resizing alone, which the users may feel uncomfortable. Another reason is that, I can't make width/height optional. So I would need to have different BBCodes for different combinations like {width present, height absent} or {width absent, height present} etc. This makes things more complicated.

Because of these, I tried to find a mod that will make necessary changes so that I could use the same [ img ] BBCode, But still use width and height, and that too optionally. But google search didn't give me positive results. There wasn't much information about this. (Found one alternative though)

So here is my method to edit the BBCode files to make this work. This is my first attempt to make a modification in PHPBB3, so I would like someone to tell how good it is.

2) Edit BBCodes files directly (CAUTION : Take necessary backups of files you are editing, as it may screw up things, if anything went wrong).

Thanks to this thread which was like a starter for me to attempt this modification. I edited a template based on Pro Silver.

a) Open <Forum Root Folder>\styles\<Template Name>\template\template.cfg
Find
Code: Select all
template_bitfield = lNg= 

Replace
Code: Select all
template_bitfield = nNg= 

(Reason could be found here)

b) Install the style. (If you have already installed this template, even if you uninstall and install the template this mod won't work. Because, the above replacement is not reflected in the Database while reinstalling the template. If you have already installed this template, go to your sql db manager, open the table TABLE-PREFIX_styles_template, browse and edit "bbcode_bitfield" field corresponding to the template you are editing. )

c) Open <Forum Root Folder>\styles\<Template Name>\template\bbcode.html
Find
Code: Select all
<!-- BEGIN img --><img src="{URL}" alt="{L_IMAGE}" /><!-- END img --> 

After that ADD this
Code: Select all
<!-- BEGIN imgw --><img src="{URL}" width="{WIDTH}" alt="{L_IMAGE}" /><!-- END imgw -->
<!--
 BEGIN imgh --><img src="{URL}" height="{HEIGHT}" alt="{L_IMAGE}" /><!-- END imgh -->
<!--
 BEGIN imgwh --><img src="{URL}" width="{WIDTH}" height="{HEIGHT}" alt="{L_IMAGE}" /><!-- END imgwh --> 


d) Open <Forum Root Folder>\includes\message_parser.php
Find
Code: Select all
'img' => array('bbcode_id' => 4,    'regexp' => array('#\[img\](.*)\[/img\]#iUe' => "\$this->bbcode_img('\$1')")), 

Replace with
Code: Select all
'img'    => array('bbcode_id' => 4,    'regexp' => array('#\[img( width=([0-9]+))?( height=([0-9]+))?\](.*)\[/img\]#iUe' => "\$this->bbcode_img('\$2','\$4','\$5')")), 



Find
Code: Select all
/**
    * Parse img tag
    */
    function bbcode_img($in)
    {
        global $user, $config;

        if (!$this->check_bbcode('img', $in))
        {
            return $in;
        }

        $in = trim($in);
        $error = false;

        $in = str_replace(' ', '%20', $in);

        // Checking urls
        if (!preg_match('#^' . get_preg_expression('url') . '$#i', $in) && !preg_match('#^' . get_preg_expression('www_url') . '$#i', $in))
        {
            return '[img]' . $in . '[/img]';
        }

        // Try to cope with a common user error... not specifying a protocol but only a subdomain
        if (!preg_match('#^[a-z0-9]+://#i', $in))
        {
            $in = 'http://' . $in;
        }

        if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
        {
            $stats = @getimagesize($in);

            if ($stats === false)
            {
                $error = true;
                $this->warn_msg[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
            }
            else
            
{
                if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $stats[1])
                {
                    $error = true;
                    $this->warn_msg[] = sprintf($user->lang['MAX_IMG_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
                }

                if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $stats[0])
                {
                    $error = true;
                    $this->warn_msg[] = sprintf($user->lang['MAX_IMG_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
                }
            }
        }

        if ($error || $this->path_in_domain($in))
        {
            return '[img]' . $in . '[/img]';
        }

        return '[img:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/img:' . $this->bbcode_uid . ']';
    }
 


Replace with

Code: Select all
/**
    * Parse img tag
    */
    function bbcode_img($width,$height,$in)
    {
        global $user, $config;

        if (!$this->check_bbcode('img', $in))
        {
            return $in;
        }
        
        $tempwidth 
= ($width)?' width='.$width:'';
        $tempheight = ($height)?' height='.$height:'';
        
        
// Do not allow 0-sizes generally being entered
        if (($width && $width <= 0) || ($height && $height <= 0))
        {            
            return 
'[img' . $tempwidth . $tempheight . ']' . $in . '[/img]';
        }
        
        
        $in 
= trim($in);
        $error = false;

        $in = str_replace(' ', '%20', $in);

        // Checking urls
        if (!preg_match('#^' . get_preg_expression('url') . '$#i', $in) && !preg_match('#^' . get_preg_expression('www_url') . '$#i', $in))
        {
            return '[img]' . $in . '[/img]';
        }

        // Try to cope with a common user error... not specifying a protocol but only a subdomain
        if (!preg_match('#^[a-z0-9]+://#i', $in))
        {
            $in = 'http://' . $in;
        }

        if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
        {
            $stats = @getimagesize($in);

            if ($stats === false)
            {
                $error = true;
                $this->warn_msg[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
            }
            else
            
{
                if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $stats[1])
                {
                    $error = true;
                    $this->warn_msg[] = sprintf($user->lang['MAX_IMG_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
                }

                if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $stats[0])
                {
                    $error = true;
                    $this->warn_msg[] = sprintf($user->lang['MAX_IMG_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
                }
            }
        }

        if ($error || $this->path_in_domain($in))
        {
            return '[img' . $tempwidth . $tempheight . ']' . $in . '[/img]';
        }

        return '[img' . $tempwidth . $tempheight . ':' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/img:' . $this->bbcode_uid . ']';
    } 



e) Open <Forum Root Folder>\includes\bbcode.php
Find
Code: Select all
case 4:
                    if ($user->optionget('viewimg'))
                    {
                        $this->bbcode_cache[$bbcode_id] = array(
                            'preg' => array(
                                '#\[img:$uid\](.*?)\[/img:$uid\]#s'        => $this->bbcode_tpl('img', $bbcode_id),
                            )
                        );
                    }
                    else
                    
{
                        $this->bbcode_cache[$bbcode_id] = array(
                            'preg' => array(
                                '#\[img:$uid\](.*?)\[/img:$uid\]#s'        => str_replace('$2', '[ img ]', $this->bbcode_tpl('url', $bbcode_id, true)),
                            )
                        );
                    }
                break;
 


Replace
Code: Select all
case 4:
                    if ($user->optionget('viewimg'))
                    {
                        $this->bbcode_cache[$bbcode_id] = array(
                            'preg' => array(
                     '#\[img(?: width=([0-9]+))?(?: height=([0-9]+))?:$uid\](.*?)\[/img:$uid\]#ise'        => "\$this->bbcode_second_pass_img('\$1','\$2','\$3')"
                            )
                        );
                    }
                    else
                    
{
                        $this->bbcode_cache[$bbcode_id] = array(
                            'preg' => array(
                                '#\[img(?: width=([0-9]+))?(?: height=([0-9]+))?:$uid\](.*?)\[/img:$uid\]#is'        => str_replace('$1', '$3', str_replace('$2', '[ img ]', $this->bbcode_tpl('url', $bbcode_id, true))),
                            )
                        );
                    }
                break; 


In function bbcode_tpl_replace($tpl_name, $tpl)
Find
Code: Select all
'img' => array('{URL}'        => '$1'), 

Replace with
Code: Select all
'img'                    => array('{URL}'        => '$3'),      
      
'imgw'                    => array('{WIDTH}'        => '$1', '{URL}'    => '$3'),
      'imgh'                    => array('{HEIGHT}'            => '$2', '{URL}'    => '$3'),
      'imgwh'                    => array('{WIDTH}'        => '$1', '{HEIGHT}'            => '$2', '{URL}'    => '$3'), 



Add this new function
Code: Select all
/**
    * Second parse img
    */
    function bbcode_second_pass_img($width,$height,$url)
    {
        // when using the /e modifier, preg_replace slashes double-quotes but does not
        // seem to slash anything else
        //$quote = str_replace('\"', '"', $quote);
        //$username = str_replace('\"', '"', $username);

        // remove newline at the beginning
        //if ($quote == "\n")
        //{
        //    $quote = '';
        //}

    if(!$width)
    {
       if(!$height)
          $img = str_replace('$3',$url,$this->bbcode_tpl('img'));
       else 
          $img 
= str_replace('$2',$height,str_replace('$3',$url,$this->bbcode_tpl('imgh')));       
    
}
    else
    
{
       if(!$height)
          $img = str_replace('$1',$width,str_replace('$3',$url,$this->bbcode_tpl('imgw')));
       else 
          $img 
= str_replace('$1',$width,str_replace('$2',$height,str_replace('$3',$url,$this->bbcode_tpl('imgwh'))));
    }   
        
        return $img
;
    } 


In function bbcode_tpl($tpl_name, $bbcode_id = -1, $skip_bitfield_check = false)
Remove (not mandatory)
Code: Select all
'img'        => '<img src="$1" alt="' . $user->lang['IMAGE'] . '" />', 



f) After making the above modifications, upload the files. Go to ACP -> Purge the Cache.

Hope it helps :)
Admin
Site Admin
 
Posts: 67
Joined: Thu May 07, 2009 2:08 pm

Re: PHPBB3 : Resize Width and Height of Image BBCode

Postby Admin » Thu Sep 24, 2009 3:10 pm

Make sure that, you "ADD" the code when specified as "ADD" and "REPLACE" when specified as "REPLACE" and "REMOVE" when specified as "REMOVE"

Try to use the code (remove the spaces near left brace "[" and right brace "]" )

[ img ]http://img15.imageshack.us/img15/1858/homeywq.jpg[ /img ]
Image

[ img width=400 ]http://img15.imageshack.us/img15/1858/homeywq.jpg[ /img ]
Image

[ img height=200 ]http://img15.imageshack.us/img15/1858/homeywq.jpg[ /img ]
Image

[ img width=400 height=50]http://img15.imageshack.us/img15/1858/homeywq.jpg[ /img ]
Image

Let me know if it works :mrgreen:
Admin
Site Admin
 
Posts: 67
Joined: Thu May 07, 2009 2:08 pm


Return to Computer Tips

Who is online

Users browsing this forum: No registered users and 1 guest

cron