CMS Made Simple: Application of User-Defined Tags

Exclusive offer: get 50% off this eBook here
CMS Made Simple Development Cookbook

CMS Made Simple Development Cookbook — Save 50%

Over 70 simple but incredibly effective recipes for extending CMS Made Simple with detailed explanations – useful for beginners and experts alike!

$26.99    $13.50
by Samuel Goldstein | May 2011 | Content Management Open Source

This article will help us explore a few applications of tags. Most of these recipes are User-Defined Tags, because the capabilities of the User-Defined Tags are nearly identical to the file type of a tag.

In this article by Samuel Goldstein, author of CMS Made Simple Development Cookbook, we will cover:

  • Displaying the User's IP address from a User-Defined Tag
  • Using the current content object in a User-Defined Tag
  • Making a variable available to Smarty from a User-Defined Tag
  • Displaying the number of pages in the CMS using a User-Defined Tag
  • Using URL parameters in a User-Defined Tag
  • Using Smarty values as inputs in a User-Defined Tag

 

 

CMS Made Simple Development Cookbook

CMS Made Simple Development Cookbook

Over 70 simple but incredibly effective recipes for extending CMS Made Simple with detailed explanations – useful for beginners and experts alike!

        Read more about this book      

(For more resources on Content management, see here.)

These recipes have been specially selected to demonstrate capabilities. While they may be useful as provided, they are designed to show the range of what can be done with tags, and to provide examples of useful operations such as setting Smarty variables, interfacing with the database, interacting with modules, and consuming data from remote web services. You are encouraged to use these recipes as starting points for your own projects.

Introduction

One of the most popular uses of CMS Made Simple involves an administrator who creates a basic site structure and template, and one or more editors who maintain page content without having to worry about the site layout. In this configuration, you can think of the CMS essentially as a big template engine with some utilities to add content.

Each page of the site comprises a page template with areas that get populated with various kinds of content. These areas are either tags or variables, where the distinction is that a tag involves the execution of code, while a variable is a simple substitution of values. The CMS comes with a large assortment of built-in tags, including the fundamental "content" tag and a variety of useful supporting tags for building navigation, links, including images, and so forth.

Because CMS Made Simple can be seen as being built around tags, it is not surprising that there are facilities for creating your own tags. You can create tags directly through the Admin panel—these are called User-Defined Tags or UDTs. If you want even more extensive capabilities in your tag, you can have those capabilities by creating a file that follows a few basic conventions.

The template engine used by CMS Made Simple comes from the Smarty project. Pages are Smarty templates, and the built-in CMS tag types are all Smarty tags. Behind the scenes, both UDTs and file-based tags also become Smarty tags.

For additional information on Smarty, the documentation provided by the Smarty project is invaluable. You can read more at http://www.smarty.net/docsv2/en/

 

Displaying the User's IP address from a User-Defined Tag

This recipe demonstrates creating a very simple User-Defined Tag, and using it to display information, that it gets from PHP globally-defined variables.

Getting ready

For this recipe, you will need to have CMS Made Simple installed and working. You will need login access to the site's Administration area as a member of the "admin" group, or as a member of a group with permissions to "Modify User-Defined Tags" and "Manage All Content".

How to do it...

  1. Log in to your CMS Administration area.
  2. Using the top menu, go to "Extensions" and click on "User Defined Tags".
  3. Click on the "Add User Defined Tag" button.
  4. In the "Name" field type "user_ip".
  5. In the "Code" text area, type the following code:
    echo 'Welcome user from '.$_SERVER['REMOTE_ADDR'].' -- enjoy your
    visit!';
  6. Click on the "Submit" button.
  7. Using the top menu, go to "Content" and click on "Pages".
  8. Click on the "Add New Content" button.
  9. In the "Title" and "Menu Text" fields, type "Tag Test".
  10. In the "Content" text area, type the following code:
    {user_ip}
  11. Click on the "Submit" button.
  12. View your site from the user side. Click on the new "Tag Test" page.

CMS Made Simple Development Cookbook

How it works...

User-Defined Tags work by linking a piece of PHP code to a tag which is recognized by Smarty. When Smarty parses a template and encounters that tag, it executes the code in question, and substitutes the tag markup with any output from that PHP code.

When we create a UDT in the CMS Made Simple admin area, the name we enter into the text field becomes the tag which Smarty will look for, and the code we enter into the text area is the PHP associated with the tag.

This recipe is an example of outputting text directly from a User-Defined Tag. It works by echoing a string, that then replaces the {user_ip} tag in the content. This substitution of the tag can take place either in a page template or in the page content, which might seem a little confusing since it's stated earlier that Smarty processes tags that it finds in templates. The confusion, though, is mostly due to terminology; CMS Made Simple processes both layout templates and page content through Smarty, so while it is being processed, page content serves as a template from Smarty's perspective.

The User-Defined Tag we create accesses one of the PHP "superglobals"—the $_SERVER variable . This variable contains information about the HTTP request and some environmental information about the PHP server. In this case, we're getting the user's IP address information to display.

 

Using the CmsObject and the current content object in a User-Defined Tag

This recipe shows you how to access the Page Content object via the CmsObject in a User-Defined Tag.

The primary technique that it demonstrates—getting a reference to the CmsObject and using the CmsObject to get a reference to other important CMS runtime objects—is one that you will use to solve many different kinds of problems.

In this recipe, we use the CmsObject to get a reference to the Page Content object. Once we have a reference to this object, we can call upon its methods to report all kinds of interesting information about the current page content.

Getting ready

For this recipe, you will need login access to your site's Administration area with permission to "Modify User-Defined Tags" and "Manage All Content".

How to do it...

  1. Log in to your CMS Administration area.
  2. Using the top menu, go to "Extensions" and click on "User Defined Tags".
  3. Click on the "Add User Defined Tag" icon.
  4. In the "Name" field, type "content_description".
  5. In the "Code" field, type the following code:
    $gCms = cmsms();
    $contentops = $gCms->GetContentOperations();
    $content_obj = $contentops->getContentObject();
    echo 'Current content object is "'.$content_obj->Name().'"<br />';
    echo 'which was created on '.$content_obj->GetCreationDate().'<br
    />';
    echo 'its alias is "'.$content_obj->Alias().'"<br />';
    echo 'and its URL is "'.$content_obj->GetURL().'"<br />';
  6. Click on the "Submit" button.
  7. Using the top menu, select "Content" and click on "Pages".
  8. Click on the "Add New Content" button.
  9. Enter "New Content Page" into the "Title" and "Menu Text" fields.
  10. In the "Content" field, enter:
    {content_description}
  11. Click on the "Submit" button.
  12. View your site from the user side. Click on the new "Content Page" page.

CMS Made Simple Development Cookbook

How it works...

CMS Made Simple uses an internal object called "CmsObject" to keep track of a great deal of what it needs to serve content. This information includes the site hierarchy, the installed and active modules, references to the database, and more. The CmsObject is available to Modules, Tags, and User-Defined Tags via the cmsms() function.

In this recipe, we want to display information from the current Content object. However, this object is not directly accessible. To get access to this object, we need to make a static call to the ContentOperations object, but this object is also not directly accessible from our code. To get access to these objects, we need to get references to them.

We start by gaining access to the CmsObject by calling the global cmsms() function. From our reference to the CmsObject, we request a reference to the ContentOperations object, that we then use to request a reference to the current content object.

Once we have the current content object, we can call assorted methods on it to retrieve information about the current content. In this recipe, we get the content's name, when it was last modified, its alias, and its URL. Since this recipe is an example, we don't format these various pieces of information or use a template, but simply echo them. In a production UDT or one in which there's any complexity to what is being displayed, it would be more advisable to use the values to populate Smarty variables for later display, or use a template for formatting them.

There's more...

There are a number of interesting objects, that CmsObject manages. References can be requested to:

  • BookmarkOperations— used in the Admin area
  • ContentOperations—which has methods to handle Content and content metadata
  • Db— which wraps the ADODB database API
  • GlobalContentOperations— which has methods to handle Global Content Blocks
  • GroupOperations— which has methods to handle Admin Groups
  • HierarchyManager— which has methods for handling site content hierarchies
  • ModuleOperations— which has methods for managing Modules
  • Smarty— which wraps the Smarty template engine
  • StylesheetOperations—which has methods for handling
  • TemplateOperations— which has methods for handling Smarty templates
  • UserOperations— which has methods for handling Admin Users
  • UserTagOperations— which has methods for handling User-Defined Tags

Getting attributes using page_attr

If you're looking to display information about the current content object, CMS Made Simple has a custom Smarty tag that provides some attributes: {page_attr}. You can use this tag to display page attribute information—simply by specifying a key to the information you're requesting. For example, to get the page's "image" attribute, you could use the tag {page_attr key="image"}. Other keys that are supported include:

  • target
  • image
  • thumbnail
  • extra1
  • extra2
  • extra3
  • searchable
  • pagedata
  • disable_wysiwyg
  • content_en

As you can see, this is not as rich a collection of information as you can get from the content object directly using your own UDT.

Old code and the use of globals

If you look at old modules or User-Defined Tags that have been posted in the CMS Made Simple forum, you may see the following code:

global $gCms;

instead of the $gCms = cmsms() used here. For a long time, the use of the global declaration was the preferred way to access the CmsObject. This approach is now deprecated for a number of reasons, most important of which is a security issue and also including portability of code between CMS Made Simple 1.x and the upcoming 2.x versions.

While use of the global declaration to access the CmsObject will likely still work, it is strongly discouraged.

 

CMS Made Simple Development Cookbook Over 70 simple but incredibly effective recipes for extending CMS Made Simple with detailed explanations – useful for beginners and experts alike!
Published: April 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on Content management, see here.)

Making a variable available to Smarty

Sometimes you will have tag-generated content that you want to show in multiple areas on a page, or that you will want to manipulate in some way, or even use the value in some kind of conditional logic. Instead of having your tag display its output directly in the template, you can have it set a Smarty variable.

This recipe demonstrates getting a reference to the Smarty engine within a User-Defined Tag, and exporting variables for use in Smarty.

Getting ready

For this recipe, you will need login access to your site's Administration area with permission to "Modify User-Defined Tags", "Modify Templates", and "Manage All Content".

How to do it...

  1. Log in to your CMS Administration area.
  2. Using the top menu, go to "Extensions" and click on "User Defined Tags".
  3. Click on the "Add User Defined Tag" icon.
  4. In the "Name" field, type "assorted_variables".
  5. In the "Code" field, type the following:
  6. $gCms = cmsms();
    $smarty = $gCms->GetSmarty();
    $smarty->assign('quotation','A computer lets you make more
    mistakes faster than any invention in human history, with the
    possible exceptions of handguns and tequila. -- Mitch Ratcliffe');
    $items = array('Brandt','Bunny','Donny','Dude','Jeffrey','Maude','
    Smokey','Walter');
    $smarty->assign_by_ref('characters',$items);
  7. Click on the "Submit" button.
  8. Using the top menu, select "Layout" and click on "Template".
  9. Click to edit the current default template.
  10. Near the top after the <body> tag , add your {assorted_variables} tag and click the "Submit" button.
  11. Using the top menu, select "Content" and click on "Pages".
  12. Click on the "Add New Content" button.
  13. Enter "Smarty Test" into the "Title" and "Menu Text" fields.
  14. If you are using a WYSIWYG editor for the content area, uncheck the checkbox labeled "Turn WYSIWYG on/off".

    CMS Made Simple Development Cookbook

  15. In the content area, type the following:

    <ul>
    {foreach from=$characters item=who}
    <li>{$who}</li>
    {/foreach}
    </ul>
    <p>{$quotation}</p>

  16. Then click the "Submit" button.
  17. View your site from the user side. Click on the new "Smarty Test" page.

CMS Made Simple Development Cookbook

How it works...

This recipe shows how you can export variables from your UDT to Smarty, so that the variables can be used in page templates and page content.

The first step is giving the UDT a way to access Smarty, since it is not directly in scope. To get this access to Smarty, we need to get a reference to the global Smarty object.

We start by gaining access to the CmsObject by calling the global cmsms() function . The CmsObject is a key internal structure for CMS Made Simple, and serves as a central resource for getting references to important CMS management objects. In this case, we retrieve a reference to the CmsObject, and then use that to get a reference to the global Smarty object.

Once we can talk to Smarty, we tell it how we want to map variables. Smarty variables are like associative arrays, in that they assign some value, object, or data structure to a static key. The assign() method is used to make this kind of mapping, as you can see when we assign our quotation string to a Smarty variable "quotation".

In this recipe, we assign an array of strings to a Smarty variable named "characters", where we use Smarty's assign_by_ref() method instead of the simple assign() method. This method instructs Smarty to use references to the source variable instead of making a copy. This guarantees that if you change the value of the Smarty variable, the change will be reflected in the source data as well. If you are using PHP 4, it also has the potential for saving memory. However, the PHP manual recommends against second-guessing how to pass variables; by specifying how to do it, you may actually have a deleterious effect on PHP's own optimizations. Furthermore, PHP 5 passes variables by reference by default. In other words, while the use of assign_by_ref() is included in this recipe for pedagogical reasons, don't use it in your code unless you have a specific need to do so.

Once our UDT is defined, we place it in the page template. Now when Smarty parses the page, the variables will be assigned to Smarty and will be made available to the rest of the template, to page content, and so on.

There's more...

Order is relevant when you export variables from a User-Defined Tag. Variables exported to Smarty by the UDT will be in scope after the inclusion of the tag. In a page template, that translates to the variables being available in the page template below the tag itself—with one caveat. CMS Made Simple processes the template <head></head> and <body></body> areas of a page template in reverse order.

The reverse order processing of <head> and <body> enables modules to export information to the page metadata, among other advantages. While you can override this behavior by the CMS configuration variable process_whole_template in general, it is better to expect that <body> gets processed first.

What this means practically, is that if you create a UDT that assigns Smarty variables, and place the tag immediately after the <body> start tag, those Smarty variables will be available to nearly everything in your page: template, content, module templates, and global content blocks. If you place your UDT in the <head> area of your page template, the variables that it exports to Smarty will be only available below the tag in the <head> area (and any cms_stylesheets included).

 

Displaying the number of pages in the CMS using a User-Defined Tag

Virtually, all of the content that CMS Made Simple displays or uses to display pages is stored in a database; therefore, it's not at all unexpected that you might want to access the database from a User-Defined Tag. Fortunately, this is not a difficult thing to do.

This recipe shows you how to get a reference to the database abstraction layer and how to issue and process a query from within your User-Defined Tag.

Getting ready

For this recipe, you will need access to your site's Administration area with permission to "Modify User-Defined Tags" and "Modify Templates". It assumes that you are using the default NCleanBlue template, but will work for any template.

How to do it...

  1. Log in to your CMS Administration area.
  2. Using the top menu, go to "Extensions" and click on "User Defined Tags".
  3. Click on the "Add User Defined Tag" icon.
  4. In the "Name" field, type "page_counter".
  5. In the "Code" field, type the following:
    $gCms=cmsms();
    $db = $gCms->GetDb();
    $count = $db->GetOne('select count(*) from '.cms_db_
    prefix().'content where active=1');
    echo 'Total pages: '.$count;
  6. Click on the "Submit" button.
  7. Using the top menu, go to "Layout" and click on "Templates".
  8. Click on "NCleanBlue" in the template list to edit the template.
  9. Find the lines where the print button tag is included, and add the page_counter tag. It will look something like:

    {* main top, holds top image and print image *}
    <div class="main-top">
    <div class="print core-float-right">
    {print showbutton=true}
    <br />
    {page_counter}
    </div>
    </div>

  10. Click on "Submit".
  11. View your site from the user side.

CMS Made Simple Development Cookbook

How it works...

This recipe shows how to execute a database query from a User-Defined Tag. CMS Made Simple uses ADODB Lite as a database abstraction layer, that makes it easier to write code that will work with a variety of databases (rather than tying you to one specific database management system or even a specific DBMS version). The database layer is accessed via method calls to the ADODB object.

The first step in this recipe is giving the UDT a way to access the database abstraction object, since it is not directly in scope. To get this access, we need to get a reference to the ADODB object.

We start by gaining access to the CmsObject by calling the global cmsms() function. The CmsObject is a key internal structure for CMS Made Simple, and serves as a central resource for getting references to important CMS management objects. In this case, we retrieve a reference to the CmsObject, and then use that to get a reference to the Db object (which is really an ADODB connection object).

Once we have this reference to the database abstraction layer, we can make database queries. In this case, we construct a query that counts the number of active content pages in our site. This query is quite straightforward, but it does have some notable features.

The first noteworthy aspect of the query is the call to cms_db_prefix(). When you install CMS Made Simple, one step in the installation asks you for a database prefix. This defaults to "cms_" and very few sites deviate from this default. It is not safe, however, to assume that every site uses the default. Some people who have a limited number of databases available to them in their hosting configuration will use the prefix to install multiple CMS Made Simple instances in a single database, for example. The cms_db_prefix() function will return the prefix of our current installation, so we don't have to worry about it.

The next noteworthy thing about our query is the use of the GetOne() method for executing it. Most ADODB methods will return a Result Set, from which you can retrieve error conditions and result data. Typically, your code will check the result set for error conditions, and then assign results to variables if the query was successful. The GetOne() method is a special shorthand for database queries that will return exactly one result; it skips the necessity to get data from a Result Set and directly returns the single result from the query.

Since the count(*) is guaranteed to return a single value, we can use this shortcut. We construct a query that looks at the content table, and counts the number of records for which the content is flagged as being active.

We execute the query, assign the result to our count variable, and then output it in a formatted string.

There's more...

We used the GetOne() method for accessing the database as described previously. This is safe to do when you are guaranteed a single result from the database query. However, it's always wise to consider what is meant by "guaranteed". An SQL count(*) command will always return a result if the query is valid, meaning it refers to an extant table and any conditions in the "where" clause are against extant fields.

In the event we're using some dynamic element to our query, and there's a chance that the query generated will not be guaranteed to return a single result, it would be preferable to use the more verbose approach of using the Execute() method instead of the GetOne() method. The Execute() method returns a Result Set, which can be checked for error conditions before retrieving result values themselves.

 

CMS Made Simple Development Cookbook Over 70 simple but incredibly effective recipes for extending CMS Made Simple with detailed explanations – useful for beginners and experts alike!
Published: April 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on Content management, see here.)

Using URL parameters safely in a User-Defined Tag

When people started writing code for website forms and data input, security was not much of a consideration—after all, websites were mostly run by researchers to share their research. It was fine to have code that made assumptions about incoming data, even for sites that faced the open Internet. Those innocent days are long gone, of course. Websites are subjected to continuous threats by automated attack scripts and malicious users looking to deface, hijack, or abuse accounts. Spammers, Phishers, Crackers, and other unsavory types can be expected to look for vulnerabilities in your code.

Today, securing web applications is a vital part of the development process.

The CMS Made Simple Module API has a collection of utilities to help guarantee that incoming parameters are safe to use. User-Defined Tags, however, don't have a similar facility, so it's imperative that you use safe practices when it comes to user input.

This recipe shows you how to safely handle incoming parameters in your User-Defined Tag.

Getting ready

For this recipe, you will need to have access to your site's Administration area with permission to "Modify User-Defined Tags" and "Manage All Content". This recipe also assumes that you have the standard default content installed; if you don't, you will need to adapt a few of the example URLs to see results.

How to do it...

  1. Log in to your CMS Administration area.
  2. Using the top menu, go to "Extensions" and click on "User Defined Tags".
  3. Click on the "Add User Defined Tag" icon.
  4. In the "Name" field, type "get_page".
  5. In the "Code" field, type the following:

    $gCms = cmsms();
    $db = $gCms->GetDb();
    $content_name='';
    if (isset($_GET['alias']) && !empty($_GET['alias']))
    {
    $res = $db->Execute('select content_name from '.cms_db_prefix().
    'content where content_alias=?',array($_GET['alias']));
    if ($res)
    {
    $row = $res->FetchRow();
    $content_name = 'Alias '.htmlspecialchars($_GET['alias']).
    ' maps to "'.$row['content_name'].'"';
    }
    else
    {
    $content_name = 'Alias '.htmlspecialchars($_GET['alias']).
    ' is not in the database.';
    }
    }

    if (!empty($content_name))
    {
    echo $content_name;
    }

  6. Click on the "Submit" button.
  7. Using the top menu, select "Content" and click on "Pages".
  8. Click on the "Add New Content" button.
  9. Enter "URL Test" into the "Title" and "Menu Text" fields.
  10. In the "Content" text area, enter the <get_page> tag.
  11. Click on the "Submit" button.
  12. Check the page on the user side.

    CMS Made Simple Development Cookbook

  13. Now test by adding "&alias=default_templates" to the end of the URL in your browser's address bar.

    CMS Made Simple Development Cookbook

  14. Now, try to use a sneaky SQL-Injection attack by adding "&alias=';delete from cms_content;" to the end of the URL in your browser's address bar.

    CMS Made Simple Development Cookbook

  15. Lastly, we try to use a sneaky Cross-Site Scripting attack (XSS) by adding "&alias=<script>alert("hi")</script>" to the end of the URL in your browser's address bar.

    CMS Made Simple Development Cookbook

How it works...

This recipe shows how to utilize user-supplied parameters to retrieve information from the database and for display, without putting the security of your server or your users at risk.

To execute a database query from a User-Defined Tag, we need to get access to the ADODB object. As described in greater detail in the previous recipe, we start by gaining access to the CmsObject by calling the global cmsms() function. From the CmsObject, we get a reference to the Db object, which we use for our actual queries.

User-Defined Tags in CMS Made Simple don't have any special mechanism for handling incoming parameters. They use the standard PHP superglobals for accessing information from the HTTP request: $_GET, $_POST, and/or $_REQUEST. So for our recipe, we will be looking to see if there is a parameter called "alias" passed in on the URL, that would then be found in the $_GET supervariable.

We start by testing to see if $_GET['alias'] is defined and has a non-blank value. If it does, we will query the database for any pages that have the provided string as their alias. The query we construct bears some examination.

As in the previous recipe, we construct our query using the cms_db_prefix() function, so that we get the correct table names. However, in the "where" clause, you can see that we don't simply substitute in the parameter that we are seeking—instead, we place a single, unquoted question mark. In the Execute() method, we pass our query and an array containing our parameter. What we're doing here is making sure we're sanitizing our parameters for the database, using a technique called "parameterized query".

Consider the case that we tested earlier, where we passed in the parameter "&alias=';delete from cms_content;". If we simply substituted $_GET['alias'] into our query string, the resulting query would be:

select content_name from cms_content where content_alias=';delete from
cms_content;

This would be interpreted by some databases as two separate queries—the first would be syntactically incorrect, and would do nothing, the second would delete all of the content in the cms_content table!

By using the parameterized query, the actual command that gets issued to the database is the harmless.

select content_name from cms_content where content_alias='\';delete
from cms_content;'

(in the case of MySQL. Other databases may use a different escaping syntax, but ADODB handles that transparently for you).

While some databases (like MySQL) protect against this particular form of query stacking automatically, there are other insidious ways of tricking the database into retrieving additional information. Some of these SQL-injection attacks cannot be automatically prevented, and can only be averted by sanitizing parameters.

After issuing our query to the database, we get returned a Result Set. We check to see if it is valid and if it contains any records. If either of those tests fail, we return a string to the user saying that the alias does not exist in the database. If the Result Set is valid, and contains more than zero records, we retrieve the results into an associative array using the FetchRow() method. We then use this to display the title of the page to which the alias maps.

In either the successful or unsuccessful case, we don't display the original parameter to the user directly. Instead, we pass it through the htmlspecialchars() function. This is to disarm any attempted cross-site scripting (XSS) attacks, as we demonstrate with the attempt to pass "&alias=<script>alert("hi")</script>" as a parameter. The htmlspecialchars() function converts a few key characters into HTML entities instead of raw characters, thereby defusing script attacks.

If we were to simply echo the parameter back to the user, a cleverly crafted URL could cause a script to send off cookie information or other data to an arbitrary site. Then an attacker could post the sneaky link on a forum or other popular site, and use it for nefarious purposes.

 

Using Smarty values as inputs in a User-Defined Tag

You may find yourself in a situation where you need to access data that a module or the CMS Made Simple core has set a variable for use in Smarty, but has not made it available via a function call.

This recipe shows you how your User-Defined Tag can access variables that have been assigned to Smarty, but which may not be easily available via other means.

Getting ready

For this recipe, you will need access to your site's Administration area with permission to "Modify User-Defined Tags" and "Manage All Content". This recipe also assumes that you have the News module installed and used by your page template. It will help if you have a few News articles published.

How to do it...

    Log in to your CMS Administration area.
  1. Using the top menu, go to "Extensions" and click on "User Defined Tags".
  2. Click on the "Add User Defined Tag" icon.
  3. In the "Name" field, type "get_news_items".
  4. In the "Code" field, type the following:

    $gCms = cmsms();
    $smarty = $gCms->GetSmarty();

    $newsitems = $smarty->get_template_vars('items');
    foreach ($newsitems as $item)
    {
    echo $item->titlelink.'<br />';
    echo $item->summary.'<br />';
    }

  5. Click the "Submit" button.
  6. Using the top menu, select "Content" and click on "Pages".
  7. Click on the "Add New Content" button.
  8. Enter "Smarty Read Test" into the "Title" and "Menu Text" fields.
  9. In the "Content" text area, enter the {get_news_info} tag.
  10. Click on the "Submit" button.
  11. View your site from the user side. Click on the new "Smarty Read Test" page.

CMS Made Simple Development Cookbook

How it works...

This recipe shows how you can import variables to your User-Defined Tag from Smarty without having to process a template.

The first step is giving the UDT access to Smarty, since it is not directly in scope. We start by creating a reference to the CmsObject by calling the global cmsms() function. The CmsObject provides us a method to retrieve a reference to the Smarty object.

Once we can talk to Smarty, we can call the get_template_vars() method to retrieve any Smarty variables that have been assigned. Smarty assignments are like associative arrays, in that the variable names are bound to some value, object, or data structure. The get_template_vars() method is the inverse of the assign() method; when a module or UDT sets a Smarty variable using assign(), we can use the get_template_vars() method to get that value back.

In this recipe, we retrieve the "items" array that the News module assigned. Since we know it's an array of StdClass objects, we can iterate through using a foreach statement, and display the specific information that we want. Obviously, we are not limited to simply displaying this data—depending upon what we're trying to achieve, we may end up using values we retrieved for database queries, calculations, or other purposes.

There's more...

The Smarty variables that are used by templates and content in CMS Made Simple have a flat namespace, like an associative array. If two modules assign arrays to the Smarty variable "items", the values will clobber one another. The last to do the assignment will determine the value that gets seen subsequently by templates. This is not normally a problem, even in the case of multiple modules using the same variable name because modules typically assign Smarty variables and process their templates in one atomic operation, so their own particular version of those variables is used in their own particular output.

The example shown in this recipe, however, makes the assumption that the only module assigning values to the variable named "items" is the News module. Therefore, this approach should be used with a little bit of caution.

Summary

In this article we took a look at examples of Tags and User-Defined Tags, and how to create tags to handle such varied tasks as setting Smarty variables, filtering content, interfacing with modules, etc. This article also included information on some key CMS components.


Further resources on this subject:


About the Author :


Samuel Goldstein

Samuel received a TRS-80 computer for his 12th birthday, and has been programming ever since. Today, he is a principal at 1969 Communications (http://www.1969web.com), a Los Angeles-based web development firm. 1969 Communications builds and maintains web-based business tools for clients which include national brands like Isuzu Commercial Vehicles and Bioness Medical Inc. 1969 Communications specializes in e-commerce, integrating web applications with back-end / legacy systems, complex workflows, content management solutions, and troubleshooting complex issues.

Before coming to 1969, Samuel served as Vice President of Technology at Magnet Interactive in Los Angeles, Director of Engineering at COW, and Lead of the Programming Department at BoxTop Interactive. Projects at these companies included development of reusable frameworks, web-based applications, and data-driven systems. Clients ranged from dot-coms to well-known companies such as Nissan/Infiniti, Quiksilver, National Lampoon, Stanford University, Guess?, USC, Kahlúa (Allied Domecq), UPN, UCLA, Major League Soccer, and SegaSoft.

Prior to focusing on Internet technology, Samuel worked as a member of the technical staff at The Aerospace Corporation, where he researched distributed systems and database technologies. He holds a Bachelor of Arts in Physics from Pomona College in Claremont, California and a Master of Science in Computer Engineering from the University of Southern California.

Books From Packt


CMS Made Simple 1.6: Beginner's Guide
CMS Made Simple 1.6: Beginner's Guide

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

Moodle as a Curriculum and Information Management System
Moodle as a Curriculum and Information Management System

WordPress 3 Complete
WordPress 3 Complete

Drupal 7 Module Development
Drupal 7 Module Development

Magento 1.4 Development Cookbook
Magento 1.4 Development Cookbook

Joomla! 1.6 First Look
Joomla! 1.6 First Look

Moodle 2.0 First Look
Moodle 2.0 First Look


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
L
X
Q
H
q
G
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software