[ Index ]

PHP Cross Reference of Joomla 1.5.26 DE

title

Body

[close]

/libraries/joomla/application/component/ -> view.php (source)

   1  <?php
   2  /**
   3   * @version        $Id: view.php 14401 2010-01-26 14:10:00Z louis $
   4   * @package        Joomla.Framework
   5   * @subpackage    Application
   6   * @copyright Copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
   7   * @license        GNU/GPL, see LICENSE.php
   8   * Joomla! is free software. This version may have been modified pursuant
   9   * to the GNU General Public License, and as distributed it includes or
  10   * is derivative of works licensed under the GNU General Public License or
  11   * other free or open source software licenses.
  12   * See COPYRIGHT.php for copyright notices and details.
  13   */
  14  
  15  // Check to ensure this file is within the rest of the framework
  16  defined('JPATH_BASE') or die();
  17  
  18  /**
  19   * Base class for a Joomla View
  20   *
  21   * Class holding methods for displaying presentation data.
  22   *
  23   * @abstract
  24   * @package        Joomla.Framework
  25   * @subpackage    Application
  26   * @since        1.5
  27   */
  28  class JView extends JObject
  29  {
  30      /**
  31       * The name of the view
  32       *
  33       * @var        array
  34       * @access protected
  35       */
  36      var $_name = null;
  37  
  38      /**
  39       * Registered models
  40       *
  41       * @var        array
  42       * @access protected
  43       */
  44      var $_models = array();
  45  
  46      /**
  47       * The base path of the view
  48       *
  49       * @var        string
  50       * @access     protected
  51       */
  52      var $_basePath = null;
  53  
  54      /**
  55       * The default model
  56       *
  57       * @var    string
  58       * @access protected
  59       */
  60      var $_defaultModel = null;
  61  
  62      /**
  63       * Layout name
  64       *
  65       * @var        string
  66       * @access     protected
  67       */
  68      var $_layout = 'default';
  69  
  70      /**
  71       * Layout extension
  72       *
  73       * @var        string
  74       * @access     protected
  75       */
  76      var $_layoutExt = 'php';
  77  
  78      /**
  79      * The set of search directories for resources (templates)
  80      *
  81      * @var array
  82      * @access protected
  83      */
  84      var $_path = array(
  85          'template' => array(),
  86          'helper' => array()
  87      );
  88  
  89      /**
  90      * The name of the default template source file.
  91      *
  92      * @var string
  93      * @access private
  94      */
  95      var $_template = null;
  96  
  97      /**
  98      * The output of the template script.
  99      *
 100      * @var string
 101      * @access private
 102      */
 103      var $_output = null;
 104  
 105      /**
 106       * Callback for escaping.
 107       *
 108       * @var string
 109       * @access private
 110       */
 111      var $_escape = 'htmlspecialchars';
 112  
 113       /**
 114       * Charset to use in escaping mechanisms; defaults to urf8 (UTF-8)
 115       *
 116       * @var string
 117       * @access private
 118       */
 119      var $_charset = 'UTF-8';
 120  
 121      /**
 122       * Constructor
 123       *
 124       * @access    protected
 125       */
 126  	function __construct($config = array())
 127      {
 128          //set the view name
 129          if (empty( $this->_name ))
 130          {
 131              if (array_key_exists('name', $config))  {
 132                  $this->_name = $config['name'];
 133              } else {
 134                  $this->_name = $this->getName();
 135              }
 136          }
 137  
 138           // set the charset (used by the variable escaping functions)
 139          if (array_key_exists('charset', $config)) {
 140              $this->_charset = $config['charset'];
 141          }
 142  
 143           // user-defined escaping callback
 144          if (array_key_exists('escape', $config)) {
 145              $this->setEscape($config['escape']);
 146          }
 147  
 148          // Set a base path for use by the view
 149          if (array_key_exists('base_path', $config)) {
 150              $this->_basePath    = $config['base_path'];
 151          } else {
 152              $this->_basePath    = JPATH_COMPONENT;
 153          }
 154  
 155          // set the default template search path
 156          if (array_key_exists('template_path', $config)) {
 157              // user-defined dirs
 158              $this->_setPath('template', $config['template_path']);
 159          } else {
 160              $this->_setPath('template', $this->_basePath.DS.'views'.DS.$this->getName().DS.'tmpl');
 161          }
 162  
 163          // set the default helper search path
 164          if (array_key_exists('helper_path', $config)) {
 165              // user-defined dirs
 166              $this->_setPath('helper', $config['helper_path']);
 167          } else {
 168              $this->_setPath('helper', $this->_basePath.DS.'helpers');
 169          }
 170  
 171          // set the layout
 172          if (array_key_exists('layout', $config)) {
 173              $this->setLayout($config['layout']);
 174          } else {
 175              $this->setLayout('default');
 176          }
 177  
 178          $this->baseurl = JURI::base(true);
 179      }
 180  
 181      /**
 182      * Execute and display a template script.
 183      *
 184      * @param string $tpl The name of the template file to parse;
 185      * automatically searches through the template paths.
 186      *
 187      * @throws object An JError object.
 188      * @see fetch()
 189      */
 190  	function display($tpl = null)
 191      {
 192          $result = $this->loadTemplate($tpl);
 193          if (JError::isError($result)) {
 194              return $result;
 195          }
 196  
 197          echo $result;
 198      }
 199  
 200      /**
 201      * Assigns variables to the view script via differing strategies.
 202      *
 203      * This method is overloaded; you can assign all the properties of
 204      * an object, an associative array, or a single value by name.
 205      *
 206      * You are not allowed to set variables that begin with an underscore;
 207      * these are either private properties for JView or private variables
 208      * within the template script itself.
 209      *
 210      * <code>
 211      * $view = new JView();
 212      *
 213      * // assign directly
 214      * $view->var1 = 'something';
 215      * $view->var2 = 'else';
 216      *
 217      * // assign by name and value
 218      * $view->assign('var1', 'something');
 219      * $view->assign('var2', 'else');
 220      *
 221      * // assign by assoc-array
 222      * $ary = array('var1' => 'something', 'var2' => 'else');
 223      * $view->assign($obj);
 224      *
 225      * // assign by object
 226      * $obj = new stdClass;
 227      * $obj->var1 = 'something';
 228      * $obj->var2 = 'else';
 229      * $view->assign($obj);
 230      *
 231      * </code>
 232      *
 233      * @access public
 234      * @return bool True on success, false on failure.
 235      */
 236  	function assign()
 237      {
 238          // get the arguments; there may be 1 or 2.
 239          $arg0 = @func_get_arg(0);
 240          $arg1 = @func_get_arg(1);
 241  
 242          // assign by object
 243          if (is_object($arg0))
 244          {
 245              // assign public properties
 246              foreach (get_object_vars($arg0) as $key => $val)
 247              {
 248                  if (substr($key, 0, 1) != '_') {
 249                      $this->$key = $val;
 250                  }
 251              }
 252              return true;
 253          }
 254  
 255          // assign by associative array
 256          if (is_array($arg0))
 257          {
 258              foreach ($arg0 as $key => $val)
 259              {
 260                  if (substr($key, 0, 1) != '_') {
 261                      $this->$key = $val;
 262                  }
 263              }
 264              return true;
 265          }
 266  
 267          // assign by string name and mixed value.
 268  
 269          // we use array_key_exists() instead of isset() becuase isset()
 270          // fails if the value is set to null.
 271          if (is_string($arg0) && substr($arg0, 0, 1) != '_' && func_num_args() > 1)
 272          {
 273              $this->$arg0 = $arg1;
 274              return true;
 275          }
 276  
 277          // $arg0 was not object, array, or string.
 278          return false;
 279      }
 280  
 281  
 282      /**
 283      * Assign variable for the view (by reference).
 284      *
 285      * You are not allowed to set variables that begin with an underscore;
 286      * these are either private properties for JView or private variables
 287      * within the template script itself.
 288      *
 289      * <code>
 290      * $view = new JView();
 291      *
 292      * // assign by name and value
 293      * $view->assignRef('var1', $ref);
 294      *
 295      * // assign directly
 296      * $view->ref =& $var1;
 297      * </code>
 298      *
 299      * @access public
 300      *
 301      * @param string $key The name for the reference in the view.
 302      * @param mixed &$val The referenced variable.
 303      *
 304      * @return bool True on success, false on failure.
 305      */
 306  
 307  	function assignRef($key, &$val)
 308      {
 309          if (is_string($key) && substr($key, 0, 1) != '_')
 310          {
 311              $this->$key =& $val;
 312              return true;
 313          }
 314  
 315          return false;
 316      }
 317  
 318      /**
 319       * Escapes a value for output in a view script.
 320       *
 321       * If escaping mechanism is one of htmlspecialchars or htmlentities, uses
 322       * {@link $_encoding} setting.
 323       *
 324       * @param  mixed $var The output to escape.
 325       * @return mixed The escaped value.
 326       */
 327      function escape($var)
 328      {
 329          if (in_array($this->_escape, array('htmlspecialchars', 'htmlentities'))) {
 330              return call_user_func($this->_escape, $var, ENT_COMPAT, $this->_charset);
 331          }
 332  
 333          return call_user_func($this->_escape, $var);
 334      }
 335  
 336      /**
 337       * Method to get data from a registered model or a property of the view
 338       *
 339       * @access    public
 340       * @param    string    The name of the method to call on the model, or the property to get
 341       * @param    string    The name of the model to reference, or the default value [optional]
 342       * @return mixed    The return value of the method
 343       */
 344      function &get( $property, $default = null )
 345      {
 346  
 347          // If $model is null we use the default model
 348          if (is_null($default)) {
 349              $model = $this->_defaultModel;
 350          } else {
 351              $model = strtolower( $default );
 352          }
 353  
 354          // First check to make sure the model requested exists
 355          if (isset( $this->_models[$model] ))
 356          {
 357              // Model exists, lets build the method name
 358              $method = 'get'.ucfirst($property);
 359  
 360              // Does the method exist?
 361              if (method_exists($this->_models[$model], $method))
 362              {
 363                  // The method exists, lets call it and return what we get
 364                  $result = $this->_models[$model]->$method();
 365                  return $result;
 366              }
 367  
 368          }
 369  
 370          // degrade to JObject::get
 371          $result = parent::get( $property, $default );
 372          return $result;
 373  
 374      }
 375  
 376      /**
 377       * Method to get the model object
 378       *
 379       * @access    public
 380       * @param    string    $name    The name of the model (optional)
 381       * @return    mixed            JModel object
 382       */
 383      function &getModel( $name = null )
 384      {
 385          if ($name === null) {
 386              $name = $this->_defaultModel;
 387          }
 388          return $this->_models[strtolower( $name )];
 389      }
 390  
 391      /**
 392      * Get the layout.
 393      *
 394      * @access public
 395      * @return string The layout name
 396      */
 397  
 398  	function getLayout()
 399      {
 400          return $this->_layout;
 401      }
 402  
 403      /**
 404       * Method to get the view name
 405       *
 406       * The model name by default parsed using the classname, or it can be set
 407       * by passing a $config['name'] in the class constructor
 408       *
 409       * @access    public
 410       * @return    string The name of the model
 411       * @since    1.5
 412       */
 413  	function getName()
 414      {
 415          $name = $this->_name;
 416  
 417          if (empty( $name ))
 418          {
 419              $r = null;
 420              if (!preg_match('/View((view)*(.*(view)?.*))$/i', get_class($this), $r)) {
 421                  JError::raiseError (500, "JView::getName() : Cannot get or parse class name.");
 422              }
 423              if (strpos($r[3], "view"))
 424              {
 425                  JError::raiseWarning('SOME_ERROR_CODE',"JView::getName() : Your classname contains the substring 'view'. ".
 426                                              "This causes problems when extracting the classname from the name of your objects view. " .
 427                                              "Avoid Object names with the substring 'view'.");
 428              }
 429              $name = strtolower( $r[3] );
 430          }
 431  
 432          return $name;
 433      }
 434  
 435      /**
 436       * Method to add a model to the view.  We support a multiple model single
 437       * view system by which models are referenced by classname.  A caveat to the
 438       * classname referencing is that any classname prepended by JModel will be
 439       * referenced by the name without JModel, eg. JModelCategory is just
 440       * Category.
 441       *
 442       * @access    public
 443       * @param    object    $model        The model to add to the view.
 444       * @param    boolean    $default    Is this the default model?
 445       * @return    object                The added model
 446       */
 447      function &setModel( &$model, $default = false )
 448      {
 449          $name = strtolower($model->getName());
 450          $this->_models[$name] = &$model;
 451  
 452          if ($default) {
 453              $this->_defaultModel = $name;
 454          }
 455          return $model;
 456      }
 457  
 458      /**
 459      * Sets the layout name to use
 460      *
 461      * @access    public
 462      * @param    string $template The template name.
 463      * @return    string Previous value
 464      * @since    1.5
 465      */
 466  
 467  	function setLayout($layout)
 468      {
 469          $previous        = $this->_layout;
 470          $this->_layout = $layout;
 471          return $previous;
 472      }
 473  
 474      /**
 475       * Allows a different extension for the layout files to be used
 476       *
 477       * @access    public
 478       * @param    string    The extension
 479       * @return    string    Previous value
 480       * @since    1.5
 481       */
 482  	function setLayoutExt( $value )
 483      {
 484          $previous    = $this->_layoutExt;
 485          if ($value = preg_replace( '#[^A-Za-z0-9]#', '', trim( $value ) )) {
 486              $this->_layoutExt = $value;
 487          }
 488          return $previous;
 489      }
 490  
 491       /**
 492       * Sets the _escape() callback.
 493       *
 494       * @param mixed $spec The callback for _escape() to use.
 495       */
 496      function setEscape($spec)
 497      {
 498          $this->_escape = $spec;
 499      }
 500  
 501      /**
 502       * Adds to the stack of view script paths in LIFO order.
 503       *
 504       * @param string|array The directory (-ies) to add.
 505       * @return void
 506       */
 507  	function addTemplatePath($path)
 508      {
 509          $this->_addPath('template', $path);
 510      }
 511  
 512      /**
 513       * Adds to the stack of helper script paths in LIFO order.
 514       *
 515       * @param string|array The directory (-ies) to add.
 516       * @return void
 517       */
 518  	function addHelperPath($path)
 519      {
 520          $this->_addPath('helper', $path);
 521      }
 522  
 523      /**
 524       * Load a template file -- first look in the templates folder for an override
 525       *
 526       * @access    public
 527       * @param string $tpl The name of the template source file ...
 528       * automatically searches the template paths and compiles as needed.
 529       * @return string The output of the the template script.
 530       */
 531  	function loadTemplate( $tpl = null)
 532      {
 533          global $mainframe, $option;
 534  
 535          // clear prior output
 536          $this->_output = null;
 537  
 538          //create the template file name based on the layout
 539          $file = isset($tpl) ? $this->_layout.'_'.$tpl : $this->_layout;
 540          // clean the file name
 541          $file = preg_replace('/[^A-Z0-9_\.-]/i', '', $file);
 542          $tpl  = preg_replace('/[^A-Z0-9_\.-]/i', '', $tpl);
 543  
 544          // load the template script
 545          jimport('joomla.filesystem.path');
 546          $filetofind    = $this->_createFileName('template', array('name' => $file));
 547          $this->_template = JPath::find($this->_path['template'], $filetofind);
 548  
 549          if ($this->_template != false)
 550          {
 551              // unset so as not to introduce into template scope
 552              unset($tpl);
 553              unset($file);
 554  
 555              // never allow a 'this' property
 556              if (isset($this->this)) {
 557                  unset($this->this);
 558              }
 559  
 560              // start capturing output into a buffer
 561              ob_start();
 562              // include the requested template filename in the local scope
 563              // (this will execute the view logic).
 564              include $this->_template;
 565  
 566              // done with the requested template; get the buffer and
 567              // clear it.
 568              $this->_output = ob_get_contents();
 569              ob_end_clean();
 570  
 571              return $this->_output;
 572          }
 573          else {
 574              return JError::raiseError( 500, 'Layout "' . $file . '" not found' );
 575          }
 576      }
 577  
 578      /**
 579       * Load a helper file
 580       *
 581       * @access    public
 582       * @param string $tpl The name of the helper source file ...
 583       * automatically searches the helper paths and compiles as needed.
 584       * @return boolean Returns true if the file was loaded
 585       */
 586  	function loadHelper( $hlp = null)
 587      {
 588          // clean the file name
 589          $file = preg_replace('/[^A-Z0-9_\.-]/i', '', $hlp);
 590  
 591          // load the template script
 592          jimport('joomla.filesystem.path');
 593          $helper = JPath::find($this->_path['helper'], $this->_createFileName('helper', array('name' => $file)));
 594  
 595          if ($helper != false)
 596          {
 597              // include the requested template filename in the local scope
 598              include_once $helper;
 599          }
 600      }
 601  
 602      /**
 603      * Sets an entire array of search paths for templates or resources.
 604      *
 605      * @access protected
 606      * @param string $type The type of path to set, typically 'template'.
 607      * @param string|array $path The new set of search paths.  If null or
 608      * false, resets to the current directory only.
 609      */
 610  	function _setPath($type, $path)
 611      {
 612          global $mainframe, $option;
 613  
 614          // clear out the prior search dirs
 615          $this->_path[$type] = array();
 616  
 617          // actually add the user-specified directories
 618          $this->_addPath($type, $path);
 619  
 620          // always add the fallback directories as last resort
 621          switch (strtolower($type))
 622          {
 623              case 'template':
 624              {
 625                  // set the alternative template search dir
 626                  if (isset($mainframe))
 627                  {
 628                      $option = preg_replace('/[^A-Z0-9_\.-]/i', '', $option);
 629                      $fallback = JPATH_BASE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.$option.DS.$this->getName();
 630                      $this->_addPath('template', $fallback);
 631                  }
 632              }    break;
 633          }
 634      }
 635  
 636      /**
 637      * Adds to the search path for templates and resources.
 638      *
 639      * @access protected
 640      * @param string|array $path The directory or stream to search.
 641      */
 642  	function _addPath($type, $path)
 643      {
 644          // just force to array
 645          settype($path, 'array');
 646  
 647          // loop through the path directories
 648          foreach ($path as $dir)
 649          {
 650              // no surrounding spaces allowed!
 651              $dir = trim($dir);
 652  
 653              // add trailing separators as needed
 654              if (substr($dir, -1) != DIRECTORY_SEPARATOR) {
 655                  // directory
 656                  $dir .= DIRECTORY_SEPARATOR;
 657              }
 658  
 659              // add to the top of the search dirs
 660              array_unshift($this->_path[$type], $dir);
 661          }
 662      }
 663  
 664      /**
 665       * Create the filename for a resource
 666       *
 667       * @access private
 668       * @param string     $type  The resource type to create the filename for
 669       * @param array     $parts An associative array of filename information
 670       * @return string The filename
 671       * @since 1.5
 672       */
 673  	function _createFileName($type, $parts = array())
 674      {
 675          $filename = '';
 676  
 677          switch($type)
 678          {
 679              case 'template' :
 680                  $filename = strtolower($parts['name']).'.'.$this->_layoutExt;
 681                  break;
 682  
 683              default :
 684                  $filename = strtolower($parts['name']).'.php';
 685                  break;
 686          }
 687          return $filename;
 688      }
 689  }


Generated: Wed Mar 28 15:54:07 2012 Cross-referenced by PHPXref 0.7.1