Translate a messege from the master domain

Pattern borrowed from WordPress
422272
public static function __($message, $textdomain=false) {
        global $CFG, $PDOX, $TSUGI_LOCALE, $TSUGI_LOCALE_RELOAD, $TSUGI_TRANSLATE;
    
        // If we have been asked to do some translation
        if ( isset($CFG->checktranslation) && $CFG->checktranslation && isset($PDOX) ) 
        {
            $string_sha = U::lti_sha256($message);
            $domain = $textdomain;
            if ( ! $domain ) $domain = textdomain(NULL);
            if ( $domain ) {
                $stmt = $PDOX->queryReturnError("INSERT INTO {$CFG->dbprefix}tsugi_string
                        (domain, string_text, string_sha256) VALUES ( :DOM, :TEXT, :SHA)
                        ON DUPLICATE KEY UPDATE updated_at = NOW()",
                    array(
                        ':DOM' => $domain,
                        ':TEXT' => $message,
                        ':SHA' => $string_sha
                    )
                );
            }
        }

        // Setup Text domain late...
        if ( $TSUGI_LOCALE_RELOAD ) {
            self::setupTextDomain();
        }

        if ( isset($TSUGI_TRANSLATE) && $TSUGI_TRANSLATE ) {
            $retval = $TSUGI_TRANSLATE->trans($message);
            // error_log("DOM=$TSUGI_LOCALE msg=$message trans=$retval");
            return $retval;
        }

        if ( ! function_exists('gettext')) return $message;
        if ( $textdomain === false ) {
            return gettext($message);
        } else {
            return dgettext($textdomain, $message);
        }
    }
26221
function translate( $context, $source, $comment = null )
    {
        $msg = $this->findMessage( $context, $source, $comment );
        if ( $msg !== null )
        {
            return $msg["translation"];
        }

        return null;
    }
141105
private function retrieve_translation_details() {
		$api_url = $this->get_api_url();

		$resp = wp_remote_get( $api_url );
		if ( is_wp_error( $resp ) || wp_remote_retrieve_response_code( $resp ) !== 200 ) {
			return null;
		}
		$body = wp_remote_retrieve_body( $resp );
		unset( $resp );

		if ( $body ) {
			$body = json_decode( $body );
			if ( empty( $body->translation_sets ) ) {
				return null;
			}
			foreach ( $body->translation_sets as $set ) {
				if ( ! property_exists( $set, 'wp_locale' ) ) {
					continue;
				}

				// For informal and formal locales, we have to complete the locale code by concatenating the slug ('formal' or 'informal') to the xx_XX part.
				if ( $set->slug !== 'default' && strtolower( $this->locale ) === strtolower( $set->wp_locale . '_' . $set->slug ) ) {
					return $set;
				}

				if ( $this->locale === $set->wp_locale ) {
					return $set;
				}
			}
		}

		return null;
	}
509089
def gettext(*args, **kwargs):
    
    key = args[0]
    key_match = TRANSLATION_KEY_RE.match(key)
    translation = _gettext(*args, **kwargs)
    if not key_match or translation != key:
        return translation

    return _get_domain(key_match).gettext(*args, **kwargs)
37416
function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText, translateNamespace) {
          if (translationId) {
            // if translation id starts with '.' and translateNamespace given, prepend namespace
            if (translateNamespace && translationId.charAt(0) === '.') {
              translationId = translateNamespace + translationId;
            }

            $translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText, scope.translateLanguage)
              .then(function (translation) {
                applyTranslation(translation, scope, true, translateAttr);
              }, function (translationId) {
                applyTranslation(translationId, scope, false, translateAttr);
              });
          } else {
            // as an empty string cannot be translated, we can solve this using successful=false
            applyTranslation(translationId, scope, false, translateAttr);
          }
        }
807374
private function getTranslationsForDomain($locale, $domain)
    {
        $allMessages = $this->getTranslationsForLocale($locale);

        if (!array_key_exists($domain, $allMessages)) {
            throw new \Exception('Domain ' . $domain . ' not found in the translations for locale ' . $locale);
        }

        return $allMessages[$domain];
    }
1181387
public function extractTranslatableSiteStrings()
    {
        $app = Application::getFacadeApplication();
        $translations = new Translations();
        $translations->insert('SiteName', $app->make('site')->getSite()->getSiteName());
        $fh = $app->make('helper/file');
        C5TLOptions::setTemporaryDirectory($fh->getTemporaryDirectory());
        $phpParser = new C5TLParserPhp();
        $blockTemplatesParser = new C5TLParserBlockTemplates();
        $themesPresetsParser = new C5TLParserThemePresets();
        $configFilesParser = new C5TLParserConfigFiles();

        $configFilesParser->parseDirectory(DIR_BASE, '', $translations);

        $processApplication = [
            DIRNAME_BLOCKS => [$phpParser, $blockTemplatesParser],
            DIRNAME_ELEMENTS => [$phpParser],
            DIRNAME_CONTROLLERS => [$phpParser],
            DIRNAME_MAIL_TEMPLATES => [$phpParser],
            DIRNAME_PAGE_TYPES => [$phpParser],
            DIRNAME_PAGES => [$phpParser],
            DIRNAME_THEMES => [$phpParser, $themesPresetsParser, $blockTemplatesParser],
            DIRNAME_VIEWS => [$phpParser],
            DIRNAME_CLASSES => [$phpParser]
        ];
        foreach ($processApplication as $dirname => $parsers) {
            if (is_dir(DIR_APPLICATION.'/'.$dirname)) {
                foreach ($parsers as $parser) {
                    /* @var $parser \C5TL\Parser */
                    $fullDirname = DIR_APPLICATION.'/'.$dirname;
                    if (is_dir($fullDirname)) {
                        $parser->parseDirectory(
                            $fullDirname,
                            DIRNAME_APPLICATION.'/'.$dirname,
                            $translations
                        );
                    }
                }
            }
        }

        if (is_dir(DIR_PACKAGES)) {
            $packages = Package::getInstalledList();
            foreach ($packages as $package) {
                $fullDirname = DIR_PACKAGES.'/'.$package->getPackageHandle();
                $phpParser->parseDirectory($fullDirname,
                    DIRNAME_PACKAGES.'/'.$package->getPackageHandle(),
                    $translations
                );
                $packageController = $package->getController();
                $packageController->getTranslatableStrings($translations);
            }
        }

        // Now, we grab dynamic content that's part of our site that we translate dynamically
        $dynamicTranslations = $this->getDynamicTranslations();
        $translations->mergeWith($dynamicTranslations);

        return $translations;
    }
367067
function translate(cond) {

    let result = {};

    // If condition is not an array...
    if (!Array.isArray(cond)) {
        //...then it is a condition cluster
        if (cond.and) {
            result = translateAndList(cond.and)
        }
        else if (cond.or) {
            result = translateOrList(cond.or)
        }
        else {
            //This is an illegal subject.
            throw new Error('Invalid query Object keys. Objects must be either "and" or "or"');
        }
    }
    else {
        //...then it's a singular condition
        assert(cond.length === 3, 'Invalid condition item. Condition items must be an array of 3 items representing field, comparator, and value')

        let fieldName = cond[0];
        fieldName = fieldName.replace('.*', '');
        let comp = cond[1];
        let value = cond[2];

        if (fieldName === 'id') {
            fieldName = '_id';
            value = Array.isArray(value) ? value : new ObjectID(value)
        }

        // construct mini block
        if (comp === '=') {

            if (value === null || value === undefined) {
                value = {};
                value['$exists'] = false;
            }

            result[fieldName] = value;
        } else if (comp === '!=' && (value === null || value === undefined)) {
            let value = {};
            value['$exists'] = true;

            result[fieldName] = value;
        } else if (comp === 'like') {

            result[fieldName] = new RegExp(value);

        } else if (comp === 'nlike') {

            result[fieldName] = {
                $not: new RegExp(value)
            };
        }
        else {
            const subCondBlock = {};

            subCondBlock[convertComp(comp)] = value;

            result[fieldName] = subCondBlock;
        }
    }

    return result;

}
1052717
private function translatePattern()
    {
        $tokenArray = $this->extractTokens( $this->namePattern );
        $objectName = $this->namePattern;

        foreach( $tokenArray as $token )
        {
            $string = $this->resolveToken( $token );
            $objectName = str_replace( $token, $string, $objectName );
        }

        return $objectName;
    }
634119
private function parsePathTranslations($domains)
    {
        $translations = array();
        if (!empty($domains)) {
            foreach ($domains as $domain => $paths) {
                if (strlen($domain) && array_key_exists('template', $paths)) {
                    $this->addPath($paths['template'], $domain);
                    $translations[] = $this->generateTemplate($paths['template'], $domain);
                }
            }
        }

        return $translations;
    }
337857
def get_translations(self, domain=None, locale=None):
        
        if locale is None:

            if self.locale is None:
                return support.NullTranslations()

            locale = self.locale

        if domain is None:
            domain = self.cfg.domain

        if (domain, locale.language) not in self.translations:
            translations = None
            for locales_dir in reversed(self.cfg.locales_dirs):
                trans = support.Translations.load(
                    locales_dir, locales=locale, domain=domain)
                if translations:
                    translations._catalog.update(trans._catalog)
                else:
                    translations = trans

            self.translations[(domain, locale.language)] = translations

        return self.translations[(domain, locale.language)]
1027432
public function dnpgettext($domain, $context, $original, $plural, $value)
    {
        $translation = $this->getTranslation($domain, $context, $original);
        $key = $this->getPluralIndex($domain, $value, $translation === false);

        if (isset($translation[$key]) && $translation[$key] !== '') {
            return $translation[$key];
        }

        return ($key === 0) ? $original : $plural;
    }
586258
public function replacePattern($pattern, Siteroot $siteroot, ElementVersion $elementVersion, $language)
    {
        $replace = [
            '%s' => $siteroot->getTitle(),
            '%b' => $elementVersion->getBackendTitle($language),
            '%p' => $elementVersion->getPageTitle($language),
            '%n' => $elementVersion->getNavigationTitle($language),
            '%r' => $this->projectTitle,
        ];

        return str_replace(array_keys($replace), array_values($replace), $pattern);
    }
551033
def translate_with_context(key, options={})
      # default to an empty scope
      scope = []

      # Use the template for scoping if there is a templ
      unless self.template.nil?
        # The outer scope will typically be the controller name ("blog_posts")
        # but can also be a dir of shared partials ("shared").
        outer_scope = self.template.base_path
        
        # The template will be the view being rendered ("show.erb" or "_ad.erb")
        inner_scope = self.template.name
        
        # Partials template names start with underscore, which should be removed
        inner_scope.sub!(/^_/, '')

        scope = [outer_scope, inner_scope]
      end
      
      # In the case of a missing translation, fall back to letting TranslationHelper
      # put in span tag for a translation_missing.
      begin
        Translator.translate_with_scope(scope, key, options.merge({:raise => true}))
      rescue Translator::TranslatorError, I18n::MissingTranslationData => exc
        # Call the original translate method
        str = translate_without_context(key, options)
        
        # View helper adds the translation missing span like:
        # In strict mode, do not allow TranslationHelper to add "translation missing" span like:
        # <span class="translation_missing">en, missing_string</span>
        if str =~ /span class\=\"translation_missing\"/
          # In strict mode, do not allow TranslationHelper to add "translation missing"
          raise if Translator.strict_mode?
          
          # Invoke callback if it is defined
          Translator.missing_translation_callback(exc, key, options)
        end

        str
      end
    end
91820
private function get_translations() {
		return array(
			'searchLabel'               => __( 'What can we help you with?', 'wordpress-seo-premium' ),
			'searchErrorLabel'          => __( 'Your search timed out. Please double-check your internet connection and try again.', 'wordpress-seo-premium' ),
			'noResultsLabel'            => __( 'No results found for', 'wordpress-seo-premium' ),
			'contactLabel'              => __( 'Send a Message', 'wordpress-seo-premium' ),
			'attachFileLabel'           => __( 'Attach a file', 'wordpress-seo-premium' ),
			'attachFileError'           => __( 'The maximum file size is 10 MB', 'wordpress-seo-premium' ),
			'nameLabel'                 => __( 'Your Name', 'wordpress-seo-premium' ),
			'nameError'                 => __( 'Please enter your name', 'wordpress-seo-premium' ),
			'emailLabel'                => __( 'Email address', 'wordpress-seo-premium' ),
			'emailError'                => __( 'Please enter a valid email address', 'wordpress-seo-premium' ),
			'topicLabel'                => __( 'Select a topic', 'wordpress-seo-premium' ),
			'topicError'                => __( 'Please select a topic from the list', 'wordpress-seo-premium' ),
			'subjectLabel'              => __( 'Subject', 'wordpress-seo-premium' ),
			'subjectError'              => __( 'Please enter a subject', 'wordpress-seo-premium' ),
			'messageLabel'              => __( 'How can we help you?', 'wordpress-seo-premium' ),
			'messageError'              => __( 'Please enter a message', 'wordpress-seo-premium' ),
			'sendLabel'                 => __( 'Send', 'wordpress-seo-premium' ),
			'contactSuccessLabel'       => __( 'Message sent, thank you!', 'wordpress-seo-premium' ),
			'contactSuccessDescription' => __( 'Someone from Team Yoast will get back to you soon, normally within a couple of hours.', 'wordpress-seo-premium' ),
		);
	}
1261009
function translateMessagesToBundle(src, translationsSrc) {
    var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

    var _ref$inputFormat = _ref.inputFormat;
    var inputFormat = _ref$inputFormat === undefined ? 'po' : _ref$inputFormat;

    var options = _objectWithoutProperties(_ref, ['inputFormat']);

    var bundle = {};
    var missing = {};
    var translations = _io2.default[inputFormat].in(translationsSrc, options);

    function attemptToCreateRenderer(node, message) {
        if (translations[message]) {
            bundle[message] = (0, _translation2.default)(node, translations[message], message);
        } else {
            missing[message] = message;
        }
    }

    var plugin = function plugin() {
        return {
            visitor: {
                CallExpression: function CallExpression(_ref2) {
                    var node = _ref2.node;

                    if ((0, _ast.isFunctionMarker)(node)) {
                        var message = (0, _extract.extractFunctionMessage)(node);
                        attemptToCreateRenderer(node, message);
                    }
                },
                JSXElement: function JSXElement(_ref3) {
                    var node = _ref3.node;

                    if ((0, _ast.isElementMarker)(node)) {
                        var message = (0, _extract.extractElementMessageWithoutSideEffects)(node);
                        attemptToCreateRenderer(node, message);
                    }
                }
            }
        };
    };

    _parsing2.default.transform(src, [plugin]);

    return { bundle: bundle, missing: missing };
}
459832
def translate_links(self, text, in_comment=None):
        
        def replace_link(matchobj):
            ref = matchobj.group(1)
            return '<a href = "%s">%s</a>' % (
                    self.translate_ref_to_url(ref, in_comment), ref)
        return re.sub('{@link ([\w#]+)}', replace_link, text)