def __call__(self): pc = getToolByName(self.context, "portal_catalog") pl = getToolByName(self.context, "portal_languages") self.results = [] for language_supported in pl.getSupportedLanguages(): translated_objects = pc.searchResults(object_provides=LP_TRANSLATABLE, Language=language_supported) for brain in translated_objects: obj = brain.getObject() if obj.isCanonical(): translations = obj.getTranslations(include_canonical=False) manager = ITranslationManager(obj) if translations: for language in translations.keys(): try: manager.register_translation(language, translations[language][0]) except KeyError: logger.warning( "%s already translated to %s: %s" % (obj.id, language, str(manager.get_translations())) ) self.results.append(str(manager.get_translations())) logger.info("Finished with transferring catalog information") return self.template()
def __call__(self): pc = getToolByName(self.context, 'portal_catalog') pl = getToolByName(self.context, 'portal_languages') self.results = [] for language_supported in pl.getSupportedLanguages(): translated_objects = pc.searchResults( object_provides=LP_TRANSLATABLE, Language=language_supported) for brain in translated_objects: obj = brain.getObject() if obj.isCanonical(): translations = obj.getTranslations(include_canonical=False) manager = ITranslationManager(obj) if translations: for language in translations.keys(): try: manager.register_translation( language, translations[language][0]) except KeyError: logger.warning( '%s already translated to %s: %s' % (obj.id, language, str(manager.get_translations()))) self.results.append(manager.get_translations()) return self.template()
def test_content_is_linked(self): items = self._run_transmogrifier() self.assertEqual(4, len(items)) manager = ITranslationManager(self.folder_en) self.assertEqual(self.folder_de, manager.get_translation('de'), 'English and German content should be linked.') self.assertEqual(2, len(manager.get_translations())) manager = ITranslationManager(self.file_de) self.assertEqual(self.file_en, manager.get_translation('en'), 'English and German content should be linked.') self.assertEqual(2, len(manager.get_translations()))
def render(self): cat = getToolByName(self.context, 'portal_catalog') query = dict(portal_type='Folder', Language='en') res = cat(query) log.info('Total no. of folders found: {0}'.format(len(res))) links = dict() for r in res: if r.getPath().split('/')[2] != 'en': log.warning( "Found a folder with lang EN not under /en: {0}".format( r.getPath())) continue obj = r.getObject() if not ITranslatable.providedBy(obj): log.warning( 'Found a folder that is not translatable, WTF: {0}'.format( r.getPath())) continue tm = ITranslationManager(obj) log.info('Handling folder {0}.'.format('/'.join( obj.getPhysicalPath()))) for lang, trans in tm.get_translations().items(): if lang == 'en': continue # Copy "Exclude from navigation", section images and related sites trans.exclude_from_nav = obj.exclude_from_nav rsl = IRelatedSites(trans).related_sites_links if len(rsl): links['/'.join(trans.getPhysicalPath())] = rsl return json.dumps(links)
def render(self): cat = getToolByName(self.context, 'portal_catalog') query = dict(portal_type='Folder', Language='en') res = cat(query) log.info('Total no. of folders found: {0}'.format(len(res))) links = dict() for r in res: if r.getPath().split('/')[2] != 'en': log.warning("Found a folder with lang EN not under /en: {0}".format( r.getPath())) continue obj = r.getObject() if not ITranslatable.providedBy(obj): log.warning('Found a folder that is not translatable, WTF: {0}'.format( r.getPath())) continue tm = ITranslationManager(obj) log.info('Handling folder {0}.'.format('/'.join(obj.getPhysicalPath()))) for lang, trans in tm.get_translations().items(): if lang == 'en': continue # Copy "Exclude from navigation", section images and related sites trans.exclude_from_nav = obj.exclude_from_nav rsl = IRelatedSites(trans).related_sites_links if len(rsl): links['/'.join(trans.getPhysicalPath())] = rsl return json.dumps(links)
def idiomesIndexer(obj): llistat = [] manager = ITranslationManager(obj) translations = manager.get_translations() for translation in translations: formula = translations[translation] for i in formula.items(): llistat.append(i[1].Title()) return llistat
def _translations(self, missing): # Figure out the "closest" translation in the parent chain of the # context. We stop at both an INavigationRoot or an ISiteRoot to look # for translations. We do want to find something that is definitely # in the language the user asked for. context = aq_inner(self.context) translations = {} chain = aq_chain(context) first_pass = True _checkPermission = getSecurityManager().checkPermission for item in chain: if ISiteRoot.providedBy(item): # We have a site root, which works as a fallback has_view_permission = bool(_checkPermission('View', item)) for c in missing: translations[c] = (item, first_pass, has_view_permission) break elif IFactoryTempFolder.providedBy(item) or \ IFactoryTool.providedBy(item): # TempFolder or portal_factory, can't have a translation continue canonical = ITranslationManager(item, None) item_trans = canonical.get_translations() for code, trans in item_trans.items(): code = str(code) if code not in translations: # make a link to a translation only if the user # has view permission has_view_permission = bool(_checkPermission('View', trans)) if (not INavigationRoot.providedBy(item) and not has_view_permission): continue # If we don't yet have a translation for this language # add it and mark it as found translations[code] = (trans, first_pass, has_view_permission) missing = missing - set((code, )) if len(missing) <= 0: # We have translations for all break if INavigationRoot.providedBy(item): # Don't break out of the navigation root jail has_view_permission = bool(_checkPermission('View', item)) for c in missing: translations[c] = (item, False, has_view_permission) break first_pass = False # return a dict of language code to tuple. the first tuple element is # the translated object, the second argument indicates wether the # translation is a direct translation of the context or something from # higher up the translation chain return translations
def temesIndexer(obj): resultat = [] temes = obj.temes for tema in temes: tema_obj = tema.to_object manager = ITranslationManager(tema_obj) translations = manager.get_translations() for translation in translations: resultat.append(translations[translation].id) return resultat
def get_all_translations(self, content): """Return all translations excluding the just modified content""" translations_list_to_process = [] content_lang = queryAdapter(content, ILanguage).get_language() canonical = ITranslationManager(content) translations = canonical.get_translations() for language in translations.keys(): if language != content_lang: translations_list_to_process.append(translations[language]) return translations_list_to_process
def getTemes(self): ltool = getToolByName(self.context, 'portal_languages') languages = ltool.getAvailableLanguageInformation() temes = self.context.temes resultat = [] for tema in temes: obj = tema.to_object manager = ITranslationManager(obj) translations = manager.get_translations() if self.context.language in translations: tema_idioma = translations[self.context.language] resultat.append({'url': tema_idioma.absolute_url, 'titol': tema_idioma.title}) return resultat
def getTemes(self): ltool = getToolByName(self.context, 'portal_languages') languages = ltool.getAvailableLanguageInformation() temes = self.context.temes resultat = [] for tema in temes: obj = tema.to_object manager = ITranslationManager(obj) translations = manager.get_translations() if self.context.language in translations: tema_idioma = translations[self.context.language] resultat.append({ 'url': tema_idioma.absolute_url, 'titol': tema_idioma.title }) return resultat
def getAudios(self): resultat = [] manager = ITranslationManager(self.context) translations = manager.get_translations() util = queryUtility(IContentLanguageAvailability) languages = util.getLanguages() for translation in translations: formula = translations[translation] for i in formula.items(): locucio = i[1] idioma = languages[locucio.title]['native'] resultat.append({'idioma': idioma, 'url': locucio.absolute_url, 'nom_formula': locucio.nom_formula, 'locucio': locucio.locucio}) return resultat
def getAudios(self): resultat = [] manager = ITranslationManager(self.context) translations = manager.get_translations() util = queryUtility(IContentLanguageAvailability) languages = util.getLanguages() for translation in translations: formula = translations[translation] for i in formula.items(): locucio = i[1] idioma = languages[locucio.title]['native'] resultat.append({ 'idioma': idioma, 'url': locucio.absolute_url, 'nom_formula': locucio.nom_formula, 'locucio': locucio.locucio }) return resultat
class BabelUtils(BrowserView): def __init__(self, context, request): self.context = context self.request = request portal_state = getMultiAdapter((context, request), name="plone_portal_state") self.portal_url = portal_state.portal_url() self.group = ITranslationManager(self.context) def getGroup(self): return self.group def getTranslatedLanguages(self): return self.group.get_translated_languages() def getPortal(self): portal_url = getToolByName(self.context, 'portal_url') return portal_url def objToTranslate(self): return self.context def gtenabled(self): registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) return settings.google_translation_key != '' def languages(self): """ Deprecated """ context = aq_inner(self.context) ls = LanguageSelector(context, self.request, None, None) ls.update() results = ls.languages() supported_langs = [v['code'] for v in results] missing = set([str(c) for c in supported_langs]) lsv = LanguageSelectorViewlet(context, self.request, None, None) translations = lsv._translations(missing) # We want to see the babel_view append_path = ('', 'babel_view',) non_viewable = set() for data in results: code = str(data['code']) data['translated'] = code in translations.keys() appendtourl = '/'.join(append_path) if data['translated']: trans, direct, has_view_permission = translations[code] if not has_view_permission: # shortcut if the user cannot see the item non_viewable.add((data['code'])) continue data['url'] = trans.absolute_url() + appendtourl else: non_viewable.add((data['code'])) # filter out non-viewable items results = [r for r in results if r['code'] not in non_viewable] return results def translated_languages(self): context = aq_inner(self.context) tool = getToolByName(context, 'portal_languages', None) checkPermission = getSecurityManager().checkPermission translations = self.group.get_translations() translated_info = [dict(code=key, info=tool.getAvailableLanguageInformation()[key], obj=translations[key]) for key in translations] default_language = tool.getDefaultLanguage() translated_shown = [] for lang_info in translated_info: # Mark the default language as the first translation shown if lang_info['code'] == default_language: lang_info['isDefault'] = True else: lang_info['isDefault'] = False # Remove the translation of the content currently being translated if lang_info['code'] == context.Language(): continue # Remove the translation in case the translator user does not have permissions over it has_view_permission = bool(checkPermission('View', lang_info['obj'])) if not has_view_permission: continue translated_shown.append(lang_info) return translated_shown
def get_len_translations(self): if not ITranslatable.providedBy(self.context): return 0 tm = ITranslationManager(self.context) return len(tm.get_translations())
class BabelUtils(BrowserView): def __init__(self, context, request): self.context = context self.request = request portal_state = getMultiAdapter((context, request), name="plone_portal_state") self.portal_url = portal_state.portal_url() self.group = ITranslationManager(self.context) def getGroup(self): return self.group def getTranslatedLanguages(self): return self.group.get_translated_languages() def getPortal(self): portal_url = getToolByName(self.context, 'portal_url') return portal_url def objToTranslate(self): return self.context def gtenabled(self): registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) return settings.google_translation_key != '' def languages(self): """ Deprecated """ context = aq_inner(self.context) ls = LanguageSelector(context, self.request, None, None) ls.update() results = ls.languages() supported_langs = [v['code'] for v in results] missing = set([str(c) for c in supported_langs]) lsv = LanguageSelectorViewlet(context, self.request, None, None) translations = lsv._translations(missing) # We want to see the babel_view append_path = ( '', 'babel_view', ) non_viewable = set() for data in results: code = str(data['code']) data['translated'] = code in translations.keys() appendtourl = '/'.join(append_path) if data['translated']: trans, direct, has_view_permission = translations[code] if not has_view_permission: # shortcut if the user cannot see the item non_viewable.add((data['code'])) continue data['url'] = trans.absolute_url() + appendtourl else: non_viewable.add((data['code'])) # filter out non-viewable items results = [r for r in results if r['code'] not in non_viewable] return results def translated_languages(self): context = aq_inner(self.context) tool = getToolByName(context, 'portal_languages', None) checkPermission = getSecurityManager().checkPermission translations = self.group.get_translations() translated_info = [ dict(code=key, info=tool.getAvailableLanguageInformation()[key], obj=translations[key]) for key in translations ] default_language = tool.getDefaultLanguage() translated_shown = [] for lang_info in translated_info: # Mark the default language as the first translation shown if lang_info['code'] == default_language: lang_info['isDefault'] = True else: lang_info['isDefault'] = False # Remove the translation of the content currently being translated if lang_info['code'] == context.Language(): continue # Remove the translation in case the translator user does not have permissions over it has_view_permission = bool( checkPermission('View', lang_info['obj'])) if not has_view_permission: continue translated_shown.append(lang_info) return translated_shown
def render(self): cat = getToolByName(self.context, 'portal_catalog') query = dict(portal_type='Folder', Language='en') res = cat(query) log.info('Total no. of folders found: {0}'.format(len(res))) for r in res: if r.getPath().split('/')[2] != 'en': log.warning( "Found a folder with lang EN not under /en: {0}".format( r.getPath())) continue obj = r.getObject() if not ITranslatable.providedBy(obj): log.warning( 'Found a folder that is not translatable, WTF: {0}'.format( r.getPath())) continue ordering = obj.getOrdering() order = ordering.idsInOrder() tm = ITranslationManager(obj) log.info('Handling folder {0}.'.format('/'.join( obj.getPhysicalPath()))) for lang, trans in tm.get_translations().items(): if lang == 'en': continue # Copy "Exclude from navigation", section images and related sites trans.exclude_from_nav = obj.exclude_from_nav IRelatedSites(trans).related_sites_links = IRelatedSites( obj).related_sites_links ISectionImage(trans).section_image = ISectionImage( obj).section_image # Copy over marker interfaces ifaces_to_add = IMarkerInterfaces( obj).getDirectlyProvidedNames() if len(ifaces_to_add): t_ifaces = IMarkerInterfaces(trans) add = t_ifaces.dottedToInterfaces(ifaces_to_add) t_ifaces.update(add=add, remove=list()) # handle the default page settings prop = 'default_page' propval = aq_base(obj).getProperty(prop, None) if propval: # get translation of default-page, if it exists (since the id might be different!) default_page = getattr(obj, propval, None) t_default_page = default_page and ITranslationManager( default_page).get_translation(lang) if not t_default_page: continue # check if marker interfaces need to be copied dp_ifaces_to_add = IMarkerInterfaces( default_page).getDirectlyProvidedNames() if len(dp_ifaces_to_add): t_dp_ifaces = IMarkerInterfaces(t_default_page) add = t_dp_ifaces.dottedToInterfaces(dp_ifaces_to_add) t_dp_ifaces.update(add=add, remove=list()) if aq_base(trans).hasProperty(prop): trans._delProperty(prop) trans._setProperty(id=prop, value=t_default_page.id, type="string") # now set the correct order t_ordering = trans.getOrdering() t_order = t_ordering.idsInOrder() for i in range(len(order)): if order[i] in t_order: t_ordering.moveObjectToPosition(order[i], i, suppress_events=True) if t_order != t_ordering.idsInOrder(): trans.reindexObject() log.info('Now, fix FOP languages') results = cat(portal_type="osha.hwccontent.focalpoint", Language='all') fopcnt = 0 for res in results: fop = res.getObject() if fop.Language() != '': fop.setLanguage('') fop.reindexObject() fopcnt += 1 log.info('Reset the language on {0} FOPs'.format(fopcnt)) return "ok"
def render(self): cat = getToolByName(self.context, 'portal_catalog') query = dict(portal_type='Folder', Language='en') res = cat(query) log.info('Total no. of folders found: {0}'.format(len(res))) for r in res: if r.getPath().split('/')[2] != 'en': log.warning("Found a folder with lang EN not under /en: {0}".format( r.getPath())) continue obj = r.getObject() if not ITranslatable.providedBy(obj): log.warning('Found a folder that is not translatable, WTF: {0}'.format( r.getPath())) continue ordering = obj.getOrdering() order = ordering.idsInOrder() tm = ITranslationManager(obj) log.info('Handling folder {0}.'.format('/'.join(obj.getPhysicalPath()))) for lang, trans in tm.get_translations().items(): if lang == 'en': continue # Copy "Exclude from navigation", section images and related sites trans.exclude_from_nav = obj.exclude_from_nav IRelatedSites(trans).related_sites_links = IRelatedSites(obj).related_sites_links ISectionImage(trans).section_image = ISectionImage(obj).section_image # Copy over marker interfaces ifaces_to_add = IMarkerInterfaces(obj).getDirectlyProvidedNames() if len(ifaces_to_add): t_ifaces = IMarkerInterfaces(trans) add = t_ifaces.dottedToInterfaces(ifaces_to_add) t_ifaces.update(add=add, remove=list()) # handle the default page settings prop = 'default_page' propval = aq_base(obj).getProperty(prop, None) if propval: # get translation of default-page, if it exists (since the id might be different!) default_page = getattr(obj, propval, None) t_default_page = default_page and ITranslationManager(default_page).get_translation(lang) if not t_default_page: continue # check if marker interfaces need to be copied dp_ifaces_to_add = IMarkerInterfaces(default_page).getDirectlyProvidedNames() if len(dp_ifaces_to_add): t_dp_ifaces = IMarkerInterfaces(t_default_page) add = t_dp_ifaces.dottedToInterfaces(dp_ifaces_to_add) t_dp_ifaces.update(add=add, remove=list()) if aq_base(trans).hasProperty(prop): trans._delProperty(prop) trans._setProperty(id=prop, value=t_default_page.id, type="string") # now set the correct order t_ordering = trans.getOrdering() t_order = t_ordering.idsInOrder() for i in range(len(order)): if order[i] in t_order: t_ordering.moveObjectToPosition( order[i], i, suppress_events=True) if t_order != t_ordering.idsInOrder(): trans.reindexObject() log.info('Now, fix FOP languages') results = cat(portal_type="osha.hwccontent.focalpoint", Language='all') fopcnt = 0 for res in results: fop = res.getObject() if fop.Language() != '': fop.setLanguage('') fop.reindexObject() fopcnt += 1 log.info('Reset the language on {0} FOPs'.format(fopcnt)) return "ok"
def exec_for_all_langs(context, method, *args, **kw): """ helper method. Takes a method and executes it on all language versions of the context """ info = [] warnings = [] errors = [] changed_languages = [] skipped_languages = [] portal_url = getToolByName(context, 'portal_url') portal_path = portal_url.getPortalPath() manager = ITranslationManager(context) translations = manager.get_translations() content_language = ILanguage(context).get_language() langs = [x for x in translations.keys() if x != content_language] langs.append(content_language) kw['content_language'] = content_language context_path = context.getPhysicalPath() dynamic_path = portal_path + '/%s/' + \ "/".join(context_path[len(portal_path) + 1:]) if dynamic_path[-1] == "/": dynamic_path = dynamic_path[:-1] # if the special keyword 'target_id' is passed, try to retrieve an object # of that name from the current context and save it in the kw arguments. # This object can the used in the method for retrieving translations. # Needed when we are not working directly on translations of the current # context, but items contained in translations of the current context. if kw.get('target_id', None): target_object = getattr(context, kw.get('target_id'), None) if target_object: kw['target_object'] = target_object if kw.get('target_path', None): targetpath = safe_unicode(kw['target_path']).encode('utf-8') if targetpath.startswith('/'): if not targetpath.startswith(portal_path): targetpath = portal_path + targetpath target_base = context.restrictedTraverse(targetpath, None) kw['target_base'] = target_base # add the portal_path to the keywords kw['portal_path'] = portal_path for lang in langs: base = manager.get_translation(lang) if base is None: log.info("Break for lang %s, no translation present" % lang) skipped_languages.append(lang) continue kw['lang'] = lang err = method(base, *args, **kw) log.info("Executing for language %s" % lang) if err: errors.extend(err) else: changed_languages.append(lang) if changed_languages: info.append( 'Executed for the following languages: %s' % ' '.join(changed_languages)) if skipped_languages: warnings.append( 'No translations for the following languages: %s' % ' '.join(skipped_languages)) return info, warnings, errors
def _get_translations_by_closest(self, supported_langs): """ Return the translations information by figuring out the 'closest' translation in the parent chain of the context. We stop at both an INavigationRoot or an ISiteRoot to look for translations. We do want to find something that is definitely in the language the user asked for regardless anything else. """ context = aq_inner(self.context) missing = set([str(c) for c in supported_langs]) translations = {} chain = aq_chain(context) first_pass = True _checkPermission = getSecurityManager().checkPermission for item in chain: if ISiteRoot.providedBy(item): # We have a site root, which works as a fallback has_view_permission = bool(_checkPermission('View', item)) for c in missing: translations[c] = (item, first_pass, has_view_permission) break elif IFactoryTempFolder.providedBy(item) or \ IFactoryTool.providedBy(item): # TempFolder or portal_factory, can't have a translation continue try: canonical = ITranslationManager(item) except TypeError: if not ITranslatable.providedBy(item): # In case there it's not translatable go to parent # This solves the problem when a parent is not ITranslatable continue else: raise item_trans = canonical.get_translations() for code, trans in item_trans.items(): code = str(code) if code not in translations: # make a link to a translation only if the user # has view permission has_view_permission = bool(_checkPermission('View', trans)) if (not INavigationRoot.providedBy(item) and not has_view_permission): continue # If we don't yet have a translation for this language # add it and mark it as found translations[code] = (trans, first_pass, has_view_permission) missing = missing - set((code, )) if len(missing) <= 0: # We have translations for all break if INavigationRoot.providedBy(item): # Don't break out of the navigation root jail has_view_permission = bool(_checkPermission('View', item)) for c in missing: translations[c] = (item, False, has_view_permission) break first_pass = False # return a dict of language code to tuple. the first tuple element is # the translated object, the second argument indicates wether the # translation is a direct translation of the context or something from # higher up the translation chain return translations
class BabelUtils(BrowserView): def __init__(self, context, request): self.context = context self.request = request portal_state = getMultiAdapter((context, request), name="plone_portal_state") self.portal_url = portal_state.portal_url() # If there is any session tg lets use the session tg sdm = self.context.session_data_manager session = sdm.getSessionData(create=True) if 'tg' in session.keys(): self.group = TranslationManager(session['tg']) else: self.group = ITranslationManager(self.context) def getGroup(self): return self.group def getTranslatedLanguages(self): return self.group.get_translated_languages() def getPortal(self): portal_url = getToolByName(self.context, 'portal_url') return portal_url def objToTranslate(self): return self.context def gtenabled(self): registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) key = settings.google_translation_key return key is not None and len(key.strip()) > 0 def languages(self): """ Deprecated """ context = aq_inner(self.context) ls = LanguageSelector(context, self.request, None, None) ls.update() results = ls.languages() supported_langs = [v['code'] for v in results] missing = set([str(c) for c in supported_langs]) lsv = LanguageSelectorViewlet(context, self.request, None, None) translations = lsv._translations(missing) # We want to see the babel_view append_path = ('', 'babel_view',) non_viewable = set() for data in results: code = str(data['code']) data['translated'] = code in translations.keys() appendtourl = '/'.join(append_path) if data['translated']: trans, direct, has_view_permission = translations[code] if not has_view_permission: # shortcut if the user cannot see the item non_viewable.add((data['code'])) continue data['url'] = trans.absolute_url() + appendtourl else: non_viewable.add((data['code'])) # filter out non-viewable items results = [r for r in results if r['code'] not in non_viewable] return results def translated_languages(self): context = aq_inner(self.context) tool = getToolByName(context, 'portal_languages', None) checkPermission = getSecurityManager().checkPermission translations = self.group.get_translations() translated_info = [dict(code=key, info=tool.getAvailableLanguageInformation()[key], obj=translations[key]) for key in translations] default_language = tool.getDefaultLanguage() translated_shown = [] for lang_info in translated_info: # Mark the default language as the first translation shown if lang_info['code'] == default_language: lang_info['isDefault'] = True else: lang_info['isDefault'] = False # Remove the translation of the content currently being translated # In case it's temporal we show as language is not already set on AT if not context.portal_factory.isTemporary(self.context) and lang_info['code'] == ILanguage(context).get_language(): continue # Remove the translation in case the translator user does not have permissions over it has_view_permission = bool(checkPermission('View', lang_info['obj'])) if not has_view_permission: continue translated_shown.append(lang_info) return translated_shown def current_language_name(self): """ Get the current language native name """ adapted = ILanguage(self.context) lang_code = adapted.get_language() util = getUtility(IContentLanguageAvailability) data = util.getLanguages(True) lang_info = data.get(lang_code) return lang_info.get('native', None) or lang_info.get('name') def max_nr_of_buttons(self): registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) return settings.buttons_babel_view_up_to_nr_translations
def getContentTranslations(self): manager = ITranslationManager(self.context) return manager.get_translations()