[ Index ]

PHP Cross Reference of Joomla 2.5.4 DE

title

Body

[close]

/administrator/components/com_templates/models/ -> style.php (source)

   1  <?php
   2  /**
   3   * @package        Joomla.Administrator
   4   * @subpackage    com_templates
   5   * @copyright    Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
   6   * @license        GNU General Public License version 2 or later; see LICENSE.txt
   7   */
   8  
   9  // No direct access.
  10  defined('_JEXEC') or die;
  11  
  12  jimport('joomla.application.component.modeladmin');
  13  
  14  /**
  15   * Template style model.
  16   *
  17   * @package        Joomla.Administrator
  18   * @subpackage    com_templates
  19   * @since        1.6
  20   */
  21  class TemplatesModelStyle extends JModelAdmin
  22  {
  23      /**
  24       * @var        string    The help screen key for the module.
  25       * @since    1.6
  26       */
  27      protected $helpKey = 'JHELP_EXTENSIONS_TEMPLATE_MANAGER_STYLES_EDIT';
  28  
  29      /**
  30       * @var        string    The help screen base URL for the module.
  31       * @since    1.6
  32       */
  33      protected $helpURL;
  34  
  35      /**
  36       * Item cache.
  37       */
  38      private $_cache = array();
  39  
  40      /**
  41       * Method to auto-populate the model state.
  42       *
  43       * Note. Calling getState in this method will result in recursion.
  44       *
  45       * @since    1.6
  46       */
  47  	protected function populateState()
  48      {
  49          $app = JFactory::getApplication('administrator');
  50  
  51          // Load the User state.
  52          $pk = (int) JRequest::getInt('id');
  53          $this->setState('style.id', $pk);
  54  
  55          // Load the parameters.
  56          $params    = JComponentHelper::getParams('com_templates');
  57          $this->setState('params', $params);
  58      }
  59  
  60      /**
  61       * Method to delete rows.
  62       *
  63       * @param    array    An array of item ids.
  64       *
  65       * @return    boolean    Returns true on success, false on failure.
  66       */
  67  	public function delete(&$pks)
  68      {
  69          // Initialise variables.
  70          $pks    = (array) $pks;
  71          $user    = JFactory::getUser();
  72          $table    = $this->getTable();
  73  
  74          // Iterate the items to delete each one.
  75          foreach ($pks as $i => $pk)
  76          {
  77              if ($table->load($pk)) {
  78                  // Access checks.
  79                  if (!$user->authorise('core.delete', 'com_templates')) {
  80                      throw new Exception(JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
  81                  }
  82                  // You should not delete a default style
  83                  if ($table->home != '0'){
  84                      JError::raiseWarning(SOME_ERROR_NUMBER, Jtext::_('COM_TEMPLATES_STYLE_CANNOT_DELETE_DEFAULT_STYLE'));
  85                      return false;
  86                  }
  87  
  88                  if (!$table->delete($pk)) {
  89                      $this->setError($table->getError());
  90                      return false;
  91                  }
  92              }
  93              else {
  94                  $this->setError($table->getError());
  95                  return false;
  96              }
  97          }
  98  
  99          // Clean cache
 100          $this->cleanCache();
 101  
 102          return true;
 103      }
 104  
 105      /**
 106       * Method to duplicate styles.
 107       *
 108       * @param    array    An array of primary key IDs.
 109       *
 110       * @return    boolean    True if successful.
 111       * @throws    Exception
 112       */
 113  	public function duplicate(&$pks)
 114      {
 115          // Initialise variables.
 116          $user    = JFactory::getUser();
 117          $db        = $this->getDbo();
 118  
 119          // Access checks.
 120          if (!$user->authorise('core.create', 'com_templates')) {
 121              throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
 122          }
 123  
 124          $table = $this->getTable();
 125  
 126          foreach ($pks as $pk)
 127          {
 128              if ($table->load($pk, true)) {
 129                  // Reset the id to create a new record.
 130                  $table->id = 0;
 131  
 132                  // Reset the home (don't want dupes of that field).
 133                  $table->home = 0;
 134  
 135                  // Alter the title.
 136                  $m = null;
 137                  $table->title = $this->generateNewTitle(null, null, $table->title);
 138  
 139                  if (!$table->check() || !$table->store()) {
 140                      throw new Exception($table->getError());
 141                  }
 142              }
 143              else {
 144                  throw new Exception($table->getError());
 145              }
 146          }
 147  
 148          // Clean cache
 149          $this->cleanCache();
 150  
 151          return true;
 152      }
 153  
 154      /**
 155       * Method to change the title.
 156       *
 157       * @param   integer  $category_id  The id of the category.
 158       * @param   string   $alias        The alias.
 159       * @param   string   $title        The title.
 160       *
 161       * @return    string  New title.
 162       * @since    1.7.1
 163       */
 164  	protected function generateNewTitle($category_id, $alias, $title)
 165      {
 166          // Alter the title
 167          $table = $this->getTable();
 168          while ($table->load(array('title'=>$title)))
 169          {
 170              $title = JString::increment($title);
 171          }
 172  
 173          return $title;
 174      }
 175  
 176      /**
 177       * Method to get the record form.
 178       *
 179       * @param    array    $data        An optional array of data for the form to interogate.
 180       * @param    boolean    $loadData    True if the form is to load its own data (default case), false if not.
 181       * @return    JForm    A JForm object on success, false on failure
 182       * @since    1.6
 183       */
 184  	public function getForm($data = array(), $loadData = true)
 185      {
 186          // Initialise variables.
 187          $app = JFactory::getApplication();
 188  
 189          // The folder and element vars are passed when saving the form.
 190          if (empty($data)) {
 191              $item        = $this->getItem();
 192              $clientId    = $item->client_id;
 193              $template    = $item->template;
 194          }
 195          else {
 196              $clientId    = JArrayHelper::getValue($data, 'client_id');
 197              $template    = JArrayHelper::getValue($data, 'template');
 198          }
 199  
 200          // These variables are used to add data from the plugin XML files.
 201          $this->setState('item.client_id',    $clientId);
 202          $this->setState('item.template',    $template);
 203  
 204          // Get the form.
 205          $form = $this->loadForm('com_templates.style', 'style', array('control' => 'jform', 'load_data' => $loadData));
 206          if (empty($form)) {
 207              return false;
 208          }
 209  
 210          // Modify the form based on access controls.
 211          if (!$this->canEditState((object) $data)) {
 212              // Disable fields for display.
 213              $form->setFieldAttribute('home', 'disabled', 'true');
 214  
 215              // Disable fields while saving.
 216              // The controller has already verified this is a record you can edit.
 217              $form->setFieldAttribute('home', 'filter', 'unset');
 218          }
 219  
 220          return $form;
 221      }
 222  
 223      /**
 224       * Method to get the data that should be injected in the form.
 225       *
 226       * @return    mixed    The data for the form.
 227       * @since    1.6
 228       */
 229  	protected function loadFormData()
 230      {
 231          // Check the session for previously entered form data.
 232          $data = JFactory::getApplication()->getUserState('com_templates.edit.style.data', array());
 233  
 234          if (empty($data)) {
 235              $data = $this->getItem();
 236          }
 237  
 238          return $data;
 239      }
 240  
 241      /**
 242       * Method to get a single record.
 243       *
 244       * @param    integer    The id of the primary key.
 245       *
 246       * @return    mixed    Object on success, false on failure.
 247       */
 248  	public function getItem($pk = null)
 249      {
 250          // Initialise variables.
 251          $pk = (!empty($pk)) ? $pk : (int) $this->getState('style.id');
 252  
 253          if (!isset($this->_cache[$pk])) {
 254              $false    = false;
 255  
 256              // Get a row instance.
 257              $table = $this->getTable();
 258  
 259              // Attempt to load the row.
 260              $return = $table->load($pk);
 261  
 262              // Check for a table object error.
 263              if ($return === false && $table->getError()) {
 264                  $this->setError($table->getError());
 265                  return $false;
 266              }
 267  
 268              // Convert to the JObject before adding other data.
 269              $properties = $table->getProperties(1);
 270              $this->_cache[$pk] = JArrayHelper::toObject($properties, 'JObject');
 271  
 272              // Convert the params field to an array.
 273              $registry = new JRegistry;
 274              $registry->loadString($table->params);
 275              $this->_cache[$pk]->params = $registry->toArray();
 276  
 277              // Get the template XML.
 278              $client    = JApplicationHelper::getClientInfo($table->client_id);
 279              $path    = JPath::clean($client->path.'/templates/'.$table->template.'/templateDetails.xml');
 280  
 281              if (file_exists($path)) {
 282                  $this->_cache[$pk]->xml = simplexml_load_file($path);
 283              }
 284              else {
 285                  $this->_cache[$pk]->xml = null;
 286              }
 287          }
 288  
 289          return $this->_cache[$pk];
 290      }
 291  
 292      /**
 293       * Returns a reference to the a Table object, always creating it.
 294       *
 295       * @param    type    The table type to instantiate
 296       * @param    string    A prefix for the table class name. Optional.
 297       * @param    array    Configuration array for model. Optional.
 298       * @return    JTable    A database object
 299      */
 300  	public function getTable($type = 'Style', $prefix = 'TemplatesTable', $config = array())
 301      {
 302          return JTable::getInstance($type, $prefix, $config);
 303      }
 304  
 305      /**
 306       * @param    object    A form object.
 307       * @param    mixed    The data expected for the form.
 308       * @throws    Exception if there is an error in the form event.
 309       * @since    1.6
 310       */
 311  	protected function preprocessForm(JForm $form, $data, $group = 'content')
 312      {
 313          // Initialise variables.
 314          $clientId    = $this->getState('item.client_id');
 315          $template    = $this->getState('item.template');
 316          $lang        = JFactory::getLanguage();
 317          $client        = JApplicationHelper::getClientInfo($clientId);
 318          if (!$form->loadFile('style_'.$client->name, true)) {
 319              throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
 320          }
 321  
 322          jimport('joomla.filesystem.file');
 323          jimport('joomla.filesystem.folder');
 324  
 325          $formFile    = JPath::clean($client->path.'/templates/'.$template.'/templateDetails.xml');
 326  
 327          // Load the core and/or local language file(s).
 328              $lang->load('tpl_'.$template, $client->path, null, false, false)
 329          ||    $lang->load('tpl_'.$template, $client->path.'/templates/'.$template, null, false, false)
 330          ||    $lang->load('tpl_'.$template, $client->path, $lang->getDefault(), false, false)
 331          ||    $lang->load('tpl_'.$template, $client->path.'/templates/'.$template, $lang->getDefault(), false, false);
 332  
 333          if (file_exists($formFile)) {
 334              // Get the template form.
 335              if (!$form->loadFile($formFile, false, '//config')) {
 336                  throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
 337              }
 338          }
 339  
 340          // Disable home field if it is default style
 341  
 342          if ((is_array($data) && array_key_exists('home', $data) && $data['home']=='1')
 343              || ((is_object($data) && isset($data->home) && $data->home=='1'))){
 344              $form->setFieldAttribute('home', 'readonly', 'true');
 345          }
 346  
 347          // Attempt to load the xml file.
 348          if (!$xml = simplexml_load_file($formFile)) {
 349              throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
 350          }
 351  
 352          // Get the help data from the XML file if present.
 353          $help = $xml->xpath('/extension/help');
 354          if (!empty($help)) {
 355              $helpKey = trim((string) $help[0]['key']);
 356              $helpURL = trim((string) $help[0]['url']);
 357  
 358              $this->helpKey = $helpKey ? $helpKey : $this->helpKey;
 359              $this->helpURL = $helpURL ? $helpURL : $this->helpURL;
 360          }
 361  
 362          // Trigger the default form events.
 363          parent::preprocessForm($form, $data, $group);
 364      }
 365  
 366      /**
 367       * Method to save the form data.
 368       *
 369       * @param    array    The form data.
 370       * @return    boolean    True on success.
 371       */
 372  	public function save($data)
 373      {
 374          // Detect disabled extension
 375          $extension = JTable::getInstance('Extension');
 376          if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $data['template'], 'client_id' => $data['client_id']))) {
 377              $this->setError(JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE'));
 378              return false;
 379          }
 380  
 381          // Initialise variables;
 382          $dispatcher = JDispatcher::getInstance();
 383          $table        = $this->getTable();
 384          $pk            = (!empty($data['id'])) ? $data['id'] : (int)$this->getState('style.id');
 385          $isNew        = true;
 386  
 387          // Include the extension plugins for the save events.
 388          JPluginHelper::importPlugin('extension');
 389  
 390          // Load the row if saving an existing record.
 391          if ($pk > 0) {
 392              $table->load($pk);
 393              $isNew = false;
 394          }
 395          if (JRequest::getVar('task') == 'save2copy') {
 396              $data['title'] = $this->generateNewTitle(null, null, $data['title']);
 397              $data['home'] = 0;
 398              $data['assigned'] ='';
 399          }
 400  
 401          // Bind the data.
 402          if (!$table->bind($data)) {
 403              $this->setError($table->getError());
 404              return false;
 405          }
 406  
 407          // Prepare the row for saving
 408          $this->prepareTable($table);
 409  
 410          // Check the data.
 411          if (!$table->check()) {
 412              $this->setError($table->getError());
 413              return false;
 414          }
 415  
 416          // Trigger the onExtensionBeforeSave event.
 417          $result = $dispatcher->trigger('onExtensionBeforeSave', array('com_templates.style', &$table, $isNew));
 418          if (in_array(false, $result, true)) {
 419              $this->setError($table->getError());
 420              return false;
 421          }
 422  
 423          // Store the data.
 424          if (!$table->store()) {
 425              $this->setError($table->getError());
 426              return false;
 427          }
 428  
 429          $user = JFactory::getUser();
 430          if ($user->authorise('core.edit', 'com_menus') && $table->client_id==0) {
 431              $n        = 0;
 432              $db        = JFactory::getDbo();
 433              $user    = JFactory::getUser();
 434  
 435              if (!empty($data['assigned']) && is_array($data['assigned'])) {
 436                  JArrayHelper::toInteger($data['assigned']);
 437  
 438                  // Update the mapping for menu items that this style IS assigned to.
 439                  $query = $db->getQuery(true);
 440                  $query->update('#__menu');
 441                  $query->set('template_style_id='.(int)$table->id);
 442                  $query->where('id IN ('.implode(',', $data['assigned']).')');
 443                  $query->where('template_style_id!='.(int) $table->id);
 444                  $query->where('checked_out in (0,'.(int) $user->id.')');
 445                  $db->setQuery($query);
 446                  $db->query();
 447                  $n += $db->getAffectedRows();
 448              }
 449  
 450              // Remove style mappings for menu items this style is NOT assigned to.
 451              // If unassigned then all existing maps will be removed.
 452              $query = $db->getQuery(true);
 453              $query->update('#__menu');
 454              $query->set('template_style_id=0');
 455              if (!empty($data['assigned'])) {
 456                  $query->where('id NOT IN ('.implode(',', $data['assigned']).')');
 457              }
 458  
 459              $query->where('template_style_id='.(int) $table->id);
 460              $query->where('checked_out in (0,'.(int) $user->id.')');
 461              $db->setQuery($query);
 462              $db->query();
 463  
 464              $n += $db->getAffectedRows();
 465              if ($n > 0) {
 466                  $app = JFactory::getApplication();
 467                  $app->enQueueMessage(JText::plural('COM_TEMPLATES_MENU_CHANGED', $n));
 468              }
 469          }
 470  
 471          // Clean the cache.
 472          $this->cleanCache();
 473  
 474          // Trigger the onExtensionAfterSave event.
 475          $dispatcher->trigger('onExtensionAfterSave', array('com_templates.style', &$table, $isNew));
 476  
 477          $this->setState('style.id', $table->id);
 478  
 479          return true;
 480      }
 481  
 482      /**
 483       * Method to set a template style as home.
 484       *
 485       * @param    int        The primary key ID for the style.
 486       *
 487       * @return    boolean    True if successful.
 488       * @throws    Exception
 489       */
 490  	public function setHome($id = 0)
 491      {
 492          // Initialise variables.
 493          $user    = JFactory::getUser();
 494          $db        = $this->getDbo();
 495  
 496          // Access checks.
 497          if (!$user->authorise('core.edit.state', 'com_templates')) {
 498              throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
 499          }
 500  
 501          $style = JTable::getInstance('Style', 'TemplatesTable');
 502          if (!$style->load((int)$id)) {
 503              throw new Exception(JText::_('COM_TEMPLATES_ERROR_STYLE_NOT_FOUND'));
 504          }
 505  
 506          // Detect disabled extension
 507          $extension = JTable::getInstance('Extension');
 508          if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $style->template, 'client_id' => $style->client_id))) {
 509              throw new Exception(JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE'));
 510          }
 511  
 512  
 513          // Reset the home fields for the client_id.
 514          $db->setQuery(
 515              'UPDATE #__template_styles' .
 516              ' SET home = \'0\'' .
 517              ' WHERE client_id = '.(int) $style->client_id .
 518              ' AND home = \'1\''
 519          );
 520  
 521          if (!$db->query()) {
 522              throw new Exception($db->getErrorMsg());
 523          }
 524  
 525          // Set the new home style.
 526          $db->setQuery(
 527              'UPDATE #__template_styles' .
 528              ' SET home = \'1\'' .
 529              ' WHERE id = '.(int) $id
 530          );
 531  
 532          if (!$db->query()) {
 533              throw new Exception($db->getErrorMsg());
 534          }
 535  
 536          // Clean the cache.
 537          $this->cleanCache();
 538  
 539          return true;
 540      }
 541  
 542      /**
 543       * Method to unset a template style as default for a language.
 544       *
 545       * @param    int        The primary key ID for the style.
 546       *
 547       * @return    boolean    True if successful.
 548       * @throws    Exception
 549       */
 550  	public function unsetHome($id = 0)
 551      {
 552          // Initialise variables.
 553          $user    = JFactory::getUser();
 554          $db        = $this->getDbo();
 555  
 556          // Access checks.
 557          if (!$user->authorise('core.edit.state', 'com_templates')) {
 558              throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
 559          }
 560  
 561          // Lookup the client_id.
 562          $db->setQuery(
 563              'SELECT client_id, home' .
 564              ' FROM #__template_styles' .
 565              ' WHERE id = '.(int) $id
 566          );
 567          $style = $db->loadObject();
 568  
 569          if ($error = $db->getErrorMsg()) {
 570              throw new Exception($error);
 571          }
 572          elseif (!is_numeric($style->client_id)) {
 573              throw new Exception(JText::_('COM_TEMPLATES_ERROR_STYLE_NOT_FOUND'));
 574          }
 575          elseif ($style->home=='1') {
 576              throw new Exception(JText::_('COM_TEMPLATES_ERROR_CANNOT_UNSET_DEFAULT_STYLE'));
 577          }
 578  
 579          // Set the new home style.
 580          $db->setQuery(
 581              'UPDATE #__template_styles' .
 582              ' SET home = \'0\'' .
 583              ' WHERE id = '.(int) $id
 584          );
 585  
 586          if (!$db->query()) {
 587              throw new Exception($db->getErrorMsg());
 588          }
 589  
 590          // Clean the cache.
 591          $this->cleanCache();
 592  
 593          return true;
 594      }
 595  
 596      /**
 597       * Get the necessary data to load an item help screen.
 598       *
 599       * @return    object    An object with key, url, and local properties for loading the item help screen.
 600       * @since    1.6
 601       */
 602  	public function getHelp()
 603      {
 604          return (object) array('key' => $this->helpKey, 'url' => $this->helpURL);
 605      }
 606  
 607      /**
 608       * Custom clean cache method
 609       *
 610       * @since    1.6
 611       */
 612  	protected function cleanCache($group = null, $client_id = 0)
 613      {
 614          parent::cleanCache('com_templates');
 615          parent::cleanCache('_system');
 616      }
 617  }


Generated: Tue Apr 3 11:40:28 2012 Cross-referenced by PHPXref 0.7.1