[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/administrator/components/com_contact/src/Model/ -> ContactModel.php (source)

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.Administrator
   5   * @subpackage  com_contact
   6   *
   7   * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
   8   * @license     GNU General Public License version 2 or later; see LICENSE.txt
   9   */
  10  
  11  namespace Joomla\Component\Contact\Administrator\Model;
  12  
  13  use Joomla\CMS\Factory;
  14  use Joomla\CMS\Form\Form;
  15  use Joomla\CMS\Helper\TagsHelper;
  16  use Joomla\CMS\Language\Associations;
  17  use Joomla\CMS\Language\LanguageHelper;
  18  use Joomla\CMS\Language\Text;
  19  use Joomla\CMS\MVC\Model\AdminModel;
  20  use Joomla\CMS\String\PunycodeHelper;
  21  use Joomla\CMS\Versioning\VersionableModelTrait;
  22  use Joomla\Component\Categories\Administrator\Helper\CategoriesHelper;
  23  use Joomla\Database\ParameterType;
  24  use Joomla\Registry\Registry;
  25  use Joomla\Utilities\ArrayHelper;
  26  
  27  // phpcs:disable PSR1.Files.SideEffects
  28  \defined('_JEXEC') or die;
  29  // phpcs:enable PSR1.Files.SideEffects
  30  
  31  /**
  32   * Item Model for a Contact.
  33   *
  34   * @since  1.6
  35   */
  36  class ContactModel extends AdminModel
  37  {
  38      use VersionableModelTrait;
  39  
  40      /**
  41       * The type alias for this content type.
  42       *
  43       * @var    string
  44       * @since  3.2
  45       */
  46      public $typeAlias = 'com_contact.contact';
  47  
  48      /**
  49       * The context used for the associations table
  50       *
  51       * @var    string
  52       * @since  3.4.4
  53       */
  54      protected $associationsContext = 'com_contact.item';
  55  
  56      /**
  57       * Batch copy/move command. If set to false, the batch copy/move command is not supported
  58       *
  59       * @var  string
  60       */
  61      protected $batch_copymove = 'category_id';
  62  
  63      /**
  64       * Allowed batch commands
  65       *
  66       * @var array
  67       */
  68      protected $batch_commands = array(
  69          'assetgroup_id' => 'batchAccess',
  70          'language_id'   => 'batchLanguage',
  71          'tag'           => 'batchTag',
  72          'user_id'       => 'batchUser',
  73      );
  74  
  75      /**
  76       * Name of the form
  77       *
  78       * @var string
  79       * @since  4.0.0
  80       */
  81      protected $formName = 'contact';
  82  
  83      /**
  84       * Batch change a linked user.
  85       *
  86       * @param   integer  $value     The new value matching a User ID.
  87       * @param   array    $pks       An array of row IDs.
  88       * @param   array    $contexts  An array of item contexts.
  89       *
  90       * @return  boolean  True if successful, false otherwise and internal error is set.
  91       *
  92       * @since   2.5
  93       */
  94      protected function batchUser($value, $pks, $contexts)
  95      {
  96          foreach ($pks as $pk) {
  97              if ($this->user->authorise('core.edit', $contexts[$pk])) {
  98                  $this->table->reset();
  99                  $this->table->load($pk);
 100                  $this->table->user_id = (int) $value;
 101  
 102                  if (!$this->table->store()) {
 103                      $this->setError($this->table->getError());
 104  
 105                      return false;
 106                  }
 107              } else {
 108                  $this->setError(Text::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT'));
 109  
 110                  return false;
 111              }
 112          }
 113  
 114          // Clean the cache
 115          $this->cleanCache();
 116  
 117          return true;
 118      }
 119  
 120      /**
 121       * Method to test whether a record can be deleted.
 122       *
 123       * @param   object  $record  A record object.
 124       *
 125       * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
 126       *
 127       * @since   1.6
 128       */
 129      protected function canDelete($record)
 130      {
 131          if (empty($record->id) || $record->published != -2) {
 132              return false;
 133          }
 134  
 135          return Factory::getUser()->authorise('core.delete', 'com_contact.category.' . (int) $record->catid);
 136      }
 137  
 138      /**
 139       * Method to test whether a record can have its state edited.
 140       *
 141       * @param   object  $record  A record object.
 142       *
 143       * @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
 144       *
 145       * @since   1.6
 146       */
 147      protected function canEditState($record)
 148      {
 149          // Check against the category.
 150          if (!empty($record->catid)) {
 151              return Factory::getUser()->authorise('core.edit.state', 'com_contact.category.' . (int) $record->catid);
 152          }
 153  
 154          // Default to component settings if category not known.
 155          return parent::canEditState($record);
 156      }
 157  
 158      /**
 159       * Method to get the row form.
 160       *
 161       * @param   array    $data      Data for the form.
 162       * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
 163       *
 164       * @return  Form|boolean  A Form object on success, false on failure
 165       *
 166       * @since   1.6
 167       */
 168      public function getForm($data = array(), $loadData = true)
 169      {
 170          Form::addFieldPath(JPATH_ADMINISTRATOR . '/components/com_users/models/fields');
 171  
 172          // Get the form.
 173          $form = $this->loadForm('com_contact.' . $this->formName, $this->formName, array('control' => 'jform', 'load_data' => $loadData));
 174  
 175          if (empty($form)) {
 176              return false;
 177          }
 178  
 179          // Modify the form based on access controls.
 180          if (!$this->canEditState((object) $data)) {
 181              // Disable fields for display.
 182              $form->setFieldAttribute('featured', 'disabled', 'true');
 183              $form->setFieldAttribute('ordering', 'disabled', 'true');
 184              $form->setFieldAttribute('published', 'disabled', 'true');
 185  
 186              // Disable fields while saving.
 187              // The controller has already verified this is a record you can edit.
 188              $form->setFieldAttribute('featured', 'filter', 'unset');
 189              $form->setFieldAttribute('ordering', 'filter', 'unset');
 190              $form->setFieldAttribute('published', 'filter', 'unset');
 191          }
 192  
 193          // Don't allow to change the created_by user if not allowed to access com_users.
 194          if (!Factory::getUser()->authorise('core.manage', 'com_users')) {
 195              $form->setFieldAttribute('created_by', 'filter', 'unset');
 196          }
 197  
 198          return $form;
 199      }
 200  
 201      /**
 202       * Method to get a single record.
 203       *
 204       * @param   integer  $pk  The id of the primary key.
 205       *
 206       * @return  mixed  Object on success, false on failure.
 207       *
 208       * @since   1.6
 209       */
 210      public function getItem($pk = null)
 211      {
 212          if ($item = parent::getItem($pk)) {
 213              // Convert the metadata field to an array.
 214              $registry = new Registry($item->metadata);
 215              $item->metadata = $registry->toArray();
 216          }
 217  
 218          // Load associated contact items
 219          $assoc = Associations::isEnabled();
 220  
 221          if ($assoc) {
 222              $item->associations = array();
 223  
 224              if ($item->id != null) {
 225                  $associations = Associations::getAssociations('com_contact', '#__contact_details', 'com_contact.item', $item->id);
 226  
 227                  foreach ($associations as $tag => $association) {
 228                      $item->associations[$tag] = $association->id;
 229                  }
 230              }
 231          }
 232  
 233          // Load item tags
 234          if (!empty($item->id)) {
 235              $item->tags = new TagsHelper();
 236              $item->tags->getTagIds($item->id, 'com_contact.contact');
 237          }
 238  
 239          return $item;
 240      }
 241  
 242      /**
 243       * Method to get the data that should be injected in the form.
 244       *
 245       * @return  mixed  The data for the form.
 246       *
 247       * @since   1.6
 248       */
 249      protected function loadFormData()
 250      {
 251          $app = Factory::getApplication();
 252  
 253          // Check the session for previously entered form data.
 254          $data = $app->getUserState('com_contact.edit.contact.data', array());
 255  
 256          if (empty($data)) {
 257              $data = $this->getItem();
 258  
 259              // Prime some default values.
 260              if ($this->getState('contact.id') == 0) {
 261                  $data->set('catid', $app->input->get('catid', $app->getUserState('com_contact.contacts.filter.category_id'), 'int'));
 262              }
 263          }
 264  
 265          $this->preprocessData('com_contact.contact', $data);
 266  
 267          return $data;
 268      }
 269  
 270      /**
 271       * Method to save the form data.
 272       *
 273       * @param   array  $data  The form data.
 274       *
 275       * @return  boolean  True on success.
 276       *
 277       * @since   3.0
 278       */
 279      public function save($data)
 280      {
 281          $input = Factory::getApplication()->input;
 282  
 283          // Create new category, if needed.
 284          $createCategory = true;
 285  
 286          // If category ID is provided, check if it's valid.
 287          if (is_numeric($data['catid']) && $data['catid']) {
 288              $createCategory = !CategoriesHelper::validateCategoryId($data['catid'], 'com_contact');
 289          }
 290  
 291          // Save New Category
 292          if ($createCategory && $this->canCreateCategory()) {
 293              $category = [
 294                  // Remove #new# prefix, if exists.
 295                  'title'     => strpos($data['catid'], '#new#') === 0 ? substr($data['catid'], 5) : $data['catid'],
 296                  'parent_id' => 1,
 297                  'extension' => 'com_contact',
 298                  'language'  => $data['language'],
 299                  'published' => 1,
 300              ];
 301  
 302              /** @var \Joomla\Component\Categories\Administrator\Model\CategoryModel $categoryModel */
 303              $categoryModel = Factory::getApplication()->bootComponent('com_categories')
 304                  ->getMVCFactory()->createModel('Category', 'Administrator', ['ignore_request' => true]);
 305  
 306              // Create new category.
 307              if (!$categoryModel->save($category)) {
 308                  $this->setError($categoryModel->getError());
 309  
 310                  return false;
 311              }
 312  
 313              // Get the Category ID.
 314              $data['catid'] = $categoryModel->getState('category.id');
 315          }
 316  
 317          // Alter the name for save as copy
 318          if ($input->get('task') == 'save2copy') {
 319              $origTable = clone $this->getTable();
 320              $origTable->load($input->getInt('id'));
 321  
 322              if ($data['name'] == $origTable->name) {
 323                  list($name, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']);
 324                  $data['name'] = $name;
 325                  $data['alias'] = $alias;
 326              } else {
 327                  if ($data['alias'] == $origTable->alias) {
 328                      $data['alias'] = '';
 329                  }
 330              }
 331  
 332              $data['published'] = 0;
 333          }
 334  
 335          $links = array('linka', 'linkb', 'linkc', 'linkd', 'linke');
 336  
 337          foreach ($links as $link) {
 338              if (!empty($data['params'][$link])) {
 339                  $data['params'][$link] = PunycodeHelper::urlToPunycode($data['params'][$link]);
 340              }
 341          }
 342  
 343          return parent::save($data);
 344      }
 345  
 346      /**
 347       * Prepare and sanitise the table prior to saving.
 348       *
 349       * @param   \Joomla\CMS\Table\Table  $table  The Table object
 350       *
 351       * @return  void
 352       *
 353       * @since   1.6
 354       */
 355      protected function prepareTable($table)
 356      {
 357          $date = Factory::getDate()->toSql();
 358  
 359          $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);
 360  
 361          $table->generateAlias();
 362  
 363          if (empty($table->id)) {
 364              // Set the values
 365              $table->created = $date;
 366  
 367              // Set ordering to the last item if not set
 368              if (empty($table->ordering)) {
 369                  $db = $this->getDatabase();
 370                  $query = $db->getQuery(true)
 371                      ->select('MAX(ordering)')
 372                      ->from($db->quoteName('#__contact_details'));
 373                  $db->setQuery($query);
 374                  $max = $db->loadResult();
 375  
 376                  $table->ordering = $max + 1;
 377              }
 378          } else {
 379              // Set the values
 380              $table->modified = $date;
 381              $table->modified_by = Factory::getUser()->id;
 382          }
 383  
 384          // Increment the content version number.
 385          $table->version++;
 386      }
 387  
 388      /**
 389       * A protected method to get a set of ordering conditions.
 390       *
 391       * @param   \Joomla\CMS\Table\Table  $table  A record object.
 392       *
 393       * @return  array  An array of conditions to add to ordering queries.
 394       *
 395       * @since   1.6
 396       */
 397      protected function getReorderConditions($table)
 398      {
 399          return [
 400              $this->getDatabase()->quoteName('catid') . ' = ' . (int) $table->catid,
 401          ];
 402      }
 403  
 404      /**
 405       * Preprocess the form.
 406       *
 407       * @param   Form    $form   Form object.
 408       * @param   object  $data   Data object.
 409       * @param   string  $group  Group name.
 410       *
 411       * @return  void
 412       *
 413       * @since   3.0.3
 414       */
 415      protected function preprocessForm(Form $form, $data, $group = 'content')
 416      {
 417          if ($this->canCreateCategory()) {
 418              $form->setFieldAttribute('catid', 'allowAdd', 'true');
 419  
 420              // Add a prefix for categories created on the fly.
 421              $form->setFieldAttribute('catid', 'customPrefix', '#new#');
 422          }
 423  
 424          // Association contact items
 425          if (Associations::isEnabled()) {
 426              $languages = LanguageHelper::getContentLanguages(false, false, null, 'ordering', 'asc');
 427  
 428              if (count($languages) > 1) {
 429                  $addform = new \SimpleXMLElement('<form />');
 430                  $fields = $addform->addChild('fields');
 431                  $fields->addAttribute('name', 'associations');
 432                  $fieldset = $fields->addChild('fieldset');
 433                  $fieldset->addAttribute('name', 'item_associations');
 434  
 435                  foreach ($languages as $language) {
 436                      $field = $fieldset->addChild('field');
 437                      $field->addAttribute('name', $language->lang_code);
 438                      $field->addAttribute('type', 'modal_contact');
 439                      $field->addAttribute('language', $language->lang_code);
 440                      $field->addAttribute('label', $language->title);
 441                      $field->addAttribute('translate_label', 'false');
 442                      $field->addAttribute('select', 'true');
 443                      $field->addAttribute('new', 'true');
 444                      $field->addAttribute('edit', 'true');
 445                      $field->addAttribute('clear', 'true');
 446                      $field->addAttribute('propagate', 'true');
 447                  }
 448  
 449                  $form->load($addform, false);
 450              }
 451          }
 452  
 453          parent::preprocessForm($form, $data, $group);
 454      }
 455  
 456      /**
 457       * Method to toggle the featured setting of contacts.
 458       *
 459       * @param   array    $pks    The ids of the items to toggle.
 460       * @param   integer  $value  The value to toggle to.
 461       *
 462       * @return  boolean  True on success.
 463       *
 464       * @since   1.6
 465       */
 466      public function featured($pks, $value = 0)
 467      {
 468          // Sanitize the ids.
 469          $pks = ArrayHelper::toInteger((array) $pks);
 470  
 471          if (empty($pks)) {
 472              $this->setError(Text::_('COM_CONTACT_NO_ITEM_SELECTED'));
 473  
 474              return false;
 475          }
 476  
 477          $table = $this->getTable();
 478  
 479          try {
 480              $db = $this->getDatabase();
 481  
 482              $query = $db->getQuery(true);
 483              $query->update($db->quoteName('#__contact_details'));
 484              $query->set($db->quoteName('featured') . ' = :featured');
 485              $query->whereIn($db->quoteName('id'), $pks);
 486              $query->bind(':featured', $value, ParameterType::INTEGER);
 487  
 488              $db->setQuery($query);
 489  
 490              $db->execute();
 491          } catch (\Exception $e) {
 492              $this->setError($e->getMessage());
 493  
 494              return false;
 495          }
 496  
 497          $table->reorder();
 498  
 499          // Clean component's cache
 500          $this->cleanCache();
 501  
 502          return true;
 503      }
 504  
 505      /**
 506       * Is the user allowed to create an on the fly category?
 507       *
 508       * @return  boolean
 509       *
 510       * @since   3.6.1
 511       */
 512      private function canCreateCategory()
 513      {
 514          return Factory::getUser()->authorise('core.create', 'com_contact');
 515      }
 516  }


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer