def resetDefaultPage(self): """ Maintain the default page of the site on the language it was defined """ previousDefaultPage = getattr(self.context, self.previousDefaultPageId) languageWrapped = ILanguage(previousDefaultPage, None) # If the previous default page cannot be adapted, do nothing. # This might be the case if it is a Python Script or other non-portal # content if languageWrapped is None: return False language = languageWrapped.get_language() pageId = self.previousDefaultPageId # test language neutral if language == '': language = self.defaultLanguage target = self.folders[language] objects = self.context.manage_cutObjects(pageId) try: target.manage_pasteObjects(objects) except ValueError, exc: # This portal_type may not be allowed. This should not be # fatal, so we only log a warning. LOG.warn("Could not move default page '%s' to folder '%s': %s" % (pageId, target.getId(), exc)) return False
def test_move_content_proper_language_folder_existing_translation_inside( self): self.assertTrue(getattr(self.portal, 'en')) self.portal.en.invokeFactory('Folder', 'new11', title=u"An archetypes based folder") new11 = self.portal.en['new11'] new11.invokeFactory('Document', 'doc11', title=u"An archetypes based doc") doc1_ca = makeTranslation(self.portal.en.new11.doc11, 'ca') doc1_ca.edit(title="Foo", language='ca') self.assertTrue(self.portal.ca.doc11) transaction.commit() # Change the content language of the created folder to 'ca' multilingualMoveObject(new11, 'ca') self.assertTrue(self.portal.ca.new11) self.assertTrue(self.portal.ca.new11.doc11) self.assertEqual( ITranslationManager(self.portal.ca.new11.doc11).get_translations(), {'ca': self.portal.ca.new11.doc11}) self.assertEqual( ITranslationManager(doc1_ca).get_translations(), {'ca': doc1_ca}) self.assertEqual(ILanguage(self.portal.ca.new11).get_language(), 'ca') self.assertEqual( ILanguage(self.portal.ca.new11.doc11).get_language(), 'ca')
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 translate_this( context, attrs=[], translation_exists=False, target_languages=[]): """ Translates the current object into all languages and transfers the given attributes """ info = list() warnings = list() errors = list() # if context is language-neutral, it must receive a language before # it is translated lang_support = ILanguage(context) manager = ITranslationManager(context) if lang_support.get_language() == '': lang_support.set_language( context.portal_languages.getPreferredLanguage()) canLang = lang_support.get_language() # if the user didn't select target languages, get all supported languages # from the language tool if not target_languages: portal_languages = getToolByName(context, 'portal_languages') target_languages = portal_languages.getSupportedLanguages() content_helper = IContentHelper(context) for lang in target_languages: if lang == canLang: continue res = list() if not manager.get_translation(lang): if not translation_exists: # need to make lang a string. It can be unicode so checkid will # freak out and lead to an infinite recursion manager.add_translation(str(lang)) res.append("Added Translation for %s" % lang) # For a new translation, make sure the title is copied as well attrs = content_helper.check_for_title_attr(attrs) else: warnings.append( u'Translation in language %s does not exist, ' 'skipping' % lang) continue else: if not translation_exists: warnings.append( u'Translation for language %s already ' 'exists, skipping' % lang) continue res.append(u"Found translation for %s " % lang) trans = manager.get_translation(lang) content_results = content_helper.copy_attributes(trans, attrs) res.extend(content_results['res']) warnings.extend(content_results['warnings']) info.append(u"\n".join(res)) return (info, warnings, errors)
def set_recursive_language(obj, language): """ Set the language at this object and recursive """ if ILanguage(obj).get_language() != language: ILanguage(obj).set_language(language) ITranslationManager(obj).update() reindex_object(obj) if IFolderish.providedBy(obj): for item in obj.items(): if ITranslatable.providedBy(item): set_recursive_language(item, language)
def createdEvent(obj, event): """ It can be a IObjectRemovedEvent - don't do anything IObjectMovedEvent IObjectAddedEvent IObjectCopiedEvent """ if IObjectRemovedEvent.providedBy(event): return portal = getSite() language_tool = getToolByName(portal, 'portal_languages') # On ObjectCopiedEvent and ObjectMovedEvent aq_parent(event.object) is # always equal to event.newParent. parent = aq_parent(event.object) if (language_tool.startNeutral() and ITranslatable.providedBy(obj)): # We leave this untouched by now. # We don't set languages set_recursive_language(obj, LANGUAGE_INDEPENDENT) elif (IPloneSiteRoot.providedBy(parent) and ITranslatable.providedBy(obj) and ILanguage(obj).get_language() == LANGUAGE_INDEPENDENT): # It's a root folder and we set the default language # ( not independent allowed ) language = language_tool.getPreferredLanguage() set_recursive_language(obj, language) elif ITranslatable.providedBy(parent): # Normal use case # We set the tg, linking language = ILanguage(parent).get_language() set_recursive_language(obj, language) sdm = obj.session_data_manager session = sdm.getSessionData() if 'tg' in session.keys() and \ not portal.portal_factory.isTemporary(obj): IMutableTG(obj).set(session['tg']) old_obj = ITranslationManager(obj).get_translation( session['old_lang']) # Copy ILanguage Independent field on on-the-fly translation cloner = ITranslationCloner(old_obj) cloner(obj) reindex_object(obj) del session['tg']
def setupSharedFolder(self): """ Create the shared neutral language folder """ doneSomething = False folderId = "shared" folder = getattr(self.context, folderId, None) wftool = getToolByName(self.context, 'portal_workflow') if folder is None: self.context.invokeFactory(self.folder_type, folderId) folder = getattr(self.context, folderId) ILanguage(folder).set_language(LANGUAGE_INDEPENDENT) folder.setTitle("Language Shared") state = wftool.getInfoFor(folder, 'review_state', None) # This assumes a direct 'publish' transition from the initial state if state != 'published': wftool.doActionFor(folder, 'publish') folder.reindexObject() doneSomething = True LOG.info("Added LANGUAGE_INDEPENDENT folder: %s" % (folderId)) if not INavigationRoot.providedBy(folder): alsoProvides(folder, INavigationRoot) doneSomething = True LOG.info("INavigationRoot setup on shared folder ") return doneSomething
def setUpLanguage(self, code, name): """ Create the language folders on top of the site """ doneSomething = False folderId = "%s" % code if code != 'id' else 'id-id' folder = getattr(self.context, folderId, None) wftool = getToolByName(self.context, 'portal_workflow') if folder is None: self.context.invokeFactory(self.folder_type, folderId) folder = getattr(self.context, folderId) ILanguage(folder).set_language(code) folder.setTitle(name) state = wftool.getInfoFor(folder, 'review_state', None) # This assumes a direct 'publish' transition from the initial state if state != 'published': wftool.doActionFor(folder, 'publish') folder.reindexObject() doneSomething = True LOG.info("Added '%s' folder: %s" % (code, folderId)) self.folders[code] = folder if not INavigationRoot.providedBy(folder): alsoProvides(folder, INavigationRoot) doneSomething = True LOG.info("INavigationRoot setup on folder '%s'" % code) return doneSomething
def __call__(self): if (self.request.method != 'POST' and not ('field' in self.request.form.keys() and 'lang_source' in self.request.form.keys())): return _("Need a field") else: manager = ITranslationManager(self.context) registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) lang_target = ILanguage(self.context).get_language() lang_source = self.request.form['lang_source'] orig_object = manager.get_translation(lang_source) try: question = orig_object.getField( self.request.form['field']).get(orig_object) except AttributeError: return _("Invalid field") if len(question) > 1600: return _("Too long field") data = { 'key': settings.google_translation_key, 'target': lang_target, 'source': lang_source, 'q': question } params = urllib.urlencode(data) url = 'https://www.googleapis.com/language/translate/v2' retorn = urllib.urlopen(url + '?' + params) return retorn.read()
def test_moved_event(self): folder = self._add_content(self.folder_it, 'Folder', 'folder_1') transaction.commit() setRoles(self.portal, TEST_USER_ID, ['Manager']) id_ = self.folder_it.manage_cutObjects(folder.getId()) self.folder_en.manage_pasteObjects(id_) copied_folder = getattr(self.folder_en, "folder_1") self.assertEqual(ILanguage(copied_folder).get_language(), 'en')
def test_created_event_on_portal(self): """when an object is created on portal it should get the default language because 'language independent' is not allowed. """ language_tool = getToolByName(self.portal, 'portal_languages') folder_1 = self._add_content(self.portal, 'Folder', 'folder_1') self.assertEqual( ILanguage(folder_1).get_language(), language_tool.getPreferredLanguage())
def __call__(self): """ Explore the site's content and place it on the right RLF """ context = aq_inner(self.context) pl = getToolByName(context, "portal_languages") pu = getToolByName(context, "portal_url") portal = pu.getPortalObject() supported_langs = pl.getSupportedLanguages() output = [] for path, obj in findObjects(portal): try: lang_adptr = ILanguage(obj) except: info_str = "Found object %s with no language support." % (path) logger.info(info_str) output.append(info_str) continue obj_lang = lang_adptr.get_language() if obj_lang not in supported_langs: info_str = "Found object %s with unsupported language %s." % ( path, obj_lang) logger.info(info_str) output.append(info_str) else: target_folder = ITranslationLocator(obj)(obj_lang) parent = aq_parent(obj) if IPloneSiteRoot.providedBy(parent) \ and ITranslatable.providedBy(obj) \ and not INavigationRoot.providedBy(obj): target_folder = getattr(portal, obj_lang, None) if target_folder != parent: cb_copy_data = parent.manage_cutObjects(obj.getId()) list_ids = target_folder.manage_pasteObjects(cb_copy_data) new_id = list_ids[0]['new_id'] new_object = target_folder[new_id] info_str = "Moved object %s to lang folder %s" % ( parent.getPhysicalPath(), obj_lang) logger.info(info_str) output.append(new_object.id) return output
def test_move_content_proper_language_folder(self): self.assertTrue(getattr(self.portal, 'en')) self.portal.en.invokeFactory('Folder', 'new1', title=u"An archetypes based folder") new1 = self.portal.en['new1'] new1.invokeFactory('Document', 'doc1', title=u"An archetypes based doc") transaction.commit() # Change the content language of the created folder to 'ca' multilingualMoveObject(new1, 'ca') self.assertTrue(self.portal.ca.new1) self.assertTrue(self.portal.ca.new1.doc1) self.assertEqual(ILanguage(self.portal.ca.new1).get_language(), 'ca') self.assertEqual( ILanguage(self.portal.ca.new1.doc1).get_language(), 'ca')
def handle_add(self, action): data, errors = self.extractData() if not errors: content = data['content'] language = data['language'] ITranslationManager(self.context).register_translation(language,\ content) ILanguage(content).set_language(language) return self.request.response.redirect(self.context.absolute_url()\ + '/add_translations')
def translated_urls(context): manager = ITranslationManager(context) translated_languages = manager.get_translated_languages() content_language = ILanguage(context).get_language() if content_language in translated_languages: translated_languages.remove(content_language) languages = [] for lang in translated_languages: languages.append(SimpleVocabulary.createTerm(lang, lang, \ manager.get_translation(lang).absolute_url())) return SimpleVocabulary(languages)
def set_recursive_language(obj, language): """ Set the language at this object and recursive """ ILanguage(obj).set_language(language) # XXX: this will create recursion, disabled # modified(obj) # update translations for each object update_on_modify(obj, None) if IFolderish.providedBy(obj): for item in obj.items(): if ITranslatable.providedBy(item): set_recursive_language(item, language)
def handle_create(self, action): data, errors = self.extractData() if not errors: language = data['language'] translation_manager = ITranslationManager(aq_inner(self.context)) if ILanguage(self.context).get_language() == LANGUAGE_INDEPENDENT: language_tool = getToolByName(self.context, 'portal_languages') default_language = language_tool.getDefaultLanguage() ILanguage(self.context).set_language(default_language) translation_manager.update() self.context.reindexObject(idxs='language') translation_manager.add_translation(language) translated = translation_manager.get_translation(language) registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) if settings.redirect_babel_view: return self.request.response.redirect( translated.absolute_url() + '/babel_edit') else: return self.request.response.redirect( translated.absolute_url() + '/edit?set_language=%s' % language)
def deletable_languages(context): manager = ITranslationManager(context) translated_languages = manager.get_translated_languages() language_tool = getToolByName(context, 'portal_languages') language_infos = language_tool.getAvailableLanguages() content_language = ILanguage(context).get_language() languages = [] for lang in translated_languages: if lang not in content_language: native = language_infos[lang].get('native', None) name = language_infos[lang].get('name', lang) languages.append(SimpleVocabulary.createTerm(lang, lang, \ native or name)) return SimpleVocabulary(languages)
def untranslated_languages(context): language_tool = getToolByName(context, 'portal_languages') language_infos = language_tool.getAvailableLanguages() default_language = language_tool.getDefaultLanguage() available_portal_languages = language_tool.supported_langs manager = ITranslationManager(context) translated_languages = manager.get_translated_languages() content_language = ILanguage(context).get_language() filter_default = (content_language == LANGUAGE_INDEPENDENT) languages = [] for lang in available_portal_languages: if lang not in translated_languages: native = language_infos[lang].get('native', None) name = language_infos[lang].get('name', lang) languages.append(SimpleVocabulary.createTerm(lang, lang, \ native or name)) return SimpleVocabulary(languages)
def add_translation(self, language): """ see interfaces """ if not language and language != '': raise KeyError('There is no target language') # event notify(ObjectWillBeTranslatedEvent(self.context, language)) # create the translated object translation_factory = ITranslationFactory(self.context) translated_object = translation_factory(language) ILanguage(translated_object).set_language(language) # reindex the translated object translated_object.reindexObject() # register the new translation self.register_translation(language, translated_object) # event notify(ObjectTranslatedEvent(self.context, translated_object, language)) return
def update(self): """ see interfaces""" language = ILanguage(self.context).get_language() # self.context.reindexObject(idxs=("Language", "TranslationGroup", )) # In case language is already on the translated languages we are going to orphan the old translation brains = self.pcatalog.unrestrictedSearchResults(TranslationGroup=self.tg, Language=language) if len(brains) == 0: # There is not a translation with this tg on this language self.register_translation(language, self.context) else: # We need to check if the language has changed brain = brains[0] content_id = self.get_id(self.context) if brain.UID != content_id: # Is a different object -> remove the old one # We get the old uuid old_object = brain.getObject() IMutableTG(old_object).set(NOTG) old_object.reindexObject(idxs=("Language", "TranslationGroup", ))
def __call__(self): if (self.request.method != 'POST' and not ('field' in self.request.form.keys() and 'lang_source' in self.request.form.keys())): return _("Need a field") else: manager = ITranslationManager(self.context) registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) lang_target = ILanguage(self.context).get_language() lang_source = self.request.form['lang_source'] orig_object = manager.get_translation(lang_source) try: question = orig_object.getField( self.request.form['field']).get(orig_object) except AttributeError: return _("Invalid field") return google_translate(question, settings.google_translation_key, lang_target, lang_source)
def resetDefaultPage(self): """ Maintain the default page of the site on the language it was defined """ previousDefaultPage = getattr(self.context, self.previousDefaultPageId) language = ILanguage(previousDefaultPage).get_language() pageId = self.previousDefaultPageId # test language neutral if language == '': language = self.defaultLanguage target = self.folders[language] objects = self.context.manage_cutObjects(pageId) try: target.manage_pasteObjects(objects) except ValueError, exc: # This portal_type may not be allowed. This should not be # fatal, so we only log a warning. LOG.warn("Could not move default page '%s' to folder '%s': %s" % (pageId, target.getId(), exc)) return False
def __call__(self): if (self.request.method != 'POST' and not ('field' in self.request.form.keys() and 'lang_source' in self.request.form.keys())): return _("Need a field") else: manager = ITranslationManager(self.context) registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) lang_target = ILanguage(self.context).get_language() lang_source = self.request.form['lang_source'] orig_object = manager.get_translation(lang_source) field = self.request.form['field'].split('.')[-1] if hasattr(orig_object, field): question = getattr(orig_object, field, '') if hasattr(question, 'raw'): question = question.raw else: return _("Invalid field") return google_translate(question, settings.google_translation_key, lang_target, lang_source)
class DXContentHelper(object): implements(IContentHelper) adapts(IDexterityContent) def __init__(self, context): self.context = context self.language = ILanguage(self.context).get_language() self.fallbacks = [self.language.split('-')[0]] def get_translatable_fields(self): field_info = [] fti = getUtility(IDexterityFTI, name=self.context.portal_type) schemas = [] schemas.append(fti.lookupSchema()) for behavior_schema in dexterityutils.getAdditionalSchemata( self.context, self.context.portal_type): if behavior_schema is not None: schemas.append(behavior_schema) for schema in schemas: for field_name in schema: field = schema[field_name] if not ILanguageIndependentField.providedBy(field) \ and field_name != 'language': title = field.title # If the field's title is a translatable Message, get # the correct translation for it. Use fallback in case # we have a combined language code such as da-dk if isinstance(title, Message): trans_util = queryUtility( ITranslationDomain, title.domain) if trans_util: trans_util.setLanguageFallbacks(self.fallbacks) title = trans_util.translate( title, self.language) else: title = translate(title, self.language) # Mark required fields if getattr(field, 'required', False): title = "%s (%s) (*)" % (title, field_name) else: title = "%s (%s)" % (title, field_name) field_info.append(( "%s|%s" % (field_name, schema.__identifier__), title, )) return field_info def check_for_title_attr(self, attrs): for attr in attrs: if attr.startswith('title|'): return attrs attrs.append('title|') return attrs def copy_attributes(self, trans, attrs): res = [] warnings = [] for attr in attrs: field_name, behavior_name = attr.split('|') behavior_interface = None behavior_instance = queryUtility(IBehavior, name=behavior_name) if behavior_instance is not None: behavior_interface = behavior_instance.interface if behavior_interface is not None: value = getattr( behavior_interface(self.context), field_name, _marker) else: value = getattr(self.context, field_name, _marker) if IRelationValue.providedBy(value): obj = value.to_object adapter = queryAdapter(trans, ILanguage) if ITranslatable.providedBy(obj): trans_obj = ITranslationManager(obj)\ .get_translation(adapter.get_language()) if trans_obj: intids = getUtility(IIntIds) value = RelationValue(intids.getId(trans_obj)) if not (value == _marker): # We check if not (value == _marker) because # z3c.relationfield has an __eq__ if behavior_interface is not None: setattr(behavior_interface(trans), field_name, value) else: setattr(trans, field_name, value) res.append( u" > Transferred attribute '%s'" % field_name) return dict(res=res, warnings=warnings)
def getMenuItems(self, context, request): """Return menu item entries in a TAL-friendly form.""" menu = [] url = context.absolute_url() lt = getToolByName(context, "portal_languages") portal_state = getMultiAdapter((context, request), name=u'plone_portal_state') portal_url = portal_state.portal_url() showflags = lt.showFlags() context_id = ITranslationManager(context).tg registry = getUtility(IRegistry) settings = registry.forInterface(IMultiLanguageExtraOptionsSchema) edit_view = 'babel_edit' if settings.redirect_babel_view else 'edit' # In case is neutral language show set language menu only if LANGUAGE_INDEPENDENT != ILanguage(context).get_language(): menu.append({ "title": _(u"title_babel_edit", default=u"Edit with babel view"), "description": _(u"description_babel_edit", default=u"Edit with the babel_edit"), "action": url + "/" + edit_view, "selected": False, "icon": None, "extra": {"id": "_edit_babel_edit", "separator": None, "class": ""}, "submenu": None, }) contexts = [context,] prt = aq_parent(context) if isDefaultPage(prt, context): contexts.append(prt) for idx,context in enumerate(contexts): url = context.absolute_url() langs = untranslated_languages(context) for lang in langs: lang_name = lang.title lang_id = lang.value icon = showflags and lt.getFlagForLanguageCode(lang_id) or None item = { "description": _(u"description_translate_into", default=u"Translate into ${lang_name}", mapping={"lang_name": lang_name}), "action": url + "/@@create_translation?language=%s" % lang_id, "selected": False, "icon": icon, "width": "14", "height": "11", "extra": {"id": "translate_into_%s" % lang_id, "separator": None, "class": "contentmenuflags"}, "submenu": None, } item['title'] = idx and _(u'create_translation_folder', default=u"Create ${lang_name} folder", mapping={"lang_name": lang_name}) \ or _(u'create_translation', default=u"Create ${lang_name}", mapping={"lang_name": lang_name}) menu.append(item) langs = translated_languages(context) urls = translated_urls(context) for lang in langs: if lang not in urls: # omit if translation is not permitted to access. continue lang_name = lang.title lang_id = lang.value icon = showflags and lt.getFlagForLanguageCode(lang_id) or None item = { "description": _(u"description_babeledit_menu", default=u"Babel edit ${lang_name}", mapping={"lang_name": lang_name}), "action": urls.getTerm(lang_id).title + "/" + edit_view, "selected": False, "icon": icon, "width": "14", "height": "11", "extra": {"id": "babel_edit_%s" % lang_id, "separator": None, "class": "contentmenuflags"}, "submenu": None, } item['title'] = idx and _(u'edit_translation_folder', default=u"Edit ${lang_name} folder", mapping={"lang_name": lang_name}) \ or _(u'edit_translation', default=u"Edit ${lang_name}", mapping={"lang_name": lang_name}) menu.append(item) item = { "description": _(u"description_add_translations", default=u"Add existing content as translation"), "action": url + "/add_translations", "selected": False, "icon": None, "extra": {"id": "_add_translations", "separator": langs and "actionSeparator" or None, "class": ""}, "submenu": None, } item['title'] = idx and _(u"title_add_translations_folder", default=u"Add translations for folder...") \ or _(u"title_add_translations", default=u"Add translations...") menu.append(item) item = { "title": _(u"title_remove_translations", default=u"Remove translations..."), "description": _( u"description_remove_translations", default=u"Delete translations or remove the relations"), "action": url + "/remove_translations", "selected": False, "icon": None, "extra": {"id": "_remove_translations", "separator": langs and "actionSeparator" or None, "class": ""}, "submenu": None, } menu.append(item) elif LANGUAGE_INDEPENDENT == ILanguage(context).get_language(): menu.append({ "title": _(u"language_folder", default=u"Return to language folder"), "description": _( u"description_language_folder", default=u"Go to the user's browser preferred language related folder"), "action": portal_url + '/' + lt.getPreferredLanguage(), "selected": False, "icon": None, "extra": {"id": "_shared_folder", "separator": None, "class": ""}, "submenu": None, }) if LANGUAGE_INDEPENDENT != ILanguage(context).get_language(): menu.append({ "title": _(u"universal_link", default=u"Universal Link"), "description": _( u"description_universal_link", default=u"Universal Language content link"), "action": portal_url + "/@@multilingual-universal-link/" + context_id, "selected": False, "icon": None, "extra": {"id": "_universal_link", "separator": None, "class": ""}, "submenu": None, }) menu.append({ "title": _(u"shared_folder", default=u"Go to shared folder"), "description": _( u"description_shared_folder", default=u"Show the language shared (neutral language) folder"), "action": portal_url + '/' + SHARED_NAME, "selected": False, "icon": None, "extra": {"id": "_shared_folder", "separator": None, "class": ""}, "submenu": None, }) menu.append({ "title": _(u"title_set_language", default=u"Set content language"), "description": _(u"description_set_language", default=u"Set or change the current content language"), "action": url + "/update_language", "selected": False, "icon": None, "extra": {"id": "_set_language", "separator": None, "class": ""}, "submenu": None, }) return menu
def setUp(self): self.portal = self.layer['portal'] self.folder_it = self._add_content(self.portal, 'Folder', 'it') self.folder_en = self._add_content(self.portal, 'Folder', 'en') ILanguage(self.folder_it).set_language('it')
def update(self, obj, data): ILanguage(obj).set_language(data['language']) IMutableTG(obj).set(data['translation_group_uuid']) manager = ITranslationManager(obj) manager.register_translation(data['language'], obj)
def getMenuItems(self, context, request): """Return menu item entries in a TAL-friendly form.""" menu = [] url = context.absolute_url() lt = getToolByName(context, "portal_languages") portal_state = getMultiAdapter((context, request), name=u'plone_portal_state') portal_url = portal_state.portal_url() showflags = lt.showFlags() context_id = IUUID(context) # In case is neutral language show set language menu only if LANGUAGE_INDEPENDENT != ILanguage(context).get_language( ) and not INavigationRoot.providedBy(context): menu.append({ "title": _(u"title_babel_edit", default=u"Edit with babel view"), "description": _(u"description_babel_edit", default=u"Edit with the babel_edit"), "action": url + "/babel_edit", "selected": False, "icon": None, "extra": { "id": "_edit_babel_edit", "separator": None, "class": "" }, "submenu": None, }) langs = untranslated_languages(context) for lang in langs: lang_name = lang.title lang_id = lang.value icon = showflags and lt.getFlagForLanguageCode(lang_id) or None item = { "title": _(u"Create ${lang_name}", mapping={"lang_name": lang_name}), "description": _(u"description_translate_into", default=u"Translate into ${lang_name}", mapping={"lang_name": lang_name}), "action": url + "/@@create_translation?form.widgets.language"\ "=%s&form.buttons.create=1" % lang_id, "selected": False, "icon": icon, "width": "14", "height": "11", "extra": {"id": "translate_into_%s" % lang_id, "separator": None, "class": ""}, "submenu": None, } menu.append(item) langs = translated_languages(context) urls = translated_urls(context) for lang in langs: lang_name = lang.title lang_id = lang.value icon = showflags and lt.getFlagForLanguageCode(lang_id) or None item = { "title": _(u"Edit ${lang_name}", mapping={"lang_name": lang_name}), "description": _(u"description_babeledit_menu", default=u"Babel edit ${lang_name}", mapping={"lang_name": lang_name}), "action": urls.getTerm(lang_id).title + "/babel_edit", "selected": False, "icon": icon, "width": "14", "height": "11", "extra": { "id": "babel_edit_%s" % lang_id, "separator": None, "class": "contentmenuflags" }, "submenu": None, } menu.append(item) menu.append({ "title": _(u"title_add_translations", default=u"Add translations..."), "description": _(u"description_add_translations", default=u"Add existing content as translation"), "action": url + "/add_translations", "selected": False, "icon": None, "extra": { "id": "_add_translations", "separator": langs and "actionSeparator" or None, "class": "" }, "submenu": None, }) menu.append({ "title": _(u"title_remove_translations", default=u"Remove translations..."), "description": _(u"description_remove_translations", default=u"Delete translations or remove the relations"), "action": url + "/remove_translations", "selected": False, "icon": None, "extra": { "id": "_remove_translations", "separator": langs and "actionSeparator" or None, "class": "" }, "submenu": None, }) elif LANGUAGE_INDEPENDENT == ILanguage(context).get_language(): menu.append({ "title": _(u"language_folder", default=u"Return to language folder"), "description": _(u"description_shared_folder", default= u"Go to the user's browser preferred language related folder" ), "action": portal_url + '/' + lt.getPreferredLanguage(), "selected": False, "icon": None, "extra": { "id": "_shared_folder", "separator": None, "class": "" }, "submenu": None, }) if LANGUAGE_INDEPENDENT != ILanguage(context).get_language(): menu.append({ "title": _(u"universal_link", default=u"Universal Link"), "description": _(u"description_universal_link", default=u"Universal Language content link"), "action": portal_url + "/multilingual-universal-link?uid=" + context_id, "selected": False, "icon": None, "extra": { "id": "_universal_link", "separator": None, "class": "" }, "submenu": None, }) menu.append({ "title": _(u"shared_folder", default=u"Go to shared folder"), "description": _(u"description_shared_folder", default=u"Show the language shared (neutral language) folder" ), "action": portal_url + '/' + SHARED_NAME, "selected": False, "icon": None, "extra": { "id": "_shared_folder", "separator": None, "class": "" }, "submenu": None, }) menu.append({ "title": _(u"title_set_language", default=u"Set content language"), "description": _(u"description_add_translations", default=u"Set or change the current content language"), "action": url + "/update_language", "selected": False, "icon": None, "extra": { "id": "_set_language", "separator": None, "class": "" }, "submenu": None, }) return menu
def __init__(self, context): self.context = context self.language = ILanguage(self.context).get_language() self.fallbacks = [self.language.split('-')[0]]
def Language(object, **kw): language = ILanguage(object).get_language() return language
def test_copied_event(self): folder = self._add_content(self.folder_it, 'Folder', 'folder_1') id_ = self.folder_it.manage_copyObjects(folder.getId()) self.folder_en.manage_pasteObjects(id_) copied_folder = getattr(self.folder_en, "folder_1") self.assertEqual(ILanguage(copied_folder).get_language(), 'en')
def test_created_event(self): """when an object is created in a folder it takes its language from the folder itself """ folder_1 = self._add_content(self.folder_it, 'Folder', 'folder_1') self.assertEqual(ILanguage(folder_1).get_language(), 'it')
def __call__(self): """ Get the JSON information about based on a nodeId """ # We get the language we are looking for lang = '' tool = getToolByName(self.context, 'portal_languages', None) if 'lang' in self.request: lang = self.request['lang'] if lang == '': lang = tool.getDefaultLanguage() # We want all or just the missing translations elements if 'all' in self.request: get_all = (self.request['all'] == 'true') else: get_all = True # Which is the root nodeId folder_path = '' if 'nodeId' in self.request: # We get the used UUID nodeId = (self.request['nodeId']) if (nodeId != 'root'): new_root = uuidToObject(nodeId) if ILanguage(new_root).get_language() == lang: folder_path = '/'.join(new_root.getPhysicalPath()) if folder_path == '': # We get the root folder root = getToolByName(self.context, 'portal_url') root = root.getPortalObject() folder_path = '/'.join(root.getPhysicalPath()) self.request.response.setHeader("Content-type", "application/json; charset=utf-8") pcatalog = getToolByName(self.context, 'portal_catalog') query = {} query['path'] = {'query': folder_path, 'depth': 1} query['sort_on'] = "sortable_title" query['sort_order'] = "ascending" query['Language'] = lang search_results = pcatalog.searchResults(query) resultat = { 'id': 'root', 'name': folder_path, 'data': {}, 'children': [] } # Get the canonicals storage = getUtility(IMultilingualStorage) canonicals = storage.get_canonicals() supported_languages = tool.getSupportedLanguages() for sr in search_results: # We want to know the translated and missing elements translations = {} if sr['UID'] in canonicals: # We look for the brain for each translation canonical = canonicals[sr['UID']] for lang in supported_languages: if lang in canonical.get_keys(): translated_obj = uuidToObject(canonical.get_item(lang)) translations[lang] = { 'url': translated_obj.absolute_url(), 'title': translated_obj.getId() } else: url_to_create = "%s/@@create_translation?form.widgets.\ language=%s&form.buttons.create=1" % (sr.getURL(), lang) translations[lang] = { 'url': url_to_create, 'title': _(u'Not translated') } if get_all: resultat['children'].append({ 'id': sr['UID'], 'name': sr['Title'], 'data': translations, 'children': [] }) else: pass return json.dumps(resultat)
def languages(self): context = aq_inner(self.context) registry = getUtility(IRegistry) find_translations_policy = registry.forInterface(IMultiLanguagePolicies).selector_lookup_translations_policy languages_info = super(LanguageSelectorViewlet, self).languages() supported_langs = [v['code'] for v in languages_info] results = [] # If it's neutral language don't do anything if ITranslatable.providedBy(context) and ILanguage(context).get_language() == LANGUAGE_INDEPENDENT: translations = {} elif find_translations_policy == 'closest': translations = self._get_translations_by_closest(supported_langs) else: translations = self._get_translations_by_dialog(supported_langs) # We want to preserve the current template / view as used for the # current object and also use it for the other languages append_path = self._findpath(context.getPhysicalPath(), self.request.get('PATH_INFO', '')) formvariables = self._formvariables(self.request.form) _checkPermission = getSecurityManager().checkPermission non_viewable = set() for lang_info in languages_info: # Avoid to modify the original language dict data = lang_info.copy() code = str(data['code']) data['translated'] = code in translations.keys() set_language = '?set_language=%s' % code try: appendtourl = '/'.join(append_path) if self.set_language: appendtourl += '?' + make_query(formvariables, dict(set_language=code)) elif formvariables: appendtourl += '?' + make_query(formvariables) except UnicodeError: appendtourl = '/'.join(append_path) if self.set_language: appendtourl += set_language 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 state = getMultiAdapter((trans, self.request), name='plone_context_state') if direct: try: data['url'] = state.canonical_object_url() + \ appendtourl except AttributeError: data['url'] = context.absolute_url() + appendtourl else: try: data['url'] = state.canonical_object_url() + \ set_language except AttributeError: data['url'] = context.absolute_url() + set_language else: has_view_permission = bool(_checkPermission('View', context)) # Ideally, we should also check the View permission of default # items of folderish objects. # However, this would be expensive at it would mean that the # default item should be loaded as well. # # IOW, it is a conscious decision to not take in account the # use case where a user has View permission a folder but not on # its default item. if not has_view_permission: non_viewable.add((data['code'])) continue state = getMultiAdapter((context, self.request), name='plone_context_state') if find_translations_policy == 'closest': try: data['url'] = state.canonical_object_url() + appendtourl except AttributeError: data['url'] = context.absolute_url() + appendtourl else: try: data['url'] = state.canonical_object_url() + NOT_TRANSLATED_YET_TEMPLATE + '?' + make_query(dict(set_language=code)) except AttributeError: data['url'] = context.absolute_url() + NOT_TRANSLATED_YET_TEMPLATE + appendtourl results.append(data) # filter out non-viewable items results = [r for r in results if r['code'] not in non_viewable] return results