[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/administrator/components/com_users/src/Model/ -> UserModel.php (source)

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.Administrator
   5   * @subpackage  com_users
   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\Users\Administrator\Model;
  12  
  13  use Joomla\CMS\Access\Access;
  14  use Joomla\CMS\Component\ComponentHelper;
  15  use Joomla\CMS\Factory;
  16  use Joomla\CMS\Form\Form;
  17  use Joomla\CMS\Language\Multilanguage;
  18  use Joomla\CMS\Language\Text;
  19  use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
  20  use Joomla\CMS\MVC\Model\AdminModel;
  21  use Joomla\CMS\Plugin\PluginHelper;
  22  use Joomla\CMS\Table\Table;
  23  use Joomla\CMS\User\User;
  24  use Joomla\CMS\User\UserHelper;
  25  use Joomla\Database\ParameterType;
  26  use Joomla\Utilities\ArrayHelper;
  27  
  28  // phpcs:disable PSR1.Files.SideEffects
  29  \defined('_JEXEC') or die;
  30  // phpcs:enable PSR1.Files.SideEffects
  31  
  32  /**
  33   * User model.
  34   *
  35   * @since  1.6
  36   */
  37  class UserModel extends AdminModel
  38  {
  39      /**
  40       * An item.
  41       *
  42       * @var    array
  43       */
  44      protected $_item = null;
  45  
  46      /**
  47       * Constructor.
  48       *
  49       * @param   array                $config   An optional associative array of configuration settings.
  50       * @param   MVCFactoryInterface  $factory  The factory.
  51       *
  52       * @see     \Joomla\CMS\MVC\Model\BaseDatabaseModel
  53       * @since   3.2
  54       */
  55      public function __construct($config = array(), MVCFactoryInterface $factory = null)
  56      {
  57          $config = array_merge(
  58              array(
  59                  'event_after_delete'  => 'onUserAfterDelete',
  60                  'event_after_save'    => 'onUserAfterSave',
  61                  'event_before_delete' => 'onUserBeforeDelete',
  62                  'event_before_save'   => 'onUserBeforeSave',
  63                  'events_map'          => array('save' => 'user', 'delete' => 'user', 'validate' => 'user')
  64              ),
  65              $config
  66          );
  67  
  68          parent::__construct($config, $factory);
  69      }
  70  
  71      /**
  72       * Returns a reference to the a Table object, always creating it.
  73       *
  74       * @param   string  $type    The table type to instantiate
  75       * @param   string  $prefix  A prefix for the table class name. Optional.
  76       * @param   array   $config  Configuration array for model. Optional.
  77       *
  78       * @return  Table  A database object
  79       *
  80       * @since   1.6
  81       */
  82      public function getTable($type = 'User', $prefix = 'Joomla\\CMS\\Table\\', $config = array())
  83      {
  84          $table = Table::getInstance($type, $prefix, $config);
  85  
  86          return $table;
  87      }
  88  
  89      /**
  90       * Method to get a single record.
  91       *
  92       * @param   integer  $pk  The id of the primary key.
  93       *
  94       * @return  mixed  Object on success, false on failure.
  95       *
  96       * @since   1.6
  97       */
  98      public function getItem($pk = null)
  99      {
 100          $pk = (!empty($pk)) ? $pk : (int) $this->getState('user.id');
 101  
 102          if ($this->_item === null) {
 103              $this->_item = array();
 104          }
 105  
 106          if (!isset($this->_item[$pk])) {
 107              $this->_item[$pk] = parent::getItem($pk);
 108          }
 109  
 110          return $this->_item[$pk];
 111      }
 112  
 113      /**
 114       * Method to get the record form.
 115       *
 116       * @param   array    $data      An optional array of data for the form to interrogate.
 117       * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
 118       *
 119       * @return  Form|bool  A Form object on success, false on failure
 120       *
 121       * @since   1.6
 122       */
 123      public function getForm($data = array(), $loadData = true)
 124      {
 125          // Get the form.
 126          $form = $this->loadForm('com_users.user', 'user', array('control' => 'jform', 'load_data' => $loadData));
 127  
 128          if (empty($form)) {
 129              return false;
 130          }
 131  
 132          $user = Factory::getUser();
 133  
 134          // If the user needs to change their password, mark the password fields as required
 135          if ($user->requireReset) {
 136              $form->setFieldAttribute('password', 'required', 'true');
 137              $form->setFieldAttribute('password2', 'required', 'true');
 138          }
 139  
 140          // When multilanguage is set, a user's default site language should also be a Content Language
 141          if (Multilanguage::isEnabled()) {
 142              $form->setFieldAttribute('language', 'type', 'frontend_language', 'params');
 143          }
 144  
 145          $userId = (int) $form->getValue('id');
 146  
 147          // The user should not be able to set the requireReset value on their own account
 148          if ($userId === (int) $user->id) {
 149              $form->removeField('requireReset');
 150          }
 151  
 152          /**
 153           * If users without core.manage permission editing their own account, remove some fields which they should
 154           * not be allowed to change and prevent them to change user name if configured
 155           */
 156          if (!$user->authorise('core.manage', 'com_users') && (int) $user->id === $userId) {
 157              if (!ComponentHelper::getParams('com_users')->get('change_login_name')) {
 158                  $form->setFieldAttribute('username', 'required', 'false');
 159                  $form->setFieldAttribute('username', 'readonly', 'true');
 160                  $form->setFieldAttribute('username', 'description', 'COM_USERS_USER_FIELD_NOCHANGE_USERNAME_DESC');
 161              }
 162  
 163              $form->removeField('lastResetTime');
 164              $form->removeField('resetCount');
 165              $form->removeField('sendEmail');
 166              $form->removeField('block');
 167          }
 168  
 169          return $form;
 170      }
 171  
 172      /**
 173       * Method to get the data that should be injected in the form.
 174       *
 175       * @return  mixed  The data for the form.
 176       *
 177       * @since   1.6
 178       * @throws  \Exception
 179       */
 180      protected function loadFormData()
 181      {
 182          // Check the session for previously entered form data.
 183          $data = Factory::getApplication()->getUserState('com_users.edit.user.data', array());
 184  
 185          if (empty($data)) {
 186              $data = $this->getItem();
 187          }
 188  
 189          $this->preprocessData('com_users.profile', $data, 'user');
 190  
 191          return $data;
 192      }
 193  
 194      /**
 195       * Override Joomla\CMS\MVC\Model\AdminModel::preprocessForm to ensure the correct plugin group is loaded.
 196       *
 197       * @param   Form    $form   A Form object.
 198       * @param   mixed   $data   The data expected for the form.
 199       * @param   string  $group  The name of the plugin group to import (defaults to "content").
 200       *
 201       * @return  void
 202       *
 203       * @since   1.6
 204       *
 205       * @throws  \Exception if there is an error in the form event.
 206       */
 207      protected function preprocessForm(Form $form, $data, $group = 'user')
 208      {
 209          parent::preprocessForm($form, $data, $group);
 210      }
 211  
 212      /**
 213       * Method to save the form data.
 214       *
 215       * @param   array  $data  The form data.
 216       *
 217       * @return  boolean  True on success.
 218       *
 219       * @since   1.6
 220       * @throws  \Exception
 221       */
 222      public function save($data)
 223      {
 224          $pk   = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('user.id');
 225          $user = User::getInstance($pk);
 226  
 227          $my = Factory::getUser();
 228          $iAmSuperAdmin = $my->authorise('core.admin');
 229  
 230          // User cannot modify own user groups
 231          if ((int) $user->id == (int) $my->id && !$iAmSuperAdmin && isset($data['groups'])) {
 232              // Form was probably tampered with
 233              Factory::getApplication()->enqueueMessage(Text::_('COM_USERS_USERS_ERROR_CANNOT_EDIT_OWN_GROUP'), 'warning');
 234  
 235              $data['groups'] = null;
 236          }
 237  
 238          if ($data['block'] && $pk == $my->id && !$my->block) {
 239              $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF'));
 240  
 241              return false;
 242          }
 243  
 244          // Make sure user groups is selected when add/edit an account
 245          if (empty($data['groups']) && ((int) $user->id != (int) $my->id || $iAmSuperAdmin)) {
 246              $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_SAVE_ACCOUNT_WITHOUT_GROUPS'));
 247  
 248              return false;
 249          }
 250  
 251          // Make sure that we are not removing ourself from Super Admin group
 252          if ($iAmSuperAdmin && $my->get('id') == $pk) {
 253              // Check that at least one of our new groups is Super Admin
 254              $stillSuperAdmin = false;
 255              $myNewGroups = $data['groups'];
 256  
 257              foreach ($myNewGroups as $group) {
 258                  $stillSuperAdmin = $stillSuperAdmin ?: Access::checkGroup($group, 'core.admin');
 259              }
 260  
 261              if (!$stillSuperAdmin) {
 262                  $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_DEMOTE_SELF'));
 263  
 264                  return false;
 265              }
 266          }
 267  
 268          // Bind the data.
 269          if (!$user->bind($data)) {
 270              $this->setError($user->getError());
 271  
 272              return false;
 273          }
 274  
 275          // Store the data.
 276          if (!$user->save()) {
 277              $this->setError($user->getError());
 278  
 279              return false;
 280          }
 281  
 282          // Destroy all active sessions for the user after changing the password or blocking him
 283          if ($data['password2'] || $data['block']) {
 284              UserHelper::destroyUserSessions($user->id, true);
 285          }
 286  
 287          $this->setState('user.id', $user->id);
 288  
 289          return true;
 290      }
 291  
 292      /**
 293       * Method to delete rows.
 294       *
 295       * @param   array  &$pks  An array of item ids.
 296       *
 297       * @return  boolean  Returns true on success, false on failure.
 298       *
 299       * @since   1.6
 300       * @throws  \Exception
 301       */
 302      public function delete(&$pks)
 303      {
 304          $user  = Factory::getUser();
 305          $table = $this->getTable();
 306          $pks   = (array) $pks;
 307  
 308          // Check if I am a Super Admin
 309          $iAmSuperAdmin = $user->authorise('core.admin');
 310  
 311          PluginHelper::importPlugin($this->events_map['delete']);
 312  
 313          if (in_array($user->id, $pks)) {
 314              $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_DELETE_SELF'));
 315  
 316              return false;
 317          }
 318  
 319          // Iterate the items to delete each one.
 320          foreach ($pks as $i => $pk) {
 321              if ($table->load($pk)) {
 322                  // Access checks.
 323                  $allow = $user->authorise('core.delete', 'com_users');
 324  
 325                  // Don't allow non-super-admin to delete a super admin
 326                  $allow = (!$iAmSuperAdmin && Access::check($pk, 'core.admin')) ? false : $allow;
 327  
 328                  if ($allow) {
 329                      // Get users data for the users to delete.
 330                      $user_to_delete = Factory::getUser($pk);
 331  
 332                      // Fire the before delete event.
 333                      Factory::getApplication()->triggerEvent($this->event_before_delete, array($table->getProperties()));
 334  
 335                      if (!$table->delete($pk)) {
 336                          $this->setError($table->getError());
 337  
 338                          return false;
 339                      } else {
 340                          // Trigger the after delete event.
 341                          Factory::getApplication()->triggerEvent($this->event_after_delete, array($user_to_delete->getProperties(), true, $this->getError()));
 342                      }
 343                  } else {
 344                      // Prune items that you can't change.
 345                      unset($pks[$i]);
 346                      Factory::getApplication()->enqueueMessage(Text::_('JERROR_CORE_DELETE_NOT_PERMITTED'), 'error');
 347                  }
 348              } else {
 349                  $this->setError($table->getError());
 350  
 351                  return false;
 352              }
 353          }
 354  
 355          return true;
 356      }
 357  
 358      /**
 359       * Method to block user records.
 360       *
 361       * @param   array    &$pks   The ids of the items to publish.
 362       * @param   integer  $value  The value of the published state
 363       *
 364       * @return  boolean  True on success.
 365       *
 366       * @since   1.6
 367       * @throws  \Exception
 368       */
 369      public function block(&$pks, $value = 1)
 370      {
 371          $app        = Factory::getApplication();
 372          $user       = Factory::getUser();
 373  
 374          // Check if I am a Super Admin
 375          $iAmSuperAdmin = $user->authorise('core.admin');
 376          $table         = $this->getTable();
 377          $pks           = (array) $pks;
 378  
 379          PluginHelper::importPlugin($this->events_map['save']);
 380  
 381          // Prepare the logout options.
 382          $options = array(
 383              'clientid' => $app->get('shared_session', '0') ? null : 0,
 384          );
 385  
 386          // Access checks.
 387          foreach ($pks as $i => $pk) {
 388              if ($value == 1 && $pk == $user->get('id')) {
 389                  // Cannot block yourself.
 390                  unset($pks[$i]);
 391                  Factory::getApplication()->enqueueMessage(Text::_('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF'), 'error');
 392              } elseif ($table->load($pk)) {
 393                  $old   = $table->getProperties();
 394                  $allow = $user->authorise('core.edit.state', 'com_users');
 395  
 396                  // Don't allow non-super-admin to delete a super admin
 397                  $allow = (!$iAmSuperAdmin && Access::check($pk, 'core.admin')) ? false : $allow;
 398  
 399                  if ($allow) {
 400                      // Skip changing of same state
 401                      if ($table->block == $value) {
 402                          unset($pks[$i]);
 403                          continue;
 404                      }
 405  
 406                      $table->block = (int) $value;
 407  
 408                      // If unblocking, also change password reset count to zero to unblock reset
 409                      if ($table->block === 0) {
 410                          $table->resetCount = 0;
 411                      }
 412  
 413                      // Allow an exception to be thrown.
 414                      try {
 415                          if (!$table->check()) {
 416                              $this->setError($table->getError());
 417  
 418                              return false;
 419                          }
 420  
 421                          // Trigger the before save event.
 422                          $result = Factory::getApplication()->triggerEvent($this->event_before_save, array($old, false, $table->getProperties()));
 423  
 424                          if (in_array(false, $result, true)) {
 425                              // Plugin will have to raise its own error or throw an exception.
 426                              return false;
 427                          }
 428  
 429                          // Store the table.
 430                          if (!$table->store()) {
 431                              $this->setError($table->getError());
 432  
 433                              return false;
 434                          }
 435  
 436                          if ($table->block) {
 437                              UserHelper::destroyUserSessions($table->id);
 438                          }
 439  
 440                          // Trigger the after save event
 441                          Factory::getApplication()->triggerEvent($this->event_after_save, [$table->getProperties(), false, true, null]);
 442                      } catch (\Exception $e) {
 443                          $this->setError($e->getMessage());
 444  
 445                          return false;
 446                      }
 447  
 448                      // Log the user out.
 449                      if ($value) {
 450                          $app->logout($table->id, $options);
 451                      }
 452                  } else {
 453                      // Prune items that you can't change.
 454                      unset($pks[$i]);
 455                      Factory::getApplication()->enqueueMessage(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), 'error');
 456                  }
 457              }
 458          }
 459  
 460          return true;
 461      }
 462  
 463      /**
 464       * Method to activate user records.
 465       *
 466       * @param   array  &$pks  The ids of the items to activate.
 467       *
 468       * @return  boolean  True on success.
 469       *
 470       * @since   1.6
 471       * @throws  \Exception
 472       */
 473      public function activate(&$pks)
 474      {
 475          $user = Factory::getUser();
 476  
 477          // Check if I am a Super Admin
 478          $iAmSuperAdmin = $user->authorise('core.admin');
 479          $table         = $this->getTable();
 480          $pks           = (array) $pks;
 481  
 482          PluginHelper::importPlugin($this->events_map['save']);
 483  
 484          // Access checks.
 485          foreach ($pks as $i => $pk) {
 486              if ($table->load($pk)) {
 487                  $old   = $table->getProperties();
 488                  $allow = $user->authorise('core.edit.state', 'com_users');
 489  
 490                  // Don't allow non-super-admin to delete a super admin
 491                  $allow = (!$iAmSuperAdmin && Access::check($pk, 'core.admin')) ? false : $allow;
 492  
 493                  if (empty($table->activation)) {
 494                      // Ignore activated accounts.
 495                      unset($pks[$i]);
 496                  } elseif ($allow) {
 497                      $table->block      = 0;
 498                      $table->activation = '';
 499  
 500                      // Allow an exception to be thrown.
 501                      try {
 502                          if (!$table->check()) {
 503                              $this->setError($table->getError());
 504  
 505                              return false;
 506                          }
 507  
 508                          // Trigger the before save event.
 509                          $result = Factory::getApplication()->triggerEvent($this->event_before_save, array($old, false, $table->getProperties()));
 510  
 511                          if (in_array(false, $result, true)) {
 512                              // Plugin will have to raise it's own error or throw an exception.
 513                              return false;
 514                          }
 515  
 516                          // Store the table.
 517                          if (!$table->store()) {
 518                              $this->setError($table->getError());
 519  
 520                              return false;
 521                          }
 522  
 523                          // Fire the after save event
 524                          Factory::getApplication()->triggerEvent($this->event_after_save, [$table->getProperties(), false, true, null]);
 525                      } catch (\Exception $e) {
 526                          $this->setError($e->getMessage());
 527  
 528                          return false;
 529                      }
 530                  } else {
 531                      // Prune items that you can't change.
 532                      unset($pks[$i]);
 533                      Factory::getApplication()->enqueueMessage(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), 'error');
 534                  }
 535              }
 536          }
 537  
 538          return true;
 539      }
 540  
 541      /**
 542       * Method to perform batch operations on an item or a set of items.
 543       *
 544       * @param   array  $commands  An array of commands to perform.
 545       * @param   array  $pks       An array of item ids.
 546       * @param   array  $contexts  An array of item contexts.
 547       *
 548       * @return  boolean  Returns true on success, false on failure.
 549       *
 550       * @since   2.5
 551       */
 552      public function batch($commands, $pks, $contexts)
 553      {
 554          // Sanitize user ids.
 555          $pks = array_unique($pks);
 556          $pks = ArrayHelper::toInteger($pks);
 557  
 558          // Remove any values of zero.
 559          if (array_search(0, $pks, true)) {
 560              unset($pks[array_search(0, $pks, true)]);
 561          }
 562  
 563          if (empty($pks)) {
 564              $this->setError(Text::_('COM_USERS_USERS_NO_ITEM_SELECTED'));
 565  
 566              return false;
 567          }
 568  
 569          $done = false;
 570  
 571          if (!empty($commands['group_id'])) {
 572              $cmd = ArrayHelper::getValue($commands, 'group_action', 'add');
 573  
 574              if (!$this->batchUser((int) $commands['group_id'], $pks, $cmd)) {
 575                  return false;
 576              }
 577  
 578              $done = true;
 579          }
 580  
 581          if (!empty($commands['reset_id'])) {
 582              if (!$this->batchReset($pks, $commands['reset_id'])) {
 583                  return false;
 584              }
 585  
 586              $done = true;
 587          }
 588  
 589          if (!$done) {
 590              $this->setError(Text::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION'));
 591  
 592              return false;
 593          }
 594  
 595          // Clear the cache
 596          $this->cleanCache();
 597  
 598          return true;
 599      }
 600  
 601      /**
 602       * Batch flag users as being required to reset their passwords
 603       *
 604       * @param   array   $userIds  An array of user IDs on which to operate
 605       * @param   string  $action   The action to perform
 606       *
 607       * @return  boolean  True on success, false on failure
 608       *
 609       * @since   3.2
 610       */
 611      public function batchReset($userIds, $action)
 612      {
 613          $userIds = ArrayHelper::toInteger($userIds);
 614  
 615          // Check if I am a Super Admin
 616          $iAmSuperAdmin = Factory::getUser()->authorise('core.admin');
 617  
 618          // Non-super super user cannot work with super-admin user.
 619          if (!$iAmSuperAdmin && UserHelper::checkSuperUserInUsers($userIds)) {
 620              $this->setError(Text::_('COM_USERS_ERROR_CANNOT_BATCH_SUPERUSER'));
 621  
 622              return false;
 623          }
 624  
 625          // Set the action to perform
 626          if ($action === 'yes') {
 627              $value = 1;
 628          } else {
 629              $value = 0;
 630          }
 631  
 632          // Prune out the current user if they are in the supplied user ID array
 633          $userIds = array_diff($userIds, array(Factory::getUser()->id));
 634  
 635          if (empty($userIds)) {
 636              $this->setError(Text::_('COM_USERS_USERS_ERROR_CANNOT_REQUIRERESET_SELF'));
 637  
 638              return false;
 639          }
 640  
 641          // Get the DB object
 642          $db = $this->getDatabase();
 643  
 644          $userIds = ArrayHelper::toInteger($userIds);
 645  
 646          $query = $db->getQuery(true);
 647  
 648          // Update the reset flag
 649          $query->update($db->quoteName('#__users'))
 650              ->set($db->quoteName('requireReset') . ' = :requireReset')
 651              ->whereIn($db->quoteName('id'), $userIds)
 652              ->bind(':requireReset', $value, ParameterType::INTEGER);
 653  
 654          $db->setQuery($query);
 655  
 656          try {
 657              $db->execute();
 658          } catch (\RuntimeException $e) {
 659              $this->setError($e->getMessage());
 660  
 661              return false;
 662          }
 663  
 664          return true;
 665      }
 666  
 667      /**
 668       * Perform batch operations
 669       *
 670       * @param   integer  $groupId  The group ID which assignments are being edited
 671       * @param   array    $userIds  An array of user IDs on which to operate
 672       * @param   string   $action   The action to perform
 673       *
 674       * @return  boolean  True on success, false on failure
 675       *
 676       * @since   1.6
 677       */
 678      public function batchUser($groupId, $userIds, $action)
 679      {
 680          $userIds = ArrayHelper::toInteger($userIds);
 681  
 682          // Check if I am a Super Admin
 683          $iAmSuperAdmin = Factory::getUser()->authorise('core.admin');
 684  
 685          // Non-super super user cannot work with super-admin user.
 686          if (!$iAmSuperAdmin && UserHelper::checkSuperUserInUsers($userIds)) {
 687              $this->setError(Text::_('COM_USERS_ERROR_CANNOT_BATCH_SUPERUSER'));
 688  
 689              return false;
 690          }
 691  
 692          // Non-super admin cannot work with super-admin group.
 693          if ((!$iAmSuperAdmin && Access::checkGroup($groupId, 'core.admin')) || $groupId < 1) {
 694              $this->setError(Text::_('COM_USERS_ERROR_INVALID_GROUP'));
 695  
 696              return false;
 697          }
 698  
 699          // Get the DB object
 700          $db = $this->getDatabase();
 701  
 702          switch ($action) {
 703              // Sets users to a selected group
 704              case 'set':
 705                  $doDelete = 'all';
 706                  $doAssign = true;
 707                  break;
 708  
 709              // Remove users from a selected group
 710              case 'del':
 711                  $doDelete = 'group';
 712                  break;
 713  
 714              // Add users to a selected group
 715              case 'add':
 716              default:
 717                  $doAssign = true;
 718                  break;
 719          }
 720  
 721          // Remove the users from the group if requested.
 722          if (isset($doDelete)) {
 723              $query = $db->getQuery(true);
 724  
 725              // Remove users from the group
 726              $query->delete($db->quoteName('#__user_usergroup_map'))
 727                  ->whereIn($db->quoteName('user_id'), $userIds);
 728  
 729              // Only remove users from selected group
 730              if ($doDelete == 'group') {
 731                  $query->where($db->quoteName('group_id') . ' = :group_id')
 732                      ->bind(':group_id', $groupId, ParameterType::INTEGER);
 733              }
 734  
 735              $db->setQuery($query);
 736  
 737              try {
 738                  $db->execute();
 739              } catch (\RuntimeException $e) {
 740                  $this->setError($e->getMessage());
 741  
 742                  return false;
 743              }
 744          }
 745  
 746          // Assign the users to the group if requested.
 747          if (isset($doAssign)) {
 748              $query = $db->getQuery(true);
 749  
 750              // First, we need to check if the user is already assigned to a group
 751              $query->select($db->quoteName('user_id'))
 752                  ->from($db->quoteName('#__user_usergroup_map'))
 753                  ->where($db->quoteName('group_id') . ' = :group_id')
 754                  ->bind(':group_id', $groupId, ParameterType::INTEGER);
 755              $db->setQuery($query);
 756              $users = $db->loadColumn();
 757  
 758              // Build the values clause for the assignment query.
 759              $query->clear();
 760              $groups = false;
 761  
 762              foreach ($userIds as $id) {
 763                  if (!in_array($id, $users)) {
 764                      $query->values($id . ',' . $groupId);
 765                      $groups = true;
 766                  }
 767              }
 768  
 769              // If we have no users to process, throw an error to notify the user
 770              if (!$groups) {
 771                  $this->setError(Text::_('COM_USERS_ERROR_NO_ADDITIONS'));
 772  
 773                  return false;
 774              }
 775  
 776              $query->insert($db->quoteName('#__user_usergroup_map'))
 777                  ->columns(array($db->quoteName('user_id'), $db->quoteName('group_id')));
 778              $db->setQuery($query);
 779  
 780              try {
 781                  $db->execute();
 782              } catch (\RuntimeException $e) {
 783                  $this->setError($e->getMessage());
 784  
 785                  return false;
 786              }
 787          }
 788  
 789          return true;
 790      }
 791  
 792      /**
 793       * Gets the available groups.
 794       *
 795       * @return  array  An array of groups
 796       *
 797       * @since   1.6
 798       */
 799      public function getGroups()
 800      {
 801          $user = Factory::getUser();
 802  
 803          if ($user->authorise('core.edit', 'com_users') && $user->authorise('core.manage', 'com_users')) {
 804              $model = $this->bootComponent('com_users')
 805                  ->getMVCFactory()->createModel('Groups', 'Administrator', ['ignore_request' => true]);
 806  
 807              return $model->getItems();
 808          } else {
 809              return null;
 810          }
 811      }
 812  
 813      /**
 814       * Gets the groups this object is assigned to
 815       *
 816       * @param   integer  $userId  The user ID to retrieve the groups for
 817       *
 818       * @return  array  An array of assigned groups
 819       *
 820       * @since   1.6
 821       */
 822      public function getAssignedGroups($userId = null)
 823      {
 824          $userId = (!empty($userId)) ? $userId : (int) $this->getState('user.id');
 825  
 826          if (empty($userId)) {
 827              $result   = array();
 828              $form     = $this->getForm();
 829  
 830              if ($form) {
 831                  $groupsIDs = $form->getValue('groups');
 832              }
 833  
 834              if (!empty($groupsIDs)) {
 835                  $result = $groupsIDs;
 836              } else {
 837                  $params = ComponentHelper::getParams('com_users');
 838  
 839                  if ($groupId = $params->get('new_usertype', $params->get('guest_usergroup', 1))) {
 840                      $result[] = $groupId;
 841                  }
 842              }
 843          } else {
 844              $result = UserHelper::getUserGroups($userId);
 845          }
 846  
 847          return $result;
 848      }
 849  
 850      /**
 851       * No longer used
 852       *
 853       * @param   integer  $userId  Ignored
 854       *
 855       * @return  \stdClass
 856       *
 857       * @since   3.2
 858       * @deprecated 4.2.0 Will be removed in 5.0
 859       */
 860      public function getOtpConfig($userId = null)
 861      {
 862          @trigger_error(
 863              sprintf(
 864                  '%s() is deprecated. Use \Joomla\Component\Users\Administrator\Helper\Mfa::getUserMfaRecords() instead.',
 865                  __METHOD__
 866              ),
 867              E_USER_DEPRECATED
 868          );
 869  
 870          // Return the configuration object
 871          return (object) array(
 872              'method' => 'none',
 873              'config' => array(),
 874              'otep'   => array()
 875          );
 876      }
 877  
 878      /**
 879       * No longer used
 880       *
 881       * @param   integer    $userId     Ignored
 882       * @param   \stdClass  $otpConfig  Ignored
 883       *
 884       * @return  boolean  True on success
 885       *
 886       * @since   3.2
 887       * @deprecated 4.2.0 Will be removed in 5.0
 888       */
 889      public function setOtpConfig($userId, $otpConfig)
 890      {
 891          @trigger_error(
 892              sprintf(
 893                  '%s() is deprecated. Multi-factor Authentication actions are handled by plugins in the multifactorauth folder.',
 894                  __METHOD__
 895              ),
 896              E_USER_DEPRECATED
 897          );
 898  
 899          return true;
 900      }
 901  
 902      /**
 903       * No longer used
 904       *
 905       * @return  string
 906       *
 907       * @since   3.2
 908       * @deprecated 4.2.0 Will be removed in 5.0
 909       */
 910      public function getOtpConfigEncryptionKey()
 911      {
 912          @trigger_error(
 913              sprintf(
 914                  '%s() is deprecated. Use \Joomla\CMS\Factory::getApplication()->get(\'secret\') instead',
 915                  __METHOD__
 916              ),
 917              E_USER_DEPRECATED
 918          );
 919  
 920          return Factory::getApplication()->get('secret');
 921      }
 922  
 923      /**
 924       * No longer used
 925       *
 926       * @param   integer  $userId  Ignored
 927       *
 928       * @return  array  Empty array
 929       *
 930       * @since   3.2
 931       * @throws  \Exception
 932       *
 933       * @deprecated 4.2.0 Will be removed in 5.0.
 934       */
 935      public function getTwofactorform($userId = null)
 936      {
 937          @trigger_error(
 938              sprintf(
 939                  '%s() is deprecated. Use \Joomla\Component\Users\Administrator\Helper\Mfa::getConfigurationInterface()',
 940                  __METHOD__
 941              ),
 942              E_USER_DEPRECATED
 943          );
 944  
 945          return [];
 946      }
 947  
 948      /**
 949       * No longer used
 950       *
 951       * @param   integer  $userId  Ignored
 952       * @param   integer  $count   Ignored
 953       *
 954       * @return  array  Empty array
 955       *
 956       * @since   3.2
 957       * @deprecated 4.2.0 Wil be removed in 5.0.
 958       */
 959      public function generateOteps($userId, $count = 10)
 960      {
 961          @trigger_error(
 962              sprintf(
 963                  '%s() is deprecated. See \Joomla\Component\Users\Administrator\Model\BackupcodesModel::saveBackupCodes()',
 964                  __METHOD__
 965              ),
 966              E_USER_DEPRECATED
 967          );
 968  
 969          return [];
 970      }
 971  
 972      /**
 973       * No longer used. Always returns true.
 974       *
 975       * @param   integer  $userId     Ignored
 976       * @param   string   $secretKey  Ignored
 977       * @param   array    $options    Ignored
 978       *
 979       * @return  boolean  Always true
 980       *
 981       * @since   3.2
 982       * @throws  \Exception
 983       *
 984       * @deprecated 4.2.0 Will be removed in 5.0. MFA validation is done in the captive login.
 985       */
 986      public function isValidSecretKey($userId, $secretKey, $options = array())
 987      {
 988          @trigger_error(
 989              sprintf(
 990                  '%s() is deprecated. Multi-factor Authentication actions are handled by plugins in the multifactorauth folder.',
 991                  __METHOD__
 992              ),
 993              E_USER_DEPRECATED
 994          );
 995  
 996          return true;
 997      }
 998  
 999      /**
1000       * No longer used
1001       *
1002       * @param   integer  $userId     Ignored
1003       * @param   string   $otep       Ignored
1004       * @param   object   $otpConfig  Ignored
1005       *
1006       * @return  boolean  Always true
1007       *
1008       * @since   3.2
1009       * @deprecated 4.2.0 Will be removed in 5.0
1010       */
1011      public function isValidOtep($userId, $otep, $otpConfig = null)
1012      {
1013          @trigger_error(
1014              sprintf(
1015                  '%s() is deprecated. Multi-factor Authentication actions are handled by plugins in the multifactorauth folder.',
1016                  __METHOD__
1017              ),
1018              E_USER_DEPRECATED
1019          );
1020  
1021          return true;
1022      }
1023  }


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