Get an email from the archive by its reference

@param string $sRef  The email's reference
@param array  $aData The data array

@return mixed        stdClass on success, false on failure
@throws \Nails\Common\Exception\FactoryException
8335
public function getByRef($sRef, $aData = [])
    {
        if (empty($aData['where'])) {
            $aData['where'] = [];
        }

        $aData['where'][] = [$this->sTableAlias . '.ref', $sRef];

        $aEmails = $this->getAll(null, null, $aData);

        return !empty($aEmails) ? reset($aEmails) : false;
    }
1162710
public static function populatePageData(array &$aData)
    {
        /** @var Locale $oLocale */
        $oLocale       = Factory::service('Locale');
        $aData['page'] = (object) [
            'title'     => '',
            'html_lang' => $oLocale->get()->getLanguage(),
            'seo'       => (object) [
                'title'       => '',
                'description' => '',
                'keywords'    => '',
            ],
        ];
    }
19240
public function update($iRefundId, array $aData = []): bool
    {
        $oDb = Factory::service('Database');

        try {

            $oDb->trans_begin();

            unset($aData['ref']);

            $bResult = parent::update($iRefundId, $aData);

            if (!$bResult) {
                throw new PaymentException('Failed to update refund.', 1);
            }

            $oDb->trans_commit();
            $this->triggerEvent(
                Events::REFUND_UPDATED,
                [$this->getRefundForEvent($iRefundId)]
            );

            return $bResult;

        } catch (\Exception $e) {
            $oDb->trans_rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }
354679
public function getEmail($reference)
    {
        if (!isset($this->emails[$reference])) {
            $this->emails[$reference] = $this->em->getRepository($this->options['email_class'])->findOneByReference($reference);
        }

        $email = $this->emails[$reference];

        if (!$email instanceof EmailInterface) {
            throw new ReferenceNotFoundException($reference, sprintf('Reference "%s" does not exist for email.', $reference));
        }

        return $email;
    }
597721
public static function copy($src, $dest, $force = false)
	{
		// Check src path
		if (!is_readable($src))
		{
			throw new \UnexpectedValueException(__METHOD__ . ': Cannot find or read file: ' . $src);
		}

		// Check folder exists
		$dir = dirname($dest);

		if (!is_dir($dir))
		{
			Dir::create($dir);
		}

		// Check is a folder or file
		if (file_exists($dest))
		{
			if ($force)
			{
				FileHelper::delete($dest);
			}
			else
			{
				throw new Exception($dest . ' has exists, copy faieed.');
			}
		}

		if (!@ copy($src, $dest))
		{
			throw new Exception(__METHOD__ . ': Copy failed.');
		}

		return true;
	}
940568
public function getList($email = NULL, $includeExpired = false, $subaccount = NULL) {
        return $this->listRejects($email, $includeExpired, $subaccount);
    }
1101039
function ldap_get_one_entry_raw($id = "GENERIC", $first = FALSE, $srch_id = FALSE, $link_identifier = FALSE)
	{
        $linkIdentifier = ((FALSE !== $link_identifier) ? $link_identifier : $this->_conn_paged);
        $rawData = FALSE;
        if ($srch_id) {
            if ($first)
            {
                $this->_entry_identifier[$id] = ldap_first_entry($linkIdentifier, $srch_id);
            }
            elseif (FALSE !== $this->_entry_identifier[$id]) {
                $this->_entry_identifier[$id] = ldap_next_entry($linkIdentifier, $this->_entry_identifier[$id]);
            }
            if (FALSE !== $this->_entry_identifier[$id]) {
                $rawData = array();
                $rawData['count'] = 0; // To be compatible with the old data organisation (counter at the beginning)
                $attributes = ldap_get_attributes($linkIdentifier, $this->_entry_identifier[$id]);
                $distinguishedname_in_attributes = FALSE;

// echo "DEBUG attributes\n";
// print_r($attributes);
                for($j=0; $j<$attributes['count']; $j++) {
                    if ('distinguishedname' == strtolower($attributes[$j]))
                    {
                        $distinguishedname_in_attributes = TRUE;
                    }
                    $values = ldap_get_values_len($linkIdentifier, $this->_entry_identifier[$id],$attributes[$j]);
                    $rawData[strtolower($attributes[$j])] = $values;
                    $rawData[strtolower($attributes[$j])]['count'] = (isset($values['count'])?$values['count']:0);
                }
                if (!$distinguishedname_in_attributes)
                {
                    $rawData['distinguishedname'][0] = ldap_get_dn($linkIdentifier, $this->_entry_identifier[$id]);
                    $rawData['distinguishedname']['count'] = 1;
                    $attributes['count']++;
                }
                $rawData['count'] = $attributes['count'];
            }
        }
		return $rawData;
	}
1117339
protected function saveEvent(array $aData)
    {
        // Set up binding params
        $aValues = $aExecParams = [];
        $bUpdating = false;

        if ($aData['id'] ?? false) {
            $bUpdating = true;
            $aExecParams[':id_value'] = $aData['id'];
            unset($aData['id']);
        }

        foreach ($aData as $strKey => $mValue) {
            $strValueParam = ':' . $strKey . '_value';
            $aValues[] = $bUpdating
                ? '`' . $strKey . '` = ' . $strValueParam
                : $strValueParam;
            $aExecParams[$strValueParam] = $mValue;
        }

        $strQuery = $bUpdating
            ? 'UPDATE sked_events SET ' . implode(',', $aValues)
                . ' WHERE `id` = :id_value'
            : 'INSERT INTO sked_events (`' . implode('`,`', array_keys($aData))
                . '`) VALUES (' . implode(',', $aValues) . ')';
        return $this->queryPDO($strQuery, $aExecParams);
    }
1073866
public function create($aData = [], $bReturnObject = false)
    {
        //  Prepare slug
        $counter = 0;

        if (!$this->isPreviewMode && empty($aData['title'])) {
            $this->setError('Title missing');
            return false;
        }

        if (empty($aData['blog_id'])) {
            $this->setError('Blog ID missing');
            return false;
        }

        // --------------------------------------------------------------------------

        /**
         * Validate or generate a slug
         */
        $sSlug  = !empty($aData['slug']) ? $aData['slug'] : '';
        $sTitle = !empty($aData['title']) ? $aData['title'] : '';

        $aData['slug'] = $this->validateSlug($sSlug, $sTitle);

        if (!$aData['slug']) {

            return false;
        }

        // --------------------------------------------------------------------------

        //  Set data
        $oDb = Factory::service('Database');
        $oDb->set('blog_id', $aData['blog_id']);
        $oDb->set('title', $aData['title']);
        $oDb->set('slug', $aData['slug']);

        if (isset($aData['type'])) {
            $oDb->set('type', $aData['type']);
        }

        if (isset($aData['body'])) {
            $oDb->set('body', $aData['body']);
        }

        if (isset($aData['seo_title'])) {
            $oDb->set('seo_title', $aData['title']);
        }

        if (isset($aData['seo_description'])) {
            $oDb->set('seo_description', $aData['seo_description']);
        }

        if (isset($aData['seo_keywords'])) {
            $oDb->set('seo_keywords', $aData['seo_keywords']);
        }

        if (isset($aData['is_published'])) {
            $oDb->set('is_published', $aData['is_published']);
        }

        //  Safety first!
        if (array_key_exists('image_id', $aData)) {

            $imageId = (int) $aData['image_id'];
            $imageId = !$imageId ? null : $imageId;

            $oDb->set('image_id', $imageId);
        }

        if (isset($aData['video_url'])) {
            $oDb->set('video_url', $aData['video_url']);
        }

        if (isset($aData['audio_url'])) {
            $oDb->set('audio_url', $aData['audio_url']);
        }

        //  Excerpt
        if (!empty($aData['excerpt'])) {
            $oDb->set('excerpt', trim($aData['excerpt']));
        } elseif (!empty($aData['body'])) {
            $oDb->set('excerpt', word_limiter(trim(strip_tags($aData['body']))), 50);
        }

        //  Publish date
        if (!empty($aData['is_published']) && isset($aData['published'])) {

            //  Published with date set
            $published = strtotime($aData['published']);

            if ($published) {

                $published = toNailsDatetime($aData['published']);
                $oDb->set('published', $published);

            } else {

                //  Failed, use NOW();
                $oDb->set('published', 'NOW()', false);
            }

        } else {
            //  No date set, use NOW()
            $oDb->set('published', 'NOW()', false);
        }

        if (isset($aData['comments_enabled'])) {
            $oDb->set('comments_enabled', (bool) $aData['comments_enabled']);
        }

        if (isset($aData['comments_expire'])) {
            if (empty($aData['comments_expire'])) {
                $oDb->set('comments_expire', null);
            } else {
                $oDb->set('comments_expire', $aData['comments_expire']);
            }
        }

        $oDb->set('created', 'NOW()', false);
        $oDb->set('modified', 'NOW()', false);
        $oDb->set('created_by', activeUser('id'));
        $oDb->set('modified_by', activeUser('id'));

        $oDb->insert($this->table);

        if ($oDb->affected_rows()) {

            $id = $oDb->insert_id();

            //  Add Gallery items, if any
            if (!empty($aData['gallery'])) {

                $galleryData = [];

                foreach ($aData['gallery'] as $order => $imageId) {
                    if ((int) $imageId) {
                        $galleryData[] = ['post_id' => $id, 'image_id' => $imageId, 'order' => $order];
                    }
                }

                if ($galleryData) {
                    $oDb->insert_batch($this->tableImg, $galleryData);
                }
            }

            // --------------------------------------------------------------------------

            //  Add Categories and tags, if any
            if (!empty($aData['categories'])) {

                $categoryData = [];

                foreach ($aData['categories'] as $catId) {
                    $categoryData[] = ['post_id' => $id, 'category_id' => $catId];
                }

                $oDb->insert_batch($this->tableCat, $categoryData);
            }

            if (!empty($aData['tags'])) {

                $tagData = [];

                foreach ($aData['tags'] as $tagId) {
                    $tagData[] = ['post_id' => $id, 'tag_id' => $tagId];
                }

                $oDb->insert_batch($this->tableTag, $tagData);
            }

            // --------------------------------------------------------------------------

            //  Add associations, if any
            if (!empty($aData['associations'])) {

                //  Fetch associations config
                $oConfig      = Factory::service('Config');
                $associations = $oConfig->item('blog_post_associations');

                foreach ($aData['associations'] as $index => $association) {

                    if (!isset($associations[$index])) {
                        continue;
                    }

                    $associationData = [];

                    foreach ($association as $associationId) {
                        $associationData[] = ['post_id' => $id, 'associated_id' => $associationId];
                    }

                    if ($associationData) {
                        $oDb->insert_batch($associations[$index]->target, $associationData);
                    }
                }
            }

            // --------------------------------------------------------------------------

            return $bReturnObject ? $this->getById($id) : $id;

        } else {
            return false;
        }
    }
887194
public static function factoryFromString($str, $associatedObject = null)
    {
        $obj = null;

        if (preg_match('/_?(cpt|tax)_(\w+)/', $str, $matches)) {
            $obj = self::factory($matches[2]);
        } elseif (preg_match('/_?(post|page)/', $str, $matches)) {
            $obj = self::factory($matches[1]);
        }

        if (!is_null($obj)) {

            if (!is_null($associatedObject)) {
                $obj->bindToObject($associatedObject);
            }

            return $obj;
        }

        throw new Exception("Unknown pattern sent to ModelEntity::factoryFromString: " . $str);
    }
29043
protected function getEmail(): AbstractMailAdapter
    {
        if (isset($this->config[self::FN_CONFIG_KEY])) {
            $mail = call_user_func($this->config[self::FN_CONFIG_KEY], $this->messages);

            if (!($mail instanceof AbstractMailAdapter)) {
                throw new Exception('Function defined in mail config under ' . self::FN_CONFIG_KEY . ' must return instance of \Koldy\Mail\Adapter\AbstractMailAdapter; ' . gettype($mail) . ' given');
            }

            return $mail;
        }

        if (count($this->messages) == 0) {
            throw new Exception('Can not prepare e-mail instance when there\'s no log messages added from before; try not to call getEmail() if messages array is empty');
        }

        $mail = Mail::create($this->config['adapter']);
        $allMessages = [];
        $firstMessage = $this->messages[0];

        foreach ($this->messages as $msg) {
            $allMessages[] = $msg->getDefaultLine();
        }

        $body = implode("\n", $allMessages);

        $level = strtoupper($firstMessage->getLevel());
        $subject = "[{$level}] {$firstMessage->getMessage()}";

        $body .= "\n\n----------\n";
        $body .= Server::signature();
        $subject = Util::truncate($subject, 140);
        $domain = Application::getDomain();

        $mail->from('alert@' . $domain, $domain)->subject($subject)->body($body);

        $to = $this->config['to'];
        if (!is_array($this->config['to']) && strpos($this->config['to'], ',') !== false) {
            $to = explode(',', $this->config['to']);
        }

        if (is_array($to)) {
            foreach ($to as $toEmail) {
                $mail->to(trim($toEmail));
            }
        } else if (is_string($to)) {
            $mail->to(trim($to));
        } else {
            throw new Exception('Unable to prepare log via email, expected array or string for \'to\', got ' . gettype($to));
        }

        return $mail;
    }
773543
public function getUserEmail(TokenCredentials $tokenCredentials, $force = false)
    {
        $data = $this->fetchUserDetails($tokenCredentials, $force);

        return $this->userEmail($data, $tokenCredentials);
    }
1135331
public function execute($aData = [])
    {
        $oDb        = Factory::service('Database');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $oResponse  = Factory::factory('DataExportSourceResponse', 'nails/module-admin');

        $oSource = $oDb
            ->select('u.id, u.first_name, u.last_name, ue.email')
            ->join(NAILS_DB_PREFIX . 'user_email ue', 'u.id = ue.user_id AND ue.is_primary = 1', 'LEFT')
            ->get($oUserModel->getTableName() . ' u');

        return $oResponse
            ->setLabel($this->getLabel())
            ->setFileName($this->getFileName())
            ->setFields(['id', 'first_name', 'last_name', 'email'])
            ->setSource($oSource);
    }
902362
protected function &_NewElement(&$aData)
    {
        $oElement = false;
        // try to fetch the element from _items first
        $sTableObject = $this->sTableObject;

        if (!empty($aData['pkg_shop_listfilter_item_type'])) {
            $oListfilterItemType = TdbPkgShopListfilterItemType::GetNewInstance($aData['pkg_shop_listfilter_item_type']);
            $sTableObject = $oListfilterItemType->fieldClass;
        }

        if (!class_exists($sTableObject, false)) {
        }

        if (!is_null($this->sTableName)) {
            $oElement = new $sTableObject();
            $oElement->table = $this->sTableName;
        } else {
            $oElement = new $sTableObject();
        }
        /** @var $oElement TCMSRecord */
        $oElement->SetLanguage($this->iLanguageId);
        $oElement->LoadFromRow($aData);

        return $oElement;
    }
518696
protected function getCountCommonCompileLikes(array &$aData)
    {
        $oDb = Factory::service('Database');

        $aLikes = [
            'like'        => 'AND',
            'or_like'     => 'OR',
            'not_like'    => 'AND',
            'or_not_like' => 'OR',
        ];

        $aLikeCompiled = [];

        foreach ($aLikes as $sLikeType => $sLikeGlue) {

            if (!empty($aData[$sLikeType])) {

                $aLikeCompiled[$sLikeType] = [];

                if (is_array($aData[$sLikeType])) {

                    /**
                     * The value is an array. For each element we need to compile as appropriate
                     * and add to $aLikeCompiled.
                     */

                    foreach ($aData[$sLikeType] as $mWhere) {

                        if (is_string($mWhere)) {

                            /**
                             * The value is a straight up string, assume this is a compiled
                             * where string,
                             */

                            $aLikeCompiled[$sLikeType][] = $mWhere;

                        } else {

                            /**
                             * The value is an array, try and determine the various parts
                             * of the query. We use strings which are unlikely to be found
                             * as falsey values (such as null) are perfectly likely.
                             */

                            //  Work out column
                            $mColumn = isset($mWhere['column']) ? $mWhere['column'] : '[NAILS-COL-NOT-FOUND]';

                            if ($mColumn === '[NAILS-COL-NOT-FOUND]') {
                                $mColumn = isset($mWhere[0]) && is_string($mWhere[0]) ? $mWhere[0] : null;
                            }

                            //  Work out value
                            $mVal = isset($mWhere['value']) ? $mWhere['value'] : '[NAILS-VAL-NOT-FOUND]';

                            if ($mVal === '[NAILS-VAL-NOT-FOUND]') {
                                $mVal = isset($mWhere[1]) ? $mWhere[1] : null;
                            }

                            //  Escaped?
                            $bEscape = isset($mWhere['escape']) ? (bool) $mWhere['escape'] : '[NAILS-ESCAPE-NOT-FOUND]';

                            if ($bEscape === '[NAILS-ESCAPE-NOT-FOUND]') {
                                $bEscape = isset($mWhere[2]) ? $mWhere[2] : true;
                            }

                            if ($bEscape) {
                                $mVal = $oDb->escape_like_str($mVal);
                            }

                            //  If the $mColumn is an array then we should concat them together
                            if (is_array($mColumn)) {
                                $mColumn = 'CONCAT_WS(" ", ' . implode(',', $mColumn) . ')';
                            }

                            //  Got something?
                            if ($mColumn) {
                                switch ($sLikeType) {

                                    case 'like' :
                                    case 'or_like' :
                                        $aLikeCompiled[$sLikeType][] = $mColumn . ' LIKE "%' . $mVal . '%"';
                                        break;

                                    case 'not_like' :
                                    case 'or_not_like' :
                                        $aLikeCompiled[$sLikeType][] = $mColumn . ' NOT LIKE "%' . $mVal . '%"';
                                        break;
                                }
                            }
                        }
                    }

                } elseif (is_string($aData[$sLikeType])) {

                    /**
                     * The value is a straight up string, assume this is a compiled
                     * where string,
                     */

                    $aLikeCompiled[$sLikeType][] = $aData[$sLikeType];
                }
            }
        }

        /**
         * Now we need to compile all the conditionals into one big super query.
         * $aWhereStr is an array of the compressed where strings... will make
         * sense shortly...
         */

        if (!empty($aLikeCompiled)) {

            $aWhereStr = [];

            foreach ($aLikeCompiled as $sLikeType => $sValue) {
                $aWhereStr[] = '(' . implode(' ' . $aLikes[$sLikeType] . ' ', $sValue) . ')';
            }

            //  And reduce $aWhereStr to an actual string, like the name suggests
            $aWhereStr = implode(' AND ', $aWhereStr);
            $oDb->where($aWhereStr);
        }
    }
552461
public static function GetInstanceDataFromSession($sListSessionKey)
    {
        if (!array_key_exists(TdbShopArticleList::SESSIN_DUMP_NAME, $_SESSION)) {
            $_SESSION[TdbShopArticleList::SESSIN_DUMP_NAME] = array();
        }
        $aList = null;
        if (array_key_exists($sListSessionKey, $_SESSION[TdbShopArticleList::SESSIN_DUMP_NAME])) {
            $aList = $_SESSION[TdbShopArticleList::SESSIN_DUMP_NAME][$sListSessionKey];
        }

        return $aList;
    }
640564
public function getAssertionsByEmailAddress($emailAddresses)
	{
		if (!$this->credentialsSet())
		{
			throw new Exception('You need to set the credentials first.');
		}

		if (!is_array($emailAddresses))
		{
			$emailAddresses = array($emailAddresses);
		}

		$query_params = implode('%20', $emailAddresses);
		$url = self::PASSPORT_API_ENDPOINT . "assertions?emailAddresses=" . $query_params;

		if ($this->request_type == 'oauth' && is_a($this->request, 'oauth'))
		{
			$this->request->setAuthType(OAUTH_AUTH_TYPE_URI);
			try
			{
				$this->request->fetch($url, null, OAUTH_HTTP_METHOD_GET, array('Content-Type' => 'application/json'));
			}
			catch (Exception $e)
			{
				throw new Exception('Assertations by email request failed.');
			}

			$response = json_decode($this->request->getLastResponse());
		}
		else if ($this->request_type == 'curl' && get_resource_type($this->request) == 'curl')
		{
			curl_setopt($this->request, CURLOPT_POST, false);
			curl_setopt($this->request, CURLOPT_URL, $url);
			curl_setopt($this->request, CURLOPT_RETURNTRANSFER, true);

			$response = curl_exec($this->request);
			$response = json_decode($response);
		}
		else
		{
			throw new Exception('Unsupported request type');
		}

		return $response;
	}