Validate a variable (placeholder) in a translated content

@param $translatedContents An array containing translated content
@param $mailVariable thevariable to validate

@return array
187146
public function validateMailVariable(array $translatedContents, $mailVariable)
    {
        $languages = array_keys($translatedContents);
        $errors = array();
        $voidCount = 0;

        foreach ($languages as $language) {
            if ($translatedContents[$language]['content'] !== '') {
                if (!strpos($translatedContents[$language]['content'], $mailVariable)) {
                    $errors[$language]['content'][] = 'missing_' . $mailVariable;
                }
            } else {
                $voidCount++;
            }

            if ($voidCount === count($languages)) {
                $errors['no_content'] = 'need_at_least_one_translation';
            }
        }

        return $errors;
    }
267608
public function getTranslatedContent(string $from, string $to, string $remoteServiceKey, Content $content): Content
    {
        $translatedFields = $this->getTranslatedFields($from, $to, $remoteServiceKey, $content);

        $contentService                           = $this->repository->getContentService();
        $contentDraft                             = $contentService->createContentDraft($content->contentInfo);
        $contentUpdateStruct                      = $contentService->newContentUpdateStruct();
        $contentUpdateStruct->initialLanguageCode = $to;

        $contentType = $this->repository->getContentTypeService()->loadContentType(
            $content->contentInfo->contentTypeId
        );

        foreach ($contentType->getFieldDefinitions() as $field) {
            /** @var FieldDefinition $field */
            $fieldName = $field->identifier;
            $newValue  = $translatedFields[$fieldName] ?? $content->getFieldValue($fieldName);
            $contentUpdateStruct->setField($fieldName, $newValue);
        }

        return $contentService->updateContent($contentDraft->versionInfo, $contentUpdateStruct);
    }
757558
public function _($translateKey, $defaultTranslation = "", $placeholders = null)
	{
		$translation = $translateKey;
		
		if (is_array($defaultTranslation) && $placeholders === null) {
			$placeholders = $defaultTranslation;
		} else {
			if ($defaultTranslation!="") {
				$translation = $defaultTranslation;
			}
		}
		if ($this->exists($translateKey)) {
			$translation = $this->_translate[$translateKey];
		}
		return $this->replacePlaceholders($translation, $placeholders);
	}
87460
public function mailto($content, $mail, array $options = []) {
        if ($content === $mail) {
            throw new \RuntimeException('El contenido no debe ser una direcci&oacute;n de email, pruebe "Contacteme"');
        }
        $data = explode('@', $mail);
        
        $user = $data[0];
        $server = key_exists(1, $data) ? explode('.', $data[1]) : [];
        
        $config = [
            'onclick' => 'this.href=\'mailto:\' + \'' 
                . $user . '\' + \'@\' + \'' 
                . (key_exists(0, $server) ? $server[0] : '') . '\' + \'.\' + \''
                . (key_exists(1, $server) ? $server[1] : '') . '\'',
            'rel' => 'nofollow'
        ] + $options;
        
        return $this->link($content, '', $config);
    }
253101
function contentObjectName( eZContentObject $contentObject, $version = false, $translation = false )
    {
        $contentObjectNamePattern = $this->ContentObjectName;

        $ini = eZINI::instance();
        $length = (int) $ini->variable('ContentSettings', 'ContentObjectNameLimit');
        $sequence = $ini->variable('ContentSettings', 'ContentObjectNameLimitSequence');
        if ( $length < 1 || $length > self::CONTENT_OBJECT_NAME_MAX_LENGTH )
        {
            $length = self::CONTENT_OBJECT_NAME_MAX_LENGTH;
        }
        $nameResolver = new eZNamePatternResolver( $contentObjectNamePattern, $contentObject, $version, $translation );
        $contentObjectName = $nameResolver->resolveNamePattern( $length, $sequence );

        return $contentObjectName;
    }
201546
public static function type_json_encode($var, array $settings)
	{
		$var = json_encode($var);

		if (array_key_exists('character_maximum_length', $settings))
		{
			$length  = intval($settings['character_maximum_length']);
			if ($length > 0 and strlen($var) > $length)
			{
				throw new InvalidContentType('Value could not be JSON encoded, exceeds max string length for field.');
			}
		}

		return $var;
	}
555136
public function translate($template, $placeholders = null)
    {
        $context = $this->_context;

        $locale = $context->locale ?: $this->getLocale();

        if ($pos = strpos($locale, '-')) {
            $fallback = substr($locale, 0, $pos);
        } else {
            $fallback = null;
        }

        if ($this->_messages === null) {
            foreach ($this->_files as $file) {
                $messages = [];
                $file = $this->alias->resolve("$file/$locale.php");
                if (is_file($file)) {
                    /** @noinspection PhpIncludeInspection */
                    $messages = require $file;
                } elseif ($fallback) {
                    $file = $this->alias->resolve("$file/$fallback.php");
                    if (is_file($file)) {
                        /** @noinspection PhpIncludeInspection */
                        $messages = require $file;
                    }
                }

                if ($messages) {
                    if ($this->_messages) {
                        /** @noinspection SlowArrayOperationsInLoopInspection */
                        $this->_messages = array_merge($this->_messages, $messages);
                    } else {
                        $this->_messages = $messages;
                    }
                }
            }
        }

        $message = isset($this->_messages[$template]) ? $this->_messages[$template] : $template;

        if ($placeholders) {
            $replaces = [];

            if (strpos($message, ':') !== false) {
                foreach ($placeholders as $k => $v) {
                    $replaces[':' . $k] = $v;
                }
            }

            if (strpos($message, '{') !== false) {
                foreach ($placeholders as $k => $v) {
                    $replaces['{' . $k . '}'] = $v;
                }
            }

            return strtr($message, $replaces);
        } else {
            return $message;
        }
    }
1035385
public function afterGetVariables(\Magento\Email\Block\Adminhtml\Template\Edit\Form $subject, $result)
    {
        $additionalConfigValues = $this->variables->getAdditionalConfigVariables();
        $optionArray = [];
        foreach ($additionalConfigValues as $variable) {
            $optionArray[] = [
                'value' => '{{config path="' . $variable['value'] . '"}}',
                'label' => $variable['label'],
            ];
        }
        if ($optionArray) {
            $result[] = [
                'label' => __('Imprint'),
                'value' => $optionArray,
            ];
        }
        return $result;
    }
1346500
public function transformVariables($message)
    {
        $patterns = [];
        $replacements = [];

        preg_match_all(static::VARIABLE_REGEX, $message, $matches);
        foreach ($matches[0] as $variable) {
            $replacements[] = $this->values[$variable];
            $patterns[] = '#' . preg_quote($variable) . '#';
        }
        $message = preg_replace($patterns, $replacements, $message);

        return $message;
    }
985363
protected function emailToArray($var)
    {
        if ($var === null) {
            return null;
        }
        if (!is_string($var) && !is_array($var)) {
            throw new InvalidArgumentException(
                sprintf('Email address must be an array or a string. (%s given)', gettype($var))
            );
        }

        // Assuming nobody's gonna set an email that is just a display name
        if (is_string($var)) {
            $regexp = '/([\w\s\'\"-_]+[\s]+)?(<)?(([\w-\._\+]+)@((?:[\w-_]+\.)+)([a-zA-Z]{2,4}))?(>)?/u';
            preg_match($regexp, $var, $out);
            $arr = [
                'email' => (isset($out[3]) ? trim($out[3]) : ''),
                'name'  => (isset($out[1]) ? trim(trim($out[1]), '\'"') : '')
            ];
        } else {
            $arr = $var;
        }

        if (!isset($arr['name'])) {
            $arr['name'] = '';
        }

        return $arr;
    }
703259
public function toMail($notifiable)
    {
        $mail = (new MailMessage())
            ->subject($this->subject)
            ->markdown($this->template, [
                'subject'    => $this->subject,
                'content'    => $this->content,
                'link'       => $this->link,
                'link_label' => $this->link_label,
                'data'       => $this->data,
            ]);

        if ($this->cc) {
            $mail->cc($this->cc);
        }

        if ($this->bcc) {
            $mail->bcc($this->bcc);
        }

        if ($this->attachments) {
            if (is_array($this->attachments)) {
                foreach ($this->attachments as $attachment) {
                    $mail->attach($attachment);
                }
            } else {
                $mail->attach($this->attachments);
            }
        }

        return $mail;
    }
237000
protected function fillContentVariables()
    {
        $contentVariables = array();
        $expectedVariables = array( 'Translation', 'OutputFormat' );

        foreach( $expectedVariables as $variable )
        {
            if( isset( $_GET[$variable] ) )
            {
                // Extract and organize variables as expected
                switch( $variable )
                {
                    case 'Translation': // @TODO => Make some control on the locale provided
                    default:
                        $contentVariables[$variable] = $_GET[$variable];
                }

                unset( $_GET[$variable] );
            }
            else
            {
                $contentVariables[$variable] = null;
            }
        }

        return $contentVariables;
    }
1111479
protected void validateMessage(Message receivedMessage, TestContext context) throws IOException {
        // extract variables from received message content
        for (VariableExtractor variableExtractor : variableExtractors) {
            variableExtractor.extractVariables(receivedMessage, context);
        }

        if (validationCallback != null) {
            if (StringUtils.hasText(receivedMessage.getName())) {
                context.getMessageStore().storeMessage(receivedMessage.getName(), receivedMessage);
            } else {
                context.getMessageStore().storeMessage(context.getMessageStore().constructMessageName(this, getOrCreateEndpoint(context)), receivedMessage);
            }

            validationCallback.validate(receivedMessage, context);
        } else {
            Message controlMessage = createControlMessage(context, messageType);
            if (StringUtils.hasText(controlMessage.getName())) {
                context.getMessageStore().storeMessage(controlMessage.getName(), receivedMessage);
            } else {
                context.getMessageStore().storeMessage(context.getMessageStore().constructMessageName(this, getOrCreateEndpoint(context)), receivedMessage);
            }

            if (!CollectionUtils.isEmpty(validators)) {
                for (MessageValidator<? extends ValidationContext> messageValidator : validators) {
                    messageValidator.validateMessage(receivedMessage, controlMessage, context, validationContexts);
                }

                if (validators.parallelStream()
                                .map(Object::getClass)
                                .noneMatch(DefaultMessageHeaderValidator.class::isAssignableFrom)) {
                    MessageValidator defaultMessageHeaderValidator = context.getMessageValidatorRegistry().getDefaultMessageHeaderValidator();
                    if (defaultMessageHeaderValidator != null) {
                        defaultMessageHeaderValidator.validateMessage(receivedMessage, controlMessage, context, validationContexts);
                    }
                }
            } else {
                List<MessageValidator<? extends ValidationContext>> validators =
                        context.getMessageValidatorRegistry().findMessageValidators(messageType, receivedMessage);

                if (validators.isEmpty()) {
                    if (controlMessage.getPayload() instanceof String &&
                            StringUtils.hasText(controlMessage.getPayload(String.class))) {
                        throw new CitrusRuntimeException(String.format("Unable to find proper message validator for message type '%s' and validation contexts '%s'", messageType, validationContexts));
                    } else if (validationContexts.stream().anyMatch(item -> JsonPathMessageValidationContext.class.isAssignableFrom(item.getClass())
                            || XpathMessageValidationContext.class.isAssignableFrom(item.getClass())
                            || ScriptValidationContext.class.isAssignableFrom(item.getClass()))) {
                        throw new CitrusRuntimeException(String.format("Unable to find proper message validator for message type '%s' and validation contexts '%s'", messageType, validationContexts));
                    } else {
                        log.warn(String.format("Unable to find proper message validator for message type '%s' and validation contexts '%s'", messageType, validationContexts));
                    }
                }

                for (MessageValidator<? extends ValidationContext> messageValidator : validators) {
                    messageValidator.validateMessage(receivedMessage, controlMessage, context, validationContexts);
                }
            }
        }
    }
454649
public function isValid($translations)
    {
        $this->message = null;

        // check if any translation contains restricted script tags
        $serializedStrings = serialize($translations);
        $invalids = array("<script", 'document.', 'javascript:', 'src=', 'background=', 'onload=');

        foreach ($invalids as $invalid) {
            if (stripos($serializedStrings, $invalid) !== false) {
                $this->message = 'script tags restricted for language files';
                return false;
            }
        }

        return true;
    }
469789
private function resetContent(Content $content, array $translatedContents)
    {
        foreach ($translatedContents as $lang => $translatedContent) {
            $this->updateTranslation($content, $translatedContent, $lang, true);
        }

        $this->updateTranslation($content, $translatedContents['en']);

        return $content;
    }
311083
public function ValidateData($sFormDataName = null)
    {
        if (is_null($sFormDataName)) {
            $sFormDataName = TdbDataExtranetUser::MSG_FORM_FIELD;
        }
        $bIsValid = parent::ValidateData($sFormDataName);
        $oMsgManager = TCMSMessageManager::GetInstance();

        // check postal code for country
        $bHasCountry = (array_key_exists('data_country_id', $this->sqlData) && !empty($this->sqlData['data_country_id']));
        $bHasPostalcode = (array_key_exists('postalcode', $this->sqlData) && !empty($this->sqlData['postalcode']));
        if ($bHasCountry && $bHasPostalcode) {
            $oCountry = TdbDataCountry::GetNewInstance();
            /** @var $oCountry TdbDataCountry */
            if ($oCountry->Load($this->sqlData['data_country_id'])) {
                if (!$oCountry->IsValidPostalcode($this->sqlData['postalcode'])) {
                    $oMsgManager->AddMessage($sFormDataName.'-postalcode', 'ERROR-USER-FIELD-INVALID-POSTALCODE');
                    $bIsValid = false;
                }
            }
        }

        return $bIsValid;
    }
1153598
function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $classAttribute = $contentObjectAttribute->contentClassAttribute();
        if ( $http->hasPostVariable( $base . '_data_text_' . $contentObjectAttribute->attribute( 'id' ) ) )
        {
            $email = $http->postVariable( $base . '_data_text_' . $contentObjectAttribute->attribute( 'id' ) );

            $trimmedEmail = trim( $email );

            if ( $trimmedEmail == "" )
            {
                // we require user to enter an address only if the attribute is not an informationcollector
                if ( !$classAttribute->attribute( 'is_information_collector' ) and
                     $contentObjectAttribute->validateIsRequired() )
                {
                    $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                         'The email address is empty.' ) );
                    return eZInputValidator::STATE_INVALID;
                }
            }
            else
            {
                // if the entered address is not empty then we should validate it in any case
                return $this->validateEMailHTTPInput( $trimmedEmail, $contentObjectAttribute );
            }
        }
        else if ( !$classAttribute->attribute( 'is_information_collector' ) and $contentObjectAttribute->validateIsRequired() )
        {
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes', 'Missing email input.' ) );
            return eZInputValidator::STATE_INVALID;
        }

        return eZInputValidator::STATE_ACCEPTED;
    }