Smarty Forum Index Smarty
The discussions here are for Smarty, a template engine for the PHP programming language.
Template resource handling is awsome!

 
Post new topic   Reply to topic    Smarty Forum Index -> Testimonials
View previous topic :: View next topic  
Author Message
bimal
Smarty Elite


Joined: 19 Apr 2007
Posts: 420
Location: Kathmandu, Nepal

PostPosted: Tue Jan 27, 2009 5:21 pm    Post subject: Template resource handling is awsome! Reply with quote

Once I was little free from my works, I went through the Smarty manual on Resources > Templates from other sources > Database driven templates, and I tried the following:

I made some admin's editor to modify the contents, and name of smarty templates stored in the database.

Then, modified the .htaccess so that all pages would be served only my index.php as:

Code:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^(.+) - [PT,L]
 RewriteRule ^(.*) index.php
</IfModule>


By this stupid thing, I got a little victory: I did not require FTP connection to maintain the website. Remembering the FTP is still a tedious thing. Using my own editor, I could modify the templates and contents.

** I called this stupid, because, I was successful to use it. But, in the next year, this website was rewritten with Joomla, and my work got dropped off.
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
bimal
Smarty Elite


Joined: 19 Apr 2007
Posts: 420
Location: Kathmandu, Nepal

PostPosted: Tue Jan 27, 2009 5:23 pm    Post subject: The main resource handler class file Reply with quote

This code allowed us to handle the smarty resources in the database. It has other functions to edit the database's template contents too.

Code:
<?php

/**
* @package includes/smarty_database
* @author Bimal Poudel, Suman Maharjan
* @copyright 2007 Bimal Poudel
*
* Smarty plugin
* -------------------------------------------------------------
* File:     class.smarty_database.iunc.php => resource.smarty_database.php
* Type:     resource
* Name:     smarty_database
* Purpose:  Fetches templates from a database
* -------------------------------------------------------------
*/


/*
Bimal Poudel
2007-040-25 00:07
*/

class smarty_database
{
   /**
   * @var mysql Database connection resource
   */
   var $db;

   /**
   * @var string Template file name
   */
   var $filename;

   /**
   * @var boolean Display messages or not?
   */
   var $debug_mode_enabled;
   
   /**
   * @var string HTML contents of the template
   */
   var $tpl_source;
   
   /**
   * @var timestamp Unix timestamp of the template file
   */
   var $tpl_timestamp;
   
   /**
   * @var pages URLs pool extcation
   */
   var $pages;

   /**
   * Constructor
   * @uses Connects to the database.
   * @uses Populates the pages()
   */
   function smarty_database()
   {
      $this->db = new mysql();
      $this->tpl_timestamp='';
      $this->pages=$this->get_pages();
   } # smarty_database()
   
   /**
   * Template contents reading handler.
   * @uses Handler - To register the Smarty template resource reading function.
   * @param $tpl_name string Name of the template (Address reference)
   * @param $tpl_source string Source of the template (Address reference)
   * @param $smarty Smarty The Smarty object (Address reference)
   */
   function smarty_read_template($tpl_name, &$tpl_source, &$smarty)
   {
      $db = new mysql();
      #$tpl_sql="select tpl_source from smarty_templates where tpl_name='{$tpl_name}';";
      #$tpl_sql="select * from smarty_templates;";

      $tpl_sql="
      SELECT
         tpl_source,
         UNIX_TIMESTAMP(tpl_timestamp) AS tpl_timestamp
      FROM
         smarty_templates
      WHERE
         tpl_name='{$tpl_name}'
      LIMIT 1;
      ";
      $db->query($tpl_sql);
      /*
      if(!$db->query($tpl_sql))
      {
         die("Error with Template finding SQL, Template unavailable: <b>{$tpl_sql}</b>, ".__FILE__.", ".__LINE__);
      }
      else
      {
      */
         $db->next_record();
         #print_r($db);
         #echo($tpl_sql);
         #print_r($db);
         
         if ($db->ROWS==1)
         {      
            $tpl_source = $db->row_data['tpl_source'];
            $this->tpl_timestamp=$db->row_data['tpl_timestamp'];
            #die($tpl_source);
            return(true);
         }
      #}

      return(false);
   } # smarty_read_template()
   
   /**
   * When was the template resource last modified?
   * If the template's timestamp changes, Smarty re-compiles the template resource.
   * @param $tpl_name string Name of the template (Address reference)
   * @param $tpl_source string Source of the template (Address reference)
   * @param $smarty Smarty The Smarty object (Address reference)
   * @return boolean Is the last modification timestamp of the template changed?
   */
   function smarty_template_timestamp($tpl_name, &$tpl_timestamp, &$smarty)
   {
      $success=false;
      # Prevent SQL call again.
      if($this->tpl_timestamp!='')
      {
         $tpl_timestamp=$this->tpl_timestamp;
         $success=true;
      }
      else
      {
         // do database call here to populate $tpl_timestamp.
         $db = new mysql();
         $db->query("
         SELECT
            UNIX_TIMESTAMP(tpl_timestamp) AS tpl_timestamp
         FROM
            smarty_templates
         WHERE
            tpl_name='{$tpl_name}'
         LIMIT 1;
         ");
         $db->next_record();
         
         if ($db->row_data['tpl_timestamp'])
         {
            $tpl_timestamp = $db->row_data['tpl_timestamp'];
            $success=true;
         }
      }
      #echo("Timestamp: <strong>{$tpl_timestamp}</strong> of this template file.");
      #die($tpl_timestamp);
      return($success);
   } # smarty_template_timestamp()
   
   /**
   * Default template: secured handler
   */
   function smarty_secure()
   {
   } # smarty_secure()
   
   /**
   * Default template: trunsted handler
   */
   function smarty_trusted()
   {
   } # smarty_trusted()

   /**
   * Prevent reading enquoted text
   * @uses Formatting - Add the shlashes, etc.
   * @var $text string Text to format
   * @return string
   */
   function __format_text($text)
   {
      #return($text); # as it is...
      $t = stripslashes($text);
      #$t = htmlspecialchars($t, ENT_QUOTES);
      return($t);
   } # __format_text()

   /**
   * Prevent writing enquoted text
   * @uses Formatting - Add the shlashes, etc.
   * @var $text string Text to format
   * @return string Unformatted string
   */
   function __unformat_text($text="")
   {
      #return($text); # as it is...
      $t = addslashes($text);
      #$t = htmlspecialchars_decode($t, ENT_NOQUOTES);
      return($t);
   } # __unformat_text()

   /**
   * Enable or disable the display of DEBUG messages
   * @var $enable_debug boolean Flag: Enable the messaging or not.
   * @uses Messaging If turned off, the messeges intended for printing will be stopped.
   * @uses Messaging Only for DEBUGing case
   */
   function __enable_debug_mode($enable_debug=false)
   {
      if($enable_debug==true)
         $this->debug_mode_enabled=true;
      else
         $this->debug_mode_enabled=false;
   } # __enable_debug_mode()
   
   /**
   * Display the debug messages
   * @var $message string Message to display
   * @uses Messaging Display the message
   * @return boolean Always false. This is call-only function.
   */
   function __debug_message($message="")
   {
      echo("<BR>$message / <strong>{$this->filename}</strong>.");
      #die();
      return(false);
   } # __debug_message()

   /**
   * Set a template file name.
   * @var $filename string Name of the template
   * @uses Setting Simply set the name of the template
   */
   function consider_file($filename)
   {
      $this->filename=$filename;
      $this->debug_mode_enabled=false;
      #echo("Okay");
   } # consider_file()

   /**
   * Read the actual template file contents, for this object.
   * Done, while the template is being edited.
   * @uses Importance Not useful in the front-end.
   * @return string HTML contents of the template resource
   */
   function file_contents()
   {
/*
      $fh = @fopen($this->filename, "r");
      if(!$fh && $this->debug_mode_enabled==true)
         return($this->__debug_message("Error reading file"));
      $text = @fread($fh, filesize($this->filename));
      @fclose($fh);
*/
      $tpl_name = $this->filename;
      $sql="SELECT * FROM smarty_templates WHERE tpl_name='{$tpl_name}' LIMIT 1;";
      #echo($sql);
      $this->db->query($sql);
      $this->db->next_record();
      $text = $this->db->row_data['tpl_source'];

      $formatted_text = $this->__unformat_text($text);
      return($text);
   } # file_contents()

   /**
   * Save the contents of a template (it's HTML) into the template resource.
   * Used while modifying a template file.
   * Resets the timestamp of the template too.
   * @uses Importance Not useful in the front-end.
   * @param $text text The contents from the template file.
   * @return boolean If template adding was successful.
   */
   function write($text="")
   {
      if($text=="")
         return;

      /*
      $fh = @fopen($this->filename, "w");
      if(!$fh && $this->debug_mode_enabled==true)
         return($this->__debug_message("Error writing file"));
      @fwrite($fh, $formatted_text, strlen($formatted_text));
      @fclose($fh);
      */
      
      $tpl_name = $this->filename;
      #$tpl_source = $this->__format_text($text);
      $tpl_source = $text;
      #die($tpl_source);
      
      $sql="DELETE FROM smarty_templates WHERE tpl_name='{$tpl_name}' LIMIT 1;";
      $this->db->query($sql);
      
      $sql="
      INSERT INTO smarty_templates (
         tpl_timestamp, tpl_name, tpl_source
      ) VALUES (
         NOW(), '{$tpl_name}', '{$tpl_source}'
      );";

      return($this->db->query($sql));
   } # write()
   
   /*
   * Build a list of clickable template resources.
   * @uses Editing Useful for the template contents editor.
   * @return string Anchor lists of the available template resources
   */
   function list_edit_templates()
   {
      $sql="SELECT id, tpl_name FROM smarty_templates ORDER BY tpl_name;";
      $this->db->query($sql);
      $list_edit="";
      while($this->db->next_record())
      {
         $list_edit.="<div style='height:25px;'><a href='?tpl_name={$this->db->row_data['tpl_name']}'>{$this->db->row_data['tpl_name']}</a></div>";
      }
      return($list_edit);
   } # list_edit_templates()

   /*
   * Build a list of clickable variable names available for a template resources.
   * @uses Editing Useful for the page contents contents editor.
   * @uses $page_name should be unique name
   * @param $page_name string Unique page name.
   * @return string Anchor lists of the available variables resources.
   */
   function list_edit_variables($page_name='')
   {
      $sql="SELECT id, content_name FROM smarty_page_contents WHERE page='{$page_name}' ORDER BY content_name;";
      $this->db->query($sql);
      $list_edit="";
      while($this->db->next_record())
      {
         $list_edit.="<div style='height:25px;'><a href='?vid={$this->db->row_data['id']}'>{$this->db->row_data['content_name']}</a></div>";
      }
      $list_edit=($list_edit=="")?"&nbsp;":$list_edit;
      return($list_edit);
   } # list_edit_variables()
   
   /**
   * Adds a new template name.
   * Later, you need to modifiy the contents. The content is set to be blank in the first.
   * @var $tpl_name string Name of the template
   * @uses Registration Add a blank template
   */
   function template_add($tpl_name='')
   {
      $sql="INSERT INTO smarty_templates (tpl_name) VALUES ('{$tpl_name}');";
      $this->db->query($sql);
   } # template_add()
   
   /**
   * know which template is associated to which page.
   * @var $page string Name of the page to find the template, associated with
   * @return Text Name of the template associated to the page $page
   */
   function template_get_name($page='')
   {
      if($page=='')
      {
         die("No page given - to select a template. ".__FILE__.", ".__LINE__);
      }
      $template_sql="SELECT * FROM smarty_page_templates WHERE page='{$page}' LIMIT 1;";
      $this->db->query($template_sql);
      $this->db->next_record();
      #print_r($this->db);
      $template = $this->db->row_data['template'];
      if($template=='')
      {
         die("Template for: {$page} did not exist in the database.<br>{$template_sql}");
         $template="file:no_template.inc.php"; # use it if this exists
      }
      return($template);
   } # template_get_name()
   
   /**
   * Extract the static contents of a page.
   * @var $page string Read the contents of the page
   * @return array
   */   
   function contents_get($page='')
   {
      $CONTENTS=array();
      $sql="
      SELECT * FROM smarty_page_contents WHERE page='{$page}'
      UNION
      SELECT * FROM smarty_page_contents WHERE page='GLOBALS' AND content_name LIKE 'PG_%'
      ;"; # No limit!
      $this->db->query($sql);
      while($this->db->next_record())
      {
         $CONTENTS[$this->db->row_data['content_name']]=$this->db->row_data['contents'];
      }
      #print_r($CONTENTS);
      return($CONTENTS);
   } # contents_get()
   
   /**
   * Add a content (static variable) of a page.
   * Needs to edit the contents values later on.
   * @return boolean It it was successful attempt to add the content name.
   */
   function content_name_add()
   {
      $content_name_sql="
      INSERT INTO smarty_page_contents (
         page, content_name
      ) VALUES (
         '{$_POST['page']}', '{$_POST['content_name_new']}'
      )
      ";
      return($this->db->query($content_name_sql));
   } # content_name_add()
   
   /**
   * Template page contents modify
   * @var boolean If it was successful attempt.
   */
   function template_page_conetnts_modify()
   {
      $_POST['pcid']+=0;
      $modify_sql="
      UPDATE smarty_page_contents SET
         #page='',
         #content_name='',
         contents='{$_POST['contents']}'
      WHERE id={$_POST['pcid']}
      ;";
      #die($modify_sql);
      return($this->db->query($modify_sql));
      #die($modify_sql);
   } # template_page_conetnts_modify()

   /**
   * Extract the URLs
   * @return array
   */
   function get_pages()
   {
      $tokens = explode('/', $_SERVER['REQUEST_URI']);
      #print("REQUEST_URIs: {$_SERVER['REQUEST_URI']} - "); print_r($tokens);
      #die("First: ".$tokens[2][0]);
   
      $page = $tokens[count($tokens)-1];
      if(!$page || $tokens[2][0]=='?')
         $page="index.inc.php"; # But natural is: index.php
      # Example: http://www.site.com/page.php?id=78&logged=true#anchor
      $pgs = explode('#', $page);
      $pgsa = explode('?', $pgs[0]);
      $pg = $pgsa[0];
      #print_r($page);
      #print_r($pgs);
      #print_r($pgsa);
   
      $tkn=array();
      $len=count($tokens)-1;
      for($i=2; $i<$len; ++$i)
      {
         $tkn[]=$tokens[$i];
      }
   
      $d = implode($tkn, '/');
   
      $dir=array();
      $dir['d']=$d;
      $dir['p']=$pg;
      $dir['dp']=($dir['d']=='')?$dir['p']:$dir['d'].'/'.$dir['p'];
      
      return($dir);
   } # get_pages()

}

?>
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
bimal
Smarty Elite


Joined: 19 Apr 2007
Posts: 420
Location: Kathmandu, Nepal

PostPosted: Tue Jan 27, 2009 5:25 pm    Post subject: Modifying Smarty's default template handing resources Reply with quote

Calling the register_resource is mandatory for this.

Code:
require_once("includes/smarty_database/class.smarty_database.inc.php");
require_once("includes/smarty/Smarty.class.php");

$smarty = new Smarty();
$smarty->template_dir = 'smarty_templates/';
$smarty->compile_dir  = 'smarty_compiles/';
$smarty->config_dir   = 'smarty_configs/';
$smarty->cache_dir    = 'smarty_cache/';
$smarty->caching      = false;

$smarty->register_resource(
   "smarty_database", array(
      array(&$sd, 'smarty_read_template'),
      array(&$sd, 'smarty_template_timestamp'),
      array(&$sd, 'smarty_secure'),
      array(&$sd, 'smarty_trusted')
   )
);
$smarty->default_resource_type="smarty_database";
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
bimal
Smarty Elite


Joined: 19 Apr 2007
Posts: 420
Location: Kathmandu, Nepal

PostPosted: Tue Jan 27, 2009 5:29 pm    Post subject: The database table structures Reply with quote

Be sure to add your own template and contents in the database.

Code:
DROP TABLE IF EXISTS smarty_page_contents;
CREATE TABLE smarty_page_contents (
  id int(11) NOT NULL auto_increment,
  `context` varchar(250) NOT NULL default 'MACA_SMARTY_SITE',
  `page` varchar(250) default NULL,
  content_name varchar(250) default NULL,
  contents text,
  PRIMARY KEY  (id),
  UNIQUE KEY page_contents (`page`,content_name)
) ;

DROP TABLE IF EXISTS smarty_page_templates;
CREATE TABLE smarty_page_templates (
  id int(11) NOT NULL auto_increment,
  `context` varchar(250) NOT NULL default 'MACA_SMARTY_SITE',
  `page` varchar(250) default NULL,
  template varchar(250) default NULL,
  PRIMARY KEY  (id),
  UNIQUE KEY `page` (`page`,`context`)
);

DROP TABLE IF EXISTS smarty_templates;
CREATE TABLE smarty_templates (
  id int(11) NOT NULL auto_increment,
  `context` varchar(250) NOT NULL default 'MACA_SMARTY_SITE',
  tpl_timestamp timestamp NULL default NULL,
  tpl_name varchar(250) default NULL,
  tpl_source text,
  tpl_comments varchar(250) default NULL,
  PRIMARY KEY  (id),
  UNIQUE KEY tpl_name (tpl_name,`context`)
);
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Smarty Forum Index -> Testimonials All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP