/**
  * Sends an email submitted through a contact form.
  *
  * @param ContactFormModel $message
  * @throws Exception
  * @return bool
  */
 public function sendMessage(ContactFormModel $message)
 {
     $settings = craft()->plugins->getPlugin('contactform')->getSettings();
     if (!$settings->toEmail) {
         throw new Exception('The "To Email" address is not set on the plugin’s settings page.');
     }
     // Fire an 'onBeforeSend' event
     Craft::import('plugins.contactform.events.ContactFormEvent');
     $event = new ContactFormEvent($this, array('message' => $message));
     $this->onBeforeSend($event);
     if ($event->isValid) {
         if (!$event->fakeIt) {
             $toEmails = ArrayHelper::stringToArray($settings->toEmail);
             foreach ($toEmails as $toEmail) {
                 $email = new EmailModel();
                 $emailSettings = craft()->email->getSettings();
                 $email->fromEmail = $emailSettings['emailAddress'];
                 $email->replyTo = $message->fromEmail;
                 $email->sender = $emailSettings['emailAddress'];
                 $email->fromName = $settings->prependSender . ($settings->prependSender && $message->fromName ? ' ' : '') . $message->fromName;
                 $email->toEmail = $toEmail;
                 $email->subject = $settings->prependSubject . ($settings->prependSubject && $message->subject ? ' - ' : '') . $message->subject;
                 $email->body = $message->message;
                 if ($message->attachment) {
                     $email->addAttachment($message->attachment->getTempName(), $message->attachment->getName(), 'base64', $message->attachment->getType());
                 }
                 craft()->email->sendEmail($email);
             }
         }
         return true;
     }
     return false;
 }
 /**
  * @param mixed|null $element
  *
  * @throws \Exception
  * @return array|string
  */
 public function getRecipients($element = null)
 {
     $recipientsString = $this->getAttribute('recipients');
     // Possibly called from entry edit screen
     if (is_null($element)) {
         return $recipientsString;
     }
     // Previously converted to array somehow?
     if (is_array($recipientsString)) {
         return $recipientsString;
     }
     // Previously stored as JSON string?
     if (stripos($recipientsString, '[') === 0) {
         return JsonHelper::decode($recipientsString);
     }
     // Still a string with possible twig generator code?
     if (stripos($recipientsString, '{') !== false) {
         try {
             $recipients = craft()->templates->renderObjectTemplate($recipientsString, $element);
             return array_unique(ArrayHelper::filterEmptyStringsFromArray(ArrayHelper::stringToArray($recipients)));
         } catch (\Exception $e) {
             throw $e;
         }
     }
     // Just a regular CSV list
     if (!empty($recipientsString)) {
         return ArrayHelper::filterEmptyStringsFromArray(ArrayHelper::stringToArray($recipientsString));
     }
     return array();
 }
Beispiel #3
0
 /**
  * @inheritDoc IFieldType::prepValue()
  *
  * @param mixed $value
  *
  * @return mixed
  */
 public function prepValue($value)
 {
     $selectedValues = ArrayHelper::stringToArray($value);
     if ($this->multi) {
         if (is_array($value)) {
             // Convert all the values to OptionData objects
             foreach ($value as &$val) {
                 $label = $this->getOptionLabel($val);
                 $val = new OptionData($label, $val, true);
             }
         } else {
             $value = array();
         }
         $value = new MultiOptionsFieldData($value);
     } else {
         // Convert the value to a SingleOptionFieldData object
         $label = $this->getOptionLabel($value);
         $value = new SingleOptionFieldData($label, $value, true);
     }
     $options = array();
     foreach ($this->getOptions() as $option) {
         $selected = in_array($option['value'], $selectedValues);
         $options[] = new OptionData($option['label'], $option['value'], $selected);
     }
     $value->setOptions($options);
     return $value;
 }
Beispiel #4
0
 /**
  * Sets an attribute's value.
  *
  * @param string $name
  * @param mixed $value
  * @return bool
  */
 public function setAttribute($name, $value)
 {
     // Set packages as an array
     if ($name == 'packages' && !is_array($value)) {
         if ($value) {
             $value = array_filter(ArrayHelper::stringToArray($value));
             sort($value);
         } else {
             $value = array();
         }
     }
     return parent::setAttribute($name, $value);
 }
 /**
  * Returns an array of pre-fetched related elements, optionally restricted by one or more
  * relations field handles.
  *
  * @param  array|null  $fieldHandles
  *
  * @return array
  */
 public function fetched($fieldHandles = null)
 {
     $elements = array();
     if ($fieldHandles) {
         $fieldHandles = ArrayHelper::stringToArray($fieldHandles);
     } else {
         $fieldHandles = array_keys($this->_elementsByFieldHandle);
     }
     foreach ($fieldHandles as $fieldHandle) {
         if (array_key_exists($fieldHandle, $this->_elementsByFieldHandle)) {
             $elements = array_merge($elements, $this->_elementsByFieldHandle[$fieldHandle]);
         }
     }
     return $elements;
 }
 /**
  * Sends an email submitted through a contact form.
  *
  * @param ContactFormModel $message
  * @throws Exception
  * @return bool
  */
 public function sendMessage(ContactFormModel $message)
 {
     $settings = craft()->plugins->getPlugin('contactform')->getSettings();
     if (!$settings->toEmail) {
         throw new Exception('The "To Email" address is not set on the plugin’s settings page.');
     }
     // Fire an 'onBeforeSend' event
     Craft::import('plugins.contactform.events.ContactFormEvent');
     $event = new ContactFormEvent($this, array('message' => $message));
     $this->onBeforeSend($event);
     if ($event->isValid) {
         if (!$event->fakeIt) {
             // Grab any "to" emails set in the plugin settings.
             $toEmails = ArrayHelper::stringToArray($settings->toEmail);
             foreach ($toEmails as $toEmail) {
                 $variables = array();
                 $email = new EmailModel();
                 $emailSettings = craft()->email->getSettings();
                 $email->fromEmail = $emailSettings['emailAddress'];
                 $email->replyTo = $message->fromEmail;
                 $email->sender = $emailSettings['emailAddress'];
                 $email->fromName = $settings->prependSender . ($settings->prependSender && $message->fromName ? ' ' : '') . $message->fromName;
                 $email->toEmail = $toEmail;
                 $email->subject = '{{ emailSubject }}';
                 $email->body = '{{ emailBody }}';
                 $variables['emailSubject'] = $settings->prependSubject . ($settings->prependSubject && $message->subject ? ' - ' : '') . $message->subject;
                 $variables['emailBody'] = $message->message;
                 if (!empty($message->htmlMessage)) {
                     // Prevent Twig tags from getting parsed
                     $email->htmlBody = str_replace(array('{', '}'), array('{', '}'), $message->htmlMessage);
                 }
                 if (!empty($message->attachment)) {
                     foreach ($message->attachment as $attachment) {
                         if ($attachment) {
                             $email->addAttachment($attachment->getTempName(), $attachment->getName(), 'base64', $attachment->getType());
                         }
                     }
                 }
                 craft()->email->sendEmail($email, $variables);
             }
         }
         return true;
     }
     return false;
 }
 /**
  * Sends an email submitted through a contact form.
  *
  * @param ContactFormModel $message
  * @throws Exception
  * @return bool
  */
 public function sendMessage(ContactFormModel $message)
 {
     $settings = craft()->plugins->getPlugin('contactform')->getSettings();
     // Fire an 'onBeforeSend' event
     Craft::import('plugins.contactform.events.ContactFormEvent');
     $event = new ContactFormEvent($this, array('message' => $message));
     $this->onBeforeSend($event);
     if ($event->isValid) {
         if (!$event->fakeIt) {
             // Get the relevant email address(es) for the message subject
             foreach ($settings->toEmail as $row) {
                 if ($message->subject == $row['subject']) {
                     if (!$row['email']) {
                         throw new Exception('The "To Email" address is not set on the plugin’s settings page.');
                     }
                     $toEmails = ArrayHelper::stringToArray($row['email']);
                 }
             }
             foreach ($toEmails as $toEmail) {
                 $email = new EmailModel();
                 $emailSettings = craft()->email->getSettings();
                 $email->fromEmail = $emailSettings['emailAddress'];
                 $email->replyTo = $message->fromEmail;
                 $email->sender = $emailSettings['emailAddress'];
                 $email->fromName = $settings->prependSender . ($settings->prependSender && $message->fromName ? ' ' : '') . $message->fromName;
                 $email->toEmail = $toEmail;
                 $email->subject = $settings->prependSubject . ($settings->prependSubject && $message->subject ? ' - ' : '') . $message->subject;
                 $email->body = "An email has been sent by {$message->fromName} ({$message->fromEmail}) using the contact form on the website. Here is the message:\n\n" . $message->message;
                 if (!empty($message->attachment)) {
                     foreach ($message->attachment as $attachment) {
                         if ($attachment) {
                             $email->addAttachment($attachment->getTempName(), $attachment->getName(), 'base64', $attachment->getType());
                         }
                     }
                 }
                 craft()->email->sendEmail($email);
             }
         }
         return true;
     }
     return false;
 }
Beispiel #8
0
 /**
  * Returns an array of {$elementType}Model instances related to the
  * elements passed in as the second parameter.
  *
  * You can optionally restrict the results to particular fields, and override the source
  * locale.
  *
  * @since 0.1.0
  *
  * @param array              $elementType     The element type for the relation
  * @param array              $sourceElements  An array of source elements
  * @param string|array|null  $fieldHandles    An optional string or array of field handles
  * @param string|null        $sourceLocale    An optional locale ID
  *
  * @return array             An array of BaseElementModel instances, populated from the results
  */
 public function elements($elementType, array &$sourceElements, $fieldHandles = null, $sourceLocale = null)
 {
     $sourceElementsById = array();
     $targetIds = array();
     // Cast the field handles to an array
     $fieldHandles = ArrayHelper::stringToArray($fieldHandles);
     // reorder the source elements by ID
     foreach ($sourceElements as $sourceElement) {
         $sourceElementsById[$sourceElement->id] = $sourceElement;
     }
     // Attach the behavior to each of the source elements
     foreach ($sourceElementsById as $sourceElement) {
         if (!$sourceElement->asa('fetched_elements')) {
             $sourceElement->attachBehavior('fetched_elements', new Fetch_FetchedElementsBehavior());
         }
     }
     // Perform the first query to get the information from the craft_relations table
     $relations = $this->_getRelations($sourceElementsById, $fieldHandles, $sourceLocale);
     // Collect the targetIds so we can fetch all the elements in one go later on
     $targetIds = array_map(function ($relation) {
         return $relation['fetchTargetId'];
     }, $relations);
     // Perform the second query to fetch all the related elements by their IDs
     $elements = craft()->elements->getCriteria($elementType)->id($targetIds)->indexBy('id')->locale($sourceLocale)->limit(null)->find();
     // Add each related element to its source element, using the Fetch_FetchedElementsBehavior
     foreach ($relations as &$relation) {
         $sourceId = $relation['fetchSourceId'];
         $fieldHandle = $relation['handle'];
         $targetId = $relation['fetchTargetId'];
         $sortOrder = (int) $relation['sortOrder'] - 1;
         $sourceElementsById[$sourceId]->addFetchedElement($elements[$targetId], $fieldHandle, $sortOrder);
         unset($sourceId, $fieldHandle, $targetId, $sourceOrder, $relation);
     }
     // Return the modified entries in their original order
     foreach ($sourceElements as &$sourceElement) {
         $sourceElement = $sourceElementsById[$sourceElement->id];
         unset($sourceElementsById[$sourceElement->id]);
     }
     return $sourceElements;
 }
 /**
  * Returns whether or not the user meets the criteria necessary to trigger the event
  *
  * @param mixed     $options
  * @param UserModel $user
  * @param array     $params
  *
  * @return bool
  */
 public function validateOptions($options, UserModel $user, array $params = array())
 {
     $isNewUser = isset($params['isNewUser']) && $params['isNewUser'];
     $whenNew = isset($options['craft']['saveUser']['whenNew']) && $options['craft']['saveUser']['whenNew'];
     $whenUpdated = isset($options['craft']['saveUser']['whenUpdated']) && $options['craft']['saveUser']['whenUpdated'];
     SproutEmailPlugin::log(Craft::t("Sprout Email '" . $this->getTitle() . "' event has been triggered"));
     // If any user groups were checked, make sure the user is in one of the groups
     if (!empty($options['craft']['saveUser']['userGroupIds']) && count($options['craft']['saveUser']['userGroupIds'])) {
         $inGroup = false;
         $existingUserGroups = $user->getGroups('id');
         // When saving a new user, we grab our groups from the post request
         // because _processUserGroupsPermissions() runs after saveUser()
         $newUserGroups = craft()->request->getPost('groups');
         if (!is_array($newUserGroups)) {
             $newUserGroups = ArrayHelper::stringToArray($newUserGroups);
         }
         foreach ($options['craft']['saveUser']['userGroupIds'] as $groupId) {
             if (array_key_exists($groupId, $existingUserGroups) || in_array($groupId, $newUserGroups)) {
                 $inGroup = true;
             }
         }
         if (!$inGroup) {
             SproutEmailPlugin::log(Craft::t('Saved user not in any selected User Group.'));
             return false;
         }
     }
     if (!$whenNew && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No settings have been selected. Please select 'When a user is created' or 'When\n\t\t\ta user is updated' from the options on the Rules tab."));
         return false;
     }
     if ($whenNew && !$isNewUser && !$whenUpdated) {
         SproutEmailPlugin::log(Craft::t("No match. 'When a user is created' is selected but the user is being updated."));
         return false;
     }
     if ($whenUpdated && $isNewUser && !$whenNew) {
         SproutEmailPlugin::log(Craft::t("No match. 'When a user is updated' is selected but the user is new."));
         return false;
     }
     return true;
 }
 /**
  * Send log.
  *
  * @return bool
  */
 public function sendLog()
 {
     // Get email address
     $recipients = craft()->amSeed_settings->getSettingsByHandleAndType('emailAddressForLogs', AmSeedModel::SettingGeneral);
     if ($recipients && $recipients->value) {
         $recipients = $recipients->value;
     } else {
         return false;
     }
     // Check for multiple recipients
     $recipients = ArrayHelper::stringToArray($recipients);
     $recipients = array_unique($recipients);
     if (!count($recipients)) {
         return false;
     }
     // Craft email settings
     $settings = craft()->email->getSettings();
     $systemEmail = !empty($settings['emailAddress']) ? $settings['emailAddress'] : '';
     $systemName = !empty($settings['senderName']) ? $settings['senderName'] : '';
     // Set email settings
     $success = false;
     $email = new EmailModel();
     $email->htmlBody = '<pre>' . print_r($this->_log, true) . '</pre>';
     $email->fromEmail = $systemEmail;
     $email->fromName = $systemName;
     $email->subject = Craft::t('Dummy generation log');
     // Send emails
     foreach ($recipients as $recipient) {
         $email->toEmail = $recipient;
         if (filter_var($email->toEmail, FILTER_VALIDATE_EMAIL)) {
             // Add variable for email event
             if (craft()->email->sendEmail($email)) {
                 $success = true;
             }
         }
     }
     return $success;
 }
 public function sendMessage(ContactForm_MessageModel $message)
 {
     $settings = craft()->plugins->getPlugin('contactform')->getSettings();
     if (!$settings->toEmail) {
         throw new Exception('The "To Email" address is not set on the plugin’s settings page.');
     }
     if (!$settings->fromEmail) {
         throw new Exception('The "From Email" address is not set on the plugin’s settings page.');
     }
     $this->validateMessage($message);
     if ($this->isValid) {
         if (!$this->fakeIt) {
             // Grab any "to" emails set in the plugin settings.
             $toEmails = ArrayHelper::stringToArray($settings->toEmail);
             foreach ($toEmails as $toEmail) {
                 $email = new EmailModel();
                 $emailSettings = craft()->email->getSettings();
                 $email->fromEmail = $settings->fromEmail;
                 $email->replyTo = $message->email;
                 $email->sender = $emailSettings['emailAddress'];
                 $email->fromName = $settings->prependSender . ($settings->prependSender && $message->name ? ' ' : '') . $message->name;
                 $email->toEmail = $toEmail;
                 $email->subject = $settings->subject;
                 $email->body = $message->message;
                 if (!empty($message->attachment)) {
                     foreach ($message->attachment as $attachment) {
                         if ($attachment) {
                             $email->addAttachment($attachment->getTempName(), $attachment->getName(), 'base64', $attachment->getType());
                         }
                     }
                 }
                 craft()->email->sendEmail($email);
             }
         }
         return true;
     }
     return false;
 }
 /**
  * Send Email Notification
  *
  */
 public function sendEmailNotification($form, $postUploads, $message, $html = true, $email = null)
 {
     $errors = false;
     $attributes = $form->getAttributes();
     $notificationSettings = $attributes['notificationSettings'];
     $toEmails = ArrayHelper::stringToArray($notificationSettings['emailSettings']['notifyEmail']);
     foreach ($toEmails as $toEmail) {
         $email = new EmailModel();
         $emailSettings = craft()->email->getSettings();
         $email->fromEmail = $emailSettings['emailAddress'];
         $email->replyTo = $emailSettings['emailAddress'];
         $email->sender = $emailSettings['emailAddress'];
         $email->fromName = $form->name;
         $email->toEmail = $toEmail;
         $email->subject = $notificationSettings['emailSettings']['emailSubject'];
         $email->body = $message;
         // TODO: Add attachments to emails
         // if ($postUploads) {
         //   foreach ($postUploads as $key => $value) {
         //     $file = \CUploadedFile::getInstanceByName($key);
         //     $email->addAttachment($file->getTempName(), $file->getName(), 'base64', $file->getType());
         //   }
         // }
         if (!craft()->email->sendEmail($email)) {
             $errors = true;
         }
     }
     return $errors ? false : true;
 }
 /**
  * @return array
  */
 protected function getOnTheFlyRecipients()
 {
     $postedRecipients = craft()->request->getPost('recipient.onTheFlyRecipients');
     return array_filter(array_map('trim', ArrayHelper::stringToArray($postedRecipients)));
 }
 /**
  * Preps a {@link DbCommand} object for querying for elements, based on a given element criteria.
  *
  * @param Venti_CriteriaModel &$criteria     The events criteria model
  *
  * @return DbCommand|false The DbCommand object, or `false` if the method was able to determine ahead of time that
  *                         there’s no chance any elements are going to be found with the given parameters.
  */
 public function buildEventsQuery(Venti_CriteriaModel $criteria)
 {
     $elementType = $criteria->getElementType();
     if (!$elementType->isLocalized()) {
         // The criteria *must* be set to the primary locale
         $criteria->locale = craft()->i18n->getPrimarySiteLocaleId();
     } else {
         if (!$criteria->locale) {
             // Default to the current app locale
             $criteria->locale = craft()->language;
         }
     }
     $query = craft()->db->createCommand()->select('venti.startDate, venti.endDate, venti.allDay, venti.isrepeat, venti.eid, venti.eventid, venti.repeat, venti.rRule, venti.summary, elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated, elements_i18n.slug, elements_i18n.uri, elements_i18n.enabled AS localeEnabled')->from('venti_events venti')->join('elements elements', 'elements.id = venti.eventid')->join('elements_i18n elements_i18n', 'elements_i18n.elementId = venti.eventid')->where('elements_i18n.locale = :locale', array(':locale' => $criteria->locale))->limit($criteria->limit)->offset($criteria->offset)->order($criteria->order);
     if ($elementType->hasContent()) {
         $contentTable = 'content';
         if ($contentTable) {
             $contentCols = 'content.id AS contentId';
             if ($elementType->hasTitles()) {
                 $contentCols .= ', content.title';
             }
             $fieldColumns = $this->getContentFieldColumnsForElementsQuery($criteria);
             foreach ($fieldColumns as $column) {
                 $contentCols .= ', content.' . $column['column'];
             }
             $query->addSelect($contentCols);
             $query->join($contentTable . ' content', 'content.elementId = elements.id');
             $query->andWhere('content.locale = :locale');
         }
     }
     if ($elementType->hasTitles() && $criteria->title) {
         $query->andWhere(DbHelper::parseParam('content.title', $criteria->title, $query->params));
     }
     if ($criteria->id) {
         $query->andWhere(DbHelper::parseParam('venti.eventid', $criteria->id, $query->params));
     }
     if ($criteria->eid) {
         $query->andWhere(DbHelper::parseParam('venti.eid', $criteria->eid, $query->params));
     }
     if ($criteria->isrepeat) {
         $query->andWhere(DbHelper::parseParam('venti.isrepeat', $criteria->isrepeat, $query->params));
     }
     if ($criteria->startDate) {
         $query->andWhere(DbHelper::parseDateParam('venti.startDate', $criteria->startDate, $query->params));
     }
     if ($criteria->endDate) {
         $query->andWhere(DbHelper::parseDateParam('venti.endDate', $criteria->endDate, $query->params));
     }
     if ($criteria->summary) {
         $query->andWhere(DbHelper::parseParam('venti.summary', $criteria->summary, $query->params));
     }
     if ($criteria->slug) {
         $query->andWhere(DbHelper::parseParam('elements_i18n.slug', $criteria->slug, $query->params));
     }
     if ($criteria->uri) {
         $query->andWhere(DbHelper::parseParam('elements_i18n.uri', $criteria->uri, $query->params));
     }
     if ($criteria->localeEnabled) {
         $query->andWhere('elements_i18n.enabled = 1');
     }
     if ($criteria->dateCreated) {
         $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', $criteria->dateCreated, $query->params));
     }
     if ($criteria->dateUpdated) {
         $query->andWhere(DbHelper::parseDateParam('elements.dateUpdated', $criteria->dateUpdated, $query->params));
     }
     if ($criteria->archived) {
         $query->andWhere('elements.archived = 1');
     } else {
         $query->andWhere('elements.archived = 0');
         if ($criteria->status) {
             $statusConditions = array();
             $statuses = ArrayHelper::stringToArray($criteria->status);
             foreach ($statuses as $status) {
                 $status = StringHelper::toLowerCase($status);
                 // Is this a supported status?
                 if (in_array($status, array_keys($this->getStatuses()))) {
                     if ($status == BaseElementModel::ENABLED) {
                         $statusConditions[] = 'elements.enabled = 1';
                     } else {
                         if ($status == BaseElementModel::DISABLED) {
                             $statusConditions[] = 'elements.enabled = 0';
                         } else {
                             $elementStatusCondition = $this->getElementQueryStatusCondition($query, $status);
                             if ($elementStatusCondition) {
                                 $statusConditions[] = $elementStatusCondition;
                             } else {
                                 if ($elementStatusCondition === false) {
                                     return false;
                                 }
                             }
                         }
                     }
                 }
             }
             if ($statusConditions) {
                 if (count($statusConditions) == 1) {
                     $statusCondition = $statusConditions[0];
                 } else {
                     array_unshift($statusConditions, 'or');
                     $statusCondition = $statusConditions;
                 }
                 $query->andWhere($statusCondition);
             }
         }
     }
     // Relational params
     // ---------------------------------------------------------------------
     if ($criteria->relatedTo) {
         $relationParamParser = new ElementRelationParamParser();
         $relConditions = $relationParamParser->parseRelationParam($criteria->relatedTo, $query);
         if ($relConditions === false) {
             return false;
         }
         $query->andWhere($relConditions);
         // If there's only one relation criteria and it's specifically for grabbing target elements, allow the query
         // to order by the relation sort order
         if ($relationParamParser->isRelationFieldQuery()) {
             $query->addSelect('sources1.sortOrder');
         }
     }
     // Search
     // ---------------------------------------------------------------------
     if ($criteria->search) {
         $elementIds = $this->_getElementIdsFromQuery($query);
         $scoredSearchResults = $criteria->order == 'score';
         $filteredElementIds = craft()->search->filterElementIdsByQuery($elementIds, $criteria->search, $scoredSearchResults);
         // No results?
         if (!$filteredElementIds) {
             return array();
         }
         $query->andWhere(array('in', 'venti.eventid', $filteredElementIds));
         if ($scoredSearchResults) {
             // Order the elements in the exact order that SearchService returned them in
             $query->order(craft()->db->getSchema()->orderByColumnValues('venti.eventid', $filteredElementIds));
         }
     }
     return $query;
 }
Beispiel #15
0
 /**
  * Ensures that a valid list of parseable headers is returned
  *
  * @param string $headerString
  *
  * @return array
  */
 public function getHeadersToParse($headerString = '')
 {
     $allowedHeaders = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
     $headers = ArrayHelper::filterEmptyStringsFromArray(ArrayHelper::stringToArray($headerString));
     if (count($headers)) {
         foreach ($headers as $key => $header) {
             $header = strtolower($header);
             if (!in_array($header, $allowedHeaders)) {
                 unset($headers[$key]);
             }
         }
     }
     return $headers;
 }
 /**
  * Preps a {@link DbCommand} object for querying for elements, based on a given element criteria.
  *
  * @param ElementCriteriaModel &$criteria     The element criteria model
  * @param string               &$contentTable The content table that should be joined in. (This variable will
  *                                            actually get defined by buildElementsQuery(), and is passed by
  *                                            reference so whatever’s calling the method will have access to its
  *                                            value.)
  * @param array                &$fieldColumns Info about the content field columns being selected. (This variable
  *                                            will actually get defined by buildElementsQuery(), and is passed by
  *                                            reference so whatever’s calling the method will have access to its
  *                                            value.)
  *
  * @return DbCommand|false The DbCommand object, or `false` if the method was able to determine ahead of time that
  *                         there’s no chance any elements are going to be found with the given parameters.
  */
 public function buildElementsQuery(&$criteria = null, &$contentTable = null, &$fieldColumns = null)
 {
     if (!$criteria instanceof ElementCriteriaModel) {
         $criteria = $this->getCriteria('Entry', $criteria);
     }
     $elementType = $criteria->getElementType();
     if (!$elementType->isLocalized()) {
         // The criteria *must* be set to the primary locale
         $criteria->locale = craft()->i18n->getPrimarySiteLocaleId();
     } else {
         if (!$criteria->locale) {
             // Default to the current app locale
             $criteria->locale = craft()->language;
         }
     }
     // Set up the query
     // ---------------------------------------------------------------------
     $query = craft()->db->createCommand()->select('elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated, elements_i18n.slug, elements_i18n.uri, elements_i18n.enabled AS localeEnabled')->from('elements elements')->join('elements_i18n elements_i18n', 'elements_i18n.elementId = elements.id')->where('elements_i18n.locale = :locale', array(':locale' => $criteria->locale))->group('elements.id');
     if ($elementType->hasContent()) {
         $contentTable = $elementType->getContentTableForElementsQuery($criteria);
         if ($contentTable) {
             $contentCols = 'content.id AS contentId';
             if ($elementType->hasTitles()) {
                 $contentCols .= ', content.title';
             }
             // TODO: Replace this with a call to getFieldsForElementsQuery() in 3.0
             $fieldColumns = $elementType->getContentFieldColumnsForElementsQuery($criteria);
             foreach ($fieldColumns as $column) {
                 $contentCols .= ', content.' . $column['column'];
             }
             $query->addSelect($contentCols);
             $query->join($contentTable . ' content', 'content.elementId = elements.id');
             $query->andWhere('content.locale = :locale');
         }
     }
     // Basic element params
     // ---------------------------------------------------------------------
     // If the 'id' parameter is set to any empty value besides `null`, don't return anything
     if ($criteria->id !== null && empty($criteria->id)) {
         return false;
     }
     if ($criteria->id) {
         $query->andWhere(DbHelper::parseParam('elements.id', $criteria->id, $query->params));
     }
     if ($criteria->archived) {
         $query->andWhere('elements.archived = 1');
     } else {
         $query->andWhere('elements.archived = 0');
         if ($criteria->status) {
             $statusConditions = array();
             $statuses = ArrayHelper::stringToArray($criteria->status);
             foreach ($statuses as $status) {
                 $status = StringHelper::toLowerCase($status);
                 // Is this a supported status?
                 if (in_array($status, array_keys($elementType->getStatuses()))) {
                     if ($status == BaseElementModel::ENABLED) {
                         $statusConditions[] = 'elements.enabled = 1';
                     } else {
                         if ($status == BaseElementModel::DISABLED) {
                             $statusConditions[] = 'elements.enabled = 0';
                         } else {
                             $elementStatusCondition = $elementType->getElementQueryStatusCondition($query, $status);
                             if ($elementStatusCondition) {
                                 $statusConditions[] = $elementStatusCondition;
                             } else {
                                 if ($elementStatusCondition === false) {
                                     return false;
                                 }
                             }
                         }
                     }
                 }
             }
             if ($statusConditions) {
                 if (count($statusConditions) == 1) {
                     $statusCondition = $statusConditions[0];
                 } else {
                     array_unshift($statusConditions, 'or');
                     $statusCondition = $statusConditions;
                 }
                 $query->andWhere($statusCondition);
             }
         }
     }
     if ($criteria->dateCreated) {
         $query->andWhere(DbHelper::parseDateParam('elements.dateCreated', $criteria->dateCreated, $query->params));
     }
     if ($criteria->dateUpdated) {
         $query->andWhere(DbHelper::parseDateParam('elements.dateUpdated', $criteria->dateUpdated, $query->params));
     }
     if ($elementType->hasTitles() && $criteria->title) {
         $query->andWhere(DbHelper::parseParam('content.title', $criteria->title, $query->params));
     }
     // i18n params
     // ---------------------------------------------------------------------
     if ($criteria->slug) {
         $query->andWhere(DbHelper::parseParam('elements_i18n.slug', $criteria->slug, $query->params));
     }
     if ($criteria->uri) {
         $query->andWhere(DbHelper::parseParam('elements_i18n.uri', $criteria->uri, $query->params));
     }
     if ($criteria->localeEnabled) {
         $query->andWhere('elements_i18n.enabled = 1');
     }
     // Relational params
     // ---------------------------------------------------------------------
     // Convert the old childOf and parentOf params to the relatedTo param
     // childOf(element)  => relatedTo({ source: element })
     // parentOf(element) => relatedTo({ target: element })
     if (!$criteria->relatedTo && ($criteria->childOf || $criteria->parentOf)) {
         $relatedTo = array('and');
         if ($criteria->childOf) {
             $relatedTo[] = array('sourceElement' => $criteria->childOf, 'field' => $criteria->childField);
         }
         if ($criteria->parentOf) {
             $relatedTo[] = array('targetElement' => $criteria->parentOf, 'field' => $criteria->parentField);
         }
         $criteria->relatedTo = $relatedTo;
     }
     if ($criteria->relatedTo) {
         $relationParamParser = new ElementRelationParamParser();
         $relConditions = $relationParamParser->parseRelationParam($criteria->relatedTo, $query);
         if ($relConditions === false) {
             return false;
         }
         $query->andWhere($relConditions);
         // If there's only one relation criteria and it's specifically for grabbing target elements, allow the query
         // to order by the relation sort order
         if ($relationParamParser->isRelationFieldQuery()) {
             $query->addSelect('sources1.sortOrder');
         }
     }
     // Give field types a chance to make changes
     // ---------------------------------------------------------------------
     if ($elementType->hasContent() && $contentTable) {
         $contentService = craft()->content;
         $originalFieldColumnPrefix = $contentService->fieldColumnPrefix;
         // TODO: $fields should already be defined by now in Craft 3.0
         $fields = $elementType->getFieldsForElementsQuery($criteria);
         $extraCriteriaAttributes = $criteria->getExtraAttributeNames();
         foreach ($fields as $field) {
             $fieldType = $field->getFieldType();
             if ($fieldType) {
                 // Was this field's parameter set on the criteria model?
                 if (in_array($field->handle, $extraCriteriaAttributes)) {
                     $fieldCriteria = $criteria->{$field->handle};
                 } else {
                     $fieldCriteria = null;
                 }
                 // Set the field's column prefix on ContentService
                 if ($field->columnPrefix) {
                     $contentService->fieldColumnPrefix = $field->columnPrefix;
                 }
                 $fieldTypeResponse = $fieldType->modifyElementsQuery($query, $fieldCriteria);
                 // Set it back
                 $contentService->fieldColumnPrefix = $originalFieldColumnPrefix;
                 // Need to bail early?
                 if ($fieldTypeResponse === false) {
                     return false;
                 }
             }
         }
     }
     // Give the element type a chance to make changes
     // ---------------------------------------------------------------------
     if ($elementType->modifyElementsQuery($query, $criteria) === false) {
         return false;
     }
     // Structure params
     // ---------------------------------------------------------------------
     if ($query->isJoined('structureelements')) {
         $query->addSelect('structureelements.root, structureelements.lft, structureelements.rgt, structureelements.level');
         if ($criteria->ancestorOf) {
             if (!$criteria->ancestorOf instanceof BaseElementModel) {
                 $criteria->ancestorOf = craft()->elements->getElementById($criteria->ancestorOf, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->ancestorOf) {
                     return false;
                 }
             }
             if ($criteria->ancestorOf) {
                 $query->andWhere(array('and', 'structureelements.lft < :ancestorOf_lft', 'structureelements.rgt > :ancestorOf_rgt', 'structureelements.root = :ancestorOf_root'), array(':ancestorOf_lft' => $criteria->ancestorOf->lft, ':ancestorOf_rgt' => $criteria->ancestorOf->rgt, ':ancestorOf_root' => $criteria->ancestorOf->root));
                 if ($criteria->ancestorDist) {
                     $query->andWhere('structureelements.level >= :ancestorOf_level', array(':ancestorOf_level' => $criteria->ancestorOf->level - $criteria->ancestorDist));
                 }
             }
         }
         if ($criteria->descendantOf) {
             if (!$criteria->descendantOf instanceof BaseElementModel) {
                 $criteria->descendantOf = craft()->elements->getElementById($criteria->descendantOf, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->descendantOf) {
                     return false;
                 }
             }
             if ($criteria->descendantOf) {
                 $query->andWhere(array('and', 'structureelements.lft > :descendantOf_lft', 'structureelements.rgt < :descendantOf_rgt', 'structureelements.root = :descendantOf_root'), array(':descendantOf_lft' => $criteria->descendantOf->lft, ':descendantOf_rgt' => $criteria->descendantOf->rgt, ':descendantOf_root' => $criteria->descendantOf->root));
                 if ($criteria->descendantDist) {
                     $query->andWhere('structureelements.level <= :descendantOf_level', array(':descendantOf_level' => $criteria->descendantOf->level + $criteria->descendantDist));
                 }
             }
         }
         if ($criteria->siblingOf) {
             if (!$criteria->siblingOf instanceof BaseElementModel) {
                 $criteria->siblingOf = craft()->elements->getElementById($criteria->siblingOf, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->siblingOf) {
                     return false;
                 }
             }
             if ($criteria->siblingOf) {
                 $query->andWhere(array('and', 'structureelements.level = :siblingOf_level', 'structureelements.root = :siblingOf_root', 'structureelements.elementId != :siblingOf_elementId'), array(':siblingOf_level' => $criteria->siblingOf->level, ':siblingOf_root' => $criteria->siblingOf->root, ':siblingOf_elementId' => $criteria->siblingOf->id));
                 if ($criteria->siblingOf->level != 1) {
                     $parent = $criteria->siblingOf->getParent();
                     if ($parent) {
                         $query->andWhere(array('and', 'structureelements.lft > :siblingOf_lft', 'structureelements.rgt < :siblingOf_rgt'), array(':siblingOf_lft' => $parent->lft, ':siblingOf_rgt' => $parent->rgt));
                     } else {
                         return false;
                     }
                 }
             }
         }
         if ($criteria->prevSiblingOf) {
             if (!$criteria->prevSiblingOf instanceof BaseElementModel) {
                 $criteria->prevSiblingOf = craft()->elements->getElementById($criteria->prevSiblingOf, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->prevSiblingOf) {
                     return false;
                 }
             }
             if ($criteria->prevSiblingOf) {
                 $query->andWhere(array('and', 'structureelements.level = :prevSiblingOf_level', 'structureelements.rgt = :prevSiblingOf_rgt', 'structureelements.root = :prevSiblingOf_root'), array(':prevSiblingOf_level' => $criteria->prevSiblingOf->level, ':prevSiblingOf_rgt' => $criteria->prevSiblingOf->lft - 1, ':prevSiblingOf_root' => $criteria->prevSiblingOf->root));
             }
         }
         if ($criteria->nextSiblingOf) {
             if (!$criteria->nextSiblingOf instanceof BaseElementModel) {
                 $criteria->nextSiblingOf = craft()->elements->getElementById($criteria->nextSiblingOf, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->nextSiblingOf) {
                     return false;
                 }
             }
             if ($criteria->nextSiblingOf) {
                 $query->andWhere(array('and', 'structureelements.level = :nextSiblingOf_level', 'structureelements.lft = :nextSiblingOf_lft', 'structureelements.root = :nextSiblingOf_root'), array(':nextSiblingOf_level' => $criteria->nextSiblingOf->level, ':nextSiblingOf_lft' => $criteria->nextSiblingOf->rgt + 1, ':nextSiblingOf_root' => $criteria->nextSiblingOf->root));
             }
         }
         if ($criteria->positionedBefore) {
             if (!$criteria->positionedBefore instanceof BaseElementModel) {
                 $criteria->positionedBefore = craft()->elements->getElementById($criteria->positionedBefore, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->positionedBefore) {
                     return false;
                 }
             }
             if ($criteria->positionedBefore) {
                 $query->andWhere(array('and', 'structureelements.rgt < :positionedBefore_rgt', 'structureelements.root = :positionedBefore_root'), array(':positionedBefore_rgt' => $criteria->positionedBefore->lft, ':positionedBefore_root' => $criteria->positionedBefore->root));
             }
         }
         if ($criteria->positionedAfter) {
             if (!$criteria->positionedAfter instanceof BaseElementModel) {
                 $criteria->positionedAfter = craft()->elements->getElementById($criteria->positionedAfter, $elementType->getClassHandle(), $criteria->locale);
                 if (!$criteria->positionedAfter) {
                     return false;
                 }
             }
             if ($criteria->positionedAfter) {
                 $query->andWhere(array('and', 'structureelements.lft > :positionedAfter_lft', 'structureelements.root = :positionedAfter_root'), array(':positionedAfter_lft' => $criteria->positionedAfter->rgt, ':positionedAfter_root' => $criteria->positionedAfter->root));
             }
         }
         if ($criteria->level || $criteria->depth) {
             // TODO: 'depth' is deprecated; use 'level' instead.
             $level = $criteria->level ? $criteria->level : $criteria->depth;
             $query->andWhere(DbHelper::parseParam('structureelements.level', $level, $query->params));
         }
     }
     // Search
     // ---------------------------------------------------------------------
     if ($criteria->search) {
         $elementIds = $this->_getElementIdsFromQuery($query);
         $scoredSearchResults = $criteria->order == 'score';
         $filteredElementIds = craft()->search->filterElementIdsByQuery($elementIds, $criteria->search, $scoredSearchResults);
         // No results?
         if (!$filteredElementIds) {
             return array();
         }
         $query->andWhere(array('in', 'elements.id', $filteredElementIds));
         if ($scoredSearchResults) {
             // Order the elements in the exact order that SearchService returned them in
             $query->order(craft()->db->getSchema()->orderByColumnValues('elements.id', $filteredElementIds));
         }
     }
     return $query;
 }
Beispiel #17
0
 public function prepUsers($data, $field)
 {
     $fieldData = array();
     if (!empty($data)) {
         $settings = $field->getFieldType()->getSettings();
         // Get source id's for connecting
         $groupIds = array();
         $sources = $settings->sources;
         if (is_array($sources)) {
             foreach ($sources as $source) {
                 list($type, $id) = explode(':', $source);
                 $groupIds[] = $id;
             }
         }
         $users = ArrayHelper::stringToArray($data);
         foreach ($users as $user) {
             $criteria = craft()->elements->getCriteria(ElementType::User);
             $criteria->groupId = $groupIds;
             $criteria->limit = $settings->limit;
             $criteria->search = $user;
             $fieldData = array_merge($fieldData, $criteria->ids());
         }
     }
     // Check for field limit - only return the specified amount
     if ($fieldData) {
         if ($field->settings['limit']) {
             $fieldData = array_chunk($fieldData, $field->settings['limit']);
             $fieldData = $fieldData[0];
         }
     }
     return $fieldData;
 }
 /**
  * Email a submission.
  *
  * @param AmForms_SubmissionModel $submission
  * @param mixed                   $overrideRecipients [Optional] Override recipients from form settings.
  *
  * @return bool
  */
 public function emailSubmission(AmForms_SubmissionModel $submission, $overrideRecipients = false)
 {
     // Do we even have a form ID?
     if (!$submission->formId) {
         return false;
     }
     // Get form if not already set
     $submission->getForm();
     $form = $submission->form;
     $submission->formName = $form->name;
     if (!$form->notificationEnabled) {
         return false;
     }
     // Get our recipients
     $recipients = ArrayHelper::stringToArray($form->notificationRecipients);
     // Send copy?
     if ($form->sendCopy) {
         $sendCopyTo = $submission->{$form->sendCopyTo};
         if (filter_var($sendCopyTo, FILTER_VALIDATE_EMAIL)) {
             $recipients[] = $sendCopyTo;
         }
     }
     if ($overrideRecipients !== false) {
         if (is_array($overrideRecipients) && count($overrideRecipients)) {
             $recipients = $overrideRecipients;
         } elseif (is_string($overrideRecipients)) {
             $recipients = ArrayHelper::stringToArray($overrideRecipients);
         }
     }
     $recipients = array_unique($recipients);
     if (!count($recipients)) {
         return false;
     }
     // Overridden recipients skips before email event, so by default, send the email!
     $sendEmail = true;
     // Fire an 'onBeforeEmailSubmission' event
     if ($overrideRecipients === false) {
         $event = new Event($this, array('submission' => $submission));
         $this->onBeforeEmailSubmission($event);
         // Override sendEmail
         $sendEmail = $event->performAction;
     }
     // Is the event giving us the go-ahead?
     if ($sendEmail) {
         // Get email body
         $body = $this->getSubmissionEmailBody($submission);
         // Other email attributes
         $subject = Craft::t($form->notificationSubject);
         if ($form->notificationSubject) {
             $subject = craft()->templates->renderObjectTemplate($form->notificationSubject, $submission);
         }
         if ($form->notificationReplyToEmail) {
             $replyTo = craft()->templates->renderObjectTemplate($form->notificationReplyToEmail, $submission);
             if (!filter_var($replyTo, FILTER_VALIDATE_EMAIL)) {
                 $replyTo = null;
             }
         }
         // Start mailing!
         $success = false;
         // @TODO Mandrill
         $email = new EmailModel();
         $email->htmlBody = $body;
         $email->fromEmail = $form->notificationSenderEmail;
         $email->fromName = $form->notificationSenderName;
         $email->subject = $subject;
         if ($replyTo) {
             $email->replyTo = $replyTo;
         }
         // Add Bcc?
         $bccEmailAddress = craft()->amForms_settings->getSettingsByHandleAndType('bccEmailAddress', AmFormsModel::SettingGeneral);
         if ($bccEmailAddress && $bccEmailAddress->value) {
             $bccAddresses = ArrayHelper::stringToArray($bccEmailAddress->value);
             $bccAddresses = array_unique($bccAddresses);
             if (count($bccAddresses)) {
                 $properBccAddresses = array();
                 foreach ($bccAddresses as $bccAddress) {
                     $bccAddress = craft()->templates->renderObjectTemplate($bccAddress, $submission);
                     if (filter_var($bccAddress, FILTER_VALIDATE_EMAIL)) {
                         $properBccAddresses[] = array('email' => $bccAddress);
                     }
                 }
                 if (count($properBccAddresses)) {
                     $email->bcc = $properBccAddresses;
                 }
             }
         }
         // Add files to the notification?
         if ($form->notificationFilesEnabled) {
             foreach ($submission->getFieldLayout()->getTabs() as $tab) {
                 // Tab fields
                 $fields = $tab->getFields();
                 foreach ($fields as $layoutField) {
                     // Get actual field
                     $field = $layoutField->getField();
                     // Find assets
                     if ($field->type == 'Assets') {
                         foreach ($submission->{$field->handle}->find() as $asset) {
                             $assetPath = craft()->amForms->getPathForAsset($asset);
                             // Add asset as attachment
                             if (IOHelper::fileExists($assetPath . $asset->filename)) {
                                 $email->addAttachment($assetPath . $asset->filename);
                             }
                         }
                     }
                 }
             }
         }
         // Send emails
         foreach ($recipients as $recipient) {
             $email->toEmail = craft()->templates->renderObjectTemplate($recipient, $submission);
             if (filter_var($email->toEmail, FILTER_VALIDATE_EMAIL)) {
                 // Add variable for email event
                 if (craft()->email->sendEmail($email, array('amFormsSubmission' => $submission))) {
                     $success = true;
                 }
             }
         }
         // Fire an 'onEmailSubmission' event
         $this->onEmailSubmission(new Event($this, array('success' => $success, 'submission' => $submission)));
         return $success;
     }
     return false;
 }
Beispiel #19
0
 /**
  * Returns the rules array used by CModel.
  *
  * @param \CModel $model
  *
  * @return array
  */
 public static function getRules(\CModel $model)
 {
     $rules = array();
     $uniqueAttributes = array();
     $uniqueRequiredAttributes = array();
     $requiredAttributes = array();
     $emailAttributes = array();
     $urlAttributes = array();
     $urlFormatAttributes = array();
     $uriAttributes = array();
     $strictLengthAttributes = array();
     $minLengthAttributes = array();
     $maxLengthAttributes = array();
     $attributes = $model->getAttributeConfigs();
     foreach ($attributes as $name => $config) {
         switch ($config['type']) {
             case AttributeType::DateTime:
                 $rules[] = array($name, 'Craft\\DateTimeValidator');
                 break;
             case AttributeType::Email:
                 $emailAttributes[] = $name;
                 break;
             case AttributeType::Enum:
                 $rules[] = array($name, 'in', 'range' => ArrayHelper::stringToArray($config['values']));
                 break;
             case AttributeType::Handle:
                 $rules[] = array($name, 'Craft\\HandleValidator', 'reservedWords' => ArrayHelper::stringToArray($config['reservedWords']));
                 break;
             case AttributeType::Locale:
                 $rules[] = array($name, 'Craft\\LocaleValidator');
                 break;
             case AttributeType::Number:
                 $rule = array($name, 'numerical');
                 if ($config['min'] !== null) {
                     $rule['min'] = $config['min'];
                 }
                 if ($config['max'] !== null) {
                     $rule['max'] = $config['max'];
                 }
                 if (!$config['decimals']) {
                     $rule['integerOnly'] = true;
                 }
                 $rules[] = $rule;
                 break;
             case AttributeType::Url:
                 $urlAttributes[] = $name;
                 break;
             case AttributeType::UrlFormat:
                 $urlFormatAttributes[] = $name;
                 break;
             case AttributeType::Uri:
                 $uriAttributes[] = $name;
                 break;
         }
         // Uniques
         if (!empty($config['unique'])) {
             if (empty($config['required']) && (isset($config['null']) && $config['null'] === false)) {
                 $uniqueRequiredAttributes[] = $name;
             } else {
                 $uniqueAttributes[] = $name;
             }
         }
         // Required
         if ($config['type'] != AttributeType::Bool && !empty($config['required'])) {
             $requiredAttributes[] = $name;
         }
         // Lengths
         if ($config['type'] != AttributeType::Number && $config['type'] != AttributeType::Mixed) {
             if (isset($config['length']) && is_numeric($config['length'])) {
                 $strictLengthAttributes[(string) $config['length']][] = $name;
             } else {
                 // Only worry about min- and max-lengths if a strict length isn't set
                 if (isset($config['minLength']) && is_numeric($config['minLength'])) {
                     $minLengthAttributes[(string) $config['minLength']][] = $name;
                 }
                 if (isset($config['maxLength']) && is_numeric($config['maxLength'])) {
                     $maxLengthAttributes[(string) $config['maxLength']][] = $name;
                 }
             }
         }
         // Compare with other attributes
         if (isset($config['compare'])) {
             $comparisons = ArrayHelper::stringToArray($config['compare']);
             foreach ($comparisons as $comparison) {
                 if (preg_match('/^(==|=|!=|>=|>|<=|<)\\s*\\b(.*)$/', $comparison, $match)) {
                     $rules[] = array($name, 'compare', 'compareAttribute' => $match[2], 'operator' => $match[1], 'allowEmpty' => true);
                 }
             }
         }
         // Regex pattern matching
         if (!empty($config['matchPattern'])) {
             $rules[] = array($name, 'match', 'pattern' => $config['matchPattern']);
         }
     }
     // If this is a BaseRecord instance, catch any unique/required indexes. We don't validate required BELONGS_TO
     // relations because they might not get set until after validation.
     if ($model instanceof BaseRecord) {
         foreach ($model->defineIndexes() as $config) {
             $unique = !empty($config['unique']);
             $required = !empty($config['required']);
             if ($unique || $required) {
                 $columns = ArrayHelper::stringToArray($config['columns']);
                 if ($unique) {
                     if (count($columns) == 1) {
                         if (empty($attributes[$columns[0]]['required']) && (isset($attributes[$columns[0]]['null']) && $attributes[$columns[0]]['null'] === false)) {
                             $uniqueRequiredAttributes[] = $columns[0];
                         } else {
                             $uniqueAttributes[] = $columns[0];
                         }
                     } else {
                         $initialColumn = array_shift($columns);
                         $rules[] = array($initialColumn, 'Craft\\CompositeUniqueValidator', 'with' => implode(',', $columns));
                     }
                 }
                 if ($required) {
                     $requiredAttributes = array_merge($requiredAttributes, $columns);
                 }
             }
         }
     }
     if ($uniqueAttributes) {
         $rules[] = array(implode(',', $uniqueAttributes), 'unique');
     }
     if ($uniqueRequiredAttributes) {
         $rules[] = array(implode(',', $uniqueRequiredAttributes), 'unique', 'allowEmpty' => false);
     }
     if ($requiredAttributes) {
         $rules[] = array(implode(',', $requiredAttributes), 'required');
     }
     if ($emailAttributes) {
         $rules[] = array(implode(',', $emailAttributes), 'email');
     }
     if ($urlAttributes) {
         $rules[] = array(implode(',', $urlAttributes), 'Craft\\UrlValidator', 'defaultScheme' => 'http');
     }
     if ($urlFormatAttributes) {
         $rules[] = array(implode(',', $urlFormatAttributes), 'Craft\\UrlFormatValidator');
     }
     if ($uriAttributes) {
         $rules[] = array(implode(',', $uriAttributes), 'Craft\\UriValidator');
     }
     if ($strictLengthAttributes) {
         foreach ($strictLengthAttributes as $strictLength => $attributeNames) {
             $rules[] = array(implode(',', $attributeNames), 'length', 'is' => (int) $strictLength);
         }
     }
     if ($minLengthAttributes) {
         foreach ($minLengthAttributes as $minLength => $attributeNames) {
             $rules[] = array(implode(',', $attributeNames), 'length', 'min' => (int) $minLength);
         }
     }
     if ($maxLengthAttributes) {
         foreach ($maxLengthAttributes as $maxLength => $attributeNames) {
             $rules[] = array(implode(',', $attributeNames), 'length', 'max' => (int) $maxLength);
         }
     }
     $rules[] = array(implode(',', array_keys($attributes)), 'safe', 'on' => 'search');
     return $rules;
 }
 /**
  * Modifies an element query targeting elements of this type.
  *
  * @param DbCommand $query
  * @param ElementCriteriaModel $criteria
  * @return mixed
  */
 public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
 {
     $query->addSelect('venti.startDate, venti.endDate, venti.allDay, venti.isrepeat, venti.eid, venti.eventid, venti.repeat, venti.rRule, venti.summary, venti.locale, entries.postDate, entries.expiryDate')->leftJoin('venti_events venti', 'venti.eventid = elements.id')->leftJoin('entries entries', 'entries.id = eventid')->group('venti.startDate');
     if ($criteria->locale) {
         $query->andWhere(DbHelper::parseParam('venti.locale', $criteria->locale, $query->params));
     }
     if ($criteria->startDate) {
         $query->andWhere(DbHelper::parseDateParam('venti.startDate', $criteria->startDate, $query->params));
     }
     if ($criteria->id) {
         $query->andWhere(DbHelper::parseParam('venti.eventid', $criteria->eventid, $query->params));
     }
     if ($criteria->eventid) {
         $query->andWhere(DbHelper::parseParam('venti.eventid', $criteria->eventid, $query->params));
     }
     if ($criteria->endDate) {
         $query->andWhere(DbHelper::parseDateParam('venti.endDate', $criteria->endDate, $query->params));
     }
     if ($criteria->summary) {
         $query->andWhere(DbHelper::parseParam('venti.summary', $criteria->summary, $query->params));
     }
     if ($criteria->isrepeat) {
         $query->andWhere(DbHelper::parseParam('venti.isrepeat', $criteria->isrepeat, $query->params));
     }
     if ($criteria->rRule) {
         $query->andWhere(DbHelper::parseParam('venti.rRule', $criteria->rRule, $query->params));
     }
     if ($criteria->eid) {
         $query->andWhere(DbHelper::parseParam('venti.eid', $criteria->eid, $query->params));
     }
     if ($criteria->repeat) {
         $query->andWhere(DbHelper::parseParam('venti.repeat', $criteria->repeat, $query->params));
     }
     if ($criteria->allDay) {
         $query->andWhere(DbHelper::parseDateParam('venti.allDay', $criteria->allDay, $query->params));
     }
     if ($criteria->between) {
         $dates = array();
         $interval = array();
         if (!is_array($criteria->between)) {
             $criteria->between = ArrayHelper::stringToArray($criteria->between);
         }
         if (count($criteria->between) == 2) {
             foreach ($criteria->between as $ref) {
                 if (!$ref instanceof \DateTime) {
                     $dates[] = DateTime::createFromString($ref, craft()->getTimeZone());
                 } else {
                     $dates[] = $ref;
                 }
             }
             if ($dates[0] > $dates[1]) {
                 $interval[0] = $dates[1];
                 $interval[1] = $dates[0];
             } else {
                 $interval = $dates;
             }
             $query->andWhere('(venti.startDate BETWEEN :betweenStartDate AND :betweenEndDate) OR (:betweenStartDate BETWEEN venti.startDate AND venti.endDate)', array(':betweenStartDate' => DateTimeHelper::formatTimeForDb($interval[0]->getTimestamp()), ':betweenEndDate' => DateTimeHelper::formatTimeForDb($interval[1]->getTimestamp())));
         }
     }
 }
Beispiel #21
0
 /**
  * Parses a date param value to a DbCommand where condition.
  *
  * @param string $key
  * @param string $operator
  * @param string|array|DateTime $dates
  * @param array &$params
  * @return mixed
  */
 public static function parseDateParam($key, $operator, $dates, &$params)
 {
     $conditions = array();
     $dates = ArrayHelper::stringToArray($dates);
     foreach ($dates as $date) {
         if (!$date instanceof \DateTime) {
             $date = DateTime::createFromString($date, Craft::getTimezone());
         }
         $param = ':p' . StringHelper::randomString(9);
         $params[$param] = DateTimeHelper::formatTimeForDb($date->getTimestamp());
         $conditions[] = $key . $operator . $param;
     }
     if (count($conditions) == 1) {
         return $conditions[0];
     } else {
         array_unshift($conditions, 'or');
         return $conditions;
     }
 }
Beispiel #22
0
 /**
  * Get a list of allowed file extensions.
  *
  * @return array
  */
 public static function getAllowedFileExtensions()
 {
     $allowedFileExtensions = ArrayHelper::stringToArray(craft()->config->get('allowedFileExtensions'));
     if (($extraExtensions = craft()->config->get('extraAllowedFileExtensions')) !== '') {
         $extraExtensions = ArrayHelper::stringToArray($extraExtensions);
         $allowedFileExtensions = array_merge($allowedFileExtensions, $extraExtensions);
     }
     return $allowedFileExtensions;
 }
 /**
  * Eager-loads image transforms requested by an element criteria model.
  *
  * @param Event $event
  *
  * @return void
  */
 public function eagerLoadTransforms(Event $event)
 {
     /** @var ElementCriteriaModel $criteria */
     $criteria = $event->sender;
     $transforms = ArrayHelper::stringToArray($criteria->withTransforms);
     craft()->assetTransforms->eagerLoadTransforms($event->params['elements'], $transforms);
 }
Beispiel #24
0
 /**
  * Returns a primary key name based on the table and column names.
  *
  * @param string       $table
  * @param string|array $columns
  *
  * @return string
  */
 public function getPrimaryKeyName($table, $columns)
 {
     $columns = ArrayHelper::stringToArray($columns);
     $name = $this->tablePrefix . $table . '_' . implode('_', $columns) . '_pk';
     return $this->trimObjectName($name);
 }
 /**
  * @inheritDoc IElementType::modifyElementsQuery()
  *
  * @param DbCommand            $query
  * @param ElementCriteriaModel $criteria
  *
  * @return bool|false|null|void
  */
 public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
 {
     $query->addSelect('entries.sectionId, entries.typeId, entries.authorId, entries.postDate, entries.expiryDate')->join('entries entries', 'entries.id = elements.id')->join('sections sections', 'sections.id = entries.sectionId')->leftJoin('structures structures', 'structures.id = sections.structureId')->leftJoin('structureelements structureelements', array('and', 'structureelements.structureId = structures.id', 'structureelements.elementId = entries.id'));
     if ($criteria->ref) {
         $refs = ArrayHelper::stringToArray($criteria->ref);
         $conditionals = array();
         foreach ($refs as $ref) {
             $parts = array_filter(explode('/', $ref));
             if ($parts) {
                 if (count($parts) == 1) {
                     $conditionals[] = DbHelper::parseParam('elements_i18n.slug', $parts[0], $query->params);
                 } else {
                     $conditionals[] = array('and', DbHelper::parseParam('sections.handle', $parts[0], $query->params), DbHelper::parseParam('elements_i18n.slug', $parts[1], $query->params));
                 }
             }
         }
         if ($conditionals) {
             if (count($conditionals) == 1) {
                 $query->andWhere($conditionals[0]);
             } else {
                 array_unshift($conditionals, 'or');
                 $query->andWhere($conditionals);
             }
         }
     }
     if ($criteria->type) {
         $typeIds = array();
         if (!is_array($criteria->type)) {
             $criteria->type = array($criteria->type);
         }
         foreach ($criteria->type as $type) {
             if (is_numeric($type)) {
                 $typeIds[] = $type;
             } else {
                 if (is_string($type)) {
                     $types = craft()->sections->getEntryTypesByHandle($type);
                     if ($types) {
                         foreach ($types as $type) {
                             $typeIds[] = $type->id;
                         }
                     } else {
                         return false;
                     }
                 } else {
                     if ($type instanceof EntryTypeModel) {
                         $typeIds[] = $type->id;
                     } else {
                         return false;
                     }
                 }
             }
         }
         $query->andWhere(DbHelper::parseParam('entries.typeId', $typeIds, $query->params));
     }
     if ($criteria->postDate) {
         $query->andWhere(DbHelper::parseDateParam('entries.postDate', $criteria->postDate, $query->params));
     } else {
         if ($criteria->after) {
             $query->andWhere(DbHelper::parseDateParam('entries.postDate', '>=' . $criteria->after, $query->params));
         }
         if ($criteria->before) {
             $query->andWhere(DbHelper::parseDateParam('entries.postDate', '<' . $criteria->before, $query->params));
         }
     }
     if ($criteria->expiryDate) {
         $query->andWhere(DbHelper::parseDateParam('entries.expiryDate', $criteria->expiryDate, $query->params));
     }
     if ($criteria->editable) {
         $user = craft()->userSession->getUser();
         if (!$user) {
             return false;
         }
         // Limit the query to only the sections the user has permission to edit
         $editableSectionIds = craft()->sections->getEditableSectionIds();
         $query->andWhere(array('in', 'entries.sectionId', $editableSectionIds));
         // Enforce the editPeerEntries permissions for non-Single sections
         $noPeerConditions = array();
         foreach (craft()->sections->getEditableSections() as $section) {
             if ($section->type != SectionType::Single && !$user->can('editPeerEntries:' . $section->id)) {
                 $noPeerConditions[] = array('or', 'entries.sectionId != ' . $section->id, 'entries.authorId = ' . $user->id);
             }
         }
         if ($noPeerConditions) {
             array_unshift($noPeerConditions, 'and');
             $query->andWhere($noPeerConditions);
         }
     }
     if ($criteria->section) {
         if ($criteria->section instanceof SectionModel) {
             $criteria->sectionId = $criteria->section->id;
             $criteria->section = null;
         } else {
             $query->andWhere(DbHelper::parseParam('sections.handle', $criteria->section, $query->params));
         }
     }
     if ($criteria->sectionId) {
         $query->andWhere(DbHelper::parseParam('entries.sectionId', $criteria->sectionId, $query->params));
     }
     if (craft()->getEdition() >= Craft::Client) {
         if ($criteria->authorId) {
             $query->andWhere(DbHelper::parseParam('entries.authorId', $criteria->authorId, $query->params));
         }
         if ($criteria->authorGroupId || $criteria->authorGroup) {
             $query->join('usergroups_users usergroups_users', 'usergroups_users.userId = entries.authorId');
             if ($criteria->authorGroupId) {
                 $query->andWhere(DbHelper::parseParam('usergroups_users.groupId', $criteria->authorGroupId, $query->params));
             }
             if ($criteria->authorGroup) {
                 $query->join('usergroups usergroups', 'usergroups.id = usergroups_users.groupId');
                 $query->andWhere(DbHelper::parseParam('usergroups.handle', $criteria->authorGroup, $query->params));
             }
         }
     }
 }
Beispiel #26
0
 /**
  * Prepare fields for fieldtypes.
  *
  * @param string &$data
  * @param string $handle
  *
  * @return mixed
  */
 public function prepForFieldType(&$data, $handle)
 {
     // Fresh up $data
     $data = StringHelper::convertToUTF8($data);
     $data = trim($data);
     // Get field info
     $field = craft()->fields->getFieldByHandle($handle);
     // If it's a field ofcourse
     if (!is_null($field)) {
         // For some fieldtypes the're special rules
         switch ($field->type) {
             case ImportModel::FieldTypeEntries:
                 // No newlines allowed
                 $data = str_replace("\n", '', $data);
                 $data = str_replace("\r", '', $data);
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get source id's for connecting
                     $sectionIds = array();
                     $sources = $settings->sources;
                     if (is_array($sources)) {
                         foreach ($sources as $source) {
                             list($type, $id) = explode(':', $source);
                             $sectionIds[] = $id;
                         }
                     }
                     // Find matching element in sections
                     $criteria = craft()->elements->getCriteria(ElementType::Entry);
                     $criteria->sectionId = $sectionIds;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Assets at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Search
                         $criteria->search = $query;
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeCategories:
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get source id
                     $source = $settings->source;
                     list($type, $id) = explode(':', $source);
                     // Get category data
                     $category = new CategoryModel();
                     $category->groupId = $id;
                     // This we append before the slugified path
                     $categoryUrl = str_replace('{slug}', '', $category->getUrlFormat());
                     // Find matching elements in categories
                     $criteria = craft()->elements->getCriteria(ElementType::Category);
                     $criteria->groupId = $id;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Categories at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Find matching element by URI (dirty, not all categories have URI's)
                         $criteria->uri = $categoryUrl . $this->slugify($query);
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeAssets:
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get folder id's for connecting
                     $folderIds = array();
                     $folders = $settings->sources;
                     if (is_array($folders)) {
                         foreach ($folders as $folder) {
                             list($type, $id) = explode(':', $folder);
                             $folderIds[] = $id;
                         }
                     }
                     // Find matching element in folders
                     $criteria = craft()->elements->getCriteria(ElementType::Asset);
                     $criteria->folderId = $folderIds;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Assets at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Search
                         $criteria->search = $query;
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeUsers:
                 // Don't connect empty fields
                 if (!empty($data)) {
                     // Get field settings
                     $settings = $field->getFieldType()->getSettings();
                     // Get group id's for connecting
                     $groupIds = array();
                     $sources = $settings->sources;
                     if (is_array($sources)) {
                         foreach ($sources as $source) {
                             list($type, $id) = explode(':', $source);
                             $groupIds[] = $id;
                         }
                     }
                     // Find matching element in sources
                     $criteria = craft()->elements->getCriteria(ElementType::User);
                     $criteria->groupId = $groupIds;
                     $criteria->limit = $settings->limit;
                     // Get search strings
                     $search = ArrayHelper::stringToArray($data);
                     // Ability to import multiple Users at once
                     $data = array();
                     // Loop through keywords
                     foreach ($search as $query) {
                         // Search
                         $criteria->search = $query;
                         // Add to data
                         $data = array_merge($data, $criteria->ids());
                     }
                 } else {
                     // Return empty array
                     $data = array();
                 }
                 break;
             case ImportModel::FieldTypeTags:
                 // Get field settings
                 $settings = $field->getFieldType()->getSettings();
                 // Get tag group id
                 $source = $settings->getAttribute('source');
                 list($type, $groupId) = explode(':', $source);
                 $tags = ArrayHelper::stringToArray($data);
                 $data = array();
                 foreach ($tags as $tag) {
                     // Find existing tag
                     $criteria = craft()->elements->getCriteria(ElementType::Tag);
                     $criteria->title = $tag;
                     $criteria->groupId = $groupId;
                     if (!$criteria->total()) {
                         // Create tag if one doesn't already exist
                         $newtag = new TagModel();
                         $newtag->getContent()->title = $tag;
                         $newtag->groupId = $groupId;
                         // Save tag
                         if (craft()->tags->saveTag($newtag)) {
                             $tagArray = array($newtag->id);
                         }
                     } else {
                         $tagArray = $criteria->ids();
                     }
                     // Add tags to data array
                     $data = array_merge($data, $tagArray);
                 }
                 break;
             case ImportModel::FieldTypeNumber:
                 // Parse as number
                 $data = LocalizationHelper::normalizeNumber($data);
                 // Parse as float
                 $data = floatval($data);
                 break;
             case ImportModel::FieldTypeDate:
                 // Parse date from string
                 $data = DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone));
                 break;
             case ImportModel::FieldTypeRadioButtons:
             case ImportModel::FieldTypeDropdown:
                 //get field settings
                 $settings = $field->getFieldType()->getSettings();
                 //get field options
                 $options = $settings->getAttribute('options');
                 // find matching option label
                 $labelSelected = false;
                 foreach ($options as $option) {
                     if ($labelSelected) {
                         continue;
                     }
                     if ($data == $option['label']) {
                         $data = $option['value'];
                         //stop looking after first match
                         $labelSelected = true;
                     }
                 }
                 break;
             case ImportModel::FieldTypeCheckboxes:
             case ImportModel::FieldTypeMultiSelect:
                 // Convert to array
                 $data = ArrayHelper::stringToArray($data);
                 break;
             case ImportModel::FieldTypeLightSwitch:
                 // Convert yes/no values to boolean
                 switch ($data) {
                     case Craft::t('Yes'):
                         $data = true;
                         break;
                     case Craft::t('No'):
                         $data = false;
                         break;
                 }
                 break;
         }
     }
     return $data;
 }
Beispiel #27
0
 /**
  * Normalizes date params and then sends them off to parseParam().
  *
  * @param string                $key
  * @param string|array|DateTime $values
  * @param array                 &$params
  *
  * @return mixed
  */
 public static function parseDateParam($key, $values, &$params)
 {
     $normalizedValues = array();
     $values = ArrayHelper::stringToArray($values);
     if (!count($values)) {
         return '';
     }
     if ($values[0] == 'and' || $values[0] == 'or') {
         $normalizedValues[] = $values[0];
         array_shift($values);
     }
     foreach ($values as $value) {
         if (is_string($value)) {
             $operator = static::_parseParamOperator($value);
         } else {
             $operator = '=';
         }
         if (!$value instanceof \DateTime) {
             $value = DateTime::createFromString($value, craft()->getTimeZone());
         }
         $normalizedValues[] = $operator . DateTimeHelper::formatTimeForDb($value->getTimestamp());
     }
     return static::parseParam($key, $normalizedValues, $params);
 }
 /**
  * Send Email Notification
  *
  */
 public function sendEmailNotification($form, $postUploads, $postData, $customSubject, $message, $html = true, $email = null)
 {
     $errors = false;
     $attributes = $form->getAttributes();
     $notificationSettings = $attributes['notificationSettings'];
     $toEmails = ArrayHelper::stringToArray($notificationSettings['emailSettings']['notifyEmail']);
     // Process Subject Line
     if ($customSubject) {
         $subject = $customSubject;
     } else {
         $subject = $notificationSettings['emailSettings']['emailSubject'];
     }
     // If submission has files
     if ($postUploads) {
         $fileAttachments = [];
         foreach ($postUploads as $file) {
             $fileAttachments[] = craft()->assets->getFileById($file);
         }
     }
     foreach ($toEmails as $toEmail) {
         $email = new EmailModel();
         $emailSettings = craft()->email->getSettings();
         $email->fromEmail = $emailSettings['emailAddress'];
         $email->replyTo = $emailSettings['emailAddress'];
         $email->sender = $emailSettings['emailAddress'];
         $email->fromName = $form->name;
         $email->toEmail = $toEmail;
         $email->subject = $subject;
         $email->body = $message;
         // Attach files to email
         if (!empty($fileAttachments)) {
             foreach ($fileAttachments as $attachment) {
                 if ($attachment) {
                     $email->addAttachment($attachment->getUrl(), $attachment->title, 'base64', $attachment->getMimeType());
                 }
             }
         }
         if (!craft()->email->sendEmail($email)) {
             $errors = true;
         }
     }
     return $errors ? false : true;
 }
 /**
  * Normalizes parentOf and childOf criteria params,
  * allowing them to be set to ElementCriteriaModel's,
  * and swapping them with their IDs.
  *
  * @param mixed $elements
  * @param mixed $fields
  * @return array
  */
 private function _normalizeRelationParams($elements, $fields)
 {
     $elementIds = array();
     $fieldIds = array();
     // Normalize the element(s)
     $elements = ArrayHelper::stringToArray($elements);
     foreach ($elements as $element) {
         if (is_numeric($element) && intval($element) == $element) {
             $elementIds[] = $element;
         } else {
             if ($element instanceof BaseElementModel) {
                 $elementIds[] = $element->id;
             } else {
                 if ($element instanceof ElementCriteriaModel) {
                     $elementIds = array_merge($elementIds, $element->ids());
                 }
             }
         }
     }
     // Normalize the field(s)
     $fields = ArrayHelper::stringToArray($fields);
     foreach ($fields as $field) {
         if (is_numeric($field) && intval($field) == $field) {
             $fieldIds[] = $field;
         } else {
             if (is_string($field)) {
                 $fieldModel = craft()->fields->getFieldByHandle($field);
                 if ($fieldModel) {
                     $fieldIds[] = $fieldModel->id;
                 }
             }
         }
     }
     return array($elementIds, $fieldIds);
 }
 /**
  * Notify admin
  *
  * @param SproutForms_FormModel  $form
  * @param SproutForms_EntryModel $entry
  */
 private function _notifyAdmin(SproutForms_FormModel $form, SproutForms_EntryModel $entry)
 {
     // Get our recipients
     $recipients = ArrayHelper::stringToArray($form->notificationRecipients);
     $recipients = array_unique($recipients);
     if (count($recipients)) {
         $email = new EmailModel();
         $tabs = $form->getFieldLayout()->getTabs();
         $settings = craft()->plugins->getPlugin('sproutforms')->getSettings();
         $templateFolderOverride = $settings->templateFolderOverride;
         $emailTemplate = craft()->path->getPluginsPath() . 'sproutforms/templates/_special/templates/';
         if ($templateFolderOverride) {
             $emailTemplateFile = craft()->path->getSiteTemplatesPath() . $templateFolderOverride . '/email';
             foreach (craft()->config->get('defaultTemplateExtensions') as $extension) {
                 if (IOHelper::fileExists($emailTemplateFile . '.' . $extension)) {
                     $emailTemplate = craft()->path->getSiteTemplatesPath() . $templateFolderOverride . '/';
                 }
             }
         }
         // Set our Sprout Forms Email Template path
         craft()->path->setTemplatesPath($emailTemplate);
         $email->htmlBody = craft()->templates->render('email', array('formName' => $form->name, 'tabs' => $tabs, 'element' => $entry));
         craft()->path->setTemplatesPath(craft()->path->getCpTemplatesPath());
         $post = (object) $_POST;
         $email->fromEmail = $form->notificationSenderEmail;
         $email->fromName = $form->notificationSenderName;
         $email->subject = $form->notificationSubject;
         // Has a custom subject been set for this form?
         if ($form->notificationSubject) {
             try {
                 $email->subject = craft()->templates->renderObjectTemplate($form->notificationSubject, $post);
             } catch (\Exception $e) {
                 SproutFormsPlugin::log($e->getMessage(), LogLevel::Error);
             }
         }
         // custom replyTo has been set for this form
         if ($form->notificationReplyToEmail) {
             try {
                 $email->replyTo = craft()->templates->renderObjectTemplate($form->notificationReplyToEmail, $post);
                 if (!filter_var($email->replyTo, FILTER_VALIDATE_EMAIL)) {
                     $email->replyTo = null;
                 }
             } catch (\Exception $e) {
                 SproutFormsPlugin::log($e->getMessage(), LogLevel::Error);
             }
         }
         foreach ($recipients as $emailAddress) {
             try {
                 $email->toEmail = craft()->templates->renderObjectTemplate($emailAddress, $post);
                 if (filter_var($email->toEmail, FILTER_VALIDATE_EMAIL)) {
                     craft()->email->sendEmail($email, array('sproutFormsEntry' => $entry));
                 }
             } catch (\Exception $e) {
                 SproutFormsPlugin::log($e->getMessage(), LogLevel::Error);
             }
         }
     }
 }