[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/components/com_contact/src/Controller/ -> ContactController.php (source)

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.Site
   5   * @subpackage  com_contact
   6   *
   7   * @copyright   (C) 2010 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\Site\Controller;
  12  
  13  use Joomla\CMS\Factory;
  14  use Joomla\CMS\Language\Text;
  15  use Joomla\CMS\Log\Log;
  16  use Joomla\CMS\Mail\Exception\MailDisabledException;
  17  use Joomla\CMS\Mail\MailTemplate;
  18  use Joomla\CMS\MVC\Controller\FormController;
  19  use Joomla\CMS\Plugin\PluginHelper;
  20  use Joomla\CMS\Router\Route;
  21  use Joomla\CMS\String\PunycodeHelper;
  22  use Joomla\CMS\Uri\Uri;
  23  use Joomla\CMS\User\User;
  24  use Joomla\CMS\Versioning\VersionableControllerTrait;
  25  use Joomla\Component\Fields\Administrator\Helper\FieldsHelper;
  26  use Joomla\Utilities\ArrayHelper;
  27  use PHPMailer\PHPMailer\Exception as phpMailerException;
  28  
  29  // phpcs:disable PSR1.Files.SideEffects
  30  \defined('_JEXEC') or die;
  31  // phpcs:enable PSR1.Files.SideEffects
  32  
  33  /**
  34   * Controller for single contact view
  35   *
  36   * @since  1.5.19
  37   */
  38  class ContactController extends FormController
  39  {
  40      use VersionableControllerTrait;
  41  
  42      /**
  43       * The URL view item variable.
  44       *
  45       * @var    string
  46       * @since  4.0.0
  47       */
  48      protected $view_item = 'form';
  49  
  50      /**
  51       * The URL view list variable.
  52       *
  53       * @var    string
  54       * @since  4.0.0
  55       */
  56      protected $view_list = 'categories';
  57  
  58      /**
  59       * Method to get a model object, loading it if required.
  60       *
  61       * @param   string  $name    The model name. Optional.
  62       * @param   string  $prefix  The class prefix. Optional.
  63       * @param   array   $config  Configuration array for model. Optional.
  64       *
  65       * @return  \Joomla\CMS\MVC\Model\BaseDatabaseModel  The model.
  66       *
  67       * @since   1.6.4
  68       */
  69      public function getModel($name = 'form', $prefix = '', $config = array('ignore_request' => true))
  70      {
  71          return parent::getModel($name, $prefix, array('ignore_request' => false));
  72      }
  73  
  74      /**
  75       * Method to submit the contact form and send an email.
  76       *
  77       * @return  boolean  True on success sending the email. False on failure.
  78       *
  79       * @since   1.5.19
  80       */
  81      public function submit()
  82      {
  83          // Check for request forgeries.
  84          $this->checkToken();
  85  
  86          $app    = $this->app;
  87          $model  = $this->getModel('contact');
  88          $stub   = $this->input->getString('id');
  89          $id     = (int) $stub;
  90  
  91          // Get the data from POST
  92          $data = $this->input->post->get('jform', array(), 'array');
  93  
  94          // Get item
  95          $model->setState('filter.published', 1);
  96          $contact = $model->getItem($id);
  97  
  98          if ($contact === false) {
  99              $this->setMessage($model->getError(), 'error');
 100  
 101              return false;
 102          }
 103  
 104          // Get item params, take menu parameters into account if necessary
 105          $active = $app->getMenu()->getActive();
 106          $stateParams = clone $model->getState()->get('params');
 107  
 108          // If the current view is the active item and a contact view for this contact, then the menu item params take priority
 109          if ($active && strpos($active->link, 'view=contact') && strpos($active->link, '&id=' . (int) $contact->id)) {
 110              // $item->params are the contact params, $temp are the menu item params
 111              // Merge so that the menu item params take priority
 112              $contact->params->merge($stateParams);
 113          } else {
 114              // Current view is not a single contact, so the contact params take priority here
 115              $stateParams->merge($contact->params);
 116              $contact->params = $stateParams;
 117          }
 118  
 119          // Check if the contact form is enabled
 120          if (!$contact->params->get('show_email_form')) {
 121              $this->setRedirect(Route::_('index.php?option=com_contact&view=contact&id=' . $stub . '&catid=' . $contact->catid, false));
 122  
 123              return false;
 124          }
 125  
 126          // Check for a valid session cookie
 127          if ($contact->params->get('validate_session', 0)) {
 128              if (Factory::getSession()->getState() !== 'active') {
 129                  $this->app->enqueueMessage(Text::_('JLIB_ENVIRONMENT_SESSION_INVALID'), 'warning');
 130  
 131                  // Save the data in the session.
 132                  $this->app->setUserState('com_contact.contact.data', $data);
 133  
 134                  // Redirect back to the contact form.
 135                  $this->setRedirect(Route::_('index.php?option=com_contact&view=contact&id=' . $stub . '&catid=' . $contact->catid, false));
 136  
 137                  return false;
 138              }
 139          }
 140  
 141          // Contact plugins
 142          PluginHelper::importPlugin('contact');
 143  
 144          // Validate the posted data.
 145          $form = $model->getForm();
 146  
 147          if (!$form) {
 148              throw new \Exception($model->getError(), 500);
 149          }
 150  
 151          if (!$model->validate($form, $data)) {
 152              $errors = $model->getErrors();
 153  
 154              foreach ($errors as $error) {
 155                  $errorMessage = $error;
 156  
 157                  if ($error instanceof \Exception) {
 158                      $errorMessage = $error->getMessage();
 159                  }
 160  
 161                  $app->enqueueMessage($errorMessage, 'error');
 162              }
 163  
 164              $app->setUserState('com_contact.contact.data', $data);
 165  
 166              $this->setRedirect(Route::_('index.php?option=com_contact&view=contact&id=' . $stub . '&catid=' . $contact->catid, false));
 167  
 168              return false;
 169          }
 170  
 171          // Validation succeeded, continue with custom handlers
 172          $results = $this->app->triggerEvent('onValidateContact', array(&$contact, &$data));
 173  
 174          foreach ($results as $result) {
 175              if ($result instanceof \Exception) {
 176                  return false;
 177              }
 178          }
 179  
 180          // Passed Validation: Process the contact plugins to integrate with other applications
 181          $this->app->triggerEvent('onSubmitContact', array(&$contact, &$data));
 182  
 183          // Send the email
 184          $sent = false;
 185  
 186          if (!$contact->params->get('custom_reply')) {
 187              $sent = $this->_sendEmail($data, $contact, $contact->params->get('show_email_copy', 0));
 188          }
 189  
 190          $msg = '';
 191  
 192          // Set the success message if it was a success
 193          if ($sent) {
 194              $msg = Text::_('COM_CONTACT_EMAIL_THANKS');
 195          }
 196  
 197          // Flush the data from the session
 198          $this->app->setUserState('com_contact.contact.data', null);
 199  
 200          // Redirect if it is set in the parameters, otherwise redirect back to where we came from
 201          if ($contact->params->get('redirect')) {
 202              $this->setRedirect($contact->params->get('redirect'), $msg);
 203          } else {
 204              $this->setRedirect(Route::_('index.php?option=com_contact&view=contact&id=' . $stub . '&catid=' . $contact->catid, false), $msg);
 205          }
 206  
 207          return true;
 208      }
 209  
 210      /**
 211       * Method to get a model object, loading it if required.
 212       *
 213       * @param   array      $data               The data to send in the email.
 214       * @param   \stdClass  $contact            The user information to send the email to
 215       * @param   boolean    $emailCopyToSender  True to send a copy of the email to the user.
 216       *
 217       * @return  boolean  True on success sending the email, false on failure.
 218       *
 219       * @since   1.6.4
 220       */
 221      private function _sendEmail($data, $contact, $emailCopyToSender)
 222      {
 223          $app = $this->app;
 224  
 225          if ($contact->email_to == '' && $contact->user_id != 0) {
 226              $contact_user      = User::getInstance($contact->user_id);
 227              $contact->email_to = $contact_user->get('email');
 228          }
 229  
 230          $templateData = [
 231              'sitename' => $app->get('sitename'),
 232              'name'     => $data['contact_name'],
 233              'contactname' => $contact->name,
 234              'email'    => PunycodeHelper::emailToPunycode($data['contact_email']),
 235              'subject'  => $data['contact_subject'],
 236              'body'     => stripslashes($data['contact_message']),
 237              'url'      => Uri::base(),
 238              'customfields' => ''
 239          ];
 240  
 241          // Load the custom fields
 242          if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact, true, $data['com_fields'])) {
 243              $output = FieldsHelper::render(
 244                  'com_contact.mail',
 245                  'fields.render',
 246                  array(
 247                      'context' => 'com_contact.mail',
 248                      'item'    => $contact,
 249                      'fields'  => $fields,
 250                  )
 251              );
 252  
 253              if ($output) {
 254                  $templateData['customfields'] = $output;
 255              }
 256          }
 257  
 258          try {
 259              $mailer = new MailTemplate('com_contact.mail', $app->getLanguage()->getTag());
 260              $mailer->addRecipient($contact->email_to);
 261              $mailer->setReplyTo($templateData['email'], $templateData['name']);
 262              $mailer->addTemplateData($templateData);
 263              $sent = $mailer->send();
 264  
 265              // If we are supposed to copy the sender, do so.
 266              if ($emailCopyToSender == true && !empty($data['contact_email_copy'])) {
 267                  $mailer = new MailTemplate('com_contact.mail.copy', $app->getLanguage()->getTag());
 268                  $mailer->addRecipient($templateData['email']);
 269                  $mailer->setReplyTo($templateData['email'], $templateData['name']);
 270                  $mailer->addTemplateData($templateData);
 271                  $sent = $mailer->send();
 272              }
 273          } catch (MailDisabledException | phpMailerException $exception) {
 274              try {
 275                  Log::add(Text::_($exception->getMessage()), Log::WARNING, 'jerror');
 276  
 277                  $sent = false;
 278              } catch (\RuntimeException $exception) {
 279                  $this->app->enqueueMessage(Text::_($exception->errorMessage()), 'warning');
 280  
 281                  $sent = false;
 282              }
 283          }
 284  
 285          return $sent;
 286      }
 287  
 288      /**
 289       * Method override to check if you can add a new record.
 290       *
 291       * @param   array  $data  An array of input data.
 292       *
 293       * @return  boolean
 294       *
 295       * @since   4.0.0
 296       */
 297      protected function allowAdd($data = array())
 298      {
 299          if ($categoryId = ArrayHelper::getValue($data, 'catid', $this->input->getInt('catid'), 'int')) {
 300              $user = $this->app->getIdentity();
 301  
 302              // If the category has been passed in the data or URL check it.
 303              return $user->authorise('core.create', 'com_contact.category.' . $categoryId);
 304          }
 305  
 306          // In the absence of better information, revert to the component permissions.
 307          return parent::allowAdd();
 308      }
 309  
 310      /**
 311       * Method override to check if you can edit an existing record.
 312       *
 313       * @param   array   $data  An array of input data.
 314       * @param   string  $key   The name of the key for the primary key; default is id.
 315       *
 316       * @return  boolean
 317       *
 318       * @since   4.0.0
 319       */
 320      protected function allowEdit($data = array(), $key = 'id')
 321      {
 322          $recordId = (int) isset($data[$key]) ? $data[$key] : 0;
 323  
 324          if (!$recordId) {
 325              return false;
 326          }
 327  
 328          // Need to do a lookup from the model.
 329          $record     = $this->getModel()->getItem($recordId);
 330          $categoryId = (int) $record->catid;
 331  
 332          if ($categoryId) {
 333              $user = $this->app->getIdentity();
 334  
 335              // The category has been set. Check the category permissions.
 336              if ($user->authorise('core.edit', $this->option . '.category.' . $categoryId)) {
 337                  return true;
 338              }
 339  
 340              // Fallback on edit.own.
 341              if ($user->authorise('core.edit.own', $this->option . '.category.' . $categoryId)) {
 342                  return ($record->created_by === $user->id);
 343              }
 344  
 345              return false;
 346          }
 347  
 348          // Since there is no asset tracking, revert to the component permissions.
 349          return parent::allowEdit($data, $key);
 350      }
 351  
 352      /**
 353       * Method to cancel an edit.
 354       *
 355       * @param   string  $key  The name of the primary key of the URL variable.
 356       *
 357       * @return  boolean  True if access level checks pass, false otherwise.
 358       *
 359       * @since   4.0.0
 360       */
 361      public function cancel($key = null)
 362      {
 363          $result = parent::cancel($key);
 364  
 365          $this->setRedirect(Route::_($this->getReturnPage(), false));
 366  
 367          return $result;
 368      }
 369  
 370      /**
 371       * Gets the URL arguments to append to an item redirect.
 372       *
 373       * @param   integer  $recordId  The primary key id for the item.
 374       * @param   string   $urlVar    The name of the URL variable for the id.
 375       *
 376       * @return  string    The arguments to append to the redirect URL.
 377       *
 378       * @since   4.0.0
 379       */
 380      protected function getRedirectToItemAppend($recordId = 0, $urlVar = 'id')
 381      {
 382          // Need to override the parent method completely.
 383          $tmpl = $this->input->get('tmpl');
 384  
 385          $append = '';
 386  
 387          // Setup redirect info.
 388          if ($tmpl) {
 389              $append .= '&tmpl=' . $tmpl;
 390          }
 391  
 392          $append .= '&layout=edit';
 393  
 394          $append .= '&' . $urlVar . '=' . (int) $recordId;
 395  
 396          $itemId = $this->input->getInt('Itemid');
 397          $return = $this->getReturnPage();
 398          $catId  = $this->input->getInt('catid');
 399  
 400          if ($itemId) {
 401              $append .= '&Itemid=' . $itemId;
 402          }
 403  
 404          if ($catId) {
 405              $append .= '&catid=' . $catId;
 406          }
 407  
 408          if ($return) {
 409              $append .= '&return=' . base64_encode($return);
 410          }
 411  
 412          return $append;
 413      }
 414  
 415      /**
 416       * Get the return URL.
 417       *
 418       * If a "return" variable has been passed in the request
 419       *
 420       * @return  string    The return URL.
 421       *
 422       * @since   4.0.0
 423       */
 424      protected function getReturnPage()
 425      {
 426          $return = $this->input->get('return', null, 'base64');
 427  
 428          if (empty($return) || !Uri::isInternal(base64_decode($return))) {
 429              return Uri::base();
 430          }
 431  
 432          return base64_decode($return);
 433      }
 434  }


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