[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/components/com_privacy/src/Model/ -> RequestModel.php (source)

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.Site
   5   * @subpackage  com_privacy
   6   *
   7   * @copyright   (C) 2018 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\Privacy\Site\Model;
  12  
  13  use Joomla\CMS\Application\ApplicationHelper;
  14  use Joomla\CMS\Factory;
  15  use Joomla\CMS\Form\Form;
  16  use Joomla\CMS\Language\Text;
  17  use Joomla\CMS\Mail\Exception\MailDisabledException;
  18  use Joomla\CMS\Mail\MailTemplate;
  19  use Joomla\CMS\MVC\Model\AdminModel;
  20  use Joomla\CMS\Router\Route;
  21  use Joomla\CMS\Table\Table;
  22  use Joomla\CMS\Uri\Uri;
  23  use Joomla\CMS\User\UserHelper;
  24  use Joomla\Component\Actionlogs\Administrator\Model\ActionlogModel;
  25  use Joomla\Component\Messages\Administrator\Model\MessageModel;
  26  use Joomla\Component\Privacy\Administrator\Table\RequestTable;
  27  use Joomla\Database\Exception\ExecutionFailureException;
  28  use PHPMailer\PHPMailer\Exception as phpmailerException;
  29  
  30  // phpcs:disable PSR1.Files.SideEffects
  31  \defined('_JEXEC') or die;
  32  // phpcs:enable PSR1.Files.SideEffects
  33  
  34  /**
  35   * Request model class.
  36   *
  37   * @since  3.9.0
  38   */
  39  class RequestModel extends AdminModel
  40  {
  41      /**
  42       * Creates an information request.
  43       *
  44       * @param   array  $data  The data expected for the form.
  45       *
  46       * @return  mixed  Exception | boolean
  47       *
  48       * @since   3.9.0
  49       */
  50      public function createRequest($data)
  51      {
  52          $app = Factory::getApplication();
  53  
  54          // Creating requests requires the site's email sending be enabled
  55          if (!$app->get('mailonline', 1)) {
  56              $this->setError(Text::_('COM_PRIVACY_ERROR_CANNOT_CREATE_REQUEST_WHEN_SENDMAIL_DISABLED'));
  57  
  58              return false;
  59          }
  60  
  61          // Get the form.
  62          $form = $this->getForm();
  63  
  64          // Check for an error.
  65          if ($form instanceof \Exception) {
  66              return $form;
  67          }
  68  
  69          // Filter and validate the form data.
  70          $data   = $form->filter($data);
  71          $return = $form->validate($data);
  72  
  73          // Check for an error.
  74          if ($return instanceof \Exception) {
  75              return $return;
  76          }
  77  
  78          // Check the validation results.
  79          if ($return === false) {
  80              // Get the validation messages from the form.
  81              foreach ($form->getErrors() as $formError) {
  82                  $this->setError($formError->getMessage());
  83              }
  84  
  85              return false;
  86          }
  87  
  88          $data['email'] = Factory::getUser()->email;
  89  
  90          // Search for an open information request matching the email and type
  91          $db    = $this->getDatabase();
  92          $query = $db->getQuery(true)
  93              ->select('COUNT(id)')
  94              ->from($db->quoteName('#__privacy_requests'))
  95              ->where($db->quoteName('email') . ' = :email')
  96              ->where($db->quoteName('request_type') . ' = :requesttype')
  97              ->whereIn($db->quoteName('status'), [0, 1])
  98              ->bind(':email', $data['email'])
  99              ->bind(':requesttype', $data['request_type']);
 100  
 101          try {
 102              $result = (int) $db->setQuery($query)->loadResult();
 103          } catch (ExecutionFailureException $exception) {
 104              // Can't check for existing requests, so don't create a new one
 105              $this->setError(Text::_('COM_PRIVACY_ERROR_CHECKING_FOR_EXISTING_REQUESTS'));
 106  
 107              return false;
 108          }
 109  
 110          if ($result > 0) {
 111              $this->setError(Text::_('COM_PRIVACY_ERROR_PENDING_REQUEST_OPEN'));
 112  
 113              return false;
 114          }
 115  
 116          // Everything is good to go, create the request
 117          $token       = ApplicationHelper::getHash(UserHelper::genRandomPassword());
 118          $hashedToken = UserHelper::hashPassword($token);
 119  
 120          $data['confirm_token']            = $hashedToken;
 121          $data['confirm_token_created_at'] = Factory::getDate()->toSql();
 122  
 123          if (!$this->save($data)) {
 124              // The save function will set the error message, so just return here
 125              return false;
 126          }
 127  
 128          // Push a notification to the site's super users, deliberately ignoring if this process fails so the below message goes out
 129          /** @var MessageModel $messageModel */
 130          $messageModel = $app->bootComponent('com_messages')->getMVCFactory()->createModel('Message', 'Administrator');
 131  
 132          $messageModel->notifySuperUsers(
 133              Text::_('COM_PRIVACY_ADMIN_NOTIFICATION_USER_CREATED_REQUEST_SUBJECT'),
 134              Text::sprintf('COM_PRIVACY_ADMIN_NOTIFICATION_USER_CREATED_REQUEST_MESSAGE', $data['email'])
 135          );
 136  
 137          // The mailer can be set to either throw Exceptions or return boolean false, account for both
 138          try {
 139              $linkMode = $app->get('force_ssl', 0) == 2 ? Route::TLS_FORCE : Route::TLS_IGNORE;
 140  
 141              $templateData = [
 142                  'sitename' => $app->get('sitename'),
 143                  'url'      => Uri::root(),
 144                  'tokenurl' => Route::link('site', 'index.php?option=com_privacy&view=confirm&confirm_token=' . $token, false, $linkMode, true),
 145                  'formurl'  => Route::link('site', 'index.php?option=com_privacy&view=confirm', false, $linkMode, true),
 146                  'token'    => $token,
 147              ];
 148  
 149              switch ($data['request_type']) {
 150                  case 'export':
 151                      $mailer = new MailTemplate('com_privacy.notification.export', $app->getLanguage()->getTag());
 152  
 153                      break;
 154  
 155                  case 'remove':
 156                      $mailer = new MailTemplate('com_privacy.notification.remove', $app->getLanguage()->getTag());
 157  
 158                      break;
 159  
 160                  default:
 161                      $this->setError(Text::_('COM_PRIVACY_ERROR_UNKNOWN_REQUEST_TYPE'));
 162  
 163                      return false;
 164              }
 165  
 166              $mailer->addTemplateData($templateData);
 167              $mailer->addRecipient($data['email']);
 168  
 169              $mailer->send();
 170  
 171              /** @var RequestTable $table */
 172              $table = $this->getTable();
 173  
 174              if (!$table->load($this->getState($this->getName() . '.id'))) {
 175                  $this->setError($table->getError());
 176  
 177                  return false;
 178              }
 179  
 180              // Log the request's creation
 181              $message = [
 182                  'action'       => 'request-created',
 183                  'requesttype'  => $table->request_type,
 184                  'subjectemail' => $table->email,
 185                  'id'           => $table->id,
 186                  'itemlink'     => 'index.php?option=com_privacy&view=request&id=' . $table->id,
 187              ];
 188  
 189              $this->getActionlogModel()->addLog([$message], 'COM_PRIVACY_ACTION_LOG_CREATED_REQUEST', 'com_privacy.request');
 190  
 191              // The email sent and the record is saved, everything is good to go from here
 192              return true;
 193          } catch (MailDisabledException | phpmailerException $exception) {
 194              $this->setError($exception->getMessage());
 195  
 196              return false;
 197          }
 198      }
 199  
 200      /**
 201       * Method for getting the form from the model.
 202       *
 203       * @param   array    $data      Data for the form.
 204       * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
 205       *
 206       * @return  Form|boolean  A Form object on success, false on failure
 207       *
 208       * @since   3.9.0
 209       */
 210      public function getForm($data = [], $loadData = true)
 211      {
 212          return $this->loadForm('com_privacy.request', 'request', ['control' => 'jform']);
 213      }
 214  
 215      /**
 216       * Method to get a table object, load it if necessary.
 217       *
 218       * @param   string  $name     The table name. Optional.
 219       * @param   string  $prefix   The class prefix. Optional.
 220       * @param   array   $options  Configuration array for model. Optional.
 221       *
 222       * @return  Table  A Table object
 223       *
 224       * @throws  \Exception
 225       * @since   3.9.0
 226       */
 227      public function getTable($name = 'Request', $prefix = 'Administrator', $options = [])
 228      {
 229          return parent::getTable($name, $prefix, $options);
 230      }
 231  
 232      /**
 233       * Method to auto-populate the model state.
 234       *
 235       * Note. Calling getState in this method will result in recursion.
 236       *
 237       * @return  void
 238       *
 239       * @since   3.9.0
 240       */
 241      protected function populateState()
 242      {
 243          // Get the application object.
 244          $params = Factory::getApplication()->getParams('com_privacy');
 245  
 246          // Load the parameters.
 247          $this->setState('params', $params);
 248      }
 249  
 250      /**
 251       * Method to fetch an instance of the action log model.
 252       *
 253       * @return  ActionlogModel
 254       *
 255       * @since   4.0.0
 256       */
 257      private function getActionlogModel(): ActionlogModel
 258      {
 259          return Factory::getApplication()->bootComponent('com_actionlogs')
 260              ->getMVCFactory()->createModel('Actionlog', 'Administrator', ['ignore_request' => true]);
 261      }
 262  }


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