Ejemplo n.º 1
0
	/**
	 * Saves a JUser object to the database. This method has been adapted from
	 * the JUser::save() method to bypass ACL checks for super users. It still
	 * calls the onUserBeforeSave and onUserAfterSave events.
	 *
	 * @param   JUser    &$user     Object to save.
	 * @param   Boolean  $dispatch  True to call the listening plugins or False to skip dispatching
	 *
	 * @return  boolean  True on success or False on failure.
	 *
	 * @since   2.0
	 * @throws  Exception
	 */
	public static function save(JUser &$user, $dispatch = true)
	{
		// Create the user table object
		$table = $user->getTable();
		$user->params = (string) $user->getParameters();
		$table->bind($user->getProperties());

		$username = $user->username;

		// Check and store the object.
		if (!$table->check())
		{
			throw new Exception(JText::sprintf('LIB_SHUSERHELPER_ERR_10511', $username, $table->getError()), 10511);
		}

		$my = JFactory::getUser();

		if ($dispatch)
		{
			// Check if we are creating a new user
			$isNew = empty($user->id);

			// Get the old user
			$oldUser = new JUser($user->id);

			// Fire the onUserBeforeSave event.
			JPluginHelper::importPlugin('user');
			$dispatcher = JDispatcher::getInstance();

			$result = $dispatcher->trigger('onUserBeforeSave', array($oldUser->getProperties(), $isNew, $user->getProperties()));

			if (in_array(false, $result, true))
			{
				// Plugin will have to raise its own error or throw an exception.
				return false;
			}
		}

		// Store the user data in the database
		if (!($result = $table->store()))
		{
			throw new Exception(JText::sprintf('LIB_SHUSERHELPER_ERR_10512', $username, $table->getError()), 10512);
		}

		// Set the id for the JUser object in case we created a new user.
		if (empty($user->id))
		{
			$user->id = $table->get('id');
		}

		if ($my->id == $table->id)
		{
			$registry = new JRegistry;
			$registry->loadString($table->params);
			$my->setParameters($registry);
		}

		if ($dispatch)
		{
			// Fire the onUserAfterSave event
			$dispatcher->trigger('onUserAfterSave', array($user->getProperties(), $isNew, $result, $user->getError()));
		}

		return $result;
	}