Go Back   vb.org Archive > vBulletin Article Depository > Read An Article > vBulletin 3 Articles

Reply
 
Thread Tools
[How-To] Using Plugins for Automatic Template Edits
mfyvie
Join Date: Mar 2007
Posts: 336

I run a forum for English-speaking people in Switzerland

Zurich, Switzerland
Show Printable Version Email this Page Subscription
mfyvie mfyvie is offline 07-02-2007, 10:00 PM


Using Plugins for Automatic Template Edits


Would you like to do make template edits without having to edit a template? Ever wondered how other mods can seem to make changes without you having to edit a single template?

The answer is vBulletin's plugin system. Before we go on you should be familiar with how to edit a template, how templates work and the basics of the the plugin system. There are other tutorials that explain these concepts, if you are new to this, please take some time to learn this stuff first - it will make it much easier to understand the concepts I'm about to present. You can find other tutorials here:

How to include a custom template via plugins by Kerry-Anne
Template editing - by Toolblast
Template mod FAQ - by Sephiroth

You should also browse other tutorials in the articles section if you need to fill gaps in your knowledge.

You'll also need a very basic understanding of PHP, but if you are new to this - don't worry you can pick it up as you go along. I've made this tutorial much easier than most others. So if you are beginner, or never tried making your own mod, please try to follow.

Right, let's begin.

How does the template thing work?

When your page loads from the server, PHP runs through the file, changing variables and getting certain data ready before presenting it to your web browser. Take a look through one of those files. Let's take a look inside online.php. Do a text search for "fetch_template" and see how many times you can see this appear in the file. You'll notice that this file is loading several templates. Take a look right at the end of the file and you'll see the last template is loaded like this:
Code:
eval('print_output("' . fetch_template('WHOSONLINE') . '");');
Our template name is WHOSONLINE, and we could edit this manually in the style manager if we wanted to - but that's old school - we are going to do it with the plugin system. Take a look a few lines above and you'll see that a hook is available just before this template loads:
Code:
($hook = vBulletinHook::fetch_hook('online_complete')) ? eval($hook) : false;
Now, the important point to understand here is that each template is really a big block of text. This big block of text is stored in a variable. We refer to this as a string. Now since we've realised that our templates are really just giant strings, we can use string manipulation functions to change them before they are presented to the user.

Using code executed at hooks to dynamically change the template

When we change templates with the plugin system there are many hooks we can use to do this - we just need to use a hook that is called somewhere before our template is processed. Choosing the right hook depends on what you are trying to do or what the rest of your mod is doing, but generally try to use a hook as close as possible to the point where your template loads. For example, if we want to change something in WHOSONLINE, what would the point be of using a hook like global_start? That would change our template every single time a page (every page, not necessarily the who's online page) is loaded on your forum. It would be more efficient to only run the code that changes the template when we are running a page that actually needs to load the template. For this reason we will be using a hook in online.php, namely online_complete.

For our example, first let's decide what we want to change in the template WHOSONLINE. Let's load the template and think of something that we want to change in that template.

Adding to the template - finding our replacement point


We are going to make a fairly lame hack here. We are going to display the username of the currently logged on user above the who's online table. So we need to insert our new code above that table, so let's find where this table starts.
Code:
<table class="tborder" cellpadding="$stylevar[cellpadding]" cellspacing="$stylevar[cellspacing]" border="0" width="100%" align="center" id="woltable">
How will we change the template dynamically?

Now remember that our template is a giant string, and we want to insert our changes into this string. How will we do this? The answer is a common php function called str_replace(). This function searches for something and replaces it with something else. All we need to do is find something within our template which is unique and easy to search for. We then replace it with our new stuff and put the old stuff back in for good measure - this means we have effectively inserted something. It's a bit like if you had a word processor document containing the sentence "The quick fox". If we wanted to insert "brown" between quick and fox we could search for "fox" and replace it with "brown fox". Our text would then read "The quick brown fox".

Inserting our sample template changes


We apply exactly the same principle to our template. The code we want to insert in this example looks like this:
Code:
$bbuserinfo[username]
But wait a second - if we actually tried to insert this code, it wouldn't work. Why not? Because this form of variable is like a shortcut when you are writing a template. However, inside the template itself, it is stored differently. Until we learn how to discover how they are really stored we are going to use this technique instead:
Code:
$currentuser = $vbulletin->userinfo['username'];
$replace = '$currentuser';
Basically we are loading up our own variable with the data inside our plugin, then we are going to call our variable directly from the template. Note that we have used single quotes in the second line because we want the variable name, rather than the contents of the variable to be passed to the template. When the template is executed, it will then fetch our variable for us. If you need to understand single and double quoting a little better, try this tutorial.

I recommend you quickly review this tutorial by Psionic Vision about variables in vBulletin. As you read it, bear in mind that you can't use the variables in this form inside the template itself, but you can use them from inside your plugin. We'll learn more about why this is in other lessons, but for now, use the technique I've described above.

Creating our plugin

We'll make this code a little a larger than we normally would, in order to make it easier to understand. Let's create our new plugin at the online_complete hook. We'll built it line by line, with explanations along the way. If you don't know what I'm talking about at this stage go into AdminCP -> Plugins & Products -> Plugin Manager -> (scroll to the bottom) Add New Plugin.
Code:
$find = '<table class=\"tborder\" cellpadding=\"$stylevar[cellpadding]\" cellspacing=\"$stylevar[cellspacing]\" border=\"0\" width=\"100%\" align=\"center\" id=\"woltable\">';
This is what we are going to look for, we've stored it in a variable called $find to make it easier to handle. Did you notice something? We've changed things slightly. Every time we have a double quote we need to "escape" it. We do this by adding a backslash character to tell PHP that we really do want a double quote stored in the variable, rather than having PHP think that we are ending or beginning a string using the double quote character. We've also enclosed our string in single quotes. Now you might be saying that at this point "But single quotes mean I don't have to escape double quotes". This is true, but not in this case. If we actually looked inside the template, as it is stored in memory, we'd find those backslash characters. If we want our search to match, we have to put them in. We could have also used the addslashes() function to do this, but we are keeping this example simple, so we put them in by hand. Remember what you see when editing the template via the style manager is not always the same as what is actually stored in memory!

Let's get to our next line:
Code:
$currentuser = $vbulletin->userinfo['username'];
$replace = '$currentuser';
We didn't have any special characters here, so we didn't need to escape anything (in the second line), but we enclosed the variable in single quotes anyway (see explanation above in the section where this code was introduced for the explanation about single quotes).

Getting down to business - str_replace()

Now we've defined what we are looking for and what we want to insert. Let's get down to business:
Code:
$vbulletin->templatecache['WHOSONLINE'] = str_replace($find, $replace . $find,  $vbulletin->templatecache['WHOSONLINE']);
Our template here is $vbulletin->templatecache['WHOSONLINE']. This command is basically saying that our template is equal to the result of the str_replace() function. Our function is going to find the occurrence of $find, and replace it with "$replace . $find" (see that? If we want to insert we have to put our original text back in!). Remember that the dot operator we just used is the same as a plus for text strings - it adds them together. The final parameter used in str_replace() is the string we want to work on - which is the template itself. Our function accepted three parameters, each separated by a comma. Go back and take a look between the round brackets if you can't identify those three parameters.

That's basically it - here's the code for our plugin:
Code:
$find = '<table class=\"tborder\" cellpadding=\"$stylevar[cellpadding]\" cellspacing=\"$stylevar[cellspacing]\" border=\"0\" width=\"100%\" align=\"center\" id=\"woltable\">';
$currentuser = $vbulletin->userinfo['username'];
$replace = '$currentuser';
$vbulletin->templatecache['WHOSONLINE'] = str_replace($find, $replace . $find, $vbulletin->templatecache['WHOSONLINE']);
Try it - create a plugin at the online_complete hook and enter this code. Don't forget to enable your plugin - it is disabled by default. Load your who's online page and you'll see the change. Don't forget to disable to plugin afterwards, you don't want this change visible on your forum permanently.

Things to watch out for and other limitations

This has been a simple example. There are some more complexities, the biggest of which is that the conditional statements in templates can't be easily replaced with this method and that any "special" variables won't work. They can be made to work, but how to do so will be the subject of a future tutorial.

Now that you know the technique, you need to bear the following in mind:
  • Consider the correct hook to use
  • Study an example from another mod, see how they did it
  • Choose simple text to search for within your template
  • Make sure what you search for is unique!
  • Make a manual template edit first, make sure what you want to do works. Then record the changes somewhere else (copy and paste into a text file), and revert the template to its previous state before starting your plugin.
  • Until you know how, avoid any conditional tags (<if>, <else> or </if>) in the text you will search for or replace.
  • Avoid searching for text in your template which runs onto more than one line. This means that there will be new line characters stored within the string, making life much more difficult. For now, just stick to inserting things onto the same line as something else - also watch out for tabs.
  • Many people manually edit their templates. Try to pick a simple chunk of text within the template that may not be a popular location to edit. Also consider providing manual template instructions in case your mod doesn't work for someone with a modified template.
How to avoid conditionals with automatic edits

Not using conditionals inside the template might be a bit limiting for you,
but consider the following point. If you want something to appear based on a
certain condition, why not change it around a little bit and don't make your
template replacement unless that condition is met inside your plugin? This
will effectively give you the same functionality, but testing for the
conditional in your plugin is simpler.

Here's an example: Let's say you were going to do something like this with
your template (insert the first part in front of the second, existing part):
Code:
<if condition="$foo">Here is our mod!</if><div>Existing template data</div>
Remove the conditional from the template and it put it into your plugin instead:
Code:
If ($foo)
{
    $vbulletin->templatecache['yourtemplate'] = str_replace("<div>Existing template data</div>", "Here is our mod!<div>Existing template data</div>", $vbulletin->templatecache['yourtemplate']);
}
This means if the condition wasn't satisfied we don't insert the text into our template. If it is, we add our text. This means we can avoid using the conditional in the template entirely. Of course, using conditionals in a template isn't a sin, it's just very difficult to do with str_replace().

It doesn't work - what now?


What if it doesn't work?
  • Go back and double check it.
  • Did you escape (insert backslashes) any double or single quote characters inside the text to find or insert?
  • Did you test it out first with a manual template edit to confirm your changes actually work?
  • Is your plugin actually enabled?
  • Does the hook you used run before your template is loaded?
  • Have you inserted any conditionals in the template text? Don't (not yet).
  • Are you sure the code in the plugin is running? Remove any conditionals you have around this code just to be extra sure that the str_replace is actually being executed.
  • Try simplifying what you are trying to do. Change the replacement to something really easy, just to confirm that str_replace() is actually running. Once it works, try to bring back your more complex replacement.
  • Did you have a syntax error in the plugin code you wrote? If so, the plugin will not have executed and the error will only be recorded in the error log of your webserver. You should check in this log to make sure it didn't generate an error. You can avoid this problem entirely by writing your php code first in a proper php editor with syntax checking built in. I use phpedit.
Where to now?

What's next? You know the basics, but what to do about more complex cases? You can check out a much more indepth look at the this subject in the advanced tutorial. How about tricks and tips for debugging when it doesn't work? Check out my debugging tutorial.

I encourage you to try this out for yourself and become comfortable with the technique. Do you have any older mods that required manual template edits? Why not revert those manual edits and try and make a plugin which does those edits automatically. If you succeed - share your plugin with the original mod author - I'm sure they will appreciate it.

Have you tried this technique successfully? Share your examples on this thread - more examples will make it easier for others to understand. Got a tricky example that you just can't get to work? Post it (after thoroughly trying to debug it yourself). I've written this tutorial because I couldn't find this information when I was learning. If this tutorial has helped you, then share what you've learned to help others.
Reply With Quote
  #2  
Old 07-12-2007, 06:13 AM
StarBuG's Avatar
StarBuG StarBuG is offline
 
Join Date: Dec 2001
Location: Germany
Posts: 1,033
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Thank you for this nice tutorial.

Defenetly worth a bookmark for me

Can't wait for your new tutorial "getting conditionals to work in plugins with str_replace" cause that is what I need

Thanks

StarBuG
Reply With Quote
  #3  
Old 07-12-2007, 06:29 AM
mfyvie mfyvie is offline
 
Join Date: Mar 2007
Location: Zurich, Switzerland
Posts: 336
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by StarBuG View Post
Can't wait for your new tutorial "getting conditionals to work in plugins with str_replace" cause that is what I need
Oops... I thought I'd added the link to part two to the end of this tutorial, but I now see that I haven't (have just done it now). You'll find part 2 here. The situation is a little trickier than I first thought, so I'll be updating part 2 with my new findings.

I'm also in the middle of writing an automatic tool to build these plugins automatically, but it's proving to be rather difficult...
Reply With Quote
  #4  
Old 07-28-2007, 05:07 AM
Grunt Grunt is offline
 
Join Date: Aug 2002
Location: TN
Posts: 118
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Thanks mfyvie - good stuff!

:cheers:
Reply With Quote
  #5  
Old 12-27-2007, 05:41 AM
leroub's Avatar
leroub leroub is offline
 
Join Date: Jul 2005
Location: In my computer
Posts: 34
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

thx for this tuto.... :up:
Reply With Quote
  #6  
Old 01-22-2008, 11:22 AM
vuiveclub vuiveclub is offline
 
Join Date: Dec 2006
Posts: 78
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

How to replace $currentuser with a custom template?

--------------- Added [DATE]1201094202[/DATE] at [TIME]1201094202[/TIME] ---------------

Nobody helps me? Sorry for my bad English. I would like to replace $currentuser with my custom template. Plz help me! Thanks
Reply With Quote
  #7  
Old 01-23-2008, 11:26 AM
mfyvie mfyvie is offline
 
Join Date: Mar 2007
Location: Zurich, Switzerland
Posts: 336
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by vuiveclub View Post
How to replace $currentuser with a custom template?

--------------- Added 23 Jan 2008 at 14:16 ---------------

Nobody helps me? Sorry for my bad English. I would like to replace $currentuser with my custom template. Plz help me! Thanks
Well I'm not sure what you are expecting - read the tutorial above - that's what it is about. Do you want me to type out the instructions a second time? The examples i've given even use $currentuser...

Is there some *aspect* of this tutorial which you think should be explained in more detail? If so, which?

But don't expect help if you ask such a broad or unclear question - sorry.
Reply With Quote
  #8  
Old 06-11-2008, 03:54 PM
4x4 Mecca 4x4 Mecca is offline
 
Join Date: Feb 2007
Posts: 396
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Thanks! This helped me with my problems.
Reply With Quote
  #9  
Old 04-27-2010, 11:09 PM
Mutt's Avatar
Mutt Mutt is offline
 
Join Date: Nov 2001
Posts: 331
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

i'm trying to do this in vb4 with no luck. is there an updated tutorial? thanks
Reply With Quote
  #10  
Old 05-07-2010, 08:20 AM
wolfe wolfe is offline
 
Join Date: Jan 2002
Posts: 900
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

so am i m8 dont know its its possible anymore hope it is tho.
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 04:23 AM.


Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2024, vBulletin Solutions Inc.
X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.05271 seconds
  • Memory Usage 2,342KB
  • Queries Executed 25 (?)
More Information
Template Usage:
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (1)ad_showthread_beforeqr
  • (11)bbcode_code
  • (2)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)modsystem_article
  • (1)navbar
  • (4)navbar_link
  • (120)option
  • (1)pagenav
  • (1)pagenav_curpage
  • (1)pagenav_pagelink
  • (10)post_thanks_box
  • (1)post_thanks_box_bit
  • (10)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (1)post_thanks_postbit
  • (10)post_thanks_postbit_info
  • (9)postbit
  • (10)postbit_onlinestatus
  • (10)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available:
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files:
  • ./showthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_post_thanks.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • forumjump
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • post_thanks_function_post_thanks_off_start
  • post_thanks_function_post_thanks_off_end
  • post_thanks_function_fetch_thanks_start
  • fetch_musername
  • post_thanks_function_fetch_thanks_end
  • post_thanks_function_thanked_already_start
  • post_thanks_function_thanked_already_end
  • post_thanks_function_fetch_thanks_bit_start
  • post_thanks_function_show_thanks_date_start
  • post_thanks_function_show_thanks_date_end
  • post_thanks_function_fetch_thanks_bit_end
  • post_thanks_function_fetch_post_thanks_template_start
  • post_thanks_function_fetch_post_thanks_template_end
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • post_thanks_function_can_thank_this_post_start
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete