[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

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

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.API
   5   * @subpackage  com_contact
   6   *
   7   * @copyright   (C) 2019 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\Api\Controller;
  12  
  13  use Joomla\CMS\Component\ComponentHelper;
  14  use Joomla\CMS\Factory;
  15  use Joomla\CMS\Form\Form;
  16  use Joomla\CMS\Language\Text;
  17  use Joomla\CMS\Log\Log;
  18  use Joomla\CMS\Mail\Exception\MailDisabledException;
  19  use Joomla\CMS\Mail\MailTemplate;
  20  use Joomla\CMS\MVC\Controller\ApiController;
  21  use Joomla\CMS\MVC\Controller\Exception\SendEmail;
  22  use Joomla\CMS\Plugin\PluginHelper;
  23  use Joomla\CMS\Router\Exception\RouteNotFoundException;
  24  use Joomla\CMS\String\PunycodeHelper;
  25  use Joomla\CMS\Uri\Uri;
  26  use Joomla\CMS\User\User;
  27  use Joomla\Component\Fields\Administrator\Helper\FieldsHelper;
  28  use Joomla\Registry\Registry;
  29  use Joomla\String\Inflector;
  30  use PHPMailer\PHPMailer\Exception as phpMailerException;
  31  use Tobscure\JsonApi\Exception\InvalidParameterException;
  32  
  33  // phpcs:disable PSR1.Files.SideEffects
  34  \defined('_JEXEC') or die;
  35  // phpcs:enable PSR1.Files.SideEffects
  36  
  37  /**
  38   * The contact controller
  39   *
  40   * @since  4.0.0
  41   */
  42  class ContactController extends ApiController
  43  {
  44      /**
  45       * The content type of the item.
  46       *
  47       * @var    string
  48       * @since  4.0.0
  49       */
  50      protected $contentType = 'contacts';
  51  
  52      /**
  53       * The default view for the display method.
  54       *
  55       * @var    string
  56       * @since  3.0
  57       */
  58      protected $default_view = 'contacts';
  59  
  60      /**
  61       * Method to allow extended classes to manipulate the data to be saved for an extension.
  62       *
  63       * @param   array  $data  An array of input data.
  64       *
  65       * @return  array
  66       *
  67       * @since   4.0.0
  68       */
  69      protected function preprocessSaveData(array $data): array
  70      {
  71          foreach (FieldsHelper::getFields('com_contact.contact') as $field) {
  72              if (isset($data[$field->name])) {
  73                  !isset($data['com_fields']) && $data['com_fields'] = [];
  74  
  75                  $data['com_fields'][$field->name] = $data[$field->name];
  76                  unset($data[$field->name]);
  77              }
  78          }
  79  
  80          return $data;
  81      }
  82  
  83      /**
  84       * Submit contact form
  85       *
  86       * @param   integer  $id Leave empty if you want to retrieve data from the request
  87       * @return  static  A \JControllerLegacy object to support chaining.
  88       *
  89       * @since   4.0.0
  90       */
  91      public function submitForm($id = null)
  92      {
  93          if ($id === null) {
  94              $id = $this->input->post->get('id', 0, 'int');
  95          }
  96  
  97          $modelName = Inflector::singularize($this->contentType);
  98  
  99          /** @var  \Joomla\Component\Contact\Site\Model\ContactModel $model */
 100          $model = $this->getModel($modelName, 'Site');
 101  
 102          if (!$model) {
 103              throw new \RuntimeException(Text::_('JLIB_APPLICATION_ERROR_MODEL_CREATE'));
 104          }
 105  
 106          $model->setState('filter.published', 1);
 107  
 108          $data    = $this->input->get('data', json_decode($this->input->json->getRaw(), true), 'array');
 109          $contact = $model->getItem($id);
 110  
 111          if ($contact->id === null) {
 112              throw new RouteNotFoundException('Item does not exist');
 113          }
 114  
 115          $contactParams = new Registry($contact->params);
 116  
 117          if (!$contactParams->get('show_email_form')) {
 118              throw new \RuntimeException(Text::_('JLIB_APPLICATION_ERROR_DISPLAY_EMAIL_FORM'));
 119          }
 120  
 121          // Contact plugins
 122          PluginHelper::importPlugin('contact');
 123  
 124          Form::addFormPath(JPATH_COMPONENT_SITE . '/forms');
 125  
 126          // Validate the posted data.
 127          $form = $model->getForm();
 128  
 129          if (!$form) {
 130              throw new \RuntimeException($model->getError(), 500);
 131          }
 132  
 133          if (!$model->validate($form, $data)) {
 134              $errors   = $model->getErrors();
 135              $messages = [];
 136  
 137              for ($i = 0, $n = \count($errors); $i < $n && $i < 3; $i++) {
 138                  if ($errors[$i] instanceof \Exception) {
 139                      $messages[] = "{$errors[$i]->getMessage()}";
 140                  } else {
 141                      $messages[] = "{$errors[$i]}";
 142                  }
 143              }
 144  
 145              throw new InvalidParameterException(implode("\n", $messages));
 146          }
 147  
 148          // Validation succeeded, continue with custom handlers
 149          $results = $this->app->triggerEvent('onValidateContact', [&$contact, &$data]);
 150  
 151          foreach ($results as $result) {
 152              if ($result instanceof \Exception) {
 153                  throw new InvalidParameterException($result->getMessage());
 154              }
 155          }
 156  
 157          // Passed Validation: Process the contact plugins to integrate with other applications
 158          $this->app->triggerEvent('onSubmitContact', [&$contact, &$data]);
 159  
 160          // Send the email
 161          $sent = false;
 162  
 163          $params = ComponentHelper::getParams('com_contact');
 164  
 165          if (!$params->get('custom_reply')) {
 166              $sent = $this->_sendEmail($data, $contact, $params->get('show_email_copy', 0));
 167          }
 168  
 169          if (!$sent) {
 170              throw new SendEmail('Error sending message');
 171          }
 172  
 173          return $this;
 174      }
 175  
 176      /**
 177       * Method to get a model object, loading it if required.
 178       *
 179       * @param   array      $data               The data to send in the email.
 180       * @param   \stdClass  $contact            The user information to send the email to
 181       * @param   boolean    $emailCopyToSender  True to send a copy of the email to the user.
 182       *
 183       * @return  boolean  True on success sending the email, false on failure.
 184       *
 185       * @since   1.6.4
 186       */
 187      private function _sendEmail($data, $contact, $emailCopyToSender)
 188      {
 189          $app = $this->app;
 190  
 191          Factory::getLanguage()->load('com_contact', JPATH_SITE, $app->getLanguage()->getTag(), true);
 192  
 193          if ($contact->email_to == '' && $contact->user_id != 0) {
 194              $contact_user      = User::getInstance($contact->user_id);
 195              $contact->email_to = $contact_user->get('email');
 196          }
 197  
 198          $templateData = [
 199              'sitename' => $app->get('sitename'),
 200              'name'     => $data['contact_name'],
 201              'contactname' => $contact->name,
 202              'email'    => PunycodeHelper::emailToPunycode($data['contact_email']),
 203              'subject'  => $data['contact_subject'],
 204              'body'     => stripslashes($data['contact_message']),
 205              'url'      => Uri::base(),
 206              'customfields' => '',
 207          ];
 208  
 209          // Load the custom fields
 210          if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact, true, $data['com_fields'])) {
 211              $output = FieldsHelper::render(
 212                  'com_contact.mail',
 213                  'fields.render',
 214                  array(
 215                      'context' => 'com_contact.mail',
 216                      'item'    => $contact,
 217                      'fields'  => $fields,
 218                  )
 219              );
 220  
 221              if ($output) {
 222                  $templateData['customfields'] = $output;
 223              }
 224          }
 225  
 226          try {
 227              $mailer = new MailTemplate('com_contact.mail', $app->getLanguage()->getTag());
 228              $mailer->addRecipient($contact->email_to);
 229              $mailer->setReplyTo($templateData['email'], $templateData['name']);
 230              $mailer->addTemplateData($templateData);
 231              $sent = $mailer->send();
 232  
 233              // If we are supposed to copy the sender, do so.
 234              if ($emailCopyToSender == true && !empty($data['contact_email_copy'])) {
 235                  $mailer = new MailTemplate('com_contact.mail.copy', $app->getLanguage()->getTag());
 236                  $mailer->addRecipient($templateData['email']);
 237                  $mailer->setReplyTo($templateData['email'], $templateData['name']);
 238                  $mailer->addTemplateData($templateData);
 239                  $sent = $mailer->send();
 240              }
 241          } catch (MailDisabledException | phpMailerException $exception) {
 242              try {
 243                  Log::add(Text::_($exception->getMessage()), Log::WARNING, 'jerror');
 244  
 245                  $sent = false;
 246              } catch (\RuntimeException $exception) {
 247                  Factory::getApplication()->enqueueMessage(Text::_($exception->errorMessage()), 'warning');
 248  
 249                  $sent = false;
 250              }
 251          }
 252  
 253          return $sent;
 254      }
 255  }


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