code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.authentication.interfaces import IAuthentication, PrincipalLookupError
from zope.pluggableauth.interfaces import IPrincipalInfo
from zope.pluggableauth.plugins.groupfolder import IGroupFolder
from zope.pluggableauth.plugins.principalfolder import IInternalPrincipalContainer
# import local interfaces
from ztfy.security.interfaces import IAuthenticatorSearchAdapter
# import Zope3 packages
from zope.component import adapts, queryUtility
from zope.i18n import translate
from zope.interface import implements
# import local packages
from ztfy.utils.request import getRequest, getRequestData, setRequestData
from ztfy.security import _
class NoPrincipal(object):
implements(IPrincipalInfo)
def __init__(self):
self.id = ''
title = _("No selected principal")
description = _("No principal was selected")
class MissingPrincipal(object):
implements(IPrincipalInfo)
def __init__(self, uid):
self.id = uid
self.request = getRequest()
@property
def title(self):
return translate(_("< missing principal %s >"), context=self.request) % self.id
@property
def description(self):
return translate(_("This principal can't be found in any authentication utility..."), context=self.request)
class PrincipalFolderSearchAdapter(object):
"""Principal folder search adapter"""
adapts(IInternalPrincipalContainer)
implements(IAuthenticatorSearchAdapter)
def __init__(self, context):
self.context = context
def search(self, query):
return self.context.search({ 'search': query })
class GroupFolderSearchAdapter(object):
"""Principal group search adapter"""
adapts(IGroupFolder)
implements(IAuthenticatorSearchAdapter)
def __init__(self, context):
self.context = context
def search(self, query):
return self.context.search({ 'search': query })
REQUEST_PRINCIPALS_KEY = 'ztfy.security.principals.cache'
def getPrincipal(uid, auth=None, request=None):
"""Get a principal"""
if not uid:
return NoPrincipal()
if request is not None:
cache = getRequestData(REQUEST_PRINCIPALS_KEY, request, None)
if cache and (uid in cache):
return cache[uid]
if auth is None:
auth = queryUtility(IAuthentication)
if auth is None:
return NoPrincipal()
try:
result = auth.getPrincipal(uid)
except PrincipalLookupError:
return MissingPrincipal(uid)
else:
if request is not None:
cache = cache or {}
cache[uid] = result
setRequestData(REQUEST_PRINCIPALS_KEY, cache, request)
return result
def findPrincipals(query, names=None):
"""Search for principals"""
query = query.strip()
if not query:
return ()
auth = queryUtility(IAuthentication)
if auth is None:
return ()
if isinstance(names, (str, unicode)):
names = names.split(',')
result = []
for name, plugin in auth.getQueriables():
if (not names) or (name in names):
search = IAuthenticatorSearchAdapter(plugin.authplugin, None)
if search is not None:
result.extend([getPrincipal(uid, auth) for uid in search.search(query)])
return sorted(result, key=lambda x: x.title) | ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/search.py | search.py |
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
from zope.interface import Interface, Attribute
from zope.lifecycleevent.interfaces import IObjectModifiedEvent
from zope.schema import Tuple, TextLine
# import local packages
from ztfy.security import _
class IBaseRoleEvent(IObjectModifiedEvent):
"""Base interface for roles events"""
principal = Attribute(_("Name of the principal who received the new role"))
role = Attribute(_("The role who was granted"))
class IGrantedRoleEvent(IBaseRoleEvent):
"""Event interface notified when a role is granted"""
class IRevokedRoleEvent(IBaseRoleEvent):
"""Event interface notified when a role is revoked"""
class ILocalRoleManager(Interface):
"""This interface is used to define classes which can handle local roles"""
__roles__ = Tuple(title=_("Local roles"),
description=_("List of roles IDs handled by local context"),
required=True,
readonly=True,
value_type=TextLine(title=_("Role ID")))
class ILocalRoleIndexer(Interface):
"""This interface is used to help indexing of local roles"""
def __getattr__(self, name):
"""Get list of principal IDs with granted role name"""
class SecurityManagerException(Exception):
"""Security manager exception"""
class ISecurityManagerRoleChecker(Interface):
"""Security manager role checker"""
def canGrantRole(role, principal):
"""Return True is role can be granted to principal"""
def canRevokeRole(role, principal):
"""Return True is role can be revoked from principal"""
class ISecurityManagerBase(Interface):
"""Untrusted security manager interface"""
def canUsePermission(permission):
"""Return true or false to specify permission usage for given principal"""
def canView():
"""Return true or false if 'zope.View' permission is granted to given principal"""
class ISecurityManagerReader(Interface):
"""Wrapper interface around Zope3 security roles and permissions"""
def getLocalRoles(principal=None):
"""Get principal allowed and denied roles on current object
Result is given as a dictionary :
{ 'allow': ['role1','role2'], 'deny': ['role3',] }
"""
def getLocalAllowedRoles(principal=None):
"""Get list of locally allowed roles"""
def getLocalDeniedRoles(principal=None):
"""Get list of locally denied roles"""
def getRoles(principal=None):
"""Get list of roles, including inherited ones
Result is given as a dictionary :
{ 'allow': ['role1','role2'], 'deny': ['role3',] }
"""
def getAllowedRoles(principal=None):
"""Get list of allowed roles, including inherited ones"""
def getDeniedRoles(principal=None):
"""Get list of denied roles, including inherited ones"""
def getLocalPrincipals(role):
"""Get list of principals with locally defined role
Result is given as a dictionary :
{ 'allow': ['principal1','principal2'], 'deny': ['principal3',] }
"""
def getLocalAllowedPrincipals(role):
"""Get list of principals with locally granted role"""
def getLocalDeniedPrincipals(role):
"""Get list of principals with locally denied role"""
def getPrincipals(role):
"""Get list of principals with access defined for allowed role, including inherited ones
Result is given as a dictionary :
{ 'allow': ['principal1','principal2'], 'deny': ['principal3',] }
"""
def getAllowedPrincipals(role):
"""Get list of principals with granted access to specified role, including inherited ones"""
def getDeniedPrincipals(role):
"""Get list of principals with denied access to specified role, including inherited ones"""
def canUseRole(role, principal=None):
"""Return true or false to specify role usage for given principal"""
class ISecurityManagerWriter(Interface):
"""Wrapper interface around Zope3 security affectations"""
def grantPermission(permission, principal):
"""Grant given permission to the principal"""
def grantRole(role, principal, notify=True):
"""Grant given role to the principal"""
def unsetPermission(permission, principal):
"""Revoke given permission to the principal, falling back to normal acquisition"""
def unsetRole(role, principal, notify=True):
"""Revoke given role to the principal, falling back to normal acquisition"""
def denyPermission(permission, principal):
"""Forbid usage of the given permission to the principal, ignoring acquisition"""
def revokeRole(role, principal, notify=True):
"""Forbid usage of the given role to the principal, ignoring acquisition"""
class ISecurityManager(ISecurityManagerBase, ISecurityManagerReader, ISecurityManagerWriter):
"""Marker interface for security management wrapper"""
class IAuthenticatorSearchAdapter(Interface):
"""Common search adapter for authenticators"""
def search(query):
"""Get principals matching search query""" | ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/interfaces.py | interfaces.py |
__docformat__ = "restructuredtext"
# import standard packages
import transaction
# import Zope3 interfaces
from zope.catalog.interfaces import ICatalog
from zope.component.interfaces import IComponentRegistry, ISite
from zope.intid.interfaces import IIntIds
from zope.processlifetime import IDatabaseOpenedWithRoot
# import local interfaces
from ztfy.security.interfaces import ILocalRoleIndexer
from ztfy.utils.interfaces import INewSiteManagerEvent
# import Zope3 packages
from zc.catalog.catalogindex import SetIndex
from zope.app.publication.zopepublication import ZopePublication
from zope.catalog.catalog import Catalog
from zope.component import adapter, queryUtility
from zope.intid import IntIds
from zope.location import locate
from zope.site import hooks
# import local packages
from ztfy.security.indexer import ALL_ROLES_INDEX_NAME
from ztfy.utils.site import locateAndRegister
def updateDatabaseIfNeeded(context):
"""Check for missing utilities at application startup"""
try:
sm = context.getSiteManager()
except:
return
default = sm['default']
# Check for required IIntIds utility
intids = queryUtility(IIntIds)
if intids is None:
intids = default.get('IntIds')
if intids is None:
intids = IntIds()
locate(intids, default)
IComponentRegistry(sm).registerUtility(intids, IIntIds, '')
default['IntIds'] = intids
# Check for security catalog and indexes
catalog = default.get('SecurityCatalog')
if catalog is None:
catalog = Catalog()
locateAndRegister(catalog, default, 'SecurityCatalog', intids)
IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'SecurityCatalog')
if catalog is not None:
if ALL_ROLES_INDEX_NAME not in catalog:
index = SetIndex(ALL_ROLES_INDEX_NAME, ILocalRoleIndexer, False)
locateAndRegister(index, catalog, ALL_ROLES_INDEX_NAME, intids)
@adapter(IDatabaseOpenedWithRoot)
def handleOpenedDatabase(event):
db = event.database
connection = db.open()
root = connection.root()
root_folder = root.get(ZopePublication.root_name, None)
for site in root_folder.values():
if ISite(site, None) is not None:
hooks.setSite(site)
updateDatabaseIfNeeded(site)
transaction.commit()
@adapter(INewSiteManagerEvent)
def handleNewSiteManager(event):
updateDatabaseIfNeeded(event.object) | ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/database.py | database.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.schema.interfaces import IField
from zope.security.interfaces import IPrincipal
# import local interfaces
from ztfy.security.interfaces import ISecurityManager
# import Zope3 packages
# import local packages
from ztfy.security import _
class RolePrincipalsProperty(object):
"""Principals list property matching local role owners"""
def __init__(self, field, role, name=None, output=str, **args):
if not IField.providedBy(field):
raise ValueError, _("Provided field must implement IField interface...")
if output not in (str, list):
raise ValueError, _("Field output must be 'list' or 'str' types")
if name is None:
name = field.__name__
self.__field = field
self.__name = name
self.__role = role
self.__output = output
self.__args = args
def __get__(self, instance, klass):
if instance is None:
return self
sm = ISecurityManager(instance, None)
if sm is None:
result = []
else:
result = sm.getLocalAllowedPrincipals(self.__role)
if self.__output is str:
return ','.join(result)
else:
return result
def __set__(self, instance, value):
if value is None:
value = []
elif isinstance(value, (str, unicode)):
value = value.split(',')
for i, v in enumerate(value):
if IPrincipal.providedBy(v):
value[i] = v.id
field = self.__field.bind(instance)
field.validate(value)
if field.readonly:
raise ValueError(self.__name, _("Field is readonly"))
sm = ISecurityManager(instance, None)
principals = sm.getLocalAllowedPrincipals(self.__role)
removed = set(principals) - set(value)
added = set(value) - set(principals)
for principal in removed:
sm.unsetRole(self.__role, principal)
for principal in added:
sm.grantRole(self.__role, principal) | ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/property.py | property.py |
# import standard packages
import hmac
from datetime import date
from hashlib import sha1
from persistent import Persistent
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
from zope.authentication.interfaces import IAuthentication
from zope.container.contained import Contained
from zope.interface import implements, Interface
from zope.pluggableauth.factories import PrincipalInfo
from zope.pluggableauth.interfaces import ICredentialsPlugin, IAuthenticatorPlugin
from zope.pluggableauth.plugins.principalfolder import IInternalPrincipalContainer
from zope.publisher.interfaces.http import IHTTPRequest
from zope.schema import TextLine
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.utils.traversing import getParent
from ztfy.security import _
class TokenCredentialsUtility(Persistent, Contained):
"""Token credentials extraction utility"""
implements(ICredentialsPlugin)
loginfield = 'login'
tokenfield = 'token'
def extractCredentials(self, request):
if not IHTTPRequest.providedBy(request):
return None
if not (request.get(self.loginfield) and request.get(self.tokenfield)):
return None
return {'login': request.get(self.loginfield),
'token': request.get(self.tokenfield)}
def challenge(self, request):
return False
def logout(self, request):
return False
class ITokenAuthenticationUtility(Interface):
"""Token authentication utility interface"""
encryption_key = TextLine(title=_("Encryption key"),
description=_("This key is used to encrypt login:password string "
"with HMAC+SHA1 protocol"),
required=True)
class TokenAuthenticationUtility(Persistent, Contained):
"""Token authentication checker utility
Be warned that authentication mechanism can only be checked against an
InternalPrincipal using plain text password manager...
"""
implements(ITokenAuthenticationUtility, IAuthenticatorPlugin)
encryption_key = FieldProperty(ITokenAuthenticationUtility['encryption_key'])
def authenticateCredentials(self, credentials):
if not isinstance(credentials, dict):
return None
if not ('login' in credentials and 'token' in credentials):
return None
login = credentials['login']
token = credentials['token']
if not (login and token):
return None
utility = getParent(self, IAuthentication)
if utility is None:
return None
for name, plugin in utility.getAuthenticatorPlugins():
if not IInternalPrincipalContainer.providedBy(plugin):
continue
try:
id = plugin.getIdByLogin(login)
principal = plugin[login]
except KeyError:
continue
else:
source = '%s:%s:%s' % (principal.login,
principal.password,
date.today().strftime('%Y%m%d'))
encoded = hmac.new(self.encryption_key.encode('utf-8'), source, sha1)
if encoded.hexdigest() == token:
return PrincipalInfo(id, principal.login, principal.title, principal.description)
def principalInfo(self, id):
return None | ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/auth/token.py | token.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import IFieldWidget
from zope.schema.interfaces import IField
# import local interfaces
from ztfy.security.browser.widget.interfaces import IPrincipalWidget, IPrincipalListWidget
from ztfy.skin.layer import IZTFYBrowserLayer
# import Zope3 packages
from z3c.form.browser.text import TextWidget
from z3c.form.widget import FieldWidget
from zope.component import adapter
from zope.interface import implementer, implementsOnly
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.jqueryui import jquery_multiselect
from ztfy.security.search import getPrincipal
class PrincipalWidget(TextWidget):
"""Principal widget"""
implementsOnly(IPrincipalWidget)
query_name = 'findPrincipals'
auth_plugins = ()
@property
def principal(self):
return getPrincipal(self.value)
@property
def principal_map(self):
if not self.value:
return u''
principal = self.principal
if principal is None:
return ''
return "{ '%s': '%s' }" % (principal.id,
principal.title.replace("'", "'"))
@property
def auth_plugins_value(self):
return (";;{'names':'%s'}" % ','.join(self.auth_plugins)) if self.auth_plugins else ''
def render(self):
jquery_multiselect.need()
return super(PrincipalWidget, self).render()
@adapter(IField, IZTFYBrowserLayer)
@implementer(IFieldWidget)
def PrincipalFieldWidget(field, request):
"""IPrincipalWidget factory for Principal fields"""
return FieldWidget(field, PrincipalWidget(request))
class PrincipalListWidget(TextWidget):
"""Principals list widget"""
implementsOnly(IPrincipalListWidget)
query_name = 'findPrincipals'
auth_plugins = ()
backspace_removes_last = FieldProperty(IPrincipalListWidget['backspace_removes_last'])
@property
def principals(self):
if not hasattr(self, '_v_principals'):
self._v_principals = sorted((getPrincipal(v) for v in self.value.split(',')), key=lambda x: x.title)
return self._v_principals
def get_value(self):
return ','.join((principal.id for principal in self.principals))
@property
def principals_map(self):
return '{ %s }' % ',\n'.join(("'%s': '%s'" % (principal.id, principal.title.replace("'", "'"))
for principal in self.principals))
@property
def auth_plugins_value(self):
return (";;{'names':'%s'}" % ','.join(self.auth_plugins)) if self.auth_plugins else ''
def render(self):
jquery_multiselect.need()
return super(PrincipalListWidget, self).render()
@adapter(IField, IZTFYBrowserLayer)
@implementer(IFieldWidget)
def PrincipalListFieldWidget(field, request):
"""IPrincipalListWidget factory for PrincipalList fields"""
return FieldWidget(field, PrincipalListWidget(request)) | ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/browser/widget/principal.py | principal.py |
=====================
ztfy.security package
=====================
.. contents::
What is ztfy.security ?
=======================
ztfy.security is a thin wrapper around zope.security and zope.securitypolicy packages.
It provides an adapter to ISecurityManager interfaces, which allows you to get and set roles and
permissions applied to a given principal on a given adapted context.
This adapter also allows you to fire events when a role is granted or revoked to a given principal ; this
functionality can be useful, for example, when you want to forbid removal of a 'contributor' role to a principal
when he already owns a set of contents.
Finally, ztfy.security provides a small set of schema fields, which can be used when you want to define a
field as a principal id or as a list of principals ids.
How to use ztfy.security ?
==========================
ztfy.security package usage is described via doctests in ztfy/security/doctests/README.txt
| ztfy.security | /ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/docs/README.txt | README.txt |
__docformat__ = "restructuredtext"
# import standard packages
import transaction
# import Zope3 interfaces
from z3c.language.negotiator.interfaces import INegotiatorManager
from zope.authentication.interfaces import IAuthentication
from zope.catalog.interfaces import ICatalog
from zope.component.interfaces import IComponentRegistry, ISite
from zope.i18n.interfaces import INegotiator
from zope.intid.interfaces import IIntIds
from zope.processlifetime import IDatabaseOpenedWithRoot
# import local interfaces
from ztfy.base.interfaces import IPathElements, IBaseContentType
from ztfy.i18n.interfaces.content import II18nBaseContent
from ztfy.security.interfaces import ISecurityManager, ILocalRoleManager, ILocalRoleIndexer
from ztfy.sendit.packet.interfaces import IPacket
from ztfy.utils.interfaces import INewSiteManagerEvent
from ztfy.utils.timezone.interfaces import IServerTimezone
# import Zope3 packages
from z3c.language.negotiator.app import Negotiator
from zc.catalog.catalogindex import SetIndex, ValueIndex, DateTimeValueIndex
from zope.app.publication.zopepublication import ZopePublication
from zope.catalog.catalog import Catalog
from zope.component import adapter, queryUtility
from zope.intid import IntIds
from zope.location import locate
from zope.pluggableauth.authentication import PluggableAuthentication
from zope.pluggableauth.plugins.groupfolder import GroupFolder, GroupInformation
from zope.pluggableauth.plugins.principalfolder import PrincipalFolder
from zope.site import hooks
# import local packages
from ztfy.utils.catalog.index import TextIndexNG
from ztfy.utils.site import locateAndRegister
from ztfy.utils.timezone.utility import ServerTimezoneUtility
def updateDatabaseIfNeeded(context):
"""Check for missing utilities at application startup"""
try:
sm = context.getSiteManager()
except:
return
default = sm['default']
# Check for required IIntIds utility
intids = queryUtility(IIntIds)
if intids is None:
intids = default.get('IntIds')
if intids is None:
intids = IntIds()
locate(intids, default)
IComponentRegistry(sm).registerUtility(intids, IIntIds, '')
default['IntIds'] = intids
# Check authentication utility
auth = default.get('Authentication')
if auth is None:
auth = PluggableAuthentication()
locateAndRegister(auth, default, 'Authentication', intids)
auth.credentialsPlugins = [ u'No Challenge if Authenticated',
u'Session Credentials',
u'Zope Realm Basic-Auth' ]
IComponentRegistry(sm).registerUtility(auth, IAuthentication)
if 'users' not in auth:
folder = PrincipalFolder('usr.')
locateAndRegister(folder, auth, 'users', intids)
auth.authenticatorPlugins += ('users',)
groups = auth.get('groups', None)
if groups is None:
groups = GroupFolder('grp.')
locateAndRegister(groups, auth, 'groups', intids)
auth.authenticatorPlugins += ('groups',)
roles_manager = ILocalRoleManager(context, None)
if 'administrators' not in groups:
group = GroupInformation('Administrators (group)', "Group of site administrators, which handle application configuration")
locateAndRegister(group, groups, 'administrators', intids)
if (roles_manager is None) or ('ztfy.SenditAdministrator' in roles_manager.__roles__):
ISecurityManager(context).grantRole('ztfy.SenditAdministrator', 'grp.administrators', False)
if 'managers' not in groups:
group = GroupInformation('Managers (group)', "Group of site system services and utilities managers")
locateAndRegister(group, groups, 'managers', intids)
if (roles_manager is None) or ('ztfy.SenditManager' in roles_manager.__roles__):
ISecurityManager(context).grantRole('ztfy.SenditManager', 'grp.managers', False)
# Check server timezone
tz = queryUtility(IServerTimezone)
if tz is None:
tz = default.get('Timezone')
if tz is None:
tz = ServerTimezoneUtility()
locateAndRegister(tz, default, 'Timezone', intids)
IComponentRegistry(sm).registerUtility(tz, IServerTimezone)
# Check I18n negotiator
i18n = queryUtility(INegotiatorManager)
if i18n is None:
i18n = default.get('I18n')
if i18n is None:
i18n = Negotiator()
locateAndRegister(i18n, default, 'I18n', intids)
i18n.serverLanguage = u'en'
i18n.offeredLanguages = [u'en']
IComponentRegistry(sm).registerUtility(i18n, INegotiator)
IComponentRegistry(sm).registerUtility(i18n, INegotiatorManager)
# Check for required catalog and index
catalog = default.get('Catalog')
if catalog is None:
catalog = Catalog()
locateAndRegister(catalog, default, 'Catalog', intids)
IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'Catalog')
if catalog is not None:
if 'paths' not in catalog:
index = SetIndex('paths', IPathElements, False)
locateAndRegister(index, catalog, 'paths', intids)
if 'content_type' not in catalog:
index = ValueIndex('content_type', IBaseContentType, False)
locateAndRegister(index, catalog, 'content_type', intids)
if 'expiration_date' not in catalog:
index = DateTimeValueIndex('expiration_date', IPacket, False, resolution=1)
locateAndRegister(index, catalog, 'expiration_date', intids)
if 'title' not in catalog:
index = TextIndexNG('title shortname description heading', II18nBaseContent, False,
languages=('fr en'),
storage='txng.storages.term_frequencies',
dedicated_storage=False,
use_stopwords=True,
use_normalizer=True,
ranking=True)
locateAndRegister(index, catalog, 'title', intids)
# Check for security catalog and indexes
catalog = default.get('SecurityCatalog')
if catalog is None:
catalog = Catalog()
locateAndRegister(catalog, default, 'SecurityCatalog', intids)
IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'SecurityCatalog')
if catalog is not None:
if 'ztfy.SenditRecipient' not in catalog:
index = SetIndex('ztfy.SenditRecipient', ILocalRoleIndexer, False)
locateAndRegister(index, catalog, 'ztfy.SenditRecipient', intids)
@adapter(IDatabaseOpenedWithRoot)
def handleOpenedDatabase(event):
db = event.database
connection = db.open()
root = connection.root()
root_folder = root.get(ZopePublication.root_name, None)
for site in root_folder.values():
if ISite(site, None) is not None:
hooks.setSite(site)
updateDatabaseIfNeeded(site)
transaction.commit()
@adapter(INewSiteManagerEvent)
def handleNewSiteManager(event):
updateDatabaseIfNeeded(event.object) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/database.py | database.py |
# import standard packages
from datetime import datetime
from persistent import Persistent
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.dublincore.interfaces import IZopeDublinCore
from zope.principalannotation.interfaces import IPrincipalAnnotationUtility
from zope.security.interfaces import IPrincipal
# import local interfaces
from ztfy.sendit.packet.interfaces import IDocument, IPacket
from ztfy.sendit.profile.interfaces.history import IDocumentHistory, IPacketHistory, IProfileHistory
# import Zope3 packages
from zope.component import adapter, queryUtility
from zope.container.btree import BTreeContainer
from zope.container.contained import Contained
from zope.event import notify
from zope.interface import implementer, implements
from zope.lifecycleevent import ObjectCreatedEvent
from zope.location.location import locate
from zope.schema.fieldproperty import FieldProperty
from ztfy.security.search import getPrincipal
# import local packages
from ztfy.security.property import RolePrincipalsProperty
from ztfy.utils.timezone import tztime
#
# Document history classes
#
class DocumentHistory(Persistent, Contained):
"""Document history object"""
implements(IDocumentHistory)
title = FieldProperty(IDocumentHistory['title'])
filename = FieldProperty(IDocumentHistory['filename'])
contentType = FieldProperty(IDocumentHistory['contentType'])
contentSize = FieldProperty(IDocumentHistory['contentSize'])
downloaders = FieldProperty(IDocumentHistory['downloaders'])
@adapter(IDocument)
@implementer(IDocumentHistory)
def DocumentHistoryFactory(document):
history = DocumentHistory()
history.title = document.title
history.filename = document.filename
history.contentType = unicode(document.data.contentType)
history.contentSize = document.data.getSize()
downloaders = {}
for uid, date in (document.downloaders or {}).items():
downloaders[unicode(getPrincipal(uid).title)] = date
history.downloaders = downloaders
return history
#
# Packet history classes
#
class PacketHistory(BTreeContainer):
"""packet history object"""
implements(IPacketHistory)
title = FieldProperty(IPacketHistory['title'])
description = FieldProperty(IPacketHistory['description'])
recipients = FieldProperty(IPacketHistory['recipients'])
creation_time = FieldProperty(IPacketHistory['creation_time'])
expiration_date = FieldProperty(IPacketHistory['expiration_date'])
deletion_time = FieldProperty(IPacketHistory['deletion_time'])
@adapter(IPacket, IProfileHistory)
@implementer(IPacketHistory)
def PacketHistoryFactory(packet, profile_history):
history = PacketHistory()
notify(ObjectCreatedEvent(history))
locate(history, profile_history)
history.title = packet.title
history.description = packet.description
history.recipients = [unicode(getPrincipal(uid).title) for uid in packet.recipients.split(',')]
history.creation_time = tztime(IZopeDublinCore(packet).created)
history.expiration_date = packet.expiration_date.date()
history.deletion_time = tztime(datetime.utcnow())
for name, document in packet.items():
history[name] = IDocumentHistory(document)
return history
#
# Profile history classes and adapters
#
class UserProfileHistory(BTreeContainer):
"""User profile history"""
implements(IProfileHistory)
owner = RolePrincipalsProperty(IProfileHistory['owner'], role='ztfy.SenditProfileOwner')
SENDIT_USER_HISTORY = 'ztfy.sendit.history'
@adapter(IPrincipal)
@implementer(IProfileHistory)
def UserProfileHistoryFactory(principal):
if principal.id == 'zope.anybody':
return None
utility = queryUtility(IPrincipalAnnotationUtility)
if utility is not None:
annotations = IAnnotations(utility.getAnnotationsById(principal.id))
history = annotations.get(SENDIT_USER_HISTORY)
if history is None:
history = annotations[SENDIT_USER_HISTORY] = UserProfileHistory()
history.owner = principal.id
notify(ObjectCreatedEvent(history))
locate(history, utility)
return history
def getUserProfileHistory(principal, create=True):
if IPrincipal.providedBy(principal):
principal = principal.id
if principal == 'zope.anybody':
return None
utility = queryUtility(IPrincipalAnnotationUtility)
if utility is not None:
annotations = IAnnotations(utility.getAnnotationsById(principal))
history = annotations.get(SENDIT_USER_HISTORY)
if (history is None) and create:
history = annotations[SENDIT_USER_HISTORY] = UserProfileHistory()
history.owner = principal
notify(ObjectCreatedEvent(history))
locate(history, utility)
return history | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/profile/history.py | history.py |
# import standard packages
from datetime import datetime
# import Zope3 interfaces
from zope.dublincore.interfaces import IZopeDublinCore
from zope.pluggableauth.interfaces import IAuthenticatorPlugin
from zope.principalannotation.interfaces import IPrincipalAnnotationUtility
# import local interfaces
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.profile.interfaces import IProfilesCleanerTask
# import Zope3 packages
from zope.component import queryUtility, getUtility
from zope.interface import implements
from zope.security.proxy import removeSecurityProxy
# import local packages
from ztfy.scheduler.task import BaseTask
from ztfy.sendit.profile import SENDIT_USER_PROFILE
from ztfy.utils.timezone import tztime
from ztfy.utils.traversing import getParent
class ProfilesCleanerTask(BaseTask):
"""Profiles cleaning task
This task is automatically deleting non-activated profiles
"""
implements(IProfilesCleanerTask)
def run(self, report):
count = 0
principal_annotations = queryUtility(IPrincipalAnnotationUtility)
if principal_annotations is None:
raise Exception("No principal annotations utility found")
principal_annotations = removeSecurityProxy(principal_annotations)
app = getParent(self, ISenditApplication)
auth_plugin = getUtility(IAuthenticatorPlugin, app.external_auth_plugin)
prefix_length = len(auth_plugin.prefix)
for principal_id, annotations in principal_annotations.annotations.items():
# only check for external users
if auth_plugin.principalInfo(principal_id) is None:
continue
# get SendIt profile
profile = annotations.get(SENDIT_USER_PROFILE)
if (profile is not None) and not profile.activated:
created = IZopeDublinCore(profile).created
# get time elapsed since profile creation date
if (tztime(datetime.utcnow()) - tztime(created)).days > app.confirmation_delay:
report.write(' - deleting profile %s (created on %s)\n' % (annotations.__name__,
tztime(created).strftime('%Y-%m-%d')))
del annotations[SENDIT_USER_PROFILE]
# delete all profile annotations if empty
if not annotations.data:
del principal_annotations.annotations[principal_id]
# delete user
del auth_plugin[principal_id[prefix_length:]]
count += 1
if count > 0:
report.write('--------------------\n')
report.write('%d profile(s) deleted' % count) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/profile/task.py | task.py |
# import standard packages
import base64
import hashlib
import hmac
import random
import sys
from datetime import datetime
from persistent import Persistent
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.pluggableauth.interfaces import IAuthenticatorPlugin
from zope.principalannotation.interfaces import IPrincipalAnnotationUtility
from zope.security.interfaces import IPrincipal
# import local interfaces
from ztfy.mail.interfaces import IPrincipalMailInfo
from ztfy.security.interfaces import ISecurityManager
from ztfy.sendit.profile.interfaces import IProfile
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
# import Zope3 packages
from zope.component import adapter, adapts, queryUtility, getUtilitiesFor
from zope.container.contained import Contained
from zope.event import notify
from zope.interface import implementer, implements, Invalid
from zope.lifecycleevent import ObjectCreatedEvent
from zope.location import locate
from zope.schema.fieldproperty import FieldProperty
from zope.security.proxy import removeSecurityProxy
# import local packages
from ztfy.security.property import RolePrincipalsProperty
from ztfy.security.search import getPrincipal
from ztfy.sendit.app.interfaces import ISenditApplication, EMAIL_REGEX
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
class UserProfile(Persistent, Contained):
"""User profile class"""
implements(IProfile)
owner = RolePrincipalsProperty(IProfile['owner'], role='ztfy.SenditProfileOwner')
@property
def owner_title(self):
return getPrincipal(self.owner).title
def getAuthenticatorPlugin(self):
result = getattr(self, '_v_authenticator', None)
if result is None:
result = (None, None, None)
for name, plugin in getUtilitiesFor(IAuthenticatorPlugin):
info = plugin.principalInfo(self.owner)
if info is not None:
result = (name, plugin, info)
break
self._v_authenticator = result
return result
def isExternal(self):
name, _plugin, _info = self.getAuthenticatorPlugin()
if name:
app = getParent(self, ISenditApplication)
return name == app.external_auth_plugin
self_registered = FieldProperty(IProfile['self_registered'])
activation_secret = FieldProperty(IProfile['activation_secret'])
activation_hash = FieldProperty(IProfile['activation_hash'])
activation_date = FieldProperty(IProfile['activation_date'])
activated = FieldProperty(IProfile['activated'])
def generateSecretKey(self, login, password):
seed = self.activation_secret = u'-'.join((str(random.randint(0, sys.maxint)) for i in range(5)))
secret = hmac.new(password.encode('utf-8'), login, digestmod=hashlib.sha256)
secret.update(seed)
self.activation_hash = base64.b32encode(secret.digest()).decode()
def checkActivation(self, hash, login, password):
if self.self_registered:
secret = hmac.new(password.encode('utf-8'), login, digestmod=hashlib.sha256)
secret.update(self.activation_secret)
if hash != base64.b32encode(secret.digest()).decode():
raise Invalid, _("Can't activate profile with given params")
else:
# Just check that hash is matching and update user password
if hash != self.activation_hash:
raise Invalid, _("Can't activate profile with given params")
app = getParent(self, ISenditApplication)
plugin = queryUtility(IAuthenticatorPlugin, app.external_auth_plugin)
principal = removeSecurityProxy(plugin[login])
principal.password = password
filtered_uploads = FieldProperty(IProfile['filtered_uploads'])
_disabled_upload = FieldProperty(IProfile['disabled_upload'])
_disabled_upload_date = FieldProperty(IProfile['disabled_upload_date'])
@property
def disabled_upload(self):
return self._disabled_upload
@disabled_upload.setter
def disabled_upload(self, value):
app = getParent(self, ISenditApplication)
if value:
if not self._disabled_upload:
self._disabled_upload_date = datetime.utcnow()
ISecurityManager(app).denyPermission('ztfy.UploadSenditPacket', self.owner)
else:
self._disabled_upload_date = None
ISecurityManager(app).unsetPermission('ztfy.UploadSenditPacket', self.owner)
self._disabled_upload = value
_disabled = FieldProperty(IProfile['disabled'])
_disabled_date = FieldProperty(IProfile['disabled_date'])
@property
def disabled(self):
return self._disabled
@disabled.setter
def disabled(self, value):
app = getParent(self, ISenditApplication)
if value:
if not self._disabled:
self._disabled_date = datetime.utcnow()
self.disabled_upload = value
ISecurityManager(app).denyPermission('ztfy.ViewSenditApplication', self.owner)
else:
self._disabled_date = None
ISecurityManager(app).unsetPermission('ztfy.ViewSenditApplication', self.owner)
self._disabled = value
quota_size = FieldProperty(IProfile['quota_size'])
max_documents = FieldProperty(IProfile['max_documents'])
quota_usage = FieldProperty(IProfile['quota_usage'])
quota_size_str = FieldProperty(IProfile['quota_size_str'])
max_documents_str = FieldProperty(IProfile['max_documents_str'])
def getQuotaSize(self, context):
result = self.quota_size
if result is None:
app = getParent(context, ISenditApplication)
result = app.default_quota_size
return result
def getQuotaUsage(self, context):
app = getParent(context, ISenditApplication)
folder = ISenditApplicationUsers(app).getUserFolder(self.owner)
if folder is not None:
return folder.getQuotaUsage()
else:
return 0
def getQuotaUsagePc(self, context):
quota = self.getQuotaSize(context)
if quota == 0:
return 0
usage = self.getQuotaUsage(context)
return int(round(1. * usage / (quota * 1024 * 1024) * 100))
def getMaxDocuments(self, context):
result = self.max_documents
if result is None:
app = getParent(context, ISenditApplication)
result = app.default_max_documents
return result
#
# Profile adapters
#
SENDIT_USER_PROFILE = 'ztfy.sendit.profile'
@adapter(IPrincipal)
@implementer(IProfile)
def UserProfileFactory(principal):
if principal.id == 'zope.anybody':
return None
utility = queryUtility(IPrincipalAnnotationUtility)
if utility is not None:
annotations = IAnnotations(utility.getAnnotationsById(principal.id))
profile = annotations.get(SENDIT_USER_PROFILE)
if profile is None:
profile = annotations[SENDIT_USER_PROFILE] = UserProfile()
profile.owner = principal.id
notify(ObjectCreatedEvent(profile))
locate(profile, utility)
return profile
def getUserProfile(principal, create=True):
if IPrincipal.providedBy(principal):
principal = principal.id
principal = principal.lower()
if principal == 'zope.anybody':
return None
utility = queryUtility(IPrincipalAnnotationUtility)
if utility is not None:
annotations = IAnnotations(utility.getAnnotationsById(principal))
profile = annotations.get(SENDIT_USER_PROFILE)
if (profile is None) and create:
profile = annotations[SENDIT_USER_PROFILE] = UserProfile()
profile.owner = principal
notify(ObjectCreatedEvent(profile))
locate(profile, utility)
return profile
#
# Profile mail adapter
#
class UserProfileMailInfoAdapter(object):
"""User profile mail info adapter"""
adapts(IProfile)
implements(IPrincipalMailInfo)
def __new__(cls, context):
_name, _plugin, info = context.getAuthenticatorPlugin()
if (not info) or (not EMAIL_REGEX.match(info.login)):
return None
return object.__new__(cls)
def __init__(self, context):
self.context = context
def getAddresses(self):
_name, _plugin, info = self.context.getAuthenticatorPlugin()
return ((info.title, info.login), ) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/profile/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
# import local interfaces
from ztfy.scheduler.interfaces import ISchedulerTask
from ztfy.sendit.app.interfaces import checkPassword, EMAIL_REGEX
# import Zope3 packages
from zope.interface import Interface, Invalid, invariant
from zope.schema import Bool, TextLine, Datetime, Int, Password
# import local packages
from ztfy.captcha.schema import Captcha
from ztfy.security.schema import Principal
from ztfy.sendit import _
#
# User profile info
#
class IProfileInfo(Interface):
"""Basic profile info"""
owner = Principal(title=_("Profile owner"))
owner_title = TextLine(title=_("Profile owner"),
readonly=True)
def getAuthenticatorPlugin(self):
"""Get authentication plug-in"""
def isExternal(self):
"""Check if profile is matching an external principal"""
class IProfileActivationInfo(Interface):
"""Profile activation info"""
self_registered = Bool(title=_("Self-registered profile?"),
description=_("'No' means that profile creation was requested by another user"),
required=True,
default=True,
readonly=True)
activation_secret = TextLine(title=_("Activation secret key"),
description=_("This activation secret key is used to generate activation hash"))
activation_hash = TextLine(title=_("Activation string"),
description=_("This activation hash string is provided in the activation message URL"))
activation_date = Datetime(title=_("Activation date"))
activated = Bool(title=_("Activated profile?"),
description=_("If 'Yes', the profile owner activated his account and changed his password"),
required=True,
default=False)
def generateSecretKey(self, login, password):
"""Generate secret key for given profile"""
def checkActivation(self, hash, login, password):
"""Check activation for given settings"""
class IProfileActivationAdminInfo(Interface):
"""Profile settings only defined by application administrator"""
filtered_uploads = Bool(title=_("Filtered uploads"),
description=_("If 'Yes', uploaded packets are filtered for invalid contents"),
required=True,
default=True)
disabled_upload = Bool(title=_("Disabled upload?"),
description=_("If 'Yes', uploading new packets is disabled"),
required=True,
default=False)
disabled_upload_date = Datetime(title=_("Disable upload date"),
required=False)
disabled = Bool(title=_("Disabled profile?"),
description=_("If 'Yes', uploading and downloading of any packet is disabled and user can't use this service anymore"),
required=True,
default=False)
disabled_date = Datetime(title=_("Disable date"),
required=False)
class IProfileQuotaInfo(Interface):
"""Profile quotas interface"""
quota_size = Int(title=_("User quota size"),
description=_("User quota size is given in megabytes. Keep empty to get default system setting, 0 for unlimited quota"),
required=False)
quota_size_str = Int(title=_("Quota size"),
description=_("Maximum allowed storage, in megabytes. 'None' means that you don't have any limit."),
readonly=True)
quota_usage = Int(title=_("Current quota usage"),
readonly=True)
max_documents = Int(title=_("User max documents count"),
description=_("Maximum number of documents which can be send in a single packet. Keep empty to get default system setting, 0 for unlimited number"),
required=False)
max_documents_str = Int(title=_("Max documents count"),
description=_("Maximum number of documents which can be send in a single packet. 'None' means that you don't have any limit."),
readonly=True)
def getQuotaSize(self, context):
"""Get user quota size"""
def getQuotaUsage(self, context):
"""Get user quota usage"""
def getQuotaUsagePc(self, context):
"""Get user quota usage in percentage"""
def getMaxDocuments(self, context):
"""Get user maximum documents sount"""
class IProfile(IProfileInfo, IProfileActivationInfo, IProfileActivationAdminInfo, IProfileQuotaInfo):
"""User profile settings info
Profile define principal settings and is stored in principals annotations utility"""
#
# Registration interfaces
#
class IUserBaseRegistrationInfo(Interface):
"""User base registration info"""
email = TextLine(title=_("E-mail address"),
required=True,
readonly=True)
firstname = TextLine(title=_("First name"),
required=True)
lastname = TextLine(title=_("Last name"),
required=True)
company_name = TextLine(title=_("Company name"),
required=False)
password = Password(title=_("New password"),
min_length=8,
required=False)
confirm_password = Password(title=_("Confirm password"),
required=False)
@invariant
def checkPassword(self):
if self.password != self.confirm_password:
raise Invalid, _("Password and confirmed password don't match")
if not self.password:
return
checkPassword(self.password)
class IUserRegistrationInfo(IUserBaseRegistrationInfo):
"""User registration info"""
email = TextLine(title=_("E-mail address"),
description=_("An email will be sent to this address to validate account activation; it will be used as future user login"),
constraint=EMAIL_REGEX.match,
required=True)
firstname = TextLine(title=_("First name"),
required=True)
lastname = TextLine(title=_("Last name"),
required=True)
company_name = TextLine(title=_("Company name"),
required=False)
password = Password(title=_("Password"),
min_length=8,
required=True)
confirm_password = Password(title=_("Confirm password"),
required=True)
captcha = Captcha(title=_("Verification code"),
description=_("If code can't be read, click on image to generate a new captcha"),
required=True)
@invariant
def checkPassword(self):
if self.password != self.confirm_password:
raise Invalid, _("Password and confirmed password don't match")
checkPassword(self.password)
class IUserRegistrationConfirmInfo(Interface):
"""User registration confirmation dialog"""
activation_hash = TextLine(title=_("Activation string"))
email = TextLine(title=_("E-mail address"),
constraint=EMAIL_REGEX.match,
required=True)
password = Password(title=_("Password"),
min_length=8,
required=True)
confirm_password = Password(title=_("Confirm password"),
required=True)
captcha = Captcha(title=_("Verification code"),
description=_("If code can't be read, click on image to generate a new captcha"),
required=True)
@invariant
def checkPassword(self):
if self.password != self.confirm_password:
raise Invalid, _("Password and confirmed password don't match")
checkPassword(self.password)
#
# Profiles cleaner task interfaces
#
class IProfilesCleanerTaskInfo(Interface):
"""Profiles cleaner task info"""
class IProfilesCleanerTask(IProfilesCleanerTaskInfo, ISchedulerTask):
"""Profiles cleaner task interface""" | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/profile/interfaces/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
from persistent import Persistent
import re
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.security.interfaces import IPrincipal
# import local interfaces
from ztfy.sendit.app.interfaces import ISenditApplication, ISenditApplicationBackInfo, FilterException
from ztfy.sendit.app.interfaces.filter import IFilteringPlugin
# import Zope3 packages
from zope.app.content import queryContentType
from zope.component import adapter, queryUtility, getUtility
from zope.event import notify
from zope.interface import implementer, implements, alsoProvides, noLongerProvides
from zope.location.location import locate, Location
from zope.schema.fieldproperty import FieldProperty
from zope.site.site import SiteManagerContainer
# import local packages
from ztfy.extfile.blob import BlobImage, BlobFile
from ztfy.file.property import FileProperty, ImageProperty
from ztfy.i18n.property import I18nTextProperty, I18nImageProperty
from ztfy.security.property import RolePrincipalsProperty
from ztfy.utils.site import NewSiteManagerEvent
from ztfy.sendit import _
class SenditApplication(Persistent, SiteManagerContainer):
"""Sendit application main class"""
implements(ISenditApplication)
__roles__ = ('ztfy.SenditManager', 'ztfy.SenditAdministrator')
title = I18nTextProperty(ISenditApplication['title'])
shortname = I18nTextProperty(ISenditApplication['shortname'])
description = I18nTextProperty(ISenditApplication['description'])
keywords = I18nTextProperty(ISenditApplication['keywords'])
heading = I18nTextProperty(ISenditApplication['heading'])
header = I18nImageProperty(ISenditApplication['header'], klass=BlobImage, img_klass=BlobImage)
illustration = I18nImageProperty(ISenditApplication['illustration'], klass=BlobImage, img_klass=BlobImage)
illustration_title = I18nTextProperty(ISenditApplication['illustration_title'])
administrators = RolePrincipalsProperty(ISenditApplication['administrators'], role='ztfy.SenditAdministrator')
managers = RolePrincipalsProperty(ISenditApplication['managers'], role='ztfy.SenditManager')
open_registration = FieldProperty(ISenditApplication['open_registration'])
confirmation_delay = FieldProperty(ISenditApplication['confirmation_delay'])
internal_auth_plugins = FieldProperty(ISenditApplication['internal_auth_plugins'])
external_auth_plugin = FieldProperty(ISenditApplication['external_auth_plugin'])
single_auth_plugins = FieldProperty(ISenditApplication['single_auth_plugins'])
_filtering_plugins = FieldProperty(ISenditApplication['filtering_plugins'])
trusted_redirects = FieldProperty(ISenditApplication['trusted_redirects'])
enable_notifications = FieldProperty(ISenditApplication['enable_notifications'])
mailer_name = FieldProperty(ISenditApplication['mailer_name'])
mail_service_owner = I18nTextProperty(ISenditApplication['mail_service_owner'])
mail_service_name = I18nTextProperty(ISenditApplication['mail_service_name'])
mail_sender_name = FieldProperty(ISenditApplication['mail_sender_name'])
mail_sender_address = FieldProperty(ISenditApplication['mail_sender_address'])
mail_subject_header = I18nTextProperty(ISenditApplication['mail_subject_header'])
mail_signature = I18nTextProperty(ISenditApplication['mail_signature'])
default_quota_size = FieldProperty(ISenditApplication['default_quota_size'])
default_max_documents = FieldProperty(ISenditApplication['default_max_documents'])
excluded_domains = FieldProperty(ISenditApplication['excluded_domains'])
excluded_addresses = FieldProperty(ISenditApplication['excluded_addresses'])
excluded_principals = FieldProperty(ISenditApplication['excluded_principals'])
back_interface = ISenditApplicationBackInfo
# Generic methods
@property
def content_type(self):
return queryContentType(self).__name__
def setSiteManager(self, sm):
SiteManagerContainer.setSiteManager(self, sm)
notify(NewSiteManagerEvent(self))
# Skin management
skin = 'Sendit'
def getSkin(self):
return self.skin
# Filters management
def checkAddressFilters(self, address):
_name, domain = address.split('@')
if domain in (self.excluded_domains or ()):
raise FilterException, _("Given address is matching an excluded domain")
for pattern in (self.excluded_addresses or ()):
if re.match(pattern, address):
raise FilterException, _("Given address is matching an exclusion filter")
def checkPrincipalsFilters(self, principal):
if IPrincipal.providedBy(principal):
principal = principal.id
if principal in self.excluded_principals.split(','):
raise FilterException, _("Given principal is matching an exclusion filter")
@property
def filtering_plugins(self):
return self._filtering_plugins
@filtering_plugins.setter
def filtering_plugins(self, value):
old = set(self._filtering_plugins or ())
new = set(value or ())
removed = old - new
added = new - old
for name in removed:
plugin = queryUtility(IFilteringPlugin, name=name)
if plugin is not None:
noLongerProvides(self, plugin.marker_interface)
for name in added:
plugin = getUtility(IFilteringPlugin, name=name)
alsoProvides(self, plugin.marker_interface)
self._filtering_plugins = value
class SenditApplicationBackInfo(Persistent, Location):
"""Medias library back-office presentation settings"""
implements(ISenditApplicationBackInfo)
custom_css = FileProperty(ISenditApplicationBackInfo['custom_css'], klass=BlobFile)
custom_banner = ImageProperty(ISenditApplicationBackInfo['custom_banner'], klass=BlobImage, img_klass=BlobImage)
custom_logo = ImageProperty(ISenditApplicationBackInfo['custom_logo'], klass=BlobImage, img_klass=BlobImage)
custom_icon = ImageProperty(ISenditApplicationBackInfo['custom_icon'])
SENDIT_APPLICATION_BACK_INFO_KEY = 'ztfy.sendit.backoffice.presentation'
@adapter(ISenditApplication)
@implementer(ISenditApplicationBackInfo)
def SenditApplicationBackInfoFactory(context):
annotations = IAnnotations(context)
info = annotations.get(SENDIT_APPLICATION_BACK_INFO_KEY)
if info is None:
info = annotations[SENDIT_APPLICATION_BACK_INFO_KEY] = SenditApplicationBackInfo()
locate(info, context, '++back++')
return info | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/app/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
import re
# import Zope3 interfaces
# import local interfaces
from ztfy.appskin.interfaces import IApplicationBase
from ztfy.i18n.interfaces import II18nAttributesAware
from ztfy.i18n.interfaces.content import II18nBaseContent
from ztfy.security.interfaces import ILocalRoleManager
from ztfy.skin.interfaces import ISkinnable, ICustomBackOfficeInfoTarget
# import Zope3 packages
from zope.interface import Interface, Invalid, invariant
from zope.schema import Bool, List, Choice, Int, TextLine
# import local packages
from ztfy.file.schema import FileField, ImageField
from ztfy.i18n.schema import I18nTextLine, I18nHTML
from ztfy.security.schema import PrincipalList
from ztfy.utils.schema import TextLineListField
from ztfy.sendit import _
EMAIL_REGEX = re.compile("[^@]+@[^@]+\.[^@]+")
def checkPassword(password):
"""Check validity of a given password"""
nbmaj = 0
nbmin = 0
nbn = 0
nbo = 0
for car in password:
if ord(car) in range(ord('A'), ord('Z') + 1):
nbmaj += 1
elif ord(car) in range(ord('a'), ord('z') + 1):
nbmin += 1
elif ord(car) in range(ord('0'), ord('9') + 1):
nbn += 1
else:
nbo += 1
if [nbmin, nbmaj, nbn, nbo].count(0) > 1:
raise Invalid(_("Your password must contain at least three of these kinds of characters: "
"lowercase letters, uppercase letters, numbers and special characters"))
#
# Custom exceptions classes
#
class FilterException(Exception):
"""Filter exclusion exception"""
#
# Sendit application interfaces
#
class ISenditApplicationInfo(II18nBaseContent):
"""Sendit application info"""
class ISenditApplicationSecurityInfo(Interface):
"""Sendit application security info"""
administrators = PrincipalList(title=_("System administrators"),
description=_("List of principals allowed to configure the whole application, "
"including system settings and utilities"),
required=False)
managers = PrincipalList(title=_("Application managers"),
description=_("List of principals which can manage application settings"),
required=False)
open_registration = Bool(title=_("Open registration"),
description=_("If 'Yes', registration will be opened to external users"),
required=True,
default=False)
confirmation_delay = Int(title=_("Confirmation delay"),
description=_("Number of days after which unconfirmed registration "
"requests will be deleted"),
required=True,
default=7)
internal_auth_plugins = List(title=_("Internal authenticators"),
description=_("List of authentication plug-ins managing internal users.\n "
"Profiles of internal users are automatically activated."),
value_type=Choice(vocabulary='AuthenticatorPlugins'),
default=[])
external_auth_plugin = Choice(title=_("External authenticator"),
description=_("Authenticator plug-in in which external users will be defined"),
vocabulary='AuthenticatorPlugins',
required=True,
default=None)
single_auth_plugins = List(title=_("Personal authentication plug-ins"),
description=_("List of authentication plug-ins which provide individual principals "
"(instead of others which provide groups)"),
required=False,
value_type=Choice(vocabulary='AuthenticatorPlugins'))
filtering_plugins = List(title=_("Packets filtering plug-ins"),
description=_("Selected plug-ins will be used to filter packets"),
required=False,
value_type=Choice(vocabulary='ZTFY Sendit filters'))
trusted_redirects = Bool(title=_("Trusted redirects?"),
description=_("You can activate this option when your server is hosted behind an "
"application firewall not using the same protocol (HTTP / HTTPS)"),
required=True,
default=False)
class ISenditApplicationMailingInfo(II18nAttributesAware):
"""Sendit application mailing info"""
enable_notifications = Bool(title=_("Enable mail notifications?"),
description=_("If 'no', mail notifications will be disabled"),
required=True,
default=False)
mailer_name = Choice(title=_("SMTP utility mailer"),
description=_("Mail delivery utility used to send mails"),
required=False,
vocabulary='ZTFY mail deliveries')
@invariant
def checkMailer(self):
if self.enable_notifications and not self.mailer_name:
raise Invalid(_("Notifications can't be enabled without mailer utility"))
mail_service_owner = I18nTextLine(title=_("Service owner name"),
description=_("Name of the entity providing this files sharing service"),
required=True)
mail_service_name = I18nTextLine(title=_("Service name"),
description=_("This name will be the name of the service given in registration "
"and notification messages"),
required=True)
mail_sender_name = TextLine(title=_("Mails sender name"),
description=_("This name will be used for messages send by the application"),
required=True)
mail_sender_address = TextLine(title=_("Mails sender address"),
description=_("This address will be used for messages send by the application"),
constraint=EMAIL_REGEX.match,
required=True)
mail_subject_header = I18nTextLine(title=_("Mails subject header prefix"),
description=_("This header will be placed in front of each message send by "
"the application"),
required=False)
mail_signature = I18nHTML(title=_("Mails signature"),
description=_("This text will be placed in bottom of each message send by the "
"application"),
required=False)
class ISenditApplicationQuotaInfo(Interface):
"""Sendit application quota info"""
default_quota_size = Int(title=_("Default quota size"),
description=_("Default user quota size is given in megabytes"),
required=True,
default=1024)
default_max_documents = Int(title=_("Default maximum documents count"),
description=_("Default maximum number of documents uploadable in a single packet"),
required=True,
default=10)
class ISenditApplicationFiltersInfo(Interface):
"""Sendit application filters info"""
excluded_domains = TextLineListField(title=_("Excluded domains"),
description=_("Target addresses from these domains will be globally excluded"),
required=False)
excluded_addresses = TextLineListField(title=_("Excluded addresses"),
description=_("Target addresses matching these regular expressions will be "
"excluded. Don't forget to protect points with an antislash!"),
required=False)
excluded_principals = PrincipalList(title=_("Excluded principals"),
description=_("Any individual or group principal present in this list will be "
"excluded"),
required=False)
def checkAddressFilters(self, address):
"""Check if given input matches any exclusion filter"""
def checkPrincipalsFilters(self, principal):
"""Check if given principal matches any exclusion filter"""
class ISenditApplication(IApplicationBase, ISenditApplicationInfo, ISenditApplicationSecurityInfo,
ISenditApplicationMailingInfo, ISenditApplicationQuotaInfo, ISenditApplicationFiltersInfo,
ISkinnable, ILocalRoleManager, ICustomBackOfficeInfoTarget):
"""Sendit application interface"""
class ISenditApplicationBackInfo(Interface):
"""Sendit application back-office presentation options"""
custom_css = FileField(title=_("Custom CSS"),
description=_("You can provide a custom CSS for your back-office"),
required=False)
custom_banner = ImageField(title=_("Custom banner"),
description=_("You can provide a custom image file which will be displayed on top of "
"back-office pages"),
required=False)
custom_logo = ImageField(title=_("Custom logo"),
description=_("You can provide a custom image file which will be displayed on top of "
"left column"),
required=False)
custom_icon = ImageField(title=_("Custom icon"),
description=_("You can provide a custom image file to be used as back-office favorite "
"icon"),
required=False) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/app/interfaces/__init__.py | __init__.py |
# import standard packages
# import Zope3 interfaces
# import local interfaces
from ztfy.sendit.app.interfaces import ISenditApplicationInfo, ISenditApplicationSecurityInfo, \
ISenditApplicationBackInfo, ISenditApplicationMailingInfo, \
ISenditApplicationQuotaInfo, ISenditApplicationFiltersInfo
from ztfy.skin.interfaces import IPropertiesMenuTarget
# import Zope3 packages
from z3c.form import field
from zope.interface import implements
from zope.traversing import namespace
# import local packages
from ztfy.jqueryui import jquery_multiselect, jquery_tinymce
from ztfy.skin.form import EditForm, DialogEditForm
from ztfy.skin.menu import DialogMenuItem
from ztfy.sendit import _
from ztfy.sendit.skin import ztfy_sendit_bo_css
class SenditApplicationPropertiesEditForm(EditForm):
"""Sendit application properties edit form"""
implements(IPropertiesMenuTarget)
legend = _("Sendit application properties")
fields = field.Fields(ISenditApplicationInfo)
def updateWidgets(self):
super(SenditApplicationPropertiesEditForm, self).updateWidgets()
self.widgets['heading'].cols = 80
self.widgets['heading'].rows = 10
self.widgets['description'].cols = 80
self.widgets['description'].rows = 3
#
# Back-office properties menus and forms
#
class SenditApplicationBackInfoEditForm(DialogEditForm):
"""Sendit application back-office infos edit form"""
legend = _("Edit back-office presentation properties")
fields = field.Fields(ISenditApplicationBackInfo)
def getContent(self):
return ISenditApplicationBackInfo(self.context)
class SenditApplicationBackInfoMenuItem(DialogMenuItem):
"""Sendit application back-office infos menu item"""
title = _(":: Back-office...")
target = SenditApplicationBackInfoEditForm
class SenditApplicationBackInfoNamespace(namespace.view):
"""++back++ application namespace traverser"""
def traverse(self, name, ignored):
return ISenditApplicationBackInfo(self.context)
#
# Sendit application security settings
#
class SenditApplicationSecurityEditForm(DialogEditForm):
"""Sendit application security settings edit form"""
legend = _("Update security settings")
fields = field.Fields(ISenditApplicationSecurityInfo).omit('filtering_plugins')
resources = (jquery_multiselect,)
class SenditApplicationSecurityMenuItem(DialogMenuItem):
"""Sendit application security menu item"""
title = _(":: Security...")
target = SenditApplicationSecurityEditForm
#
# Sendit application mailing settings
#
class SenditApplicationMailingEditForm(DialogEditForm):
"""Sendit application mailing settings edit form"""
legend = _("Update mailing settings")
fields = field.Fields(ISenditApplicationMailingInfo)
resources = (jquery_tinymce,)
class SenditApplicationMailingMenuItem(DialogMenuItem):
"""Sendit application mailing settings menu item"""
title = _(":: Mailing settings...")
target = SenditApplicationMailingEditForm
#
# Sendit application quota settings
#
class SenditApplicationQuotaEditForm(DialogEditForm):
"""Sendit application default quota edit form"""
legend = _("Update default user quota")
fields = field.Fields(ISenditApplicationQuotaInfo)
class SenditApplicationQuotaMenuItem(DialogMenuItem):
"""Sendit application default quota menu item"""
title = _(":: User quota...")
target = SenditApplicationQuotaEditForm
#
# Sendit application filters settings
#
class SenditApplicationFiltersEditForm(DialogEditForm):
"""Sendit application filters edit form"""
legend = _("Update application filters")
fields = field.Fields(ISenditApplicationFiltersInfo)
cssClass = "form edit filters"
resources = (jquery_multiselect, ztfy_sendit_bo_css)
class SenditApplicationFiltersMenuItem(DialogMenuItem):
"""Sendit application filters menu item"""
title = _(":: Recipients filters...")
target = SenditApplicationFiltersEditForm
#
# Sendit application plug-ins settings
#
class SenditApplicationPluginsEditForm(DialogEditForm):
"""Sendit application plug-ins settings edit form"""
legend = _("Select packets filters")
fields = field.Fields(ISenditApplicationSecurityInfo).select('filtering_plugins')
def getOutput(self, writer, parent, changes=()):
if changes:
return writer.write({ 'output': 'RELOAD' })
else:
return super(SenditApplicationPluginsEditForm, self).getOutput(writer, parent, changes)
class SenditApplicationPluginsMenuItem(DialogMenuItem):
"""Sendit application packets filters menu item"""
title = _(":: Filtering plug-ins...")
target = SenditApplicationPluginsEditForm | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/app/browser/__init__.py | __init__.py |
# import standard packages
import mimetypes
import re
from persistent import Persistent
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.app.file.interfaces import IFile
# import local interfaces
from ztfy.file.interfaces import IArchiveExtractor
from ztfy.sendit.app.interfaces.filter import FilteredPacketException
from ztfy.sendit.packet.interfaces.filter import IMimetypeFilterPluginInfo, IMimetypeFilterPlugin, IMimetypeFilterTarget
# import Zope3 packages
from zope.component import adapter, queryUtility
from zope.container.contained import Contained
from zope.event import notify
from zope.i18n import translate
from zope.interface import implementer, implements
from zope.lifecycleevent import ObjectCreatedEvent
from zope.location.location import locate
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.extfile import getMagicContentType
from ztfy.utils.list import unique
from ztfy.utils.request import queryRequest
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
EXT_REG = re.compile('[,\s]')
class MimetypeFilterPlugin(object):
"""MIME types filter"""
implements(IMimetypeFilterPlugin)
marker_interface = IMimetypeFilterTarget
config_interface = IMimetypeFilterPluginInfo
def filter(self, packet):
target = getParent(packet, self.marker_interface)
if target is None:
return
info = self.config_interface(target, None)
if info is None:
return
for document in packet.values():
self.filterElement(info, document.filename, document.data)
def filterElement(self, config, filename, data):
if IFile.providedBy(data):
data = data.data
# check extensions
extensions = EXT_REG.split(config.forbidden_extensions or '')
if extensions:
if '.' in filename:
_name, ext = filename.rsplit('.', 1)
else:
_name, ext = filename, ''
if '.' + ext in extensions:
raise FilteredPacketException(translate(_("A document containing invalid data (%s) has been uploaded. "
"Your packet has been rejected."), context=queryRequest())
% filename)
# check MIME types
magic_type = getMagicContentType(data)
if magic_type in (config.forbidden_magic_types or ()):
raise FilteredPacketException(translate(_("A document containing invalid data (%s) has been uploaded. "
"Your packet has been rejected."), context=queryRequest()) %
filename)
mime_type, _encoding = mimetypes.guess_type(filename)
for name in unique((mime_type, magic_type)):
if name:
extractor = queryUtility(IArchiveExtractor, name=name)
if extractor is not None:
extractor.initialize(data)
for content, filename in extractor.getContents():
self.filterElement(config, filename, content)
else:
extension = mimetypes.guess_extension(name)
if extension:
mime_types = config.forbidden_mimetypes or ()
if extension in mime_types:
raise FilteredPacketException(translate(_("A document containing invalid data (%s) has "
"been uploaded. Your packet has been rejected."),
context=queryRequest()) % filename)
class MimetypeFilterPluginInfo(Persistent, Contained):
"""MIME types packet filter configuration info"""
implements(IMimetypeFilterPluginInfo)
forbidden_extensions = FieldProperty(IMimetypeFilterPluginInfo['forbidden_extensions'])
forbidden_mimetypes = FieldProperty(IMimetypeFilterPluginInfo['forbidden_mimetypes'])
forbidden_magic_types = FieldProperty(IMimetypeFilterPluginInfo['forbidden_magic_types'])
MIMETYPE_FILTER_INFO_KEY = 'ztfy.sendit.filter.mimetype'
@adapter(IMimetypeFilterTarget)
@implementer(IMimetypeFilterPluginInfo)
def MimetypeFilterPluginInfoFactory(context):
"""SendIt application MIME types filter adapter"""
annotations = IAnnotations(context)
info = annotations.get(MIMETYPE_FILTER_INFO_KEY)
if info is None:
info = annotations[MIMETYPE_FILTER_INFO_KEY] = MimetypeFilterPluginInfo()
notify(ObjectCreatedEvent(info))
locate(info, context)
return info | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/packet/filter.py | filter.py |
# import standard packages
from datetime import datetime
# import Zope3 interfaces
from hurry.query.interfaces import IQuery
# import local interfaces
from ztfy.sendit.packet.interfaces import IPacketArchiverTask
# import Zope3 packages
from hurry.query.query import And
from hurry.query.value import Eq, Le
from zope.component import getUtility
from zope.interface import implements
from zope.traversing.api import getParent, getName
# import local packages
from ztfy.scheduler.task import BaseTask
from ztfy.security.search import getPrincipal
from ztfy.utils.size import getHumanSize
from ztfy.utils.timezone import tztime
from ztfy.utils.request import newParticipation, endParticipation
from zope.schema.fieldproperty import FieldProperty
class PacketArchiverTask(BaseTask):
"""Packet archiver task"""
implements(IPacketArchiverTask)
principal_id = FieldProperty(IPacketArchiverTask['principal_id'])
def run(self, report):
newParticipation(self.principal_id)
try:
query = getUtility(IQuery)
params = []
params.append(Eq(('Catalog', 'content_type'), 'IPacket'))
params.append(Le(('Catalog', 'expiration_date'), tztime(datetime.utcnow())))
for packet in query.searchResults(And(*params)):
user = getParent(packet)
report.write("Removing packet: %s\n" % packet.title)
owner = getPrincipal(user.owner)
report.write(" - owner: %s (%s)\n" % (owner.title, owner.id))
report.write(" - recipients:\n%s\n" % '\n'.join((' > %s' % getPrincipal(recipient).title for recipient in packet.recipients.split(','))))
packet_size = sum((document.data.getSize() for document in packet.values()))
report.write(" - %d document(s) removed (%s)\n" % (len(packet.values()),
getHumanSize(packet_size)))
report.write('--------------------\n')
parent = getParent(packet)
del parent[getName(packet)]
finally:
endParticipation() | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/packet/task.py | task.py |
# import standard packages
# import Zope3 interfaces
from z3c.language.switch.interfaces import II18n
from zope.pluggableauth.interfaces import IAuthenticatorPlugin
from zope.sendmail.interfaces import IMailDelivery
# import local interfaces
from ztfy.mail.interfaces import IPrincipalMailInfo
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.app.interfaces.filter import IFilteringPlugin
from ztfy.sendit.packet.interfaces import IDocumentDownloadEvent, IPacket, IPacketDeleteEvent, \
NOTIFICATION_NAMED, NOTIFICATION_NONE
from ztfy.sendit.profile.interfaces.history import IPacketHistory
from ztfy.sendit.user.interfaces import IUser
from ztfy.skin.interfaces import IFormObjectCreatedEvent
# import Zope3 packages
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import adapter, queryUtility, getUtilitiesFor, getMultiAdapter
from zope.i18n import translate
from zope.lifecycleevent.interfaces import IObjectRemovedEvent
from zope.traversing.api import getName
# import local packages
from ztfy.mail.message import HTMLMessage
from ztfy.sendit.profile import getUserProfile
from ztfy.sendit.profile.history import getUserProfileHistory
from ztfy.utils.list import unique
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
#
# New packet notifications
#
RECIPIENT_NOTIFICATION_TEMPLATE = ViewPageTemplateFile('templates/recipient_notification.pt')
@adapter(IPacket, IFormObjectCreatedEvent)
def handleNewPacket(packet, event):
"""Send notification message to packet recipients"""
app = getParent(packet, ISenditApplication)
# get packet sender
user = getParent(packet, IUser)
source_profile = getUserProfile(user.owner)
if source_profile.filtered_uploads:
# execute filtering plug-ins
for name in (app.filtering_plugins or ()):
filter = queryUtility(IFilteringPlugin, name)
if filter is not None:
# this should raise an exception when an invalid packet is uploaded
filter.filter(packet)
# send mail notifications
if not app.enable_notifications:
return
mailer = queryUtility(IMailDelivery, app.mailer_name)
if mailer is None:
return
# get mail source
source_mail = None
source_info = IPrincipalMailInfo(source_profile, None)
if source_info is None:
_name, _plugin, principal_info = source_profile.getAuthenticatorPlugin()
if principal_info is not None:
source_info = IPrincipalMailInfo(principal_info, None)
if source_info is not None:
source_mail = source_info.getAddresses()
if source_mail:
source_mail = source_mail[0]
if not source_mail:
source_mail = (app.mail_sender_name, app.mail_sender_address)
# generate targets addresses
recipients = packet.recipients.split(',')
addresses = []
for recipient in recipients:
recipient_mail = None
recipient_profile = getUserProfile(recipient, create=False)
if recipient_profile is not None:
recipient_mail = IPrincipalMailInfo(recipient_profile, None)
if recipient_mail is None:
for _name, plugin in getUtilitiesFor(IAuthenticatorPlugin):
recipient_info = plugin.principalInfo(recipient)
if recipient_info is not None:
recipient_mail = IPrincipalMailInfo(recipient_info, None)
if recipient_mail is not None:
break
if recipient_mail is not None:
addresses.extend(recipient_mail.getAddresses())
# check for address uniqueness
addresses = unique(addresses, idfun=lambda x: x[1])
request = event.view.request
for address in addresses:
message_body = RECIPIENT_NOTIFICATION_TEMPLATE(event.view, app=app, packet=packet)
message = HTMLMessage(subject=translate(_("[%s] A new packet is waiting for you"), context=request) % II18n(app).queryAttribute('mail_subject_header', request=request),
fromaddr="%s via %s <%s>" % (source_mail[0], app.mail_sender_name, app.mail_sender_address),
toaddr="%s <%s>" % address,
html=message_body)
message.add_header('Sender', "%s <%s>" % source_mail)
message.add_header('Return-Path', "%s <%s>" % source_mail)
message.add_header('Reply-To', "%s <%s>" % source_mail)
message.add_header('Errors-To', source_mail[1])
mailer.send(app.mail_sender_address, (address[1],), message.as_string())
#
# Manual packet deletion notification
#
DELETE_NOTIFICATION_TEMPLATE = ViewPageTemplateFile('templates/delete_notification.pt')
@adapter(IPacketDeleteEvent)
def handleManuallyDeletedPacket(event):
"""Send notification message on package deletion"""
packet = event.object
app = getParent(packet, ISenditApplication)
if not app.enable_notifications:
return
mailer = queryUtility(IMailDelivery, app.mailer_name)
if mailer is None:
return
# get mail source
user = getParent(packet, IUser)
source_mail = None
source_profile = getUserProfile(user.owner)
source_info = IPrincipalMailInfo(source_profile, None)
if source_info is None:
_name, _plugin, principal_info = source_profile.getAuthenticatorPlugin()
if principal_info is not None:
source_info = IPrincipalMailInfo(principal_info, None)
if source_info is not None:
source_mail = source_info.getAddresses()
if source_mail:
source_mail = source_mail[0]
if not source_mail:
source_mail = (app.mail_sender_name, app.mail_sender_address)
# generate targets addresses
recipients = packet.recipients.split(',')
addresses = []
for recipient in recipients:
recipient_mail = None
recipient_profile = getUserProfile(recipient, create=False)
if recipient_profile is not None:
recipient_mail = IPrincipalMailInfo(recipient_profile, None)
if recipient_mail is None:
for _name, plugin in getUtilitiesFor(IAuthenticatorPlugin):
recipient_info = plugin.principalInfo(recipient)
if recipient_info is not None:
recipient_mail = IPrincipalMailInfo(recipient_info, None)
if recipient_mail is not None:
break
if recipient_mail is not None:
addresses.extend(recipient_mail.getAddresses())
# check for address uniqueness
addresses = unique(addresses, idfun=lambda x: x[1])
request = event.view.request
for address in addresses:
message_body = DELETE_NOTIFICATION_TEMPLATE(event.view, app=app, packet=packet)
message = HTMLMessage(subject=translate(_("[%s] A packet has been deleted"), context=request) % II18n(app).queryAttribute('mail_subject_header', request=request),
fromaddr="%s via %s <%s>" % (source_mail[0], app.mail_sender_name, app.mail_sender_address),
toaddr="%s <%s>" % address,
html=message_body)
message.add_header('Sender', "%s <%s>" % source_mail)
message.add_header('Return-Path', "%s <%s>" % source_mail)
message.add_header('Reply-To', "%s <%s>" % source_mail)
message.add_header('Errors-To', source_mail[1])
mailer.send(app.mail_sender_address, (address[1],), message.as_string())
#
# Handle all packet deletion to update owner's profile history
#
@adapter(IPacket, IObjectRemovedEvent)
def handleDeletedPacket(packet, event):
"""Update owner's history on packet deletion"""
user = getParent(packet, IUser)
history = getUserProfileHistory(user.owner)
history[getName(packet)] = getMultiAdapter((packet, history), IPacketHistory)
#
# Download notification
#
DOWNLOAD_NOTIFICATION_TEMPLATE = ViewPageTemplateFile('templates/download_notification.pt')
@adapter(IDocumentDownloadEvent)
def handleDocumentDownload(event):
"""Send notification message on document download"""
document = event.object
app = getParent(document, ISenditApplication)
if not app.enable_notifications:
return
mailer = queryUtility(IMailDelivery, app.mailer_name)
if mailer is None:
return
request = event.request
principal = event.downloader
# check notification mode
packet = getParent(document, IPacket)
if (packet.notification_mode == NOTIFICATION_NONE) or \
((packet.notification_mode == NOTIFICATION_NAMED) and (principal.id not in packet.recipients.split(','))):
return
user = getParent(document, IUser)
# get mail target
target_mail = None
target_profile = getUserProfile(user.owner)
target_info = IPrincipalMailInfo(target_profile, None)
if target_info is None:
_name, _plugin, principal_info = target_profile.getAuthenticatorPlugin()
if principal_info is not None:
target_info = IPrincipalMailInfo(principal_info, None)
if target_info is not None:
target_mail = target_info.getAddresses()
if target_mail:
target_mail = target_mail[0]
if not target_mail:
return
# get mail source
source_mail = None
source_profile = getUserProfile(principal.id)
source_info = IPrincipalMailInfo(source_profile, None)
if source_info is None:
_name, _plugin, principal_info = source_profile.getAuthenticatorPlugin()
if principal_info is not None:
source_info = IPrincipalMailInfo(principal_info, None)
if source_info is not None:
source_mail = source_info.getAddresses()
if source_mail:
source_mail = source_mail[0]
if not source_mail:
source_mail = (app.mail_sender_name, app.mail_sender_address)
message_body = DOWNLOAD_NOTIFICATION_TEMPLATE(event.view, app=app, packet=packet, document=document, downloader=principal)
message = HTMLMessage(subject=translate(_("[%s] Download notification"), context=request) % II18n(app).queryAttribute('mail_subject_header', request=request),
fromaddr="%s via %s <%s>" % (source_mail[0], app.mail_sender_name, app.mail_sender_address),
toaddr="%s <%s>" % target_mail,
html=message_body)
message.add_header('Sender', "%s <%s>" % source_mail)
message.add_header('Return-Path', "%s <%s>" % source_mail)
message.add_header('Reply-To', "%s <%s>" % source_mail)
message.add_header('Errors-To', source_mail[1])
mailer.send(app.mail_sender_address, (target_mail[1],), message.as_string()) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/packet/events.py | events.py |
# import standard packages
from datetime import timedelta
from persistent import Persistent
# import Zope3 interfaces
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.sendit.packet.interfaces import IPacket, IDocument, \
IDocumentDownloadEvent, IPacketDeleteEvent, \
BACKUP_DURATIONS
# import Zope3 packages
from zope.app.content import queryContentType
from zope.component.interfaces import ObjectEvent
from zope.container.contained import Contained
from zope.interface import implements
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.base.ordered import OrderedContainer
from ztfy.extfile.blob import BlobFile
from ztfy.file.property import FileProperty
from ztfy.security.property import RolePrincipalsProperty
from ztfy.utils.size import getHumanSize
from ztfy.utils.timezone import tztime
class Document(Persistent, Contained):
"""Document persistent class"""
implements(IDocument)
title = FieldProperty(IDocument['title'])
data = FileProperty(IDocument['data'], klass=BlobFile)
filename = None
downloaders = FieldProperty(IDocument['downloaders'])
@property
def content_type(self):
return queryContentType(self).__name__
def getSize(self, request=None):
return getHumanSize(self.data.getSize(), request)
class DocumentDownloadEvent(ObjectEvent):
"""Document download event"""
implements(IDocumentDownloadEvent)
def __init__(self, object, request, view):
self.object = object
self.request = request
self.downloader = request.principal
self.view = view
class Packet(OrderedContainer):
"""Packet persistent class"""
implements(IPacket)
title = FieldProperty(IPacket['title'])
description = FieldProperty(IPacket['description'])
recipients = RolePrincipalsProperty(IPacket['recipients'], role='ztfy.SenditRecipient')
notification_mode = FieldProperty(IPacket['notification_mode'])
backup_time = FieldProperty(IPacket['backup_time'])
@property
def content_type(self):
return queryContentType(self).__name__
@property
def expiration_date(self):
creation_date = IZopeDublinCore(self).created
return tztime(creation_date) + timedelta(days=BACKUP_DURATIONS[self.backup_time])
@property
def downloaders(self):
result = {}
[ result.update(document.downloaders or {}) for document in self.values() ]
return result
class PacketDeleteEvent(ObjectEvent):
"""Packet delete event"""
implements(IPacketDeleteEvent)
def __init__(self, object, view):
self.object = object
self.view = view | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/packet/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.component.interfaces import IObjectEvent
from zope.container.interfaces import IContainer
from zope.location.interfaces import IContained
from zope.schema.interfaces import IObject, IList
# import local interfaces
from ztfy.base.interfaces import IBaseContentType
from ztfy.scheduler.interfaces import ISchedulerTask
# import Zope3 packages
from zope.container.constraints import contains
from zope.interface import Interface, Attribute
from zope.schema import TextLine, Text, Choice, Dict, Datetime
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
# import local packages
from ztfy.file.schema import FileField
from ztfy.security.schema import PrincipalList, Principal
from ztfy.sendit import _
#
# Interface vocabularies
#
NOTIFICATION_NONE = 0
NOTIFICATION_NAMED = 1
NOTIFICATION_ALL = 2
NOTIFICATIONS = (_("No notification"),
_("Notification on named users download"),
_("Notification on all downloads"))
NOTIFICATIONS_VOCABULARY = SimpleVocabulary([SimpleTerm(i, i, t) for i, t in enumerate(NOTIFICATIONS)])
BACKUP_LENGTHS = {1: _("1 week"),
2: _("2 weeks"),
4: _("4 weeks"),
8: _("8 weeks")}
BACKUP_DURATIONS = dict(((i, i*7) for i in BACKUP_LENGTHS.keys()))
BACKUP_DURATIONS_VOCABULARY = SimpleVocabulary([SimpleTerm(i, i, t) for i, t in sorted(BACKUP_LENGTHS.items())])
#
# Document interfaces
#
class IDocumentField(IObject):
"""Document field interface"""
class IDocumentsListField(IList):
"""Documents list field interface"""
class IDocumentInfo(Interface):
"""Document info"""
title = TextLine(title=_("Title"),
required=False)
data = FileField(title=_("Document data"),
required=True)
filename = Attribute(_("File name"))
def getSize(self, request=None):
"""Get document size in human form"""
class IDocumentDownloadInfo(Interface):
"""Document download info"""
downloaders = Dict(title=_("Document downloaders"),
required=False,
key_type=TextLine(),
value_type=Datetime())
class IDocument(IDocumentInfo, IDocumentDownloadInfo, IContained):
"""Document interface"""
class IDocumentDownloadEvent(IObjectEvent):
"""Document download event"""
request = Attribute(_("Download request"))
downloader = Attribute(_("Document downloader principal"))
view = Attribute(_("View in which download occurred"))
#
# Packet interfaces
#
class IPacketInfo(Interface):
"""Basic packet info"""
title = TextLine(title=_("Packet title"),
required=True)
description = Text(title=_("Description"),
required=False)
recipients = PrincipalList(title=_("Packet recipients"),
description=_("Input is assisted. You can search principals individually, "
"or by searching for groups or structures"),
required=True)
notification_mode = Choice(title=_("Notification mode"),
description=_("You can choose how you will be notified when your recipients "
"will download this packet"),
required=True,
vocabulary=NOTIFICATIONS_VOCABULARY,
default=NOTIFICATION_NAMED)
backup_time = Choice(title=_("Conservation duration"),
description=_("Nomber of days during which this packet will be available"),
required=True,
vocabulary=BACKUP_DURATIONS_VOCABULARY,
default=2)
expiration_date = Attribute(_("Packet expiration date"))
class IPacketDownloadInfo(Interface):
"""Packet download info"""
downloaders = Dict(title=_("Document downloaders"),
required=False,
key_type=TextLine(),
value_type=Datetime())
class IPacket(IPacketInfo, IPacketDownloadInfo, IContainer, IContained, IBaseContentType):
"""Packet info"""
contains(IDocument)
class IPacketFilteredEvent(IObjectEvent):
"""Packet filter event"""
class IPacketDeleteEvent(IObjectEvent):
"""Packet delete event"""
view = Attribute(_("View in which deletion occurred"))
#
# Packet archiver task interfaces
#
class IPacketArchiverTaskInfo(Interface):
"""Packet archiver task info"""
principal_id = Principal(title=_("Task execution principal"),
description=_("ID of the principal running the task"),
required=True,
default=u'zope.manager')
class IPacketArchiverTask(IPacketArchiverTaskInfo, ISchedulerTask):
"""Packet archiver task interface""" | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/packet/interfaces/__init__.py | __init__.py |
# import standard packages
from persistent import Persistent
from xmlrpclib import Binary
# import Zope3 interfaces
from zope.pluggableauth.interfaces import ICredentialsPlugin
# import local interfaces
from ztfy.sendit.client.interfaces import ISenditClient, ISenditClientDocument, ISenditClientPacket
# import Zope3 packages
from zope.component import queryUtility
from zope.container.contained import Contained
from zope.interface import implements
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.file.property import FileProperty
from ztfy.utils.protocol.xmlrpc import getClient
from ztfy.utils.request import getRequest, queryRequest
from ztfy.sendit import _
class SenditClientDocument(object):
"""Sendit client document"""
implements(ISenditClientDocument)
title = FieldProperty(ISenditClientDocument['title'])
filename = FieldProperty(ISenditClientDocument['filename'])
data = FieldProperty(ISenditClientDocument['data'])
class SenditClientPacket(object):
"""Sendit client packet"""
implements(ISenditClientPacket)
title = FieldProperty(ISenditClientPacket['title'])
description = FieldProperty(ISenditClientPacket['description'])
recipients = FieldProperty(ISenditClientPacket['recipients'])
notification_mode = FieldProperty(ISenditClientPacket['notification_mode'])
backup_time = FieldProperty(ISenditClientPacket['backup_time'])
documents = FieldProperty(ISenditClientPacket['documents'])
class SenditClientUtility(Persistent, Contained):
"""Sendit XML-RPC client utility"""
implements(ISenditClient)
server_url = FieldProperty(ISenditClient['server_url'])
def _getCredentials(self, request=None):
plugin = queryUtility(ICredentialsPlugin, 'Session Credentials')
if plugin is not None:
if request is None:
request = getRequest()
creds = plugin.extractCredentials(request)
if creds is not None:
return (creds['login'], creds['password'])
return (None, None)
def _getHeaders(self, request=None):
if request is None:
request = queryRequest()
if request is None:
headers = None
else:
headers = { 'Accept-Language': request.getHeader('Accept-Language') }
return headers
def searchPrincipals(self, query, names=None, request=None, credentials=()):
"""Search principals matching given query"""
if not self.server_url:
raise ValueError, _("Can't execute client methods without defined SendIt server URL")
credentials = credentials or self._getCredentials(request)
xmlrpc = getClient(self.server_url, credentials, allow_none=1, headers=self._getHeaders(request))
return xmlrpc.searchPrincipals(query, names)
def getPrincipalInfo(self, principal_id, request=None, credentials=None):
"""Get user profile info"""
if not self.server_url:
raise ValueError, _("Can't execute client methods without defined SendIt server URL")
credentials = credentials or self._getCredentials(request)
xmlrpc = getClient(self.server_url, credentials, allow_none=1, headers=self._getHeaders(request))
return xmlrpc.getPrincipalInfo(principal_id)
def canRegisterPrincipal(self, request=None, credentials=None):
"""Check if external principals can be registered"""
if not self.server_url:
return False
credentials = credentials or self._getCredentials(request)
xmlrpc = getClient(self.server_url, credentials, allow_none=1, headers=self._getHeaders(request))
return xmlrpc.canRegisterPrincipal()
def registerPrincipal(self, email, firstname, lastname, company_name=None, request=None, credentials=None):
"""Create a new profile with given attributes"""
if not self.server_url:
raise ValueError, _("Can't execute client methods without defined SendIt server URL")
credentials = credentials or self._getCredentials(request)
xmlrpc = getClient(self.server_url, credentials, allow_none=1, headers=self._getHeaders(request))
return xmlrpc.registerPrincipal(email, firstname, lastname, company_name)
def uploadPacket(self, packet, request=None, credentials=None):
"""Send a new packet with given properties"""
if not self.server_url:
raise ValueError, _("Can't execute client methods without defined SendIt server URL")
if not ISenditClientPacket.providedBy(packet):
raise ValueError, _("Send packet must implement ISenditClientPacket interface")
credentials = credentials or self._getCredentials(request)
xmlrpc = getClient(self.server_url, credentials, allow_none=1, headers=self._getHeaders(request))
documents = [ { 'title': document.title,
'filename': document.filename,
'data': Binary(document.data) } for document in packet.documents ]
return xmlrpc.uploadPacket(packet.title,
packet.description,
packet.recipients,
packet.notification_mode,
packet.backup_time,
documents) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/client/__init__.py | __init__.py |
# import standard packages
from xmlrpclib import Fault
# import Zope3 interfaces
from z3c.form.interfaces import IErrorViewSnippet
from z3c.json.interfaces import IJSONWriter
# import local interfaces
from ztfy.sendit.client.interfaces import ISenditClientInfo, ISenditClient
from ztfy.sendit.profile.interfaces import IUserRegistrationInfo
# import Zope3 packages
from z3c.form import field, button
from z3c.formjs import jsaction, ajax
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import getUtility, queryUtility, getMultiAdapter
from zope.i18n import translate
from zope.interface import Interface, Invalid
# import local packages
from ztfy.skin.form import EditForm, DialogAddForm
from ztfy.sendit import _
class SenditClientEditForm(EditForm):
"""Sendit client utility edit form"""
legend = _("Sendit client properties")
fields = field.Fields(ISenditClientInfo)
class ISenditPrincipalRegistrationFormButtons(Interface):
"""Default dialog add form buttons"""
register = jsaction.JSButton(title=_("Register user"))
cancel = jsaction.JSButton(title=_("Cancel"))
class SenditPrincipalRegistrationForm(DialogAddForm):
"""Sendit principal registration form"""
legend = _("Register new external user")
help = _("""Use this form to register a new external user. This recipient will have to activate his account before downloading any packet.\n"""
"""WARNING: once registered, such users are not private to your profile but are shared with all application users!""")
fields = field.Fields(IUserRegistrationInfo).select('email', 'firstname', 'lastname', 'company_name')
buttons = button.Buttons(ISenditPrincipalRegistrationFormButtons)
prefix = 'register_dialog.'
@jsaction.handler(buttons['register'])
def register_handler(self, event, selector):
return '$.ZTFY.form.add(this.form);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
@ajax.handler
def ajaxCreate(self):
writer = getUtility(IJSONWriter)
self.updateWidgets()
error = None
errors = ()
client = queryUtility(ISenditClient)
if client is None:
error = Invalid(_("Missing Sendit client utility"))
view = getMultiAdapter((error, self.request, None, None, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if not errors:
data, errors = self.extractData()
if not errors:
try:
info = client.registerPrincipal(data.get('email'),
data.get('firstname'),
data.get('lastname'),
data.get('company_name'))
if info is None:
raise Invalid(_("An unknown error occurred. Can't register external user."))
except Fault, f:
error = Invalid(f.faultString)
except Exception, e:
error = Invalid(translate(_("Can't register external principal: %s"), context=self.request) % e.message)
if error:
view = getMultiAdapter((error, self.request, None, None, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if errors:
self.widgets.errors = errors
self.status = self.formErrorsMessage
return writer.write(self.getAjaxErrors())
else:
return writer.write({ 'output': u"OK" }) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/client/browser/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
from datetime import datetime
# import Zope3 interfaces
from z3c.form.interfaces import DISPLAY_MODE
from zope.pluggableauth.interfaces import IAuthenticatorPlugin
from zope.security.interfaces import Unauthorized
# import local interfaces
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.profile.interfaces import IProfileQuotaInfo, IProfileActivationInfo, IProfileActivationAdminInfo, \
IProfile
from ztfy.sendit.skin.app.registration import IUserBaseRegistrationInfo
# import Zope3 packages
from z3c.form import field
from zope.component import getUtility
from zope.i18n import translate
# import local packages
from ztfy.sendit.skin.page import BaseSenditProtectedPage
from ztfy.skin.form import BaseDialogDisplayForm, BaseDialogEditForm
from ztfy.utils.date import formatDatetime
from ztfy.utils.size import getHumanSize
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
class SenditApplicationProfileView(BaseSenditProtectedPage, BaseDialogDisplayForm):
"""Sendit application profile view"""
legend = _("Profile view")
icon_class = 'icon-cog'
fields = field.Fields(IProfileActivationInfo).select('activation_date') + \
field.Fields(IProfileQuotaInfo).select('quota_size_str', 'quota_usage', 'max_documents_str') + \
field.Fields(IProfileActivationAdminInfo).omit('disabled_date')
def __call__(self):
try:
BaseSenditProtectedPage.__call__(self)
except Unauthorized:
return u''
else:
return BaseDialogDisplayForm.__call__(self)
def update(self):
self.profile = IProfile(self.request.principal)
super(SenditApplicationProfileView, self).update()
def getContent(self):
return self.profile
def updateWidgets(self):
super(SenditApplicationProfileView, self).updateWidgets()
self.widgets['activation_date'].mode = DISPLAY_MODE
self.widgets['activation_date'].value = formatDatetime(self.profile.activation_date or datetime.utcnow())
quota_size = self.profile.getQuotaSize(self.context)
if quota_size == 0:
self.widgets['quota_size_str'].value = translate(_("None"), context=self.request)
else:
self.widgets['quota_size_str'].value = getHumanSize(quota_size * 1024 * 1024, self.request)
self.widgets['quota_usage'].value = getHumanSize(self.profile.getQuotaUsage(self.context), self.request)
max_documents = self.profile.getMaxDocuments(self.context)
if max_documents == 0:
self.widgets['max_documents_str'].value = translate(_("None"), context=self.request)
else:
self.widgets['max_documents_str'].value = max_documents
def updateActions(self):
super(SenditApplicationProfileView, self).updateActions()
self.actions['dialog_close'].addClass('btn')
class SenditApplicationSettingsView(BaseSenditProtectedPage, BaseDialogEditForm):
"""Sendit application settings view"""
legend = _("User settings")
icon_class = 'icon-user'
fields = field.Fields(IUserBaseRegistrationInfo)
def __call__(self):
try:
BaseSenditProtectedPage.__call__(self)
except Unauthorized:
return u''
else:
return BaseDialogEditForm.__call__(self)
def updateActions(self):
super(SenditApplicationSettingsView, self).updateActions()
self.actions['dialog_submit'].addClass('btn btn-inverse')
self.actions['dialog_cancel'].addClass('btn')
def getContent(self):
app = getParent(self.context, ISenditApplication)
plugin = getUtility(IAuthenticatorPlugin, app.external_auth_plugin)
return plugin.principalInfo(self.request.principal.id)
def updateContent(self, content, data):
app = getParent(self.context, ISenditApplication)
plugin = getUtility(IAuthenticatorPlugin, app.external_auth_plugin)
prefix = plugin.prefix
user = plugin[self.request.principal.id[len(prefix):]]
user.title = '%s %s' % (data.get('lastname'), data.get('firstname'))
user.description = data.get('company_name') or u''
if data.get('password'):
user.password = data.get('password')
return {IUserBaseRegistrationInfo: ['lastname', 'firstname', 'company_name', 'password']} | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/profile/__init__.py | __init__.py |
$(document).ready(function(){$.ZTFY.sendit={form:{addDocument:function(a){var f=$(a).parents("DIV.widgets-suffix");var j=f.prev();var g=$('INPUT[name="documents.widgets.data"], INPUT[name="documents.widgets.data:list"]',j);if(!g.val()){return}var h=j.clone();var i=$("DIV.documents_list").removeClass("hidden");$("DIV.label",j).hide();var k=$('INPUT[name="documents.widgets.title"], INPUT[name="documents.widgets.title:list"]',j);var b=$('<input type="hidden" name="documents.widgets.title" />').val(k.val());$("<span>").text(b.val()).insertAfter(k);k.replaceWith(b);g.attr("disabled",true);$("<i>").attr("class","icon icon-trash").attr("title","Enlever ce document").click($.ZTFY.sendit.form.removeDocument).insertAfter(g);j.detach().appendTo(i);$("INPUT, INPUT",h).val(null);h.insertBefore(f);var c=$(a).parents("DIV.actions");var e=c.data("sendit-documents-count");var d=$("DIV.widgets",i).length;if((d!=0)&&(d>=e-1)){$(a).attr("disabled",true)}},removeDocument:function(a){$(this).parents("DIV.widgets").remove();$("INPUT:button",$("DIV.widgets-suffix DIV.actions")).attr("disabled",false)},removeOldDocument:function(a){$(a).parents("DIV.item").remove()},checkDocumentsUpload:function(c,b){var d=$(b).data("sendit-documents-group");var a=$('DIV[id="'+d+'"]',c);$("INPUT:text, INPUT:hidden, INPUT:radio, INPUT:file, TEXTAREA",a).each(function(f,g){var e=$(g).attr("name");if(e&&!e.endsWith(":list")){$(g).attr("name",e+":list")}});$("INPUT:file",a).attr("disabled",false)},checkDocumentsInputs:function(d,b){var f=$(b).data("sendit-documents-id");var c=$(b).data("sendit-documents-name");var a=!$('INPUT[id="'+f+'"]').hasClass("required");var e=-1;$('INPUT[id^="'+f+'"]',$("DIV.document")).each(function(g,h){$(h).attr("id",f+"-"+g).attr("name",c+"."+g);if($(h).val()){a=true}e=g});$('INPUT[name="'+c+'.count"]',d).val(e+1);if(a){return true}else{return" - vous devez fournir au moins un document à télécharger !!"}},deletePacketCallback:function(a,b){if(b=="success"){if(typeof(a)=="string"){a=$.parseJSON(a)}var c=a.output;switch(c){case"OK":var d=$('DIV[id="delete_'+a.packet_oid+'"]');d.closest("TR").remove()}$.ZTFY.dialog.close()}}},profile:{openDialog:function(b){var a=$('INPUT[name="principal_id"]',"FIELDSET.profile-search").val();if(a){$.ZTFY.dialog.open("@@profile_edit.html?uid="+a)}}}};$("FIELDSET.profile-search").on("click","A.bit-box",$.ZTFY.sendit.profile.openDialog)}); | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/resources/js/ztfy.sendit.min.js | ztfy.sendit.min.js |
$(document).ready(function(){
// === Sendit custom classes === //
$.ZTFY.sendit = {
form: {
/**
* Add a new document to documents upload form
*/
addDocument: function(source) {
var button = $(source).parents('DIV.widgets-suffix');
var document = button.prev();
// Get widgets values
var file_input = $('INPUT[name="documents.widgets.data"], INPUT[name="documents.widgets.data:list"]', document);
if (!file_input.val())
return;
// Clone initial document
var new_document = document.clone();
var list = $('DIV.documents_list').removeClass('hidden');
$('DIV.label', document).hide();
// Get components and values
var title = $('INPUT[name="documents.widgets.title"], INPUT[name="documents.widgets.title:list"]', document);
var hidden_title = $('<input type="hidden" name="documents.widgets.title" />').val(title.val());
// Create new components
$('<span>').text(hidden_title.val()).insertAfter(title);
title.replaceWith(hidden_title);
file_input.attr('disabled', true);
$('<i>').attr('class', 'icon icon-trash')
.attr('title', "Enlever ce document")
.click($.ZTFY.sendit.form.removeDocument)
.insertAfter(file_input);
document.detach()
.appendTo(list);
$('INPUT, INPUT', new_document).val(null);
new_document.insertBefore(button);
// Check for hiding button when adding "max documents count" documents
var actions = $(source).parents('DIV.actions');
var max_documents = actions.data('sendit-documents-count');
var nb_documents = $('DIV.widgets', list).length;
if ((nb_documents != 0) && (nb_documents >= max_documents-1))
$(source).attr('disabled', true);
},
/**
* Remove an upload entry from upload form
*/
removeDocument: function(event) {
$(this).parents('DIV.widgets').remove();
$('INPUT:button', $('DIV.widgets-suffix DIV.actions')).attr('disabled', false);
},
/**
* Remove an existing document
*/
removeOldDocument: function(source) {
$(source).parents('DIV.item').remove();
},
/**
* Check documents upload
*/
checkDocumentsUpload: function(form, input) {
var id = $(input).data('sendit-documents-group');
var subform = $('DIV[id="'+id+'"]', form);
$('INPUT:text, INPUT:hidden, INPUT:radio, INPUT:file, TEXTAREA', subform).each(function(index, element) {
var name = $(element).attr('name');
if (name && !name.endsWith(':list')) {
$(element).attr('name', name + ':list');
}
});
$('INPUT:file', subform).attr('disabled', false);
},
/**
* Check documents upload entries
*/
checkDocumentsInputs: function(form, input) {
var id = $(input).data('sendit-documents-id');
var name = $(input).data('sendit-documents-name');
var upload_ok = !$('INPUT[id="'+id+'"]').hasClass('required');
var last_index = -1;
$('INPUT[id^="'+id+'"]', $('DIV.document')).each(function(index, element) {
$(element).attr('id', id + '-' + index)
.attr('name', name + '.' + index);
if ($(element).val()) {
upload_ok = true;
}
last_index = index;
});
$('INPUT[name="'+name+'.count"]', form).val(last_index+1);
if (upload_ok) {
return true;
} else {
return ' - vous devez fournir au moins un document à télécharger !!';
}
},
/**
* Remove user packet
*/
deletePacketCallback: function(result, status) {
if (status == 'success') {
if (typeof(result) == "string")
result = $.parseJSON(result);
var output = result.output;
switch (output) {
case 'OK':
var button = $('DIV[id="delete_' + result.packet_oid + '"]');
button.closest('TR').remove();
}
$.ZTFY.dialog.close();
}
}
},
/**
* Profile management
*/
profile: {
openDialog: function(source) {
var uid = $('INPUT[name="principal_id"]', 'FIELDSET.profile-search').val();
if (uid)
$.ZTFY.dialog.open('@@profile_edit.html?uid=' + uid);
}
}
}
$('FIELDSET.profile-search').on('click', 'A.bit-box', $.ZTFY.sendit.profile.openDialog);
}); | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/resources/js/ztfy.sendit.js | ztfy.sendit.js |
# import standard packages
import random
import string
from datetime import datetime
from os import urandom
# import Zope3 interfaces
from z3c.form.interfaces import IErrorViewSnippet, HIDDEN_MODE
from z3c.language.switch.interfaces import II18n
from zope.pluggableauth.interfaces import IAuthenticatorPlugin, IPrincipalInfo
from zope.publisher.interfaces import NotFound
from zope.sendmail.interfaces import IMailDelivery
# import local interfaces
from ztfy.appskin.interfaces import IAnonymousPage
from ztfy.mail.interfaces import IPrincipalMailInfo
from ztfy.security.interfaces import ISecurityManager
from ztfy.sendit.app.interfaces import FilterException
from ztfy.sendit.profile.interfaces import IProfile, IUserBaseRegistrationInfo, IUserRegistrationInfo, \
IUserRegistrationConfirmInfo
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
# import Zope3 packages
from z3c.form import field, button
from z3c.formjs import jsaction
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import adapts, queryUtility, getMultiAdapter
from zope.event import notify
from zope.i18n import translate
from zope.interface import implements, Interface, Invalid
from zope.lifecycleevent import ObjectCreatedEvent
from zope.pluggableauth.plugins.principalfolder import InternalPrincipal
from zope.schema.fieldproperty import FieldProperty
from zope.security.proxy import removeSecurityProxy
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.mail.message import HTMLMessage
from ztfy.sendit.profile import getUserProfile
from ztfy.skin.form import BaseAddForm, BaseDialogAddForm
from ztfy.skin.page import TemplateBasedPage
from ztfy.sendit import _
#
# User registration
#
class PrincipalInfoRegistrationAdapter(object):
"""Principal info registration adapter"""
adapts(IPrincipalInfo)
implements(IUserBaseRegistrationInfo)
email = FieldProperty(IUserRegistrationInfo['email'])
firstname = FieldProperty(IUserRegistrationInfo['firstname'])
lastname = FieldProperty(IUserRegistrationInfo['lastname'])
company_name = FieldProperty(IUserRegistrationInfo['company_name'])
password = FieldProperty(IUserRegistrationInfo['password'])
confirm_password = FieldProperty(IUserRegistrationInfo['confirm_password'])
def __init__(self, context):
self.email = context.login
self.lastname, self.firstname = context.title.split(' ', 1)
self.company_name = context.description
class UserRegistrationForm(BaseAddForm):
"""User registration form"""
implements(IAnonymousPage)
legend = _("Please enter registration info")
shortname = _("Registration")
icon_class = 'icon-user'
fields = field.Fields(IUserRegistrationInfo)
registration_message_template = ViewPageTemplateFile('templates/register_message.pt')
def __call__(self):
if not self.context.open_registration:
raise NotFound(self.context, 'register.html', self.request)
return super(UserRegistrationForm, self).__call__()
def updateActions(self):
super(UserRegistrationForm, self).updateActions()
self.actions['register'].addClass('btn btn-inverse')
@button.buttonAndHandler(_('Register'), name='register')
def handleRegister(self, action):
data, errors = self.extractData()
if not errors:
error = None
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
if plugin.has_key(data.get('email').lower()):
error = Invalid(_("Address already used"))
else:
try:
self.context.checkAddressFilters(data.get('email').lower())
except FilterException:
error = Invalid(_("This email domain or address has been excluded by system administrator"))
if error:
view = getMultiAdapter((error, self.request, self.widgets['email'],
self.widgets['email'].field, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
self.widgets.errors = errors
if errors:
self.status = self.formErrorsMessage
return
obj = self.createAndAdd(data)
if obj is not None:
# mark only as finished if we get the new object
self._finishedAdd = True
def create(self, data):
# create principal
email = data.get('email').lower()
principal = InternalPrincipal(login=email,
password=data.get('password'),
title='%s %s' % (data.get('lastname'), data.get('firstname')),
description=data.get('company_name') or '')
notify(ObjectCreatedEvent(principal))
# create profile
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
profile = getUserProfile(plugin.prefix + principal.login)
profile.generateSecretKey(email, data.get('password'))
# prepare notification message
mailer = queryUtility(IMailDelivery, self.context.mailer_name)
if mailer is not None:
self.request.form['hash'] = profile.activation_hash
message_body = self.registration_message_template(request=self.request,
context=self.context,
hash=profile.activation_hash)
message = HTMLMessage(subject=translate(_("[%s] Please confirm registration"),
context=self.request) %
II18n(self.context).queryAttribute('mail_subject_header',
request=self.request),
fromaddr="%s <%s>" % (self.context.mail_sender_name,
self.context.mail_sender_address),
toaddr="%s <%s>" % (principal.title, principal.login),
html=message_body)
mailer.send(self.context.mail_sender_address, (principal.login,), message.as_string())
return principal
def add(self, object):
plugin = removeSecurityProxy(queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin))
plugin[object.login] = object
ISecurityManager(object).grantRole('ztfy.SenditProfileOwner', plugin.prefix + object.login)
ISecurityManager(object).grantRole('zope.Manager', plugin.prefix + object.login)
def updateContent(self, object, data):
pass
def nextURL(self):
return '%s/@@register_ok.html' % absoluteURL(self.context, self.request)
class UserRegistrationOK(TemplateBasedPage):
"""User registration confirm view"""
implements(IAnonymousPage)
def __call__(self):
if not self.context.open_registration:
raise NotFound(self.context, 'register_ok.html', self.request)
return super(UserRegistrationOK, self).__call__()
#
# External user registration form
#
class IExternalUserRegistrationFormButtons(Interface):
"""Default dialog add form buttons"""
register = jsaction.JSButton(title=_("Register user"))
cancel = jsaction.JSButton(title=_("Cancel"))
def generatePassword(length=20):
"""Small password generator"""
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (urandom(1024))
return ''.join(random.choice(chars) for _i in range(length))
class ExternalUserRegistrationForm(BaseDialogAddForm):
"""External user registration form
This form is usable by internal users to declare external users.
Form can always be used even when auto-registration is enabled.
"""
legend = _("Register new external user")
help = _("""Use this form to register a new external user. This recipient will have to activate his account before downloading any packet.\n"""
"""WARNING: once registered, such users are not private to your profile but are shared with all application users!""")
icon_class = 'icon-user'
fields = field.Fields(IUserRegistrationInfo).select('email', 'firstname', 'lastname', 'company_name')
registration_message_template = ViewPageTemplateFile('templates/register_message.pt')
buttons = button.Buttons(IExternalUserRegistrationFormButtons)
prefix = 'register_dialog.'
@jsaction.handler(buttons['register'])
def register_handler(self, event, selector):
return '$.ZTFY.form.add(this.form);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
def updateActions(self):
super(ExternalUserRegistrationForm, self).updateActions()
self.actions['register'].addClass('btn btn-inverse')
self.actions['cancel'].addClass('btn')
def extractData(self, setErrors=True):
data, errors = super(ExternalUserRegistrationForm, self).extractData(setErrors)
if not errors:
error = None
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
email = data.get('email').lower()
if plugin.has_key(email):
error = Invalid(_("Address already used"))
else:
try:
self.context.checkAddressFilters(email)
except FilterException:
error = Invalid(_("This email domain or address has been excluded by system administrator"))
if error:
view = getMultiAdapter((error, self.request, self.widgets['email'], self.widgets['email'].field, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
self.widgets.errors = errors
if errors:
self.status = self.formErrorsMessage
return data, errors
def create(self, data):
# create principal
email = data.get('email').lower()
password = generatePassword()
principal = InternalPrincipal(login=email,
password=password,
title='%s %s' % (data.get('lastname'), data.get('firstname')),
description=data.get('company_name') or '')
notify(ObjectCreatedEvent(principal))
# create profile
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
profile = getUserProfile(plugin.prefix + principal.login)
profile.self_registered = False
profile.generateSecretKey(email, password)
# prepare notification message
mailer = queryUtility(IMailDelivery, self.context.mailer_name)
if mailer is not None:
source_mail = None
source_profile = IProfile(self.request.principal)
source_info = IPrincipalMailInfo(source_profile, None)
if source_info is None:
_name, _plugin, principal_info = source_profile.getAuthenticatorPlugin()
if principal_info is not None:
source_info = IPrincipalMailInfo(principal_info, None)
if source_info is not None:
source_mail = source_info.getAddresses()
if source_mail:
source_mail = source_mail[0]
if not source_mail:
source_mail = (self.context.mail_sender_name, self.context.mail_sender_address)
message_body = self.registration_message_template(request=self.request,
context=self.context,
hash=profile.activation_hash)
message = HTMLMessage(subject=translate(_("[%s] Please confirm registration"), context=self.request) %
II18n(self.context).queryAttribute('mail_subject_header', request=self.request),
fromaddr="%s via %s <%s>" % (source_mail[0],
self.context.mail_sender_name,
self.context.mail_sender_address),
toaddr="%s <%s>" % (principal.title, principal.login),
html=message_body)
message.add_header('Sender', "%s <%s>" % source_mail)
message.add_header('Return-Path', "%s <%s>" % source_mail)
message.add_header('Reply-To', "%s <%s>" % source_mail)
message.add_header('Errors-To', source_mail[1])
mailer.send(self.context.mail_sender_address, (principal.login,), message.as_string())
return principal
def add(self, object):
plugin = removeSecurityProxy(queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin))
plugin[object.login] = object
ISecurityManager(object).grantRole('ztfy.SenditProfileOwner', plugin.prefix + object.login)
ISecurityManager(object).grantRole('zope.Manager', plugin.prefix + object.login)
def updateContent(self, object, data):
pass
#
# Registration confirmation
#
class UserRegistrationConfirm(BaseAddForm):
"""User registration confirmation form"""
implements(IAnonymousPage)
legend = _("Registration confirmation form")
shortname = _("Registration")
icon_class = 'icon-user'
fields = field.Fields(IUserRegistrationConfirmInfo)
def updateWidgets(self):
super(UserRegistrationConfirm, self).updateWidgets()
self.widgets['activation_hash'].mode = HIDDEN_MODE
self.widgets['activation_hash'].value = self.request.form.get('hash') or self.widgets['activation_hash'].value
def updateActions(self):
super(UserRegistrationConfirm, self).updateActions()
self.actions['register'].addClass('btn btn-inverse')
@button.buttonAndHandler(_('Confirm registration'), name='register')
def handleRegister(self, action):
data, errors = self.extractData()
if not errors:
email = data.get('email').lower()
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
profile = getUserProfile(plugin.prefix + email, create=False)
try:
profile.checkActivation(data.get('activation_hash'), email, data.get('password'))
except:
error = Invalid(_("Can't validate activation. Please check your password and activation key."))
view = getMultiAdapter((error, self.request, None, None, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
self.widgets.errors = errors
else:
profile.activation_date = datetime.utcnow()
profile.activated = True
ISenditApplicationUsers(self.context).addUserFolder(plugin.prefix + email)
if errors:
self.status = self.formErrorsMessage
return
self._finishedAdd = True
def nextURL(self):
return '%s/@@register_finish.html' % absoluteURL(self.context, self.request)
class UserRegistrationFinish(TemplateBasedPage):
"""User registration finished view"""
implements(IAnonymousPage) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/registration.py | registration.py |
# import standard packages
from datetime import datetime
from httplib import UNAUTHORIZED
# import Zope3 interfaces
from z3c.form.interfaces import HIDDEN_MODE, IErrorViewSnippet
from z3c.language.switch.interfaces import II18n
from zope.authentication.interfaces import IAuthentication
from zope.component.interfaces import ISite
from zope.pluggableauth.interfaces import IAuthenticatedPrincipalCreated, IAuthenticatorPlugin
from zope.publisher.interfaces.browser import IBrowserSkinType
from zope.security.interfaces import IUnauthorized
from zope.sendmail.interfaces import IMailDelivery
from zope.session.interfaces import ISession
# import local interfaces
from ztfy.appskin.interfaces import IAnonymousPage
from ztfy.sendit.app.interfaces import ISenditApplication, EMAIL_REGEX, FilterException
from ztfy.sendit.profile.interfaces import IProfile
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
from ztfy.skin.interfaces import IDefaultView
# import Zope3 packages
from z3c.form import field, button
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import adapter, queryMultiAdapter, getMultiAdapter, queryUtility, getUtilitiesFor
from zope.i18n import translate
from zope.interface import implements, Interface, Invalid
from zope.publisher.skinnable import applySkin
from zope.schema import TextLine, Password
from zope.site import hooks
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.mail.message import HTMLMessage
from ztfy.sendit.profile import getUserProfile
from ztfy.skin.form import BaseAddForm
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
class ILoginFormFields(Interface):
"""Login form fields interface"""
username = TextLine(title=_("login-field", "Login"),
description=_("Principal ID or email address"),
required=True)
password = Password(title=_("password-field", "Password"),
required=True)
came_from = TextLine(title=_("camefrom-field", "Login origin"),
required=False)
def isUnauthorized(form):
return IUnauthorized.providedBy(form.context)
def isUnauthorizedOrSubmitted(form):
return isUnauthorized(form) or form.request.form.get(form.prefix + 'buttons.redirect')
def canRegister(form):
if isUnauthorized(form):
return False
context = form.context
app = getParent(context, ISenditApplication)
return (app is not None) and app.open_registration
class LoginView(BaseAddForm):
"""Main login view"""
implements(IAnonymousPage)
legend = _("Please entel valid credentials to login")
css_class = 'login_view'
icon_class = 'icon-lock'
disable_submit_flag = True
fields = field.Fields(ILoginFormFields)
def __call__(self):
if isUnauthorized(self):
context, _action, _permission = self.context.args
self.request.response.setStatus(UNAUTHORIZED)
else:
context = self.context
self.app = getParent(context, ISenditApplication)
return super(LoginView, self).__call__()
@property
def action(self):
return '%s/@@login.html' % absoluteURL(self.app, self.request)
@property
def help(self):
profile = IProfile(self.request.principal, None)
if (profile is not None) and profile.disabled:
return _("This account is disabled. Please login with an enabled account or contact the administrator.")
if canRegister(self):
return _("Please enter login credentials or click 'Register' button to request a new account")
def updateWidgets(self):
super(LoginView, self).updateWidgets()
self.widgets['came_from'].mode = HIDDEN_MODE
origin = self.request.get('came_from') or self.request.get(self.prefix + self.widgets.prefix + 'came_from')
if not origin:
origin = self.request.getURL()
stack = self.request.getTraversalStack()
if stack:
origin += '/' + '/'.join(stack[::-1])
self.widgets['came_from'].value = origin
def updateActions(self):
super(LoginView, self).updateActions()
self.actions['login'].addClass('btn')
if canRegister(self):
self.actions['register'].addClass('btn btn-warning')
if isUnauthorized(self):
self.actions['redirect'].addClass('btn btn-warning')
self.actions['forgotten_password'].addClass('btn pull-right')
def extractData(self, setErrors=True):
data, errors = super(LoginView, self).extractData(setErrors=setErrors)
if errors:
self.logout()
return data, errors
self.request.form['login'] = data['username'].lower()
self.request.form['password'] = data['password']
self.principal = None
context = getParent(self.context, ISite)
while context is not None:
old_site = hooks.getSite()
try:
hooks.setSite(context)
for _name, auth in getUtilitiesFor(IAuthentication):
try:
self.principal = auth.authenticate(self.request)
if self.principal is not None:
profile = IProfile(self.principal)
if not profile.activated:
error = Invalid(_("This user profile is not activated. Please check your mailbox to get activation instructions."))
view = getMultiAdapter((error, self.request, None, None, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if setErrors:
self.widgets.errors = errors
return data, errors
except:
continue
finally:
hooks.setSite(old_site)
context = getParent(context, ISite, allow_context=False)
if self.principal is None:
error = Invalid(_("Invalid credentials"))
view = getMultiAdapter((error, self.request, None, None, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if setErrors:
self.widgets.errors = errors
self.logout()
return data, errors
@button.buttonAndHandler(_("login-button", "Login"), name="login")
def handleLogin(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
app = getParent(self.context, ISenditApplication)
if self.principal is not None:
ISenditApplicationUsers(app).addUserFolder(self.principal)
if isUnauthorized(self):
context, _action, _permission = self.context.args
self.request.response.redirect(absoluteURL(context, self.request),
trusted=app.trusted_redirects)
else:
came_from = data.get('came_from')
if came_from:
self.request.response.redirect(came_from,
trusted=app.trusted_redirects)
else:
target = queryMultiAdapter((self.context, self.request, Interface), IDefaultView)
self.request.response.redirect('%s/%s' % (absoluteURL(self.context, self.request),
target.viewname if target is not None else '@@index.html'),
trusted=app.trusted_redirects)
return ''
else:
self.request.response.redirect('%s/@@login.html?came_from=%s' % (absoluteURL(self.context, self.request),
data.get('came_from')),
trusted=app.trusted_redirects)
def logout(self):
sessionData = ISession(self.request)['zope.pluggableauth.browserplugins']
sessionData['credentials'] = None
@button.buttonAndHandler(_("register-button", "Register"), name="register", condition=canRegister)
def handleRegister(self, action):
app = getParent(self.context, ISenditApplication)
self.request.response.redirect('%s/@@register.html' % absoluteURL(self.context, self.request),
trusted=app.trusted_redirects)
@button.buttonAndHandler(_("home-button", "Go back home"), name="redirect", condition=isUnauthorizedOrSubmitted)
def handleRedirect(self, action):
app = getParent(self.context, ISenditApplication)
self.request.response.redirect('%s/@@index.html' % absoluteURL(app, self.request),
trusted=app.trusted_redirects)
@button.buttonAndHandler(_("forgotten-password-button", "Forgotten password"), name="forgotten_password")
def handleForgottenPassword(self, action):
app = getParent(self.context, ISenditApplication)
self.request.response.redirect('%s/@@forgotten_password.html' % absoluteURL(app, self.request),
trusted=app.trusted_redirects)
class ForgottenPasswordView(BaseAddForm):
"""Forgotten password view"""
implements(IAnonymousPage)
legend = _("Please enter a valid e-mail address")
css_class = 'login_view'
icon_class = 'icon-lock'
disable_submit_flag = True
fields = field.Fields(ILoginFormFields).select('username')
forgotten_password_template = ViewPageTemplateFile('templates/forgotten_password.pt')
help = _("Please enter an already registered email address which will be used to send a new activation code.")
def updateActions(self):
super(ForgottenPasswordView, self).updateActions()
self.actions['activate'].addClass('btn')
def extractData(self, setErrors=True):
data, errors = super(ForgottenPasswordView, self).extractData(setErrors)
error = None
if not EMAIL_REGEX.match(data['username']):
error = Invalid(_("Given login is not a valid email address!"))
else:
try:
self.context.checkAddressFilters(data['username'].lower())
except FilterException:
error = Invalid(_("This email domain or address has been excluded by system administrator"))
else:
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
if not plugin.has_key(data['username'].lower()):
error = Invalid(_("This email address is not registered!"))
if error is not None:
view = getMultiAdapter((error, self.request, None, None, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if setErrors:
self.widgets.errors = errors
return data, errors
@button.buttonAndHandler(_("activate", "Send activation code"), name='activate')
def handleActivation(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
email = data.get('username').lower()
# get profile
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
profile = getUserProfile(plugin.prefix + email, create=False)
if profile is not None:
mailer = queryUtility(IMailDelivery, self.context.mailer_name)
if mailer is not None:
principal = plugin.get(email)
message_body = self.forgotten_password_template(request=self.request,
context=self.context,
hash=profile.activation_hash)
message = HTMLMessage(subject=translate(_("[%s] Forgotten password"),
context=self.request) %
II18n(self.context).queryAttribute('mail_subject_header',
request=self.request),
fromaddr="%s <%s>" % (self.context.mail_sender_name,
self.context.mail_sender_address),
toaddr="%s <%s>" % (principal.title, principal.login),
html=message_body)
mailer.send(self.context.mail_sender_address, (principal.login,), message.as_string())
self.request.response.redirect('%s/@@forgotten_password_ack.html' % absoluteURL(self.context, self.request),
trusted=self.context.trusted_redirects)
class ForgottenPasswordAckView(BaseAddForm):
"""Forgotten password acknowledgement view"""
implements(IAnonymousPage)
legend = _("Activation message has been sent")
css_class = 'login_view'
icon_class = 'icon-lock'
disable_submit_flah = True
fields = field.Fields(Interface)
buttons = button.Buttons(Interface)
help = _("A new activation message has been sent to given email address. Please check your messages and follow "
"the instructions.")
class LogoutView(BaseAddForm):
"""Main logout view"""
def __call__(self):
skin = queryUtility(IBrowserSkinType, self.context.getSkin())
applySkin(self.request, skin)
context = getParent(self.context, ISite)
while context is not None:
old_site = hooks.getSite()
try:
hooks.setSite(context)
for _name, auth in getUtilitiesFor(IAuthentication):
auth.logout(self.request)
finally:
hooks.setSite(old_site)
context = getParent(context, ISite, allow_context=False)
target = queryMultiAdapter((self.context, self.request, Interface), IDefaultView)
app = getParent(self.context, ISenditApplication)
self.request.response.redirect('%s/%s' % (absoluteURL(self.context, self.request),
target.viewname if target is not None else '@@SelectedManagementView.html'),
trusted=app.trusted_redirects)
return ''
@adapter(IAuthenticatedPrincipalCreated)
def handleAuthenticatedPrincipal(event):
"""Handle authenticated principals
Internal principals are automatically activated
"""
app = getParent(event.authentication, ISenditApplication)
if app is not None:
profile = IProfile(event.principal)
if not profile.activated:
name, _plugin, _info = profile.getAuthenticatorPlugin()
if name in app.internal_auth_plugins:
profile.activation_date = datetime.utcnow()
profile.activated = True | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/login.py | login.py |
# import standard packages
# import Zope3 interfaces
from hurry.query.interfaces import IQuery
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.sendit.profile.interfaces import IProfile
from ztfy.sendit.skin.app.interfaces import ISenditInboxTable, ISenditOutboxTable
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
# import Zope3 packages
from hurry.query.query import And
from hurry.query.set import AnyOf
from hurry.query.value import Eq
from zope.component import getUtility
from zope.i18n import translate
from zope.interface import implements
# import local packages
from ztfy.sendit.skin.page import BaseSenditApplicationPage
from ztfy.skin.container import InnerContainerBaseView
from ztfy.utils.property import cached_property
from ztfy.utils.request import getRequestData, setRequestData
from ztfy.sendit import _
class SenditDashboardInboxView(InnerContainerBaseView):
"""Sendit dashboard inbox view"""
implements(ISenditInboxTable)
cssClasses = {'table': 'table table-bordered table-striped table-hover'}
sortOn = None
@cached_property
def values(self):
results = getRequestData('ztfy.sendit.inbox', self.request)
if results is None:
query = getUtility(IQuery)
params = (Eq(('Catalog', 'content_type'), 'IPacket'),
AnyOf(('SecurityCatalog', 'ztfy.SenditRecipient'),
(self.request.principal.id,) + tuple(self.request.principal.groups)))
results = query.searchResults(And(*params))
setRequestData('ztfy.sendit.inbox', results, self.request)
return sorted(results, key=lambda x: IZopeDublinCore(x).created, reverse=True)[:3]
class SenditDashboardOutboxView(InnerContainerBaseView):
"""Sendit dashboard outbox view"""
implements(ISenditOutboxTable)
cssClasses = {'table': 'table table-bordered table-striped table-hover'}
sortOn = None
@cached_property
def quota_pc(self):
profile = IProfile(self.request.principal)
return profile.getQuotaUsagePc(self.context)
@property
def quota_title(self):
return translate(_("Used quota: %d%%"), context=self.request) % self.quota_pc
@cached_property
def values(self):
folder = ISenditApplicationUsers(self.context).getUserFolder()
if folder is not None:
return sorted(folder.values(), key=lambda x: IZopeDublinCore(x).created, reverse=True)[:3]
else:
return ()
class SenditApplicationDashboard(BaseSenditApplicationPage):
"""Sendit application dashboard"""
shortname = _("Dashboard")
inbox = None
outbox = None
def update(self):
super(SenditApplicationDashboard, self).update()
self.inbox = SenditDashboardInboxView(self, self.request)
self.inbox.update()
self.outbox = SenditDashboardOutboxView(self, self.request)
self.outbox.update() | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/dashboard.py | dashboard.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.table.interfaces import IBatchProvider
# import local interfaces
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.profile.interfaces.history import IProfileHistory
from ztfy.sendit.skin.layer import ISenditLayer
# import Zope3 packages
from z3c.table.batch import BatchProvider
from z3c.table.column import GetAttrColumn, Column
from z3c.table.table import Table
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import adapts
from zope.interface import implements
# import local packages
from ztfy.sendit.skin.page import BaseSenditApplicationPage
from ztfy.utils.date import formatDatetime, formatDate
from ztfy.utils.size import getHumanSize
from ztfy.sendit import _
class SenditApplicationHistory(BaseSenditApplicationPage, Table):
"""Sendit application history view"""
shortname = _("History")
cssClasses = {'table': 'table table-bordered table-striped table-hover'}
sortOn = None
batchSize = 20
startBatchingAt = 20
def __init__(self, context, request):
BaseSenditApplicationPage.__init__(self, context, request)
Table.__init__(self, context, request)
def update(self):
BaseSenditApplicationPage.update(self)
Table.update(self)
@property
def values(self):
history = IProfileHistory(self.request.principal)
return sorted(history.values(), key=lambda x: x.creation_time, reverse=True)
class SendedColumn(GetAttrColumn):
"""History sended date column"""
header = _("Send on")
cssClasses = {'th': 'span3',
'td': 'small'}
weight = 0
def getValue(self, obj):
return formatDatetime(obj.creation_time, request=self.request)
class PacketColumn(Column):
"""Outbox packet column"""
header = _("Packet content")
template = ViewPageTemplateFile('templates/history_packet.pt')
weight = 10
def renderCell(self, item):
self.context = item
return self.template(self)
def getSize(self, document):
return getHumanSize(document.contentSize)
def getDate(self, date):
return formatDatetime(date, request=self.request)
def getExpirationDate(self):
return formatDate(self.context.expiration_date, request=self.request)
def getArchiveDate(self):
return formatDatetime(self.context.deletion_time, request=self.request)
class SenditApplicationHistoryBatchProvider(BatchProvider):
"""History batch provider"""
adapts(ISenditApplication, ISenditLayer, SenditApplicationHistory)
implements(IBatchProvider)
def renderBatchLink(self, batch, cssClass=None):
return '<li%s>%s</li>' % (' class="active"' if batch == self.batch else '',
super(SenditApplicationHistoryBatchProvider, self).renderBatchLink(batch, cssClass)) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/history.py | history.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from hurry.query.interfaces import IQuery
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.sendit.skin.app.interfaces import ISenditInboxTable
# import Zope3 packages
from hurry.query import And
from hurry.query.value import Eq
from hurry.query.set import AnyOf
from z3c.table.column import Column, GetAttrColumn
from z3c.table.table import Table
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import getUtility
from zope.i18n import translate
from zope.interface import implements
# import local packages
from ztfy.security.search import getPrincipal
from ztfy.sendit.skin.page import BaseSenditApplicationPage
from ztfy.sendit.user.interfaces import IUser
from ztfy.utils.date import formatDatetime
from ztfy.utils.property import cached_property
from ztfy.utils.request import getRequestData, setRequestData
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
class SenditApplicationInbox(BaseSenditApplicationPage, Table):
"""Sendit application inbox view"""
implements(ISenditInboxTable)
shortname = _("Inbox")
cssClasses = {'table': 'table table-bordered table-striped table-hover'}
sortOn = None
batchSize = 9999
def __init__(self, context, request):
BaseSenditApplicationPage.__init__(self, context, request)
Table.__init__(self, context, request)
def update(self):
BaseSenditApplicationPage.update(self)
Table.update(self)
@cached_property
def values(self):
results = getRequestData('ztfy.sendit.inbox', self.request)
if results is None:
query = getUtility(IQuery)
params = (Eq(('Catalog', 'content_type'), 'IPacket'),
AnyOf(('SecurityCatalog', 'ztfy.SenditRecipient'),
(self.request.principal.id,) + tuple(self.request.principal.groups)))
results = query.searchResults(And(*params))
setRequestData('ztfy.sendit.inbox', results, self.request)
return sorted(results, key=lambda x: IZopeDublinCore(x).created, reverse=True)
class SenderColumn(GetAttrColumn):
"""Inbox sender column"""
header = _("Sender")
cssClasses = {'th': 'span3'}
weight = 0
def getValue(self, obj):
user = getParent(obj, IUser)
return '%s<br /><span class="small">%s</span>' % \
(getPrincipal(user.owner).title,
translate(_("Sent on: %s"), context=self.request) %
formatDatetime(IZopeDublinCore(obj).created, request=self.request))
class PacketColumn(Column):
"""Inbox packet column"""
header = _("Packet content")
template = ViewPageTemplateFile('templates/inbox_packet.pt')
weight = 10
def renderCell(self, item):
self.context = item
return self.template(self)
def getDate(self, date):
return formatDatetime(date, request=self.request) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/inbox.py | inbox.py |
# import standard packages
# import Zope3 interfaces
from zope.publisher.interfaces import NotFound
# import local interfaces
from ztfy.appskin.interfaces import IApplicationResources
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.skin.app.interfaces import ISenditApplicationPresentationInfo
from ztfy.sendit.skin.layer import ISenditLayer
from ztfy.skin.interfaces.metas import IContentMetasHeaders
# import Zope3 packages
from zope.component import adapts, queryMultiAdapter
from zope.interface import implements, Interface
from zope.publisher.browser import BrowserPage
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.sendit.skin import ztfy_sendit
from ztfy.skin.metas import LinkMeta
from ztfy.utils.traversing import getParent
class SenditApplicationIconView(BrowserPage):
"""'favicon.ico' application view"""
def __call__(self):
icon = ISenditApplicationPresentationInfo(self.context).site_icon
if icon is not None:
view = queryMultiAdapter((icon, self.request), Interface, 'index.html')
if view is not None:
return view()
raise NotFound(self.context, 'favicon.ico', self.request)
class SenditApplicationMetasHeadersAdapter(object):
"""Sendit application metas adapter"""
adapts(Interface, ISenditLayer)
implements(IContentMetasHeaders)
def __init__(self, context, request):
self.context = context
self.request = request
@property
def metas(self):
result = []
site = getParent(self.context, ISenditApplication)
if site is not None:
info = ISenditApplicationPresentationInfo(site)
if info.site_icon:
result.append(LinkMeta('icon', info.site_icon.contentType, absoluteURL(info.site_icon, self.request)))
else:
result.append(LinkMeta('icon', 'image/png', '%s/@@/favicon.ico' % absoluteURL(site, self.request)))
else:
result.append(LinkMeta('icon', 'image/png', '/@@/favicon.ico'))
return result
class SenditApplicationResourcesAdapter(object):
"""Sendit application resources adapter"""
adapts(Interface, ISenditLayer)
implements(IApplicationResources)
def __init__(self, context, request):
self.context = context
self.request = request
resources = (ztfy_sendit,) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import HIDDEN_MODE
from z3c.json.interfaces import IJSONWriter
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.security.interfaces import ISecurityManager
from ztfy.sendit.profile.interfaces import IProfile
from ztfy.sendit.skin.app.interfaces import ISenditOutboxTable
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
# import Zope3 packages
from z3c.form import field, button
from z3c.formjs import jsaction, ajax
from z3c.table.column import Column, GetAttrColumn
from z3c.table.table import Table
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import getUtility
from zope.event import notify
from zope.i18n import translate
from zope.interface import implements, Interface
from zope.schema import Bool, Int
from zope.traversing.api import getParent, getName
# import local packages
from ztfy.jqueryui import jquery_multiselect_css
from ztfy.security.search import getPrincipal
from ztfy.sendit.packet import PacketDeleteEvent
from ztfy.sendit.skin.page import BaseSenditApplicationPage
from ztfy.skin.form import BaseDialogAddForm
from ztfy.utils.catalog import getIntIdUtility
from ztfy.utils.date import formatDatetime, formatDate
from ztfy.sendit import _
class SenditApplicationOutbox(BaseSenditApplicationPage, Table):
"""Sendit application outbox page"""
implements(ISenditOutboxTable)
shortname = _("Outbox")
cssClasses = {'table': 'table table-bordered table-striped table-hover'}
sortOn = None
batchSize = 9999
def __init__(self, context, request):
BaseSenditApplicationPage.__init__(self, context, request)
Table.__init__(self, context, request)
def update(self):
BaseSenditApplicationPage.update(self)
Table.update(self)
jquery_multiselect_css.need()
@property
def quota_pc(self):
profile = IProfile(self.request.principal)
return profile.getQuotaUsagePc(self.context)
@property
def quota_title(self):
return translate(_("Used quota: %d%%"), context=self.request) % self.quota_pc
@property
def values(self):
folder = ISenditApplicationUsers(self.context).getUserFolder()
if folder is not None:
return sorted(folder.values(), key=lambda x: IZopeDublinCore(x).created, reverse=True)
else:
return ()
class SendedColumn(GetAttrColumn):
"""Inbox sended date column"""
header = _("Send on")
cssClasses = {'th': 'span3',
'td': 'small'}
weight = 0
def getValue(self, obj):
intids = getIntIdUtility(request=self.request)
packet_oid = intids.register(obj)
return """%s
<br /><br /><br />
<div class="centered" id="delete_%d">
<input type="button" class="btn btn-small btn-warning" value="%s" onclick="$.ZTFY.dialog.open('@@deletePacket.html?packet_oid:int=%d');" />
</div>
""" % (formatDatetime(IZopeDublinCore(obj).created, request=self.request),
packet_oid,
translate(_("Delete packet"), context=self.request),
packet_oid)
class PacketColumn(Column):
"""Outbox packet column"""
header = _("Packet content")
template = ViewPageTemplateFile('templates/outbox_packet.pt')
weight = 10
def renderCell(self, item):
self.context = item
return self.template(self)
def getPrincipal(self, principal):
return getPrincipal(principal).title
def getDate(self, date):
return formatDatetime(date, request=self.request)
def getExpirationDate(self):
return formatDate(self.context.expiration_date, request=self.request)
#
# Packet delete form
#
class ISenditOutboxDeleteInfo(Interface):
"""Packet deletion form info"""
packet_oid = Int(title=_("Packet OID"),
required=True)
notify_recipients = Bool(title=_("Notify recipients?"),
description=_("Do you want to notify recipients of this packet that it won't "
"be available anymore?"),
required=True,
default=True)
class ISenditOutboxDeleteButtons(Interface):
"""Default dialog add form buttons"""
delete = jsaction.JSButton(title=_("Delete packet"))
cancel = jsaction.JSButton(title=_("Cancel"))
class SenditOutboxDeleteForm(BaseDialogAddForm):
"""Delete packet from outbox"""
legend = _("Delete packet?")
help = _("You can delete this packet to get more free space without waiting for its expiration date.\n"
"But it won't be available anymore for its recipients")
fields = field.Fields(ISenditOutboxDeleteInfo)
buttons = button.Buttons(ISenditOutboxDeleteButtons)
def updateWidgets(self):
super(SenditOutboxDeleteForm, self).updateWidgets()
self.widgets['packet_oid'].value = self.request.form.get('packet_oid')
self.widgets['packet_oid'].mode = HIDDEN_MODE
@jsaction.handler(buttons['delete'])
def add_handler(self, event, selector):
return '$.ZTFY.form.add(this.form, null, $.ZTFY.sendit.form.deletePacketCallback);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
def updateActions(self):
super(SenditOutboxDeleteForm, self).updateActions()
self.actions['delete'].addClass('btn btn-inverse')
self.actions['cancel'].addClass('btn')
@ajax.handler
def ajaxCreate(self):
writer = getUtility(IJSONWriter)
self.updateWidgets()
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return writer.write(self.getAjaxErrors())
packet_oid = data.get('packet_oid')
intids = getIntIdUtility(request=self.request)
packet = intids.queryObject(packet_oid)
if (packet is not None) and ISecurityManager(packet).canUsePermission('ztfy.ManageSenditPacket'):
if data.get('notify_recipients'):
notify(PacketDeleteEvent(packet, self))
parent = getParent(packet)
del parent[getName(packet)]
return writer.write({'output': u"OK",
'packet_oid': packet_oid})
else:
return writer.write({'output': u'NONE'}) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/outbox.py | outbox.py |
# import standard packages
from persistent import Persistent
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
# import local interfaces
from ztfy.sendit.skin.app.interfaces import ISenditApplicationPresentationInfo
from ztfy.skin.interfaces import IPresentationTarget
# import Zope3 packages
from zope.component import adapter, adapts
from zope.container.contained import Contained
from zope.interface import implementer, implements
from zope.location import locate
# import local packages
from ztfy.file.property import ImageProperty
from ztfy.i18n.property import I18nTextProperty
from ztfy.jqueryui import jquery_jsonrpc
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.skin.layer import ISenditLayer
from ztfy.sendit.skin.menu import SenditLayerDialogMenuItem
from ztfy.skin.presentation import BasePresentationEditForm
from ztfy.sendit import _
SENDIT_APPLICATION_PRESENTATION_KEY = 'ztfy.sendit.app.presentation'
class SenditApplicationPresentation(Persistent, Contained):
"""Sendit application presentation class"""
implements(ISenditApplicationPresentationInfo)
site_icon = ImageProperty(ISenditApplicationPresentationInfo['site_icon'])
logo = ImageProperty(ISenditApplicationPresentationInfo['logo'])
footer_text = I18nTextProperty(ISenditApplicationPresentationInfo['footer_text'])
@adapter(ISenditApplication)
@implementer(ISenditApplicationPresentationInfo)
def SenditApplicationPresentationFactory(context):
annotations = IAnnotations(context)
presentation = annotations.get(SENDIT_APPLICATION_PRESENTATION_KEY)
if presentation is None:
presentation = annotations[SENDIT_APPLICATION_PRESENTATION_KEY] = SenditApplicationPresentation()
locate(presentation, context, '++presentation++')
return presentation
class SenditApplicationPresentationTargetAdapter(object):
adapts(ISenditApplication, ISenditLayer)
implements(IPresentationTarget)
target_interface = ISenditApplicationPresentationInfo
def __init__(self, context, request):
self.context, self.request = context, request
class SenditApplicationPresentationEditForm(BasePresentationEditForm):
"""Site manager presentation edit form"""
legend = _("Edit presentation properties")
parent_interface = ISenditApplication
class SenditApplicationPresentationMenuItem(SenditLayerDialogMenuItem):
"""Site manager presentation menu item"""
title = _(" :: Presentation model...")
def render(self):
result = super(SenditApplicationPresentationMenuItem, self).render()
if result:
jquery_jsonrpc.need()
return result | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/presentation.py | presentation.py |
# import standard packages
import uuid
from random import randrange
from xmlrpclib import Binary
# import Zope3 interfaces
from z3c.language.switch.interfaces import II18n
from zope.pluggableauth.interfaces import IAuthenticatorPlugin
from zope.sendmail.interfaces import IMailDelivery
# import local interfaces
from ztfy.mail.interfaces import IPrincipalMailInfo
from ztfy.security.interfaces import ISecurityManager
from ztfy.sendit.app.interfaces import FilterException
from ztfy.sendit.profile.interfaces import IProfile
from ztfy.sendit.skin.app.xmlrpc.interfaces import ISenditApplicationServices
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
# import Zope3 packages
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.component import getUtilitiesFor, queryUtility
from zope.event import notify
from zope.i18n import translate
from zope.interface import implements
from zope.interface.exceptions import Invalid
from zope.lifecycleevent import ObjectCreatedEvent
from zope.pluggableauth.plugins.principalfolder import InternalPrincipal
from zope.publisher.xmlrpc import XMLRPCView
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.mail.message import HTMLMessage
from ztfy.security.search import findPrincipals, getPrincipal, MissingPrincipal
from ztfy.sendit.packet import Packet, Document
from ztfy.sendit.profile import getUserProfile
from ztfy.sendit.skin.app.registration import generatePassword
from ztfy.skin.form import FormObjectCreatedEvent
from ztfy.sendit import _
def getPrincipalTitle(principal):
title = principal.title
if '@' in principal.id:
_name, domain = principal.id.split('@')
title = '%s (%s)' % (title, domain)
return title
class SenditApplicationServicePublisher(XMLRPCView):
"""Sendit application services publisher"""
implements(ISenditApplicationServices)
registration_message_template = ViewPageTemplateFile('../templates/register_message.pt')
def searchPrincipals(self, query, names=None):
"""Search for registered principals"""
app = self.context
return [{'value': principal.id,
'caption': getPrincipalTitle(principal)}
for principal in findPrincipals(query, names)
if principal.id not in (app.excluded_principals or ())]
def getPrincipalInfo(self, principal_id):
"""Get registered principal info, or None if not found"""
for _name, plugin in getUtilitiesFor(IAuthenticatorPlugin):
info = plugin.principalInfo(principal_id)
if info is not None:
return {'id': info.id,
'title': info.title}
return None
def canRegisterPrincipal(self):
"""Is external principals registration opened"""
profile = IProfile(self.request.principal)
name, _plugin, _info = profile.getAuthenticatorPlugin()
if name is None:
return False
return name in self.context.internal_auth_plugins
def registerPrincipal(self, email, firstname, lastname, company_name=None):
"""Create a new external principal"""
# check for existing of filtered principal
plugin = queryUtility(IAuthenticatorPlugin, self.context.external_auth_plugin)
if plugin.has_key(email):
raise Invalid(_("Address already used"))
else:
try:
self.context.checkAddressFilters(email)
except FilterException:
raise Invalid(_("This email domain or address has been excluded by system administrator"))
# create principal
password = generatePassword()
principal = InternalPrincipal(login=email,
password=password,
title='%s %s' % (lastname, firstname),
description=company_name or u'')
notify(ObjectCreatedEvent(principal))
plugin[principal.login] = principal
ISecurityManager(principal).grantRole('ztfy.SenditProfileOwner', plugin.prefix + principal.login)
ISecurityManager(principal).grantRole('zope.Manager', plugin.prefix + principal.login)
# create profile
profile = getUserProfile(plugin.prefix + principal.login)
profile.self_registered = False
profile.generateSecretKey(email, password)
# prepare notification message
mailer = queryUtility(IMailDelivery, self.context.mailer_name)
if mailer is not None:
source_mail = None
source_profile = IProfile(self.request.principal)
source_info = IPrincipalMailInfo(source_profile, None)
if source_info is None:
_name, _plugin, principal_info = source_profile.getAuthenticatorPlugin()
if principal_info is not None:
source_info = IPrincipalMailInfo(principal_info, None)
if source_info is not None:
source_mail = source_info.getAddresses()
if source_mail:
source_mail = source_mail[0]
if not source_mail:
source_mail = (self.context.mail_sender_name, self.context.mail_sender_address)
message_body = self.registration_message_template(request=self.request,
context=self.context,
hash=profile.activation_hash)
message = HTMLMessage(subject=translate(_("[%s] Please confirm registration"), context=self.request) %
II18n(self.context).queryAttribute('mail_subject_header',
request=self.request),
fromaddr="%s via %s <%s>" % (source_mail[0],
self.context.mail_sender_name,
self.context.mail_sender_address),
toaddr="%s <%s>" % (principal.title, principal.login),
html=message_body)
message.add_header('Sender', "%s <%s>" % source_mail)
message.add_header('Return-Path', "%s <%s>" % source_mail)
message.add_header('Reply-To', "%s <%s>" % source_mail)
message.add_header('Errors-To', source_mail[1])
mailer.send(self.context.mail_sender_address, (principal.login,), message.as_string())
info = plugin.principalInfo(plugin.prefix + principal.login)
return info.id if info is not None else None
def uploadPacket(self, title, description, recipients, notification_mode, backup_time, documents):
"""Create a new packet"""
# Check profile quota
profile = getUserProfile(self.request.principal)
if profile.getQuotaUsage(self.context) >= (profile.getQuotaSize(self.context) * 1024 * 1024):
raise ValueError, translate(_("Your storage quota is exceeded. You can't upload any new packet without "
"freeing some space..."), context=self.request)
# Check recipients
errors = []
if isinstance(recipients, (str, unicode)):
recipients = recipients.split(',')
for recipient in recipients:
if isinstance(getPrincipal(recipient), MissingPrincipal):
errors.append(recipient)
if errors:
raise ValueError, translate(_("Your packet contains unknown recipients: %s"), context=self.request) % \
', '.join(errors)
# Create new packet
packet = Packet()
notify(ObjectCreatedEvent(packet))
packet.title = unicode(title, 'utf-8') if not isinstance(title, unicode) else title
if description:
packet.description = unicode(description, 'utf-8') if not isinstance(description, unicode) else description
packet.recipients = recipients
packet.notification_mode = notification_mode
packet.backup_time = backup_time
packet_name = str(uuid.uuid1(randrange(0, 1 << 48L) | 0x010000000000L))
user = ISenditApplicationUsers(self.context).getUserFolder(self.request.principal)
user[packet_name] = packet
for doc_data in documents:
if not isinstance(doc_data.get('data'), Binary):
raise ValueError, translate(_("Document data must be set as XML-RPC binary"), context=self.request)
document = Document()
notify(ObjectCreatedEvent(document))
document_name = str(uuid.uuid1(randrange(0, 1 << 48L) | 0x010000000000L))
packet[document_name] = document
title = doc_data.get('title') or translate(_("< document without title >"), context=self.request)
document.title = unicode(title, 'utf-8') if not isinstance(title, unicode) else title
document.data = doc_data.get('data').data
filename = doc_data.get('filename')
document.filename = unicode(filename, 'utf-8') if not isinstance(filename, unicode) else filename
notify(FormObjectCreatedEvent(packet, self))
return absoluteURL(packet, self.request) | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/app/xmlrpc/__init__.py | __init__.py |
# import standard packages
import random
import tempfile
import uuid
import zipfile
from datetime import datetime
from urllib import quote
# import Zope3 interfaces
from z3c.form.interfaces import IErrorViewSnippet
from zope.security.interfaces import Unauthorized
# import local interfaces
from ztfy.security.interfaces import ISecurityManager
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.packet.interfaces import IPacket, IPacketInfo, IDocumentInfo
from ztfy.sendit.profile.interfaces import IProfile
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
from ztfy.skin.interfaces import ICustomUpdateSubForm
# import Zope3 packages
from z3c.form import field, button
from zope.component import getMultiAdapter, queryMultiAdapter
from zope.event import notify
from zope.i18n import translate
from zope.interface import implements, Interface, Invalid
from zope.lifecycleevent import ObjectCreatedEvent
from zope.publisher.browser import FileUpload
from zope.security.proxy import removeSecurityProxy
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.sendit.packet import Packet, Document, DocumentDownloadEvent
from ztfy.sendit.profile import getUserProfile
from ztfy.sendit.skin.packet.widget import PacketRecipientsWidgetFactory
from ztfy.sendit.skin.page import BaseSenditProtectedPage
from ztfy.skin.form import BaseAddForm, AddSubForm
from ztfy.skin.page import TemplateBasedPage
from ztfy.utils.traversing import getParent
from ztfy.sendit import _
#
# Packet documents schema field
#
class PacketDocumentsSubform(AddSubForm):
"""Packets documents sub-form"""
implements(ICustomUpdateSubForm)
legend = _("Selected documents")
fields = field.Fields(IDocumentInfo)
prefix = 'documents.'
ignoreContext = True
def extractData(self, setErrors=True):
self.widgets.setErrors = setErrors
doc_data = { 'documents': [] }
errors = ()
prefix = self.prefix + self.widgets.prefix
fieldnames = ('title', 'data')
values = [ self.request.form.get(prefix + name) for name in fieldnames ]
[ doc_data['documents'].append({ 'title': title,
'data': data }) for title, data in zip(*values) if data ]
if not doc_data['documents']:
data_widget = self.widgets['data']
error = Invalid(_("You must provide at least one document"))
view = getMultiAdapter((error, self.request, data_widget, data_widget.field, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if errors and setErrors:
self.widgets.errors = self.errors = errors
return doc_data, errors
def updateContent(self, object, data):
data, _errors = self.extractData()
for doc_data in data.get('documents'):
document = Document()
notify(ObjectCreatedEvent(document))
document_name = str(uuid.uuid1(random.randrange(0, 1 << 48L) | 0x010000000000L))
object[document_name] = document
document.title = doc_data['title'] or translate(_("< document without title >"), context=self.request)
document.data = doc_data['data']
if isinstance(doc_data['data'], FileUpload):
document.filename = doc_data['data'].filename
class PacketAddForm(BaseSenditProtectedPage, BaseAddForm):
"""Sendit packet add form"""
permission = 'ztfy.UploadSenditPacket'
legend = _("Uploading a new packet")
shortname = _("New packet upload")
icon_class = 'icon-upload'
fields = field.Fields(IPacketInfo).select('title', 'description',
'recipients', 'notification_mode', 'backup_time')
fields['recipients'].widgetFactory = PacketRecipientsWidgetFactory
def __call__(self):
try:
BaseSenditProtectedPage.__call__(self)
except Unauthorized:
return u''
else:
return BaseAddForm.__call__(self)
def createSubForms(self):
self.documents = PacketDocumentsSubform(self.context, self.request, self)
return (self.documents,)
def updateWidgets(self):
super(PacketAddForm, self).updateWidgets()
profile = IProfile(self.request.principal)
if profile.isExternal():
app = getParent(self.context, ISenditApplication)
self.widgets['recipients'].auth_plugins = set(app.single_auth_plugins) & set(app.internal_auth_plugins)
self.widgets['notification_mode'].addClass('span6')
def updateActions(self):
super(PacketAddForm, self).updateActions()
self.actions['upload'].addClass('btn btn-inverse')
@button.buttonAndHandler(_('Upload packet'), name='upload')
def handleUpload(self, action):
profile = getUserProfile(self.request.principal)
if profile.getQuotaUsage(self.context) >= (profile.getQuotaSize(self.context) * 1024 * 1024):
self.status = _("Your storage quota is exceeded. You can't upload any new packet "
"without freeing some space...")
return
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
obj = self.createAndAdd(data)
if obj is not None:
# mark only as finished if we get the new object
self._finishedAdd = True
def extractData(self, setErrors=True):
data, errors = super(PacketAddForm, self).extractData(setErrors)
for subform in self.subforms:
_data, sub_errors = subform.extractData(setErrors)
errors += sub_errors
if errors:
if setErrors:
self.widgets.errors = errors
self.status = self.formErrorsMessage
return data, errors
def create(self, data):
return Packet()
def add(self, object):
# create packet
packet_name = str(uuid.uuid1(random.randrange(0, 1 << 48L) | 0x010000000000L))
user = ISenditApplicationUsers(self.context).getUserFolder(self.request.principal)
user[packet_name] = object
def nextURL(self):
return '%s/@@outbox.html' % absoluteURL(self.context, self.request)
class PacketRejectView(TemplateBasedPage):
"""Rejected packet exception view"""
shortname = _("Upload error!")
def render(self):
self.request.response.setStatus(403)
return super(PacketRejectView, self).render()
class PacketDownloadView(object):
"""Download full packet as ZIP file"""
permission = 'ztfy.ViewSenditPacket'
def download(self):
security = ISecurityManager(self.context, None)
if not security.canUsePermission(self.permission):
app = getParent(self.context, ISenditApplication)
self.request.response.redirect('%s/@@login.html?came_from=%s' % (absoluteURL(self.context, self.request),
quote(absoluteURL(self, self.request), ':/')),
trusted=app.trusted_redirects)
raise Unauthorized
packet = self.context
# init ZIP file
principal_id = self.request.principal.id
output = tempfile.TemporaryFile(suffix='.zip')
zip = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED)
# store documents data
for document in packet.values():
zip.writestr(document.filename.encode('utf-8'), document.data.data)
if principal_id not in packet.downloaders:
notify(DocumentDownloadEvent(document, self.request, self))
if principal_id not in (document.downloaders or {}):
downloaders = removeSecurityProxy(document.downloaders) or {}
downloaders[principal_id] = datetime.utcnow()
document.downloaders = downloaders
zip.close()
self.request.response.setHeader('Content-Type', 'application/zip')
self.request.response.setHeader('Content-Disposition',
'attachment; filename="%s.zip"' % packet.title.encode('utf-8'))
return output
class DocumentDownloadView(object):
"""Document download view"""
permission = 'ztfy.ViewSenditPacket'
def download(self):
security = ISecurityManager(self.context, None)
if not security.canUsePermission(self.permission):
app = getParent(self.context, ISenditApplication)
self.request.response.redirect('%s/@@login.html?came_from=%s' % (absoluteURL(self.context, self.request),
quote(absoluteURL(self, self.request), ':/')),
trusted=app.trusted_redirects)
raise Unauthorized
document = self.context
packet = getParent(document, IPacket)
# update document download time
principal_id = self.request.principal.id
if principal_id not in packet.downloaders:
notify(DocumentDownloadEvent(document, self.request, self))
if principal_id not in (document.downloaders or {}):
downloaders = removeSecurityProxy(document.downloaders) or {}
downloaders[principal_id] = datetime.utcnow()
document.downloaders = downloaders
# return document
view = queryMultiAdapter((document.data, self.request), Interface, 'index.html')
if view is not None:
if document.filename is not None:
self.request.response.setHeader('Content-Disposition',
'attachment; filename="%s"' % document.filename.encode('utf-8'))
return view() | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/skin/packet/__init__.py | __init__.py |
# import standard packages
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
# import local interfaces
from ztfy.sendit.app.interfaces import ISenditApplication
from ztfy.sendit.user.interfaces import ISenditApplicationUsers
# import Zope3 packages
from zope.component import adapter
from zope.container.folder import Folder
from zope.interface import implementer, implements
from zope.location import locate
from zope.publisher.interfaces import NotFound
from zope.security.interfaces import IPrincipal
# import local packages
from ztfy.sendit.user import User
from ztfy.utils.request import queryRequest
class UsersFolder(Folder):
"""Users folder class"""
implements(ISenditApplicationUsers)
def getUserFolder(self, principal=None):
if principal is None:
request = queryRequest()
if request is not None:
principal = request.principal
if principal is None:
raise NotFound(self, principal)
if IPrincipal.providedBy(principal):
principal = principal.id
return self.get(principal)
def addUserFolder(self, principal=None):
if principal is None:
request = queryRequest()
if request is not None:
principal = request.principal
if principal is None:
raise NotFound(self, principal)
if IPrincipal.providedBy(principal):
principal = principal.id
# initialize users folder
user = self.get(principal)
if user is None:
user = self[principal] = User()
user.owner = principal
return user
SENDIT_APPLICATION_USERS_KEY = 'ztfy.sendit.users'
@adapter(ISenditApplication)
@implementer(ISenditApplicationUsers)
def SenditApplicationUsersFactory(context):
annotations = IAnnotations(context)
container = annotations.get(SENDIT_APPLICATION_USERS_KEY)
if container is None:
container = annotations[SENDIT_APPLICATION_USERS_KEY] = UsersFolder()
locate(container, context, '++users++')
return container | ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/src/ztfy/sendit/user/folder.py | folder.py |
.. contents::
Introduction
============
ztfy.sendit is a small package which provides an application which authenticated users can
use to send files to remote contacts, like in SendIt web site.
It's main use case is for principals from inside an organization who want to share documents
with their remote contacts; contacts selection can be done via any registered authentication
plug-in.
You can customize your application so that external users registration is opened or made only
by organization's inner principals.
| ztfy.sendit | /ztfy.sendit-0.1.20.tar.gz/ztfy.sendit-0.1.20/docs/README.txt | README.txt |
# import standard packages
# import Zope3 interfaces
from zope.lifecycleevent.interfaces import IObjectAddedEvent, IObjectCopiedEvent, IObjectRemovedEvent
# import local interfaces
from ztfy.sequence.interfaces import ISequentialIntIds, ISequentialIdTarget, ISequentialIdInfo
# import Zope3 packages
from zope.component import adapter, queryUtility
from zope.interface import implements
from zope.intid import IntIds
from zope.schema.fieldproperty import FieldProperty
# import local packages
class SequentialIntIds(IntIds):
"""Sequential IDs utility"""
implements(ISequentialIntIds)
prefix = FieldProperty(ISequentialIntIds['prefix'])
hex_oid_length = FieldProperty(ISequentialIntIds['hex_oid_length'])
_lastId = 0
def _generateId(self):
self._lastId += 1
return self._lastId
def register(self, ob):
if not ISequentialIdTarget.providedBy(ob):
return None
return super(SequentialIntIds, self).register(ob)
def generateHexId(self, obj, oid):
return (u'%%s%%s%%.%dx' % self.hex_oid_length) % (self.prefix or '',
getattr(obj, 'prefix', ''),
oid)
@adapter(ISequentialIdTarget, IObjectAddedEvent)
def handleNewSequentialIdTarget(obj, event):
"""Set unique ID for each added object"""
utility = queryUtility(ISequentialIntIds, getattr(obj, 'sequence_name', ''))
if utility is not None:
info = ISequentialIdInfo(obj)
if not info.oid:
oid = info.oid = utility.register(obj)
info.hex_oid = utility.generateHexId(obj, oid)
@adapter(ISequentialIdTarget, IObjectCopiedEvent)
def handleCopiedSequentialIdTarget(obj, event):
"""Reset unique ID when an object is copied"""
info = ISequentialIdInfo(obj)
info.oid = None
info.hex_oid = None
@adapter(ISequentialIdTarget, IObjectRemovedEvent)
def handleRemovedSequentialIdTarget(obj, event):
"""Unregister object when it is removed"""
utility = queryUtility(ISequentialIntIds, getattr(obj, 'sequence_name', ''))
if (utility is not None) and (utility.queryId(obj) is not None):
utility.unregister(obj) | ztfy.sequence | /ztfy.sequence-0.1.1.tar.gz/ztfy.sequence-0.1.1/src/ztfy/sequence/utility.py | utility.py |
.. contents::
Introduction
============
ZTFY.sequence is a small package used to set sequential identifiers on selected persistent
contents.
The SequentialIntIds utility is based on zope.intid.IntIds utility, but overrides a few methods
to be able to define these sequential IDs.
Classes for which we want to get these sequential IDs have to implement the ISequentialIntIdTarget
marker interface. They can also implement two attributes, which allows to define the name of
the sequence to use and a prefix.
This prefix, which can also be defined on the utility, is used to define an ID in hexadecimal
form, as for example 'LIB-IMG-000012ae7c', based on the 'main' numeric ID.
Sequence utility
================
Sequences are handled by a utility implementing ISequentialIntIds interface and registered for
that interface.
You can set two optional parameters on this utility, to define the first hexadecimal ID prefix
as well as the length of hexadecimal ID (not including prefix).
| ztfy.sequence | /ztfy.sequence-0.1.1.tar.gz/ztfy.sequence-0.1.1/docs/README.txt | README.txt |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
options, args = parser.parse_args()
######################################################################
# load/install setuptools
try:
if options.allow_site_packages:
import setuptools
import pkg_resources
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
sys.path[:] = [x for x in sys.path if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/bootstrap.py | bootstrap.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import HIDDEN_MODE
from z3c.json.interfaces import IJSONWriter
from zope.authentication.interfaces import IAuthentication, ILogout
from zope.component.interfaces import ISite
from zope.security.interfaces import IUnauthorized
# import local interfaces
from ztfy.skin.interfaces import IDefaultView, ILoginFormFields
# import Zope3 packages
from z3c.form import field, button
from z3c.formjs import ajax
from zope.component import adapts, queryMultiAdapter, getUtility, getUtilitiesFor, hooks
from zope.interface import implements
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.skin.form import AddForm
from ztfy.utils.traversing import getParent
from ztfy.skin import _
class LogoutAdapter(object):
adapts(IAuthentication)
implements(ILogout)
def __init__(self, auth):
self.auth = auth
def logout(self, request):
return self.auth.logout(request)
class LoginLogoutView(ajax.AJAXRequestHandler):
"""Base login/logout view"""
@ajax.handler
def login(self):
writer = getUtility(IJSONWriter)
context = getParent(self.context, ISite)
while context is not None:
old_site = hooks.getSite()
try:
hooks.setSite(context)
for _name, auth in getUtilitiesFor(IAuthentication):
if auth.authenticate(self.request) is not None:
return writer.write('OK')
finally:
hooks.setSite(old_site)
context = getParent(context, ISite, allow_context=False)
return writer.write('NOK')
@ajax.handler
def logout(self):
writer = getUtility(IJSONWriter)
context = getParent(self.context, ISite)
while context is not None:
old_site = hooks.getSite()
try:
hooks.setSite(context)
for _name, auth in getUtilitiesFor(IAuthentication):
if auth.logout(self.request):
return writer.write('OK')
finally:
hooks.setSite(old_site)
context = getParent(context, ISite, allow_context=False)
return writer.write('NOK')
class LoginForm(AddForm):
"""ZMI login form"""
title = _("Login form")
legend = _("Please enter valid credentials to login")
fields = field.Fields(ILoginFormFields)
def __call__(self):
self.request.response.setStatus(401)
return super(LoginForm, self).__call__()
def updateWidgets(self):
super(LoginForm, self).updateWidgets()
self.widgets['came_from'].mode = HIDDEN_MODE
if IUnauthorized.providedBy(self.context):
self.widgets['came_from'].value = self.request.getURL()
@button.buttonAndHandler(_("login-button", "Login"))
def handleLogin(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
self.request.form['login'] = data['username']
self.request.form['password'] = data['password']
if IUnauthorized.providedBy(self.context):
context, _layer, _permission = self.context.args
else:
context = self.context
site = getParent(context, ISite)
while site is not None:
old_site = hooks.getSite()
try:
hooks.setSite(site)
for _name, auth in getUtilitiesFor(IAuthentication):
if auth.authenticate(self.request) is not None:
target = data.get('came_from')
if target:
self.request.response.redirect(target)
else:
target = queryMultiAdapter((context, self.request, self), IDefaultView)
if target is not None:
self.request.response.redirect(target.getAbsoluteURL())
else:
self.request.response.redirect('%s/@@SelectedManagementView.html' % absoluteURL(self.context, self.request))
return u''
finally:
hooks.setSite(old_site)
site = getParent(site, ISite, allow_context=False) | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/security.py | security.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import IActions, IButtonForm, ISubForm, IHandlerForm, IWidgets, \
DISPLAY_MODE
from z3c.json.interfaces import IJSONWriter
from z3c.language.switch.interfaces import II18n
from zope.container.interfaces import IContainer
from zope.contentprovider.interfaces import IContentProvider
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.baseskin.interfaces.form import IBaseForm, IGroupsBasedForm, IViewletsBasedForm, IForm, \
IWidgetsGroup, ISubFormViewlet, ICustomUpdateSubForm, IFormObjectCreatedEvent
from ztfy.skin.interfaces import IDialog, IEditFormButtons, IDialogAddFormButtons, IDialogDisplayFormButtons, \
IDialogEditFormButtons, IDialogTitle
# import Zope3 packages
from z3c.form import subform, button
from z3c.formjs import ajax, jsaction
from z3c.formui import form
from zope.component import getMultiAdapter, getUtility, queryMultiAdapter
from zope.event import notify
from zope.i18n import translate
from zope.interface import implements
from zope.lifecycleevent import Attributes, ObjectCreatedEvent, ObjectModifiedEvent
from zope.security.proxy import removeSecurityProxy
from zope.traversing.api import getName
# import local packages
from ztfy.jqueryui import jquery_tipsy, jquery_tools, jquery_progressbar
from ztfy.skin.page import BaseBackView
from ztfy.utils.property import cached_property
from ztfy.utils.traversing import getParent
from ztfy.skin import _
#
# Custom forms base classes
#
class AjaxForm(ajax.AJAXRequestHandler):
"""Custom base form class used to handle AJAX errors
This base class may be combined with other form based classes (form.AddForm or form.EditForm)
which provide standard form methods
"""
def getAjaxErrors(self):
errors = {}
errors['status'] = translate(self.status, context=self.request)
for error in self.errors:
error.update()
error = removeSecurityProxy(error)
if hasattr(error, 'widget'):
widget = removeSecurityProxy(error.widget)
if widget is not None:
errors.setdefault('errors', []).append({'id': widget.id,
'widget': translate(widget.label, context=self.request),
'message': translate(error.message, context=self.request)})
else:
errors.setdefault('errors', []).append({'message': translate(error.message, context=self.request)})
else:
errors.setdefault('errors', []).append({'message': translate(error.message, context=self.request)})
return {'output': u'ERRORS',
'errors': errors}
class ViewletsBasedForm(form.Form):
"""Viewlets based form"""
implements(IViewletsBasedForm)
managers = []
def __init__(self, context, request):
self.context = context
self.request = request
self.viewlets = []
@property
def errors(self):
result = []
for viewlet in self.viewlets:
_data, errors = viewlet.extractData()
result.extend(errors)
return tuple(result)
def updateActions(self):
super(ViewletsBasedForm, self).updateActions()
for name in self.managers:
manager = queryMultiAdapter((self.context, self.request, self), IContentProvider, name)
if manager is not None:
manager.update()
self.viewlets.extend(manager.viewlets)
def updateContent(self, object, data):
for subform in self.viewlets:
subform_data, _errors = subform.extractData()
form.applyChanges(subform, object, subform_data)
class SubFormViewlet(subform.EditSubForm):
"""Sub-form viewlet"""
implements(ISubFormViewlet)
legend = None
switchable = False
visible = True
callbacks = {}
def __init__(self, context, request, parentForm, manager):
super(SubFormViewlet, self).__init__(context, request, parentForm)
self.manager = manager
@property
def ignoreContext(self):
return self.parentForm.ignoreContext
def updateWidgets(self):
self.widgets = getMultiAdapter((self, self.request, self.getContent()), IWidgets)
self.widgets.ignoreContext = self.ignoreContext
self.widgets.update()
def getWidgetCallback(self, widget):
return self.callbacks.get(widget)
#
# Form widgets groups
#
class WidgetsGroup(object):
"""Widgets group class"""
implements(IWidgetsGroup)
def __init__(self, id, widgets=(), legend=None, help=None, cssClass='', switch=False, hide_if_empty=False,
checkbox_switch=False, checkbox_on=False, checkbox_field=None):
self.id = id
self.legend = (legend is None) and id or legend
self.help = help
self.cssClass = cssClass
self.switch = switch
self.checkbox_switch = checkbox_switch
self.checkbox_on = checkbox_on
self.checkbox_field = checkbox_field
self.hide_if_empty = hide_if_empty
self.widgets = widgets
@property
def switchable(self):
return self.switch or self.checkbox_switch
@cached_property
def visible(self):
if self.checkbox_switch:
return self.checkbox_on
if not (self.switch and self.hide_if_empty):
return True
for widget in self.widgets:
if not widget.ignoreContext:
field = widget.field
context = widget.context
name = field.getName()
value = getattr(context, name, None)
if value and (value != field.default):
return True
return False
@property
def checkbox_widget(self):
if self.checkbox_field is None:
return None
for widget in self.widgets:
if widget.field is self.checkbox_field.field:
return widget
@property
def visible_widgets(self):
for widget in self.widgets:
if (self.checkbox_field is None) or (widget.field is not self.checkbox_field.field):
yield widget
def NamedWidgetsGroup(id, widgets, names=(), legend=None, help=None, cssClass='', switch=False, hide_if_empty=False,
checkbox_switch=False, checkbox_on=False, checkbox_field=None):
"""Create a widgets group based on widgets names"""
return WidgetsGroup(id, [widgets.get(name) for name in names], legend, help, cssClass, switch, hide_if_empty,
checkbox_switch, checkbox_on, checkbox_field)
class GroupsBasedForm(object):
"""Groups based form"""
implements(IGroupsBasedForm)
def __init__(self):
self._groups = []
def addGroup(self, group):
self._groups.append(group)
@property
def groups(self):
result = self._groups[:]
others = []
for widget in self.widgets.values():
found = False
for group in result:
if widget in group.widgets:
found = True
break
if not found:
others.append(widget)
if others:
result.insert(0, WidgetsGroup(None, others))
return result
#
# Add forms
#
class FormObjectCreatedEvent(ObjectCreatedEvent):
"""Form object created event"""
implements(IFormObjectCreatedEvent)
def __init__(self, object, view):
self.object = object
self.view = view
class BaseAddForm(form.AddForm, GroupsBasedForm):
"""Custom AddForm
This form overrides creation process to allow created contents to be
'parented' before changes to be applied. This is required for ExtFile
properties to work correctly.
"""
implements(IForm, IBaseForm)
autocomplete = 'on'
display_hints_on_widgets = False
cssClass = 'form add'
formErrorsMessage = _('There were some errors.')
callbacks = {}
def __init__(self, context, request):
form.AddForm.__init__(self, context, request)
GroupsBasedForm.__init__(self)
# override button to get translated label
@button.buttonAndHandler(_('Add'), name='add')
def handleAdd(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
obj = self.createAndAdd(data)
if obj is not None:
# mark only as finished if we get the new object
self._finishedAdd = True
def update(self):
jquery_tipsy.need()
jquery_progressbar.need()
super(BaseAddForm, self).update()
self.getForms()
[subform.update() for subform in self.subforms]
[tabform.update() for tabform in self.tabforms]
def updateWidgets(self):
super(BaseAddForm, self).updateWidgets()
self.getForms()
[subform.updateWidgets() for subform in self.subforms]
[tabform.updateWidgets() for tabform in self.tabforms]
@property
def status_class(self):
if self.errors:
return 'status error'
elif self.status == self.successMessage:
return 'status success'
elif self.status:
return 'status warning'
else:
return 'status'
def createSubForms(self):
return []
def createTabForms(self):
return []
def getForms(self, with_self=True):
if not hasattr(self, 'subforms'):
self.subforms = [form for form in self.createSubForms()
if form is not None]
if not hasattr(self, 'tabforms'):
tabforms = self.tabforms = [form for form in self.createTabForms()
if form is not None]
if tabforms:
jquery_tools.need()
if with_self:
return [self, ] + self.subforms + self.tabforms
else:
return self.subforms + self.tabforms
def getWidgetCallback(self, widget):
return self.callbacks.get(widget)
@property
def errors(self):
result = []
for subform in self.getForms():
result.extend(subform.widgets.errors)
return result
def createAndAdd(self, data):
object = self.create(data)
notify(ObjectCreatedEvent(object))
self.add(object)
self.updateContent(object, data)
notify(FormObjectCreatedEvent(object, self))
return object
def updateContent(self, object, data):
form.applyChanges(self, object, data)
self.getForms()
for subform in self.subforms:
if ICustomUpdateSubForm.providedBy(subform):
ICustomUpdateSubForm(subform).updateContent(object, data)
else:
form.applyChanges(subform, object, data)
for tabform in self.tabforms:
if ICustomUpdateSubForm.providedBy(tabform):
ICustomUpdateSubForm(tabform).updateContent(object, data)
else:
form.applyChanges(tabform, object, data)
class AddForm(BaseBackView, BaseAddForm):
"""Add form"""
def update(self):
BaseBackView.update(self)
BaseAddForm.update(self)
class AddSubForm(subform.EditSubForm):
"""Add sub-form"""
callbacks = {}
def __init__(self, context, request, parentForm):
super(AddSubForm, self).__init__(None, request, parentForm)
def updateWidgets(self):
self.widgets = getMultiAdapter((self, self.request, self.getContent()), IWidgets)
self.widgets.ignoreContext = True
self.widgets.update()
def getWidgetCallback(self, widget):
return self.callbacks.get(widget)
class BaseDialogAddForm(AjaxForm, BaseAddForm):
"""Custom AJAX add form dialog"""
implements(IDialog, IBaseForm)
buttons = button.Buttons(IDialogAddFormButtons)
prefix = 'add_dialog.'
layout = None
parent_interface = IContainer
parent_view = None
handle_upload = False
changes_output = u'OK'
nochange_output = u'NONE'
resources = ()
@jsaction.handler(buttons['add'])
def add_handler(self, event, selector):
return '$.ZTFY.form.add(this.form);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
def updateActions(self):
super(BaseDialogAddForm, self).updateActions()
if 'dialog_cancel' in self.actions:
self.actions['dialog_cancel'].addClass('button-cancel')
elif 'cancel' in self.actions:
self.actions['cancel'].addClass('button-cancel')
@ajax.handler
def ajaxCreate(self):
# Create resources through AJAX request
# JSON results have to be included in a textarea to handle JQuery.Form plugin file uploads
writer = getUtility(IJSONWriter)
self.updateWidgets()
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return writer.write(self.getAjaxErrors())
self.createAndAdd(data)
if self.parent_interface is not None:
parent = getParent(self.context, self.parent_interface)
if parent is not None:
notify(ObjectModifiedEvent(parent))
else:
parent = None
return self.getOutput(writer, parent)
def getOutput(self, writer, parent):
if self.parent_view is not None:
view = self.parent_view(parent, self.request)
view.update()
return '<textarea>%s</textarea>' % writer.write({'output': u"<!-- OK -->\n" + view.output()})
else:
return writer.write({'output': self.changes_output})
class DialogAddForm(BaseBackView, BaseDialogAddForm):
"""Base back-office add form"""
def update(self):
BaseBackView.update(self)
BaseDialogAddForm.update(self)
#
# Edit forms
#
class BaseEditForm(form.EditForm, GroupsBasedForm):
"""Custom EditForm"""
implements(IForm, IBaseForm)
buttons = button.Buttons(IEditFormButtons)
autocomplete = 'on'
display_hints_on_widgets = False
cssClass = 'form edit'
formErrorsMessage = _('There were some errors.')
successMessage = _('Data successfully updated.')
noChangesMessage = _('No changes were applied.')
callbacks = {}
def __init__(self, context, request):
form.EditForm.__init__(self, context, request)
GroupsBasedForm.__init__(self)
def update(self):
jquery_tipsy.need()
jquery_progressbar.need()
super(BaseEditForm, self).update()
self.getForms()
[subform.update() for subform in self.subforms]
[tabform.update() for tabform in self.tabforms]
def updateWidgets(self):
super(BaseEditForm, self).updateWidgets()
self.getForms()
[subform.updateWidgets() for subform in self.subforms]
[tabform.updateWidgets() for tabform in self.tabforms]
@property
def status_class(self):
if self.errors:
return 'status error'
elif self.status == self.successMessage:
return 'status success'
elif self.status:
return 'status warning'
else:
return 'status'
def createSubForms(self):
return []
def createTabForms(self):
return []
def getForms(self, with_self=True):
if not hasattr(self, 'subforms'):
self.subforms = [form for form in self.createSubForms()
if form is not None]
if not hasattr(self, 'tabforms'):
tabforms = self.tabforms = [form for form in self.createTabForms()
if form is not None]
if tabforms:
jquery_tools.need()
if with_self:
return [self, ] + self.subforms + self.tabforms
else:
return self.subforms + self.tabforms
def getWidgetCallback(self, widget):
return self.callbacks.get(widget)
@button.handler(buttons['submit'])
def submit(self, action):
super(BaseEditForm, self).handleApply(self, action)
@button.handler(buttons['reset'])
def reset(self, action):
self.request.response.redirect(self.request.getURL())
def updateActions(self):
super(BaseEditForm, self).updateActions()
if 'reset' in self.actions:
self.actions['reset'].addClass('button-cancel')
elif 'cancel' in self.actions:
self.actions['cancel'].addClass('button-cancel')
def applyChanges(self, data):
content = self.getContent()
changes = self.updateContent(content, data)
# ``changes`` is a dictionary; if empty, there were no changes
if changes:
# Construct change-descriptions for the object-modified event
descriptions = []
for interface, names in changes.items():
descriptions.append(Attributes(interface, *names))
# Send out a detailed object-modified event
notify(ObjectModifiedEvent(content, *descriptions))
return changes
def updateContent(self, content, data):
changes = form.applyChanges(self, content, data)
self.getForms()
for subform in self.subforms:
if ICustomUpdateSubForm.providedBy(subform):
changes.update(ICustomUpdateSubForm(subform).updateContent(content, data) or {})
else:
changes.update(form.applyChanges(subform, content, data))
for tabform in self.tabforms:
if ICustomUpdateSubForm.providedBy(tabform):
changes.update(ICustomUpdateSubForm(tabform).updateContent(content, data) or {})
else:
changes.update(form.applyChanges(tabform, content, data))
return changes
@property
def errors(self):
result = []
for subform in self.getForms():
result.extend(subform.widgets.errors)
return result
class EditForm(BaseBackView, BaseEditForm):
"""Edit form"""
def update(self):
BaseBackView.update(self)
BaseEditForm.update(self)
class EditSubForm(subform.EditSubForm):
"""Custom EditSubForm
Actually no custom code..."""
tabLabel = None
callbacks = {}
def getWidgetCallback(self, widget):
return self.callbacks.get(widget)
class BaseDialogEditForm(AjaxForm, BaseEditForm):
"""Base dialog simple edit form"""
implements(IDialog)
buttons = button.Buttons(IDialogEditFormButtons)
prefix = 'edit_dialog.'
layout = None
parent_interface = IContainer
parent_view = None
handle_upload = False
changes_output = u'OK'
nochange_output = u'NONE'
resources = ()
@property
def title(self):
result = None
adapter = queryMultiAdapter((self.context, self.request, self), IDialogTitle)
if adapter is not None:
result = adapter.getTitle()
if result is None:
i18n = II18n(self.context, None)
if i18n is not None:
result = II18n(self.context).queryAttribute('title', request=self.request)
if result is None:
dc = IZopeDublinCore(self.context, None)
if dc is not None:
result = dc.title
if not result:
result = '{{ %s }}' % getName(self.context)
return result
@jsaction.handler(buttons['dialog_submit'])
def submit_handler(self, event, selector):
return '''$.ZTFY.form.edit(this.form);'''
@jsaction.handler(buttons['dialog_cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
def updateActions(self):
super(BaseDialogEditForm, self).updateActions()
if 'dialog_cancel' in self.actions:
self.actions['dialog_cancel'].addClass('button-cancel')
@ajax.handler
def ajaxEdit(self):
writer = getUtility(IJSONWriter)
self.updateWidgets()
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return writer.write(self.getAjaxErrors())
changes = self.applyChanges(data)
parent = None
if changes and (self.parent_interface is not None):
parent = getParent(self.context, self.parent_interface)
if parent is not None:
notify(ObjectModifiedEvent(parent))
return self.getOutput(writer, parent, changes)
def getOutput(self, writer, parent, changes=()):
if self.parent_view is not None:
view = self.parent_view(parent, self.request)
view.update()
return '<textarea>%s</textarea>' % writer.write({'output': u"<!-- OK -->\n" + view.output()})
else:
status = changes and self.changes_output or self.nochange_output
return writer.write({'output': status})
class DialogEditForm(BaseBackView, BaseDialogEditForm):
"""Base back-office edit form"""
def update(self):
BaseBackView.update(self)
BaseDialogEditForm.update(self)
#
# Display forms
#
class BaseDisplayForm(form.DisplayForm, GroupsBasedForm):
"""Custom DisplayForm"""
implements(IForm, IBaseForm)
autocomplete = 'on'
display_hints_on_widgets = False
cssClass = 'form display'
callbacks = {}
def __init__(self, context, request):
form.DisplayForm.__init__(self, context, request)
GroupsBasedForm.__init__(self)
@property
def name(self):
"""See interfaces.IInputForm"""
return self.prefix.strip('.')
@property
def id(self):
return self.name.replace('.', '-')
def update(self):
super(BaseDisplayForm, self).update()
self.getForms()
[subform.update() for subform in self.subforms]
[tabform.update() for tabform in self.tabforms]
def updateWidgets(self):
super(BaseDisplayForm, self).updateWidgets()
self.getForms()
[subform.updateWidgets() for subform in self.subforms]
[tabform.updateWidgets() for tabform in self.tabforms]
@property
def status_class(self):
if self.errors:
return 'status error'
elif self.status == self.successMessage:
return 'status success'
elif self.status:
return 'status warning'
else:
return 'status'
def createSubForms(self):
return []
def createTabForms(self):
return []
def getForms(self, with_self=True):
if not hasattr(self, 'subforms'):
self.subforms = [form for form in self.createSubForms()
if form is not None]
if not hasattr(self, 'tabforms'):
tabforms = self.tabforms = [form for form in self.createTabForms()
if form is not None]
if tabforms:
jquery_tools.need()
if with_self:
return [self, ] + self.subforms + self.tabforms
else:
return self.subforms + self.tabforms
def getWidgetCallback(self, widget):
return self.callbacks.get(widget)
@property
def errors(self):
result = []
for subform in self.getForms():
result.extend(subform.widgets.errors)
return result
class DisplayForm(BaseBackView, BaseDisplayForm):
"""Display form"""
def update(self):
BaseBackView.update(self)
BaseDisplayForm.update(self)
class DisplaySubForm(form.DisplayForm):
"""Custom display sub-form"""
implements(IForm, ISubForm, IHandlerForm)
autocomplete = 'on'
display_hints_on_widgets = False
cssClass = 'form display'
tabLabel = None
mode = DISPLAY_MODE
def __init__(self, context, request, parentForm):
self.context = context
self.request = request
self.parentForm = self.__parent__ = parentForm
class BaseDialogDisplayForm(AjaxForm, BaseDisplayForm):
"""Custom AJAX display dialog base class"""
implements(IDialog, IButtonForm)
buttons = button.Buttons(IDialogDisplayFormButtons)
resources = ()
@property
def title(self):
result = None
i18n = II18n(self.context, None)
if i18n is not None:
result = II18n(self.context).queryAttribute('title', request=self.request)
if result is None:
dc = IZopeDublinCore(self.context, None)
if dc is not None:
result = dc.title
if not result:
result = '{{ %s }}' % getName(self.context)
return result
def update(self):
super(BaseDialogDisplayForm, self).update()
self.updateActions()
def updateActions(self):
self.actions = getMultiAdapter((self, self.request, self.getContent()),
IActions)
self.actions.update()
if 'dialog_close' in self.actions:
self.actions['dialog_close'].addClass('button-cancel')
@jsaction.handler(buttons['dialog_close'])
def close_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
class DialogDisplayForm(BaseBackView, BaseDialogDisplayForm):
"""Default back-office display form"""
def update(self):
BaseBackView.update(self)
BaseDialogDisplayForm.update(self) | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/form.py | form.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from hurry.query.interfaces import IQuery
from z3c.language.switch.interfaces import II18n
from zope.intid.interfaces import IIntIds
# import local interfaces
from ztfy.base.interfaces import IBaseContent
from ztfy.base.interfaces.container import IOrderedContainer
from ztfy.skin.interfaces import IDefaultView, IContainedDefaultView
from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer
# import Zope3 packages
from z3c.jsonrpc.publisher import MethodPublisher
from zope.component import adapts, getUtility
from zope.interface import implements, Interface
from zope.traversing.browser import absoluteURL
# import local packages
from ztfy.utils.catalog.index import Text
class BaseContentDefaultViewAdapter(object):
"""Default front-office URL adapter"""
adapts(IBaseContent, IZTFYBrowserLayer, Interface)
implements(IDefaultView)
viewname = ''
def __init__(self, context, request, view):
self.context = context
self.request = request
self.view = view
def getAbsoluteURL(self):
return absoluteURL(self.context, self.request)
class BaseContentDefaultBackViewAdapter(object):
"""Default back-office URL adapter"""
adapts(IBaseContent, IZTFYBackLayer, Interface)
implements(IDefaultView)
viewname = '@@properties.html'
def __init__(self, context, request, view):
self.context = context
self.request = request
self.view = view
def getAbsoluteURL(self):
return '%s/%s' % (absoluteURL(self.context, self.request), self.viewname)
class BaseContainedDefaultBackViewAdapter(object):
"""Default container back-office URL adapter"""
adapts(IOrderedContainer, IZTFYBackLayer, Interface)
implements(IContainedDefaultView)
viewname = '@@contents.html'
def __init__(self, context, request, view):
self.context = context
self.request = request
self.view = view
def getAbsoluteURL(self):
return '%s/%s' % (absoluteURL(self.context, self.request), self.viewname)
class BaseContentSearchView(MethodPublisher):
"""Base content XML-RPC search view"""
def searchByTitle(self, query):
if not query:
return []
query_util = getUtility(IQuery)
intids = getUtility(IIntIds)
result = []
for obj in query_util.searchResults(Text(('Catalog', 'title'),
{'query': query + '*',
'ranking': True})):
result.append({'value': str(intids.register(obj)),
'caption': II18n(obj).queryAttribute('title')})
return result | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/content.py | content.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import IWidget, IFieldWidget, IMultiWidget, ITextWidget, IFormLayer, NO_VALUE
from z3c.language.switch.interfaces import II18n
from zope.interface.common.idatetime import ITZInfo
from zope.intid.interfaces import IIntIds
from zope.schema.interfaces import IField, IDatetime
# import local interfaces
from ztfy.skin.interfaces import IDateWidget, IDatetimeWidget, IFixedWidthTextAreaWidget
from ztfy.skin.layer import IZTFYBrowserLayer
from ztfy.utils.schema import IDatesRangeField, IColorField, ITextLineListField
# import Zope3 packages
from z3c.form.browser.text import TextWidget
from z3c.form.browser.textarea import TextAreaWidget
from z3c.form.browser.widget import HTMLFormElement
from z3c.form.converter import DatetimeDataConverter as BaseDatetimeDataConverter, SequenceDataConverter, FormatterValidationError
from z3c.form.widget import FieldWidget, Widget
from zope.component import adapter, adapts, getUtility
from zope.i18n import translate
from zope.i18n.format import DateTimeParseError
from zope.interface import implementer, implements, implementsOnly
from zope.schema import Bool, TextLine
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.jqueryui import jquery_datetime, jquery_colorpicker, jquery_multiselect
from ztfy.skin import ztfy_skin_base
from ztfy.skin import _
#
# Date and DateTime widgets
#
class DateWidget(TextWidget):
"""Date input widget"""
implementsOnly(IDateWidget)
@property
def pattern(self):
result = self.request.locale.dates.getFormatter('date', 'short').getPattern()
return result.replace('d', '%d') \
.replace('dd', '%d') \
.replace('%d%d', '%d') \
.replace('MM', '%m') \
.replace('M', '%m') \
.replace('yy', '%y')
def render(self):
result = super(DateWidget, self).render()
if result:
ztfy_skin_base.need()
jquery_datetime.need()
return result
@adapter(IField, IFormLayer)
@implementer(IFieldWidget)
def DateFieldWidget(field, request):
"""IFieldWidget factory for DateField"""
return FieldWidget(field, DateWidget(request))
class DatetimeWidget(TextWidget):
"""Datetime input widget"""
implementsOnly(IDatetimeWidget)
@property
def pattern(self):
result = self.request.locale.dates.getFormatter('dateTime', 'short').getPattern()
return result.replace('d', '%d') \
.replace('dd', '%d') \
.replace('%d%d', '%d') \
.replace('MM', '%m') \
.replace('M', '%m') \
.replace('yy', '%y') \
.replace('HH', '%H') \
.replace('h', '%H') \
.replace('mm', '%M') \
.replace('a', '%p')
def render(self):
result = super(DatetimeWidget, self).render()
if result:
ztfy_skin_base.need()
jquery_datetime.need()
return result
@adapter(IField, IFormLayer)
@implementer(IFieldWidget)
def DatetimeFieldWidget(field, request):
"""IFieldWidget factory for DatetimeField"""
return FieldWidget(field, DatetimeWidget(request))
class DatetimeDataConverter(BaseDatetimeDataConverter):
adapts(IDatetime, IDatetimeWidget)
def toFieldValue(self, value):
value = super(DatetimeDataConverter, self).toFieldValue(value)
if value and not value.tzinfo:
tz = ITZInfo(self.widget.request)
value = tz.localize(value)
return value
#
# Dates range widget
#
class IDatesRangeWidget(IMultiWidget):
"""Dates range widget interface"""
class DatesRangeDataConverter(SequenceDataConverter):
"""Dates range data converter"""
adapts(IDatesRangeField, IDatesRangeWidget)
def toWidgetValue(self, value):
if value is self.field.missing_value:
return u'', u''
locale = self.widget.request.locale
formatter = locale.dates.getFormatter('date', 'short')
return (formatter.format(value[0]) if value[0] else None,
formatter.format(value[1]) if value[1] else None)
def toFieldValue(self, value):
if not value:
return self.field.missing_value
try:
locale = self.widget.request.locale
formatter = locale.dates.getFormatter('date', 'short')
pattern_parts = formatter.getPattern().split('/')
if 'yy' in pattern_parts:
pattern_year_index = pattern_parts.index('yy')
else:
pattern_year_index = -1
result = []
for index in range(2):
if not value[index]:
result.append(None)
else:
if pattern_year_index >= 0:
value = list(value)
value_parts = value[index].split('/')
if len(value_parts[pattern_year_index]) == 4:
value_parts[pattern_year_index] = value_parts[pattern_year_index][2:]
value[index] = '/'.join(value_parts)
result.append(formatter.parse(value[index]))
return tuple(result)
except DateTimeParseError, err:
raise FormatterValidationError(err.args[0], value)
class DatesRangeWidget(HTMLFormElement, Widget):
"""Dates range widget"""
implements(IDatesRangeWidget)
@property
def pattern(self):
result = self.request.locale.dates.getFormatter('date', 'short').getPattern()
return result.replace('dd', '%d').replace('MM', '%m').replace('yy', '%y')
@property
def begin_id(self):
return '%s-begin' % self.id
@property
def begin_name(self):
return '%s.begin' % self.name
@property
def begin_date(self):
return (self.value[0] or '') if self.value else ''
@property
def end_id(self):
return '%s-end' % self.id
@property
def end_name(self):
return '%s.end' % self.name
@property
def end_date(self):
return (self.value[1] or '') if self.value else ''
def extract(self, default=NO_VALUE):
begin_date = self.request.get(self.begin_name)
end_date = self.request.get(self.end_name)
return (begin_date, end_date)
def render(self):
result = super(DatesRangeWidget, self).render()
if result:
ztfy_skin_base.need()
jquery_datetime.need()
return result
@adapter(IDatesRangeField, IFormLayer)
@implementer(IFieldWidget)
def DatesRangeFieldWidgetFactory(field, request):
"""IDatesRangeField widget factory"""
return FieldWidget(field, DatesRangeWidget(request))
#
# Color widget
#
class IColorWidget(ITextWidget):
"""Color widget interface"""
class ColorWidget(TextWidget):
"""Color widget"""
implementsOnly(IColorWidget)
def render(self):
result = super(ColorWidget, self).render()
if result:
ztfy_skin_base.need()
jquery_colorpicker.need()
return result
@adapter(IColorField, IFormLayer)
@implementer(IFieldWidget)
def ColorFieldWidgetFactory(field, request):
"""IColorField widget factory"""
return FieldWidget(field, ColorWidget(request))
#
# Textline list widget
#
class ITextLineListWidget(ITextWidget):
"""TextLineList widget interface"""
backspace_removes_last = Bool(title=_("Backspace key removes last value?"),
required=True,
default=True)
class TextLineListDataConverter(SequenceDataConverter):
"""TextLineList field data converter"""
adapts(ITextLineListField, IWidget)
def toWidgetValue(self, value):
if value is self.field.missing_value:
return u''
return '|'.join(value)
def toFieldValue(self, value):
if not value:
return self.field.missing_value
return value.split('|')
class TextLineListWidget(TextWidget):
"""TextLineList field widget"""
implementsOnly(ITextLineListWidget)
backspace_removes_last = FieldProperty(ITextLineListWidget['backspace_removes_last'])
def render(self):
result = super(TextLineListWidget, self).render()
if result:
ztfy_skin_base.need()
return result
@adapter(ITextLineListField, IFormLayer)
@implementer(IFieldWidget)
def TextLineListFieldWidgetFactory(field, request):
return FieldWidget(field, TextLineListWidget(request))
#
# Fixed width text area widget
#
class FixedWidthTextAreaWidget(TextAreaWidget):
"""Custom fixed width text area widget"""
implementsOnly(IFixedWidthTextAreaWidget)
@adapter(IField, IZTFYBrowserLayer)
@implementer(IFieldWidget)
def FixedWidthTextAreaFieldWidget(field, request):
"""IFixedWidthTextAreaWidget factory"""
return FieldWidget(field, FixedWidthTextAreaWidget(request))
#
# Internal reference widget
#
class IInternalReferenceWidget(ITextWidget):
"""Interface reference widget interface"""
target_title = TextLine(title=_("Target title"),
readonly=True)
class InternalReferenceWidget(TextWidget):
"""Internal reference selection widget"""
implementsOnly(IInternalReferenceWidget)
def render(self):
jquery_multiselect.need()
return super(InternalReferenceWidget, self).render()
@property
def target_title(self):
if not self.value:
return u''
value = self.request.locale.numbers.getFormatter('decimal').parse(self.value)
intids = getUtility(IIntIds)
target = intids.queryObject(value)
if target is not None:
title = II18n(target).queryAttribute('title', request=self.request)
return translate(_('%s (OID: %d)'), context=self.request) % (title, value)
else:
return translate(_("< missing target >"), context=self.request)
@adapter(IField, IZTFYBrowserLayer)
@implementer(IFieldWidget)
def InternalReferenceFieldWidget(field, request):
"""IFieldWidget factory for InternalReferenceWidget"""
return FieldWidget(field, InternalReferenceWidget(request)) | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/widget.py | widget.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.language.switch.interfaces import II18n
from z3c.template.interfaces import IPageTemplate
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.base.interfaces.container import IOrderedContainer
from ztfy.skin.interfaces import IContainedDefaultView, IDefaultView
from ztfy.skin.interfaces.container import IOrderedContainerBaseView, IContainerAddFormMenuTarget, \
IIdColumn, INameColumn, ITitleColumn, IStatusColumn, IActionsColumn, \
IContainerTableViewTitleCell, IContainerTableViewStatusCell, \
IContainerTableViewActionsCell, IOrderedContainerSorterColumn, IContainerBaseView
# import Zope3 packages
from z3c.formjs import ajax
from z3c.table.batch import BatchProvider
from z3c.table.column import Column, FormatterColumn, GetAttrColumn
from z3c.table.table import Table
from z3c.template.template import getViewTemplate, getPageTemplate
from zope.i18n import translate
from zope.component import getMultiAdapter, queryMultiAdapter
from zope.interface import implements
from zope.traversing.api import getName
# import local packages
from ztfy.jqueryui import jquery_ui_css, jquery_jsonrpc, jquery_ui_base, jquery_tipsy
from ztfy.skin.menu import MenuItem
from ztfy.skin.page import BaseBackView, TemplateBasedPage
from ztfy.utils.timezone import tztime
from ztfy.skin import _
class ContainerContentsViewMenu(MenuItem):
"""Container contents menu"""
title = _("Contents")
class OrderedContainerSorterColumn(Column):
implements(IOrderedContainerSorterColumn)
header = u''
weight = 1
cssClasses = {'th': 'sorter',
'td': 'sorter'}
def renderCell(self, item):
return '<img class="handler" src="/--static--/ztfy.skin/img/sort.png" />'
class IdColumn(Column):
implements(IIdColumn)
weight = 0
cssClasses = {'th': 'hidden',
'td': 'hidden id'}
def renderHeadCell(self):
return u''
def renderCell(self, item):
return getName(item)
class NameColumn(IdColumn):
implements(INameColumn)
cssClasses = {}
def renderCell(self, item):
result = getName(item)
adapter = queryMultiAdapter((item, self.request, self.table), IContainedDefaultView)
if adapter is None:
adapter = queryMultiAdapter((item, self.request, self.table), IDefaultView)
if adapter is not None:
result = '<a href="%s">%s</a>' % (adapter.getAbsoluteURL(), result)
return result
class TitleColumn(Column):
implements(ITitleColumn)
header = _("Title")
weight = 10
cssClasses = {'td': 'title'}
def renderCell(self, item):
adapter = queryMultiAdapter((item, self.request, self.table, self), IContainerTableViewTitleCell)
prefix = (adapter is not None) and adapter.prefix or ''
before = (adapter is not None) and adapter.before or ''
after = (adapter is not None) and adapter.after or ''
suffix = (adapter is not None) and adapter.suffix or ''
i18n = II18n(item, None)
if i18n is not None:
title = i18n.queryAttribute('title', request=self.request)
else:
title = IZopeDublinCore(item).title
result = "%s%s%s" % (before, title or '{{ ' + getName(item) + ' }}', after)
adapter = queryMultiAdapter((item, self.request, self.table), IContainedDefaultView)
if adapter is None:
adapter = queryMultiAdapter((item, self.request, self.table), IDefaultView)
if adapter is not None:
url = adapter.getAbsoluteURL()
if url:
result = '<a href="%s">%s</a>' % (url, result)
return '%s%s%s' % (prefix, result, suffix)
class CreatedColumn(FormatterColumn, GetAttrColumn):
"""Created date column."""
header = _('Created')
weight = 100
cssClasses = {'td': 'date'}
formatterCategory = u'dateTime'
formatterLength = u'short'
attrName = 'created'
def renderCell(self, item):
formatter = self.getFormatter()
dc = IZopeDublinCore(item, None)
value = self.getValue(dc)
if value:
value = formatter.format(tztime(value))
return value
class ModifiedColumn(FormatterColumn, GetAttrColumn):
"""Created date column."""
header = _('Modified')
weight = 110
cssClasses = {'td': 'date'}
formatterCategory = u'dateTime'
formatterLength = u'short'
attrName = 'modified'
def renderCell(self, item):
formatter = self.getFormatter()
dc = IZopeDublinCore(item, None)
value = self.getValue(dc)
if value:
value = formatter.format(tztime(value))
return value
class StatusColumn(Column):
implements(IStatusColumn)
header = _("Status")
weight = 200
cssClasses = {'td': 'status'}
def renderCell(self, item):
adapter = queryMultiAdapter((item, self.request, self.table, self), IContainerTableViewStatusCell)
if adapter is not None:
return adapter.content
return ''
class ActionsColumn(Column):
implements(IActionsColumn)
header = _("Actions")
weight = 210
cssClasses = {'td': 'actions'}
def renderCell(self, item):
adapter = queryMultiAdapter((item, self.request, self.table, self), IContainerTableViewActionsCell)
if adapter is not None:
return adapter.content
return ''
class ContainerBatchProvider(BatchProvider):
"""Custom container batch provider"""
batchSpacer = u'<a>...</a>'
class BaseContainerBaseView(TemplateBasedPage, Table):
"""Container-like base view"""
implements(IContainerBaseView)
legend = _("Container's content")
empty_message = _("This container is empty")
data_attributes = {}
batchSize = 25
startBatchingAt = 25
output = getViewTemplate()
def __init__(self, context, request):
super(BaseContainerBaseView, self).__init__(context, request)
Table.__init__(self, context, request)
@property
def title(self):
result = None
i18n = II18n(self.context, None)
if i18n is not None:
result = II18n(self.context).queryAttribute('title', request=self.request)
if result is None:
dc = IZopeDublinCore(self.context, None)
if dc is not None:
result = dc.title
if not result:
result = '{{ %s }}' % getName(self.context)
return result
def getCSSClass(self, element, cssClass=None):
result = super(BaseContainerBaseView, self).getCSSClass(element, cssClass)
result += ' ' + ' '.join(('data-%s=%s' % (k, v) for k, v in self.data_attributes.items()))
return result
@property
def empty_value(self):
return translate(self.empty_message, context=self.request)
def update(self):
TemplateBasedPage.update(self)
Table.update(self)
jquery_tipsy.need()
jquery_ui_css.need()
jquery_jsonrpc.need()
class ContainerBaseView(BaseBackView, BaseContainerBaseView):
"""Back-office container base view"""
def update(self):
BaseBackView.update(self)
BaseContainerBaseView.update(self)
class OrderedContainerBaseView(ajax.AJAXRequestHandler, ContainerBaseView):
"""Order container base view"""
implements(IOrderedContainerBaseView, IContainerAddFormMenuTarget)
sortOn = None
interface = None
container_interface = IOrderedContainer
batchSize = 10000
startBatchingAt = 10000
cssClasses = {'table': 'orderable'}
def update(self):
super(OrderedContainerBaseView, self).update()
jquery_ui_base.need()
jquery_jsonrpc.need()
@ajax.handler
def ajaxUpdateOrder(self, *args, **kw):
self.updateOrder()
def updateOrder(self, context=None):
ids = self.request.form.get('ids', [])
if ids:
if context is None:
context = self.context
container = self.container_interface(context)
container.updateOrder(ids, self.interface)
class InnerContainerBaseView(Table):
"""A container table displayed inside another view"""
template = getPageTemplate()
data_attributes = {}
def __init__(self, view, request):
Table.__init__(self, view.context, request)
self.__parent__ = view
self.__name__ = u''
def getCSSClass(self, element, cssClass=None):
result = super(InnerContainerBaseView, self).getCSSClass(element, cssClass)
result += ' ' + ' '.join(('data-%s=%s' % (k, v) for k, v in self.data_attributes.items()))
return result
def render(self):
if self.template is None:
template = getMultiAdapter((self, self.request), IPageTemplate)
return template(self)
return self.template() | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/container.py | container.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.publisher.interfaces.browser import IBrowserSkinType
# import local interfaces
from ztfy.skin.interfaces import IDialogMenu, ISkinnable
# import Zope3 packages
from z3c.menu.simple.menu import ContextMenuItem
from zope.component import queryUtility
from zope.interface import implements
# import local packages
from ztfy.utils.traversing import getParent
from ztfy.skin import _
class MenuItem(ContextMenuItem):
"""Default menu item"""
@property
def css(self):
css = getattr(self, 'cssClass', '')
if self.selected:
css += ' ' + self.activeCSS
else:
css += ' ' + self.inActiveCSS
if self.title.strip().startswith('::'):
css += ' submenu'
return css
@property
def selected(self):
return self.request.getURL().endswith('/' + self.viewURL)
class SkinTargetMenuItem(MenuItem):
"""Customized menu item for specific skin targets"""
skin = None
def render(self):
skinnable = getParent(self.context, ISkinnable)
if skinnable is None:
return u''
skin_name = skinnable.getSkin()
if skin_name is None:
return u''
skin = queryUtility(IBrowserSkinType, skin_name)
if (skin is self.skin) or skin.extends(self.skin):
return super(SkinTargetMenuItem, self).render()
else:
return u''
class JsMenuItem(MenuItem):
"""Customized menu item with javascript link URL"""
@property
def url(self):
return self.viewURL
class SkinTargetJsMenuItem(JsMenuItem):
"""Customized JS menu item for specific skin targets"""
skin = None
def render(self):
skinnable = getParent(self.context, ISkinnable)
if skinnable is None:
return u''
skin_name = skinnable.getSkin()
if skin_name is None:
return u''
skin = queryUtility(IBrowserSkinType, skin_name)
if (skin is self.skin) or skin.extends(self.skin):
return super(SkinTargetJsMenuItem, self).render()
else:
return u''
class DialogMenuItem(JsMenuItem):
"""Customized javascript menu item used to open a dialog"""
implements(IDialogMenu)
target = None
def render(self):
result = super(DialogMenuItem, self).render()
if result and (self.target is not None):
for resource in self.target.resources:
resource.need()
return result
class SkinTargetDialogMenuItem(SkinTargetJsMenuItem):
"""Customized JS dialog menu item for specific skin targets"""
implements(IDialogMenu)
target = None
def render(self):
result = super(SkinTargetJsMenuItem, self).render()
if result and (self.target is not None):
for resource in self.target.resources:
resource.need()
return result
class PropertiesMenuItem(MenuItem):
"""Default properties menu item"""
title = _("Properties") | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/menu.py | menu.py |
__docformat__ = "restructuredtext"
# import standard packages
import copy
# import Zope3 interfaces
from hurry.query.interfaces import IQuery
from z3c.json.interfaces import IJSONWriter
from z3c.language.switch.interfaces import II18n
from zope.dublincore.interfaces import IZopeDublinCore
from zope.intid.interfaces import IIntIds
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserSkinType
from zope.traversing.interfaces import TraversalError
# import local interfaces
from ztfy.skin.interfaces import ISkinnable, IPresentationTarget, IPresentationForm, IBaseIndexView
# import Zope3 packages
from z3c.form import field
from z3c.formjs import ajax
from z3c.template.template import getLayoutTemplate
from zope.component import queryUtility, queryMultiAdapter, getUtility
from zope.interface import implements
from zope.publisher.skinnable import applySkin
from zope.traversing import namespace
# import local packages
from ztfy.skin.form import DialogEditForm
from ztfy.skin.page import TemplateBasedPage
from ztfy.utils.catalog.index import Text
from ztfy.utils.traversing import getParent
#
# Presentation management classes
#
class PresentationNamespaceTraverser(namespace.view):
"""++presentation++ namespace"""
def getSkin(self):
skinnable = getParent(self.context, ISkinnable)
if skinnable is None:
return None
skin_name = skinnable.getSkin()
if skin_name is None:
return None
return queryUtility(IBrowserSkinType, skin_name)
def traverse(self, name, ignored):
skin = self.getSkin()
if skin is None:
raise TraversalError('++presentation++')
fake = copy.copy(self.request)
applySkin(fake, skin)
adapter = queryMultiAdapter((self.context, fake), IPresentationTarget)
if adapter is not None:
try:
return adapter.target_interface(self.context)
except:
pass
raise TraversalError('++presentation++')
class BasePresentationEditForm(DialogEditForm):
"""Presentation edit form"""
implements(IPresentationForm)
layout = getLayoutTemplate()
def __init__(self, context, request):
super(BasePresentationEditForm, self).__init__(context, request)
skin = self.getSkin()
if skin is None:
raise NotFound(self.context, self.name, self.request)
fake = copy.copy(self.request)
applySkin(fake, skin)
adapter = queryMultiAdapter((self.context, fake, self), IPresentationTarget)
if adapter is None:
adapter = queryMultiAdapter((self.context, fake), IPresentationTarget)
if adapter is None:
raise NotFound(self.context, self.name, self.request)
self.interface = adapter.target_interface
def getContent(self):
return self.interface(self.context)
@property
def fields(self):
return field.Fields(self.interface)
def getSkin(self):
skinnable = getParent(self.context, ISkinnable)
if skinnable is None:
return None
skin_name = skinnable.getSkin()
if skin_name is None:
return None
return queryUtility(IBrowserSkinType, skin_name)
@ajax.handler
def ajaxEdit(self):
return super(BasePresentationEditForm, self).ajaxEdit(self)
@ajax.handler
def ajaxSearch(self):
writer = getUtility(IJSONWriter)
title = self.request.form.get('title')
if not title:
return writer.write(None)
query = getUtility(IQuery)
intids = getUtility(IIntIds)
result = []
for obj in query.searchResults(Text(('Catalog', 'title'),
{'query': title + '*',
'ranking': True})):
i18n = II18n(obj, None)
result.append({'oid': intids.register(obj),
'title': i18n.queryAttribute('title') if i18n is not None else IZopeDublinCore(obj).title})
return writer.write(result)
#
# Base index view
#
class BaseIndexView(TemplateBasedPage):
"""Base index view"""
implements(IBaseIndexView)
presentation = None
def update(self):
super(BaseIndexView, self).update()
adapter = queryMultiAdapter((self.context, self.request, self), IPresentationTarget)
if adapter is None:
adapter = queryMultiAdapter((self.context, self.request), IPresentationTarget)
if adapter is not None:
interface = adapter.target_interface
self.presentation = interface(self.context) | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/presentation.py | presentation.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import ITextWidget, ITextAreaWidget
# import local interfaces
from z3c.form import button
from z3c.formjs import jsaction
# most interfaces have moved to ZTFY.baseskin package; please use them directly...
# following imports are kept only for compatibility reasons
from ztfy.baseskin.interfaces import *
from ztfy.baseskin.interfaces.form import *
# import Zope3 packages
from zope.interface import Attribute, Interface
from zope.schema import Bool, TextLine
# import local packages
from ztfy.skin import _
#
# Default forms buttons interfaces
#
class IAddFormButtons(Interface):
"""Default add form buttons"""
add = button.Button(name='add', title=_("Add"), condition=checkSubmitButton)
class IDialogAddFormButtons(Interface):
"""Default dialog add form buttons"""
add = jsaction.JSButton(name='add', title=_("Add"))
cancel = jsaction.JSButton(name='cancel', title=_("Cancel"))
class IDialogDisplayFormButtons(Interface):
"""Default dialog display form buttons"""
dialog_close = jsaction.JSButton(name='close', title=_("Close"))
class IEditFormButtons(Interface):
"""Default edit form buttons"""
submit = button.Button(name='submit', title=_("Submit"), condition=checkSubmitButton)
reset = button.Button(name='reset', title=_("Reset"))
class IDialogEditFormButtons(Interface):
"""Default dialog edit form buttons"""
dialog_submit = jsaction.JSButton(name='dialog_submit', title=_("Submit"), condition=checkSubmitButton)
dialog_cancel = jsaction.JSButton(name='dialog_cancel', title=_("Cancel"))
#
# Custom widgets interfaces
#
class IDateWidget(ITextWidget):
"""Marker interface for date widget"""
class IDatetimeWidget(ITextWidget):
"""Marker interface for datetime widget"""
class IFixedWidthTextAreaWidget(ITextAreaWidget):
"""Marker interface for fixed width text area widget"""
#
# Default views interfaces
#
class IPropertiesMenuTarget(Interface):
"""Marker interface for properties menus"""
class IDialogMenu(Interface):
"""Dialog access menu interface"""
target = Attribute(_("Target dialog class"))
#
# Breadcrumb interfaces
#
class IBreadcrumbInfo(Interface):
"""Get custom breadcrumb info of a given context"""
visible = Bool(title=_("Visible ?"),
required=True,
default=True)
title = TextLine(title=_("Title"),
required=True)
path = TextLine(title=_("Path"),
required=False)
#
# Back-office custom properties marker interface
#
class ICustomBackOfficeInfoTarget(Interface):
"""Marker interface for custom back-office properties"""
back_interface = Attribute(_("Back-office properties custom interface")) | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/interfaces/__init__.py | __init__.py |
(function(a){String.prototype.startsWith=function(d){var b=this.length;var c=d.length;if(b<c){return false}return(this.substr(0,c)===d)};String.prototype.endsWith=function(d){var b=this.length;var c=d.length;if(b<c){return false}return(this.substr(b-c)===d)};if(!Array.prototype.indexOf){Array.prototype.indexOf=function(c){var b=this.length;var d=Number(arguments[1])||0;d=(d<0)?Math.ceil(d):Math.floor(d);if(d<0){d+=b}for(;d<b;d++){if(d in this&&this[d]===c){return d}}return -1}}a.expr[":"].econtains=function(e,c,d,b){return(e.textContent||e.innerText||a(e).text()||"").toLowerCase()===d[3].toLowerCase()};a.expr[":"].withtext=function(e,c,d,b){return(e.textContent||e.innerText||a(e).text()||"")===d[3]};if(a.scrollbarWidth===undefined){a.scrollbarWidth=function(){var c,d,b;if(b===undefined){c=a('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body");d=c.children();b=d.innerWidth()-d.height(99).innerWidth();c.remove()}return b}}a.UTF8={encode:function(d){d=d.replace(/\r\n/g,"\n");var b="";for(var f=0;f<d.length;f++){var e=d.charCodeAt(f);if(e<128){b+=String.fromCharCode(e)}else{if((e>127)&&(e<2048)){b+=String.fromCharCode((e>>6)|192);b+=String.fromCharCode((e&63)|128)}else{b+=String.fromCharCode((e>>12)|224);b+=String.fromCharCode(((e>>6)&63)|128);b+=String.fromCharCode((e&63)|128)}}}return b},decode:function(b){var e="";var g=0;var h=0,f=0,d=0;while(g<b.length){h=b.charCodeAt(g);if(h<128){e+=String.fromCharCode(h);g++}else{if((h>191)&&(h<224)){f=b.charCodeAt(g+1);e+=String.fromCharCode(((h&31)<<6)|(f&63));g+=2}else{f=b.charCodeAt(g+1);d=b.charCodeAt(g+2);e+=String.fromCharCode(((h&15)<<12)|((f&63)<<6)|(d&63));g+=3}}}return e}};if(a.ZTFY===undefined){a.ZTFY={}}a.ZTFY.getScript=function(c,e,d){var b={dataType:"script",url:c,success:e,error:a.ZTFY.ajax.error,cache:d===undefined?true:d};return a.ajax(b)};a.ZTFY.getFunctionByName=function(f,c){var e=f.split(".");var d=e.pop();c=(c===undefined||c===null)?window:c;for(var b=0;b<e.length;b++){c=c[e[b]]}return c[d]};a.ZTFY.executeFunctionByName=function(e,c){var d=a.ZTFY.getFunctionByName(e,c);var b=Array.prototype.slice.call(arguments,2);return d.apply(c,b)};a.ZTFY.getQueryVar=function(d,e){if(d.indexOf("?")<0){return false}if(!d.endsWith("&")){d+="&"}var b=new RegExp(".*?[&\\?]"+e+"=(.*?)&.*");var c=d.replace(b,"$1");return c===d?false:c};a.ZTFY.rgb2hex=function(b){return"#"+a.map(b.match(/\b(\d+)\b/g),function(c){return("0"+parseInt(c).toString(16)).slice(-2)}).join("")};a.ZTFY.skin={stopEvent:function(b){if(!b){b=window.event}if(b){if(b.stopPropagation){b.stopPropagation();b.preventDefault()}else{b.cancelBubble=true;b.returnValue=false}}},getCSS:function(b,h,g){var e=function(i){return i.replace(/{[^{}]*}/g,function(j){return a.ZTFY.getFunctionByName(j.substr(1,j.length-2))})};var d=a("HEAD");var c=a('link[data-ztfy-id="'+h+'"]',d);if(c.length===0){var f=e(b);if(g){f+="?_="+new Date().getTime()}a("<link />").attr({rel:"stylesheet",type:"text/css",href:f,"data-ztfy-id":h}).appendTo(d)}},switcher:function(b){a(b).toggle()}};a.ZTFY.ajax={check:function(b,c,d){if(typeof(b)==="undefined"){a.ZTFY.getScript(c,d)}else{d()}},getAddr:function(d){var b=d||a("HTML HEAD BASE").attr("href")||window.location.href;var c=b.replace(/\+\+skin\+\+\w+\//,"");return c.substr(0,c.lastIndexOf("/")+1)},post:function(e,g,c,b,f){var h;if(e.startsWith(window.location.protocol)){h=e}else{h=a.ZTFY.ajax.getAddr()+e}var d={url:h,type:"post",cache:false,data:a.param(g,true),dataType:f||"json",success:c,error:b||a.ZTFY.ajax.error};a.ajax(d)},submit:function(f,d,g,c,b,e){a.ZTFY.ajax.check(a.progressBar,"/--static--/ztfy.jqueryui/js/jquery-progressbar.min.js",function(){var j;var i=a.progressBar.submit(f);if(d.startsWith(window.location.protocol)){j=d}else{j=a.ZTFY.ajax.getAddr()+d}if(i&&(j.indexOf("X-Progress-ID")<0)){j+="?X-Progress-ID="+i}var h={url:j,type:"post",iframe:true,data:g,dataType:e||"json",success:c,error:b||a.ZTFY.ajax.error};a(f).ajaxSubmit(h)})},error:function(d,b,c){if(!c){return}a.ZTFY.ajax.check(jAlert,"/--static--/ztfy.jqueryui/js/jquery-alerts.min.js",function(){jAlert(b+":\n\n"+c,a.ZTFY.I18n.ERROR_OCCURED,null)})}};a.ZTFY.json={getAddr:function(b){return a.ZTFY.ajax.getAddr(b)},getQuery:function(e,h,g,f){var b;if((g===null)||(g==="")||(g==="null")){g=undefined}else{if(typeof(g)==="string"){g=a.ZTFY.getFunctionByName(g)}}var d=a.isFunction(g);var c={url:a.ZTFY.json.getAddr(),type:"POST",method:h,async:d,params:{query:e},complete:g,success:function(j,i){b=j.result},error:function(k,i,j){jAlert(k.responseText,"Error !",window.location.reload)}};c.params=a.extend(c.params,f||{});a.jsonRpc(c);return b},post:function(h,f,c,b,e){var g=a.ZTFY.json.getAddr();if(e){g+="/"+e}var d={url:g,type:"post",cache:false,method:h,params:f,success:c,error:b};a.jsonRpc(d)}};a.ZTFY.loader={div:null,start:function(d){d.empty();var b=a('<div class="loader"></div>').appendTo(d);var c=a('<img class="loading" src="/--static--/ztfy.skin/img/loading.gif" />').appendTo(b);a.ZTFY.loader.div=b},stop:function(){if(a.ZTFY.loader.div!==null){a.ZTFY.loader.div.replaceWith("");a.ZTFY.loader.div=null}}};a.ZTFY.plugins={_registry:null,register:function(d,c,b){if(this._registry===null){this._registry=[]}this._registry.push([d,c,b])},callAndRegister:function(e,c,d,b){e.call(c,d,b);if(this._registry===null){this._registry=[]}this._registry.push([e,c,b])},call:function(f){var b=this._registry;if(b===null){return}for(var d in b){if(!a.isNumeric(d)){continue}var g=b[d][0];var e=b[d][1];var c=b[d][2];g.call(e,f,c)}},callCustomPlugins:function(b){a("[data-ztfy-plugin]",b).each(function(){var d=this;var c=a(this).data("ztfy-plugin").split(/\s+/);a(c).each(function(){var e=a.ZTFY.getFunctionByName(this);e.call(window,d)})})}};a.ZTFY.widgets={initTabs:function(b){if(typeof(a.fn.tabs)==="undefined"){return}a("DIV.form #tabforms UL.tabs",b).tabs("DIV.panes > DIV")},initDatatables:function(b){if(typeof(a.fn.dataTable)==="undefined"){return}a('[data-ztfy-widget="datatable"]',b).each(function(){var e=a(this);var d=e.data();var c={bJQueryUI:true,iDisplayLength:25,sPaginationType:"full_numbers",sDom:'fl<t<"F"p>',oLanguage:{sProcessing:a.ZTFY.I18n.DATATABLE_sProcessing,sSearch:a.ZTFY.I18n.DATATABLE_sSearch,sLengthMenu:a.ZTFY.I18n.DATATABLE_sLengthMenu,sInfo:a.ZTFY.I18n.DATATABLE_sInfo,sInfoEmpty:a.ZTFY.I18n.DATATABLE_sInfoEmpty,sInfoFiltered:a.ZTFY.I18n.DATATABLE_sInfoFiltered,sInfoPostFix:a.ZTFY.I18n.DATATABLE_sInfoPostFix,sLoadingRecords:a.ZTFY.I18n.DATATABLE_sLoadingRecords,sZeroRecords:a.ZTFY.I18n.DATATABLE_sZeroRecords,sEmptyTable:a.ZTFY.I18n.DATATABLE_sEmptyTable,oPaginate:{sFirst:a.ZTFY.I18n.DATATABLE_oPaginate_sFirst,sPrevious:a.ZTFY.I18n.DATATABLE_oPaginate_sPrevious,sNext:a.ZTFY.I18n.DATATABLE_oPaginate_sNext,sLast:a.ZTFY.I18n.DATATABLE_oPaginate_sLast},oAria:{sSortAscending:a.ZTFY.I18n.DATATABLE_oAria_sSortAscending,sSortDescending:a.ZTFY.I18n.DATATABLE_oAria_sSortDescending}}};a.extend(c,d.ztfyDatatableOptions||{});e.dataTable(c)})},initDates:function(b){if(typeof(a.fn.dynDateTime)==="undefined"){return}if(a.i18n_calendar===undefined){var c=a("html").attr("lang")||a("html").attr("xml:lang");a.i18n_calendar=c;if(c){if(c==="en"){a.ZTFY.getScript("/--static--/ztfy.jqueryui/js/lang/calendar-"+c+".min.js")}else{a.ZTFY.getScript("/--static--/ztfy.jqueryui/js/lang/calendar-"+c+"-utf8.js")}}}a('[data-ztfy-widget="datetime"]',b).each(function(){var d=a(this);d.dynDateTime({showsTime:d.data("datetime-showtime"),ifFormat:d.data("datetime-format"),button:d.data("datetime-button")})})},initMultiselect:function(b){if(typeof(a.fn.multiselect)==="undefined"){return}a('[data-ztfy-widget="multiselect"]',b).each(function(){var e=a(this);var d=e.data();var c=d.multiselectReferences||"{}";if(typeof(c)==="string"){c=a.parseJSON(c.replace(/'/g,'"'))}e.multiselect({readonly:d.multiselectReadonly,input_class:d.multiselectClass,separator:d.multiselectSeparator||",",min_query_length:d.multiselectMinLength||3,input_references:c,on_search:function(i){if(d.multiselectSearchCallback){var j=a.ZTFY.getFunctionByName(d.multiselectSearchCallback);var g=(d.multiselectSearchArgs||"").split(";");if(g.length>2){var f=g.length-1;var h=g[f];if(h){g[f]=a.parseJSON(h.replace(/'/g,'"'))}}g.splice(0,0,i);return j.apply(window,g)}else{return""}},on_search_timeout:d.multiselectSearchTimeout||300,max_complete_results:d.multiselectMaxResults||20,enable_new_options:d.multiselectEnableNew,complex_search:d.multiselectComplexSearch,max_selection_length:d.multiselectMaxSelectionLength,backspace_removes_last:d.multiselectBackspaceRemovesLast===false?false:true})})},initColors:function(b){if(typeof(a.fn.ColorPicker)==="undefined"){return}a('[data-ztfy-widget="color-selector"]',b).each(function(){var c=a(this);var d=a("INPUT",c);a("DIV",c).css("background-color","#"+d.val());if(c.data("readonly")===undefined){c.ColorPicker({color:"#"+d.val(),onShow:function(e){a(e).fadeIn(500);return false},onHide:function(e){a(e).fadeOut(500);return false},onChange:function(e,h,f){var g=a(this).data().colorpicker.el;a("INPUT",g).val(h);a("DIV",g).css("background-color","#"+h)},onSubmit:function(){a(this).ColorPickerHide()}})}})},initHints:function(b){a.ZTFY.ajax.check(a.fn.tipsy,"/--static--/ztfy.jqueryui/js/jquery-tipsy.min.js",function(){var c=a("DIV.form",a(b));if(c.data("ztfy-inputs-hints")===true){a('INPUT[type!="hidden"]:not(.nohint), SELECT, TEXTAREA',c).each(function(d,e){a(e).tipsy({html:true,fallback:a("A.hint",a(e).closest("DIV.row")).attr("title"),gravity:"nw"});a("A.hint:not(.nohide)",a(e).closest("DIV.row")).hide()})}a(".hint",c).tipsy({gravity:function(d){return a(this).data("ztfy-hint-gravity")||"sw"},offset:function(d){return a(this).data("ztfy-hint-offset")||0}})})},initTinyMCE:function(b){if(typeof(tinyMCE)==="undefined"){return}a('[data-ztfy-widget="TinyMCE"]',b).each(function(){var f=a(this).data();var d={script_url:"/--static--/ztfy.jqueryui/js/tiny_mce/tiny_mce.js"};var e=f.tinymceOptions.split(";");for(var c in e){if(!a.isNumeric(c)){continue}var g=e[c].split("=");switch(g[1]){case"true":d[g[0]]=true;break;case"false":d[g[0]]=false;break;default:d[g[0]]=g[1]}}if(!tinyMCE.settings){tinyMCE.init(d)}});a('[data-ztfy-widget="TinyMCE"]',b).click(function(c){if(c instanceof a.Event){c=c.srcElement||c.target}if(tinyMCE.activeEditor){tinyMCE.execCommand("mceRemoveControl",false,tinyMCE.activeEditor.id)}tinyMCE.execCommand("mceAddControl",false,a(c).attr("id"))})},initFancybox:function(b){if(typeof(a.fn.fancybox)==="undefined"){return}a('[data-ztfy-widget="fancybox"]',b).each(function(){var e=a(this).data();var d=a(e.fancyboxSelector||"IMG",this);if(e.fancyboxParent!==undefined){d=d.parents(e.fancyboxParent)}var c={type:e.fancyboxType||"image",titleShow:e.fancyboxShowTitle,titlePosition:e.fancyboxTitlePosition||"outside",hideOnContentClick:e.fancyboxClickHide===undefined?true:e.fancyboxClickHide,overlayOpacity:e.fancyboxOverlayOpacity||0.5,padding:e.fancyboxPadding||10,margin:e.fancyboxMargin||20,transitionIn:e.fancyboxTransitionIn||"elastic",transitionOut:e.fancyboxTransitionOut||"elastic"};if(e.fancyboxTitleFormat){c.titleFormat=a.ZTFY.getFunctionByName(e.fancyboxTitleFormat)}else{c.titleFormat=function(j,k,g,i){if(j&&j.length){var f='<span id="fancybox-title-over"><strong>'+j+"</strong>";var h=a(k[g]).data("fancybox-description");if(h){f+="<br />"+h}f+="</span>";return f}else{return null}}}if(e.fancyboxComplete){c.onComplete=a.ZTFY.getFunctionByName(e.fancyboxComplete)}else{c.onComplete=function(){a("#fancybox-wrap").hover(function(){a("#fancybox-title").slideDown("slow")},function(){a("#fancybox-title").slideUp("slow")})}}d.fancybox(c)})}};a.ZTFY.dialog={switchGroup:function(b,c){b=a(b);c=a('DIV[id="group_'+c+'"]');if(b.attr("type")==="checkbox"){if(b.is(":checked")){c.show()}else{c.hide()}}else{if(b.attr("src").endsWith("pl.png")){c.show();b.attr("src","/--static--/ztfy.skin/img/mi.png")}else{c.hide();b.attr("src","/--static--/ztfy.skin/img/pl.png")}}b.parents("FIELDSET:first").toggleClass("switched")},options:{expose:{maskId:"mask",color:"#444",opacity:0.6,zIndex:1000},top:"5%",api:true,oneInstance:false,closeOnClick:false,onBeforeLoad:function(){var c=this.getOverlay();a.ZTFY.loader.start(c);var b=a.ZTFY.dialog.dialogs[a.ZTFY.dialog.getCount()-1];c.load(b.src,b.callback);if(a.browser.msie&&(a.browser.version<"7")){a("select").css("visibility","hidden")}},onClose:function(){a.ZTFY.dialog.onClose();if(a.browser.msie&&(a.browser.version<"7")){a("select").css("visibility","hidden")}}},dialogs:[],getCount:function(){return a.ZTFY.dialog.dialogs.length},getCurrent:function(){var b=a.ZTFY.dialog.getCount();return a("#dialog_"+b)},open:function(g,e,i){if(typeof(a.fn.overlay)==="undefined"){jAlert(a.ZTFY.I18n.MISSING_OVERLAY,a.ZTFY.I18n.ERROR_OCCURED);return}g=g.replace(/ /g,"%20");if(a.isFunction(e)){i=e;e=null}e=typeof(window.event)!=="undefined"?window.event:e;a.ZTFY.skin.stopEvent(e);if(!a.ZTFY.dialog.dialogs){a.ZTFY.dialog.dialogs=[]}var c=a.ZTFY.dialog.getCount()+1;var h="dialog_"+c;var b={};var f={maskId:"mask_"+h,color:"#444",opacity:0.6,zIndex:a.ZTFY.dialog.options.expose.zIndex+c};a.extend(b,a.ZTFY.dialog.options,{expose:f});a.ZTFY.dialog.dialogs.push({src:g,callback:i||a.ZTFY.dialog.openCallback,body:a('<div class="overlay"></div>').attr("id",h).css("z-index",f.zIndex+1).appendTo(a("body"))});var d=a("#"+h);d.empty().overlay(b).load();if(a.fn.draggable){d.draggable({handle:'DIV[id="osx-container"], H1',containment:"window"})}},openCallback:function(b,e,m){if(e==="error"){a(this).html(b)}else{var h=a.ZTFY.dialog.getCurrent();a.ZTFY.plugins.call(h);a.ZTFY.plugins.callCustomPlugins(h);var g=a("DIV.viewspace",h);var i=a("H1",h);var j=a("DIV.legend",h);var d=a("DIV.form > FIELDSET > DIV.help",h);var c=a("DIV.actions",h);if(g.length>0){var k=a(window).height()-i.height()-j.height()-d.height()-c.height()-180;var f=g.position();var l=a.scrollbarWidth();g.css("max-height",k);if(g.get(0).scrollHeight>k){a("<div></div>").addClass("scrollmarker").addClass("top").css("width",g.width()-l/2).css("top",f.top).hide().appendTo(g);a("<div></div>").addClass("scrollmarker").addClass("bottom").css("width",g.width()-l/2).css("top",f.top+k-10).appendTo(g);g.scroll(function(q){var r=q.srcElement||q.target;var p=a(r);var n=a("DIV.scrollmarker.top",p);var t=p.scrollTop();if(t>0){n.show()}else{n.hide()}var o=a("DIV.scrollmarker.bottom",p);var u=parseInt(p.css("max-height"));var s=u+t-10;if(s>=r.scrollHeight-20){o.hide()}else{o.show()}})}g.scroll(function(n){a("DIV.jquery-multiselect-autocomplete",g).each(function(q,r){var p=a("BODY").scrollTop();var s=a(r).closest(".widget");var t=s.offset();var o=s.height();a(r).css("top",t.top+o-p)})});a(g).on("keydown","INPUT",function(n){if(n.which===13){n.preventDefault();if(a(n.target).data("ztfy-widget")!=="multiselect"){a("INPUT[type=button]:first",c).click()}}});a("A.close",h).tipsy({gravity:"e"})}}},close:function(){a("#dialog_"+a.ZTFY.dialog.getCount()).overlay().close()},onClose:function(){if(typeof(tinyMCE)!=="undefined"){if(tinyMCE.activeEditor){tinyMCE.execCommand("mceRemoveControl",false,tinyMCE.activeEditor.id)}}var b=a.ZTFY.dialog.getCount();var c="dialog_"+b;a("DIV.tipsy").remove();a("#"+c).remove();a("#mask_"+c).remove();a.ZTFY.dialog.dialogs.pop()}};a.ZTFY.form={check:function(b){a.ZTFY.ajax.check(a.fn.ajaxSubmit,"/--static--/ztfy.jqueryui/js/jquery-form.min.js",b)},hideStatus:function(){a("DIV.form DIV.status").animate({opacity:0,height:0,"margin-top":0,"margin-bottom":0,"padding-top":0,"padding-bottom":0},2000,function(){a(this).remove()})},getSubmitCallbacks:function(e){var c=a(e);var d=[];var b=c.data("ztfy-submit-callback");if(b){d.push([c,b])}a("[data-ztfy-submit-callback]",a(e)).each(function(){var f=a(this);d.push([f,f.data("ztfy-submit-callback")])});return d},checkSubmitCallbacks:function(c){var g=a.ZTFY.form.getSubmitCallbacks(c);if(!g.length){return true}var d=[];var e=true;for(var f in g){if(!a.isNumeric(f)){continue}var i=g[f];var h=i[0];var b=i[1];var j=a.ZTFY.executeFunctionByName(b,undefined,c,h);if((j!==undefined)&&(j!==true)){if(j===false){e=false}else{if(typeof(j)==="string"){d.push(j)}else{if(j.length&&(j.length>0)){d=d.concat(j)}}}}}if(d.length>1){jAlert(a.ZTFY.I18n.ERRORS_OCCURED+"\n"+d.join("\n"),a.ZTFY.I18n.WARNING);return false}else{if(d.length===1){jAlert(a.ZTFY.I18n.ERROR_OCCURED+"\n"+d.join("\n"),a.ZTFY.I18n.WARNING);return false}else{return e}}},submit:function(c){var b=a(this);if(b.data("submitted")||!a.ZTFY.form.checkSubmitCallbacks(this)){a.ZTFY.skin.stopEvent(c);return false}if(!b.data("ztfy-disable-submit-flag")){b.data("submitted",true)}if(a("IFRAME.progress",b).length>0){a.ZTFY.ajax.check(a.progressBar,"/--static--/ztfy.jqueryui/js/jquery-progressbar.min.js",function(){if(a.progressBar){a.progressBar.submit(b)}})}},reset:function(b){b.reset();a("input:first",b).focus()},showErrors:function(o){var k=a.ZTFY.dialog.getCurrent();var h=a("DIV.status",k).outerHeight(true);a("DIV.status",k).remove();a("DIV.error",k).each(function(i,p){a("DIV.widget",a(p)).detach().insertAfter(a(p));a(p).remove()});var d=a("<div></div>").addClass("status error");a("<div></div>").addClass("summary").text(o.errors.status).appendTo(d);var m=a("<ul></ul>").appendTo(d);if(o.errors.errors){for(var f in o.errors.errors){if(!a.isNumeric(f)){continue}var l=o.errors.errors[f];if(l.widget){a("<li></li>").text(l.widget+" : "+l.message).appendTo(m);var g=a('[id="'+l.id+'"]',k).parents("DIV.widget");var n=a(g).parents("DIV.row");var c=a("<div></div>").addClass("error").append(a("<div></div>").addClass("error").text(l.message)).insertBefore(g);g.detach().appendTo(c)}else{a("<li></li>").text(l.message).appendTo(m)}}}var j=a("DIV.viewspace",k);d.insertBefore(j);var b=d.outerHeight(true);if(b!==h){j.css("max-height",parseInt(j.css("max-height"))-b+h);var e=a("DIV.scrollmarker.top",k);e.css("top",parseInt(e.css("top"))-h+b)}a("FORM",k).data("submitted",false)},add:function(e,d,g,f,c){var b=a(e);if(b.data("submitted")||!a.ZTFY.form.checkSubmitCallbacks(e)){return false}f=f||{};b.data("submitted",true);a.ZTFY.form.check(function(){if(typeof(tinyMCE)!=="undefined"){tinyMCE.triggerSave()}if(d){f.parent=d}var i=b.attr("action").replace(/\?X-Progress-ID=.*/,"");var h="/@@ajax/"+(c||"ajaxCreate");a(a.ZTFY.form).data("add_action",i);a.ZTFY.ajax.submit(e,i+h,f,g||a.ZTFY.form._addCallback,null,"json")});return false},_addCallback:function(j,f){if(f==="success"){if(typeof(j)==="string"){j=a.parseJSON(j)}var d=j.output;var i,h;switch(d){case"ERRORS":a.ZTFY.form.showErrors(j);break;case"OK":a.ZTFY.dialog.close();a("DIV.status").remove();i=j.message||a.ZTFY.I18n.DATA_UPDATED;a("DIV.required-info").after('<div class="status success"><div class="summary">'+i+"</div></div>");break;case"NONE":a.ZTFY.dialog.close();a("DIV.status").remove();i=j.message||a.ZTFY.I18n.NO_UPDATE;a("DIV.required-info").after('<div class="status warning"><div class="summary">'+i+"</div></div>");break;case"MESSAGE":jAlert(j.message,j.title||a.ZTFY.I18n.INFO);h=a.ZTFY.dialog.getCurrent();a("FORM",h).data("submitted",false);break;case"PASS":a.ZTFY.dialog.close();a("DIV.status").remove();break;case"RELOAD":var g=new Date().getTime();if(window.location.href.indexOf("?")>=0){var b;var e=a.ZTFY.getQueryVar(window.location.href,"_");if(e===false){b=window.location.href+"&_="+g}else{b=window.location.href.replace(e,g)}window.location.href=b}else{window.location.href=window.location.href+"?_="+g}break;case"REDIRECT":window.location.href=j.target;break;case"CALLBACK":if(j.close_dialog){a.ZTFY.dialog.close()}a.ZTFY.executeFunctionByName(j.callback,undefined,j.options);break;default:if(d&&d.startsWith("<!-- OK -->")){a.ZTFY.dialog.close();a("DIV.form").replaceWith(d)}else{h=a.ZTFY.dialog.getCurrent();a("DIV.dialog",h).replaceWith(d);var c=a("FORM",h);c.attr("action",a(a.ZTFY.form).data("add_action"));a('INPUT[id="'+c.attr("id")+'-buttons-add"]',h).bind("click",function(k){a.ZTFY.form.add(this.form,j.parent)});a('INPUT[id="'+c.attr("id")+'-buttons-cancel"]',h).bind("click",function(k){a.ZTFY.dialog.close()});a("#tabforms UL.tabs",h).tabs(a(h).selector+" DIV.panes > DIV")}}if(d!=="ERRORS"){setTimeout(a.ZTFY.form.hideStatus,2000)}}},edit:function(d,f,g,e,c){var b=a(d);if(b.data("submitted")||!a.ZTFY.form.checkSubmitCallbacks(d)){return false}b.data("submitted",true);a.ZTFY.form.check(function(){if(typeof(tinyMCE)!=="undefined"){tinyMCE.triggerSave()}var i=b.attr("action").replace(/\?X-Progress-ID=.*/,"");var h="/@@ajax/"+(c||"ajaxEdit");a(a.ZTFY.form).data("edit_action",i);a.ZTFY.ajax.submit(d,i+h,e||{},g||a.ZTFY.form._editCallback,null,"json")});return false},_editCallback:function(k,g,e){if(g==="success"){if(typeof(k)==="string"){k=a.parseJSON(k)}var d=k.output;var j,i;switch(d){case"ERRORS":a.ZTFY.form.showErrors(k);break;case"OK":a.ZTFY.dialog.close();a("DIV.status").remove();j=k.message||a.ZTFY.I18n.DATA_UPDATED;a("DIV.required-info").after('<div class="status success"><div class="summary">'+j+"</div></div>");break;case"NONE":a.ZTFY.dialog.close();a("DIV.status").remove();j=k.message||a.ZTFY.I18n.NO_UPDATE;a("DIV.required-info").after('<div class="status warning"><div class="summary">'+j+"</div></div>");break;case"MESSAGE":jAlert(k.message,k.title||a.ZTFY.I18n.INFO);i=a.ZTFY.dialog.getCurrent();a("FORM",i).data("submitted",false);break;case"PASS":a.ZTFY.dialog.close();a("DIV.status").remove();break;case"RELOAD":var h=new Date().getTime();if(window.location.href.indexOf("?")>=0){var b;var f=a.ZTFY.getQueryVar(window.location.href,"_");if(f===false){b=window.location.href+"&_="+h}else{b=window.location.href.replace(f,h)}window.location.href=b}else{window.location.href=window.location.href+"?_="+h}break;case"REDIRECT":window.location.href=k.target;break;case"CALLBACK":if(k.close_dialog){a.ZTFY.dialog.close()}a.ZTFY.executeFunctionByName(k.callback,undefined,k.options);break;default:if(d&&d.startsWith("<!-- OK -->")){a.ZTFY.dialog.close();a("DIV.form").replaceWith(d)}else{i=a.ZTFY.dialog.getCurrent();a("DIV.dialog",i).replaceWith(d);var c=a("FORM",i);c.attr("action",a(a.ZTFY.form).data("edit_action"));a('INPUT[id="'+c.attr("id")+'-buttons-dialog_submit"]',i).bind("click",function(l){a.ZTFY.form.edit(this.form)});a('INPUT[id="'+c.attr("id")+'-buttons-dialog_cancel"]',i).bind("click",function(l){a.ZTFY.dialog.close()});a("#tabforms UL.tabs",i).tabs(a(i).selector+" DIV.panes > DIV")}}if(d!=="ERRORS"){setTimeout(a.ZTFY.form.hideStatus,2000)}}},remove:function(c,d,e,b){jConfirm(a.ZTFY.I18n.CONFIRM_REMOVE,a.ZTFY.I18n.CONFIRM,function(j){if(j){var h={id:c};var g=a(d).closest("DIV.dialog").data("ztfy-url");var i=g||window.location.href;a.ZTFY.form.ajax_source=d;var f="/@@ajax/"+(b||"ajaxRemove");a.ZTFY.ajax.post(i+f,h,e||a.ZTFY.form._removeCallback,null,"text")}})},_removeCallback:function(b,c){if((c==="success")&&(b==="OK")){a(a.ZTFY.form.ajax_source).parents("TR").remove()}},update:function(c,d,b){a.ZTFY.form.check(function(){if(typeof(tinyMCE)!=="undefined"){tinyMCE.triggerSave()}var f=a(c).formToArray(true);var e="/@@ajax/"+(b||"ajaxUpdate");a.ZTFY.ajax.post(a(c).attr("action")+e,f,d||a.ZTFY.form._updateCallback,null,"text")});return false},_updateCallback:function(b,c){if((c==="success")&&(b==="OK")){a("DIV.status").remove();a("LEGEND").after('<div class="status success"><div class="summary">'+a.ZTFY.I18n.DATA_UPDATED+"</div></div>")}}};a.ZTFY.container={remove:function(c,d,e){var b={_source:d,url:a.ZTFY.json.getAddr(e),type:"POST",method:"remove",params:{id:c},success:function(g,f){a(this._source).parents("BODY").css("cursor","default");a(this._source).parents("TR").remove()},error:function(h,f,g){jAlert(h.responseText,a.ZTFY.I18n.ERROR_OCCURED,window.location.reload)}};jConfirm(a.ZTFY.I18n.CONFIRM_REMOVE,a.ZTFY.I18n.CONFIRM,function(f){if(f){a(d).parents("BODY").css("cursor","wait");a.jsonRpc(b)}})}};a.ZTFY.sortable={options:{handle:"IMG.handler",axis:"y",containment:"parent",placeholder:"sorting-holder",stop:function(c,e){var b=[];a("TD.id",this).each(function(f){b[b.length]=a(this).text()});var d={ids:b};if(b.length>1){a.ZTFY.ajax.post(window.location.href+"/@@ajax/ajaxUpdateOrder",d,null,function(h,f,g){jAlert(h.responseText,a.ZTFY.I18n.ERROR_OCCURED,window.location.reload)})}}},init:function(b){if(typeof(a.fn.sortable)==="undefined"){return}a("TABLE.orderable TBODY",b).sortable(a.ZTFY.sortable.options)}};a.ZTFY.treeview={init:function(b){if(typeof(a.fn.treeTable)==="undefined"){return}a("TABLE.treeview",b).each(function(){var d=a(this);var c=d.data();d.treeTable({treeColumn:c.treeColumn===undefined?1:c.treeColumn,initialState:c.initialState===undefined?"expanded":c.initialState})})},changeParent:function(c,e){var g=a(e.draggable.parents("TR"));if(g.appendBranchTo(this)){var d=g.attr("id").substr("node-".length);var f=a(this).attr("id").substr("node-".length);var b={url:a.ZTFY.json.getAddr(),type:"POST",method:"changeParent",params:{source:parseInt(d),target:parseInt(f)},error:function(j,h,i){jAlert(j.responseText,a.ZTFY.I18n.ERROR_OCCURED,window.location.reload)}};a.jsonRpc(b)}}};a.ZTFY.reference={activate:function(b){a("INPUT[name="+b+"]").attr("readonly","").val("").focus();a("INPUT[name="+b+"]").prev().val("")},keyPressed:function(b){if(b.which===13){a.ZTFY.reference.search(this);return false}},search:function(d){var b;var c={url:a.ZTFY.ajax.getAddr(),type:"POST",method:"searchByTitle",async:false,params:{query:d},success:function(f,e){b=f.result},error:function(g,e,f){jAlert(g.responseText,"Error !",window.location.reload)}};a.jsonRpc(c);return b},select:function(b,d){var c=a.ZTFY.reference.source;a(c).prev().val(b);a(c).val(d+" (OID: "+b+")").attr("readonly","readonly");a("#selector").overlay().close();a("#selector").remove();return false}};a.ZTFY.extras={initDownloader:function(b,d,c){a.ZTFY.form.check(function(){var g=a(b).attr("action");var e=g+d;var f=a('IFRAME[name="downloadFrame"]');if(f.length===0){f=a("<iframe></iframe>").hide().attr("name","downloadFrame").appendTo(a("BODY"))}a(b).attr("action",e).attr("target","downloadFrame").ajaxSubmit({data:c,iframe:true,iframeTarget:f});a(b).attr("action",g).attr("target",null);a.ZTFY.dialog.close();a("BODY").css("cursor","auto")})},initContainerSize:function(b){a(b).css("min-height",a(a(b).data("container-sizer")).height())},initCaptcha:function(c){if(c instanceof a.Event){c=c.srcElement||c.target}var d=a(c).data();var b=new Date();var e="@@captcha.jpeg?id="+d.captchaId+unescape("%26")+b.getTime();a(c).attr("src",e).off("click").on("click",a.ZTFY.extras.initCaptcha)}};a.ZTFY.I18n={INFO:"Information",WARNING:"!! WARNING !!",ERROR_OCCURED:"An error occured!",ERRORS_OCCURED:"Some errors occured!",BAD_LOGIN_TITLE:"Bad login!",BAD_LOGIN_MESSAGE:"Your anthentication credentials didn't allow you to open a session; please check your credentials or contact administrator.",CONFIRM:"Confirm",CONFIRM_REMOVE:"Removing this content can't be undone. Do you confirm?",NO_UPDATE:"No changes were applied.",DATA_UPDATED:"Data successfully updated.",MISSING_OVERLAY:"JQuery « overlay » plug-in is required; please include JQuery-tools resources in your page!",DATATABLE_sProcessing:"Processing...",DATATABLE_sSearch:"Search:",DATATABLE_sLengthMenu:"Show _MENU_ entries",DATATABLE_sInfo:"Showing _START_ to _END_ of _TOTAL_ entrie",DATATABLE_sInfoEmpty:"Showing 0 to 0 of 0 entries",DATATABLE_sInfoFiltered:"(filtered from _MAX_ total entries))",DATATABLE_sInfoPostFix:"",DATATABLE_sLoadingRecords:"Loading...",DATATABLE_sZeroRecords:"No matching records found",DATATABLE_sEmptyTable:"No data available in table",DATATABLE_oPaginate_sFirst:"First",DATATABLE_oPaginate_sPrevious:"Previous",DATATABLE_oPaginate_sNext:"Next",DATATABLE_oPaginate_sLast:"Last",DATATABLE_oAria_sSortAscending:": sort ascending",DATATABLE_oAria_sSortDescending:": sort descending"};a.ZTFY.initPage=function(b){a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initTabs,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initDatatables,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initDates,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initMultiselect,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initHints,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initColors,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initTinyMCE,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.widgets.initFancybox,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.sortable.init,window,b);a.ZTFY.plugins.callAndRegister(a.ZTFY.treeview.init,window,b);a.ZTFY.plugins.callCustomPlugins(b);a('A[rel="external"]').attr("target","_blank");a(b).on("submit","FORM",a.ZTFY.form.submit)};a(document).ready(function(){a(document).ajaxStart(function(){a("BODY").css("cursor","wait")});a(document).ajaxStop(function(){a("BODY").css("cursor","auto")});var b=a("BODY").hasClass("layout");if(b){a.ZTFY.initPage(document)}var c=a("HTML").attr("lang")||a("HTML").attr("xml:lang");if(c&&(c!=="en")){a.ZTFY.getScript("/--static--/ztfy.skin/js/i18n/"+c+".js",function(){if(!b){a.ZTFY.initPage(document)}})}else{if(!b){a.ZTFY.initPage(document)}}})})(jQuery); | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/resources/js/ztfy.skin.min.js | ztfy.skin.min.js |
(function($) {
'use strict';
/**
* String prototype extensions
*/
String.prototype.startsWith = function(str) {
var slen = this.length;
var dlen = str.length;
if (slen < dlen) {
return false;
}
return (this.substr(0,dlen) === str);
};
String.prototype.endsWith = function(str) {
var slen = this.length;
var dlen = str.length;
if (slen < dlen) {
return false;
}
return (this.substr(slen-dlen) === str);
};
/**
* Array prototype extensions
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
/**
* JQuery 'econtains' expression
* Case insensitive contains expression
*/
$.expr[":"].econtains = function(obj, index, meta, stack) {
return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() === meta[3].toLowerCase();
};
/**
* JQuery 'withtext' expression
* Case sensitive exact search expression
*/
$.expr[":"].withtext = function(obj, index, meta, stack) {
return (obj.textContent || obj.innerText || $(obj).text() || "") === meta[3];
};
/**
* JQuery 'scrollbarWidth' function
* Get width of vertical scrollbar
*/
if ($.scrollbarWidth === undefined) {
$.scrollbarWidth = function() {
var parent,
child,
width;
if (width === undefined) {
parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
child = parent.children();
width = child.innerWidth() - child.height(99).innerWidth();
parent.remove();
}
return width;
};
}
/**
* UTF-8 encoding class
* Mainly used by IE...
*/
$.UTF8 = {
// public method for url encoding
encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// public method for url decoding
decode : function (utftext) {
var string = "";
var i = 0;
var c = 0,
c2 = 0,
c3 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}; /** $.UTF8 */
/**
* ZTFY.skin extensions to JQuery
*/
if ($.ZTFY === undefined) {
$.ZTFY = {};
}
/**
* Get script using browser cache
*/
$.ZTFY.getScript = function(url, callback, use_cache) {
var options = {
dataType: 'script',
url: url,
success: callback,
error: $.ZTFY.ajax.error,
cache: use_cache === undefined ? true : use_cache
};
return $.ajax(options);
};
/**
* Get and execute a function given by name
* Small piece of code by Jason Bunting
*/
$.ZTFY.getFunctionByName = function(functionName, context) {
var namespaces = functionName.split(".");
var func = namespaces.pop();
context = (context === undefined || context === null) ? window : context;
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func];
};
$.ZTFY.executeFunctionByName = function(functionName, context /*, args */) {
var func = $.ZTFY.getFunctionByName(functionName, context);
var args = Array.prototype.slice.call(arguments, 2);
return func.apply(context, args);
};
/**
* Extract parameter value from given query string
*/
$.ZTFY.getQueryVar = function(src, varName) {
// Check src
if (src.indexOf('?') < 0) {
return false;
}
if (!src.endsWith('&')) {
src += '&';
}
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = src.replace(regex, "$1");
// If the string is the same, we didn't find a match - return false
return val === src ? false : val;
};
/**
* Color conversion function
*/
$.ZTFY.rgb2hex = function(color) {
return "#" + $.map(color.match(/\b(\d+)\b/g), function(digit) {
return ('0' + parseInt(digit).toString(16)).slice(-2);
}).join('');
};
/**
* Generic ZTFY functions
*/
$.ZTFY.skin = {
/**
* Events management
*/
stopEvent: function(event) {
if (!event) {
event = window.event;
}
if (event) {
if (event.stopPropagation) {
event.stopPropagation();
event.preventDefault();
} else {
event.cancelBubble = true;
event.returnValue = false;
}
}
},
getCSS: function(url, id, devmode) {
var getSource = function(url) {
return url.replace(/{[^{}]*}/g, function(match) {
return $.ZTFY.getFunctionByName(match.substr(1, match.length-2));
});
};
var head = $('HEAD');
var css = $('link[data-ztfy-id="' + id + '"]', head);
if (css.length === 0) {
var source = getSource(url);
if (devmode) {
source += '?_=' + new Date().getTime();
}
$('<link />').attr({rel: 'stylesheet',
type: 'text/css',
href: source,
'data-ztfy-id': id})
.appendTo(head);
}
},
switcher: function(div) {
$(div).toggle();
}
};
/**
* AJAX management
*/
$.ZTFY.ajax = {
check: function(checker, source, callback) {
if (typeof(checker) === 'undefined') {
$.ZTFY.getScript(source, callback);
} else {
callback();
}
},
getAddr: function(addr) {
var href = addr || $('HTML HEAD BASE').attr('href') || window.location.href;
var target = href.replace(/\+\+skin\+\+\w+\//, '');
return target.substr(0, target.lastIndexOf("/")+1);
},
post: function(url, data, onsuccess, onerror, datatype) {
var addr;
if (url.startsWith(window.location.protocol)) {
addr = url;
} else {
addr = $.ZTFY.ajax.getAddr() + url;
}
var options = {
url: addr,
type: 'post',
cache: false,
data: $.param(data, true), /* use traditional JQuery params decoding */
dataType: datatype || 'json',
success: onsuccess,
error: onerror || $.ZTFY.ajax.error
};
$.ajax(options);
},
submit: function(form, url, data, onsuccess, onerror, datatype) {
$.ZTFY.ajax.check($.progressBar, '/--static--/ztfy.jqueryui/js/jquery-progressbar.min.js', function() {
var addr;
var uuid = $.progressBar.submit(form);
if (url.startsWith(window.location.protocol)) {
addr = url;
} else {
addr = $.ZTFY.ajax.getAddr() + url;
}
if (uuid && (addr.indexOf('X-Progress-ID') < 0)) {
addr += "?X-Progress-ID=" + uuid;
}
var options = {
url: addr,
type: 'post',
iframe: true,
data: data,
dataType: datatype || 'json',
success: onsuccess,
error: onerror || $.ZTFY.ajax.error
};
$(form).ajaxSubmit(options);
});
},
error: function(request, status, error) {
if (!error) {
return;
}
$.ZTFY.ajax.check(jAlert, '/--static--/ztfy.jqueryui/js/jquery-alerts.min.js', function() {
jAlert(status + ':\n\n' + error, $.ZTFY.I18n.ERROR_OCCURED, null);
});
}
}; /** $.ZTFY.ajax */
/**
* JSON management
*/
$.ZTFY.json = {
getAddr: function(addr) {
return $.ZTFY.ajax.getAddr(addr);
},
getQuery: function(query, method, callback, params) {
var result;
if ((callback === null) || (callback === '') || (callback === 'null')) {
callback = undefined;
} else if (typeof(callback) === 'string') {
callback = $.ZTFY.getFunctionByName(callback);
}
var async = $.isFunction(callback);
var options = {
url: $.ZTFY.json.getAddr(),
type: 'POST',
method: method,
async: async,
params: {
query: query
},
complete: callback,
success: function(data, status) {
result = data.result;
},
error: function(request, status, error) {
jAlert(request.responseText, "Error !", window.location.reload);
}
};
options.params = $.extend(options.params, params || {});
$.jsonRpc(options);
return result;
},
post: function(method, params, onsuccess, onerror, base) {
var addr = $.ZTFY.json.getAddr();
if (base) {
addr += '/' + base;
}
var options = {
url: addr,
type: 'post',
cache: false,
method: method,
params: params,
success: onsuccess,
error: onerror
};
$.jsonRpc(options);
}
}; /** $.ZTFY.json */
/**
* Loading management
*/
$.ZTFY.loader = {
div: null,
start: function(parent) {
parent.empty();
var $div = $('<div class="loader"></div>').appendTo(parent);
var $img = $('<img class="loading" src="/--static--/ztfy.skin/img/loading.gif" />').appendTo($div);
$.ZTFY.loader.div = $div;
},
stop: function() {
if ($.ZTFY.loader.div !== null) {
$.ZTFY.loader.div.replaceWith('');
$.ZTFY.loader.div = null;
}
}
}; /** $.ZTFY.loader */
/**
* Plug-ins management
*
* Plug-ins are registered on page startup and re-applied automatically
* in each dialog.
* An entry point is also available for custom plug-ins not handled by
* default ZTFY package
*/
$.ZTFY.plugins = {
_registry: null,
register: function(callback, context, options) {
if (this._registry === null) {
this._registry = [];
}
this._registry.push([callback, context, options]);
},
callAndRegister: function(callback, context, parent, options) {
callback.call(context, parent, options);
if (this._registry === null) {
this._registry = [];
}
this._registry.push([callback, context, options]);
},
call: function(parent) {
var registry = this._registry;
if (registry === null) {
return;
}
for (var index in registry) {
if (!$.isNumeric(index)) { // IE indexOf !
continue;
}
var callback = registry[index][0];
var context = registry[index][1];
var options = registry[index][2];
callback.call(context, parent, options);
}
},
callCustomPlugins: function(parent) {
$('[data-ztfy-plugin]', parent).each(function() {
var element = this;
var plugins = $(this).data('ztfy-plugin').split(/\s+/);
$(plugins).each(function() {
var funct = $.ZTFY.getFunctionByName(this);
funct.call(window, element);
});
});
}
}; /** $.ZTFY.plugins */
/**
* Widgets management
*
* This is a small set of "standard" ZTFY widgets handled by custom packages
* but for which javascript code is defined into ZTFY.skin
*/
$.ZTFY.widgets = {
// Default tabs
initTabs: function(parent) {
if (typeof($.fn.tabs) === 'undefined') {
return;
}
$('DIV.form #tabforms UL.tabs', parent).tabs('DIV.panes > DIV');
},
// DataTables plug-in
initDatatables: function(parent) {
if (typeof($.fn.dataTable) === 'undefined') {
return;
}
$('[data-ztfy-widget="datatable"]', parent).each(function() {
var $this = $(this);
var data = $this.data();
var options = {
"bJQueryUI": true,
"iDisplayLength": 25,
"sPaginationType": "full_numbers",
"sDom": 'fl<t<"F"p>',
"oLanguage": {
"sProcessing": $.ZTFY.I18n.DATATABLE_sProcessing,
"sSearch": $.ZTFY.I18n.DATATABLE_sSearch,
"sLengthMenu": $.ZTFY.I18n.DATATABLE_sLengthMenu,
"sInfo": $.ZTFY.I18n.DATATABLE_sInfo,
"sInfoEmpty": $.ZTFY.I18n.DATATABLE_sInfoEmpty,
"sInfoFiltered": $.ZTFY.I18n.DATATABLE_sInfoFiltered,
"sInfoPostFix": $.ZTFY.I18n.DATATABLE_sInfoPostFix,
"sLoadingRecords": $.ZTFY.I18n.DATATABLE_sLoadingRecords,
"sZeroRecords": $.ZTFY.I18n.DATATABLE_sZeroRecords,
"sEmptyTable": $.ZTFY.I18n.DATATABLE_sEmptyTable,
"oPaginate": {
"sFirst": $.ZTFY.I18n.DATATABLE_oPaginate_sFirst,
"sPrevious": $.ZTFY.I18n.DATATABLE_oPaginate_sPrevious,
"sNext": $.ZTFY.I18n.DATATABLE_oPaginate_sNext,
"sLast": $.ZTFY.I18n.DATATABLE_oPaginate_sLast
},
"oAria": {
"sSortAscending": $.ZTFY.I18n.DATATABLE_oAria_sSortAscending,
"sSortDescending": $.ZTFY.I18n.DATATABLE_oAria_sSortDescending
}
}
};
$.extend(options, data.ztfyDatatableOptions || {});
$this.dataTable(options);
});
},
// Dates input plug-in
initDates: function(parent) {
if (typeof($.fn.dynDateTime) === 'undefined') {
return;
}
if ($.i18n_calendar === undefined) {
var lang = $('html').attr('lang') || $('html').attr('xml:lang');
$.i18n_calendar = lang;
if (lang) {
if (lang === 'en') {
$.ZTFY.getScript('/--static--/ztfy.jqueryui/js/lang/calendar-' + lang + '.min.js');
} else {
$.ZTFY.getScript('/--static--/ztfy.jqueryui/js/lang/calendar-' + lang + '-utf8.js');
}
}
}
$('[data-ztfy-widget="datetime"]', parent).each(function() {
var $this = $(this);
$this.dynDateTime({
showsTime: $this.data('datetime-showtime'),
ifFormat: $this.data('datetime-format'),
button: $this.data('datetime-button')
});
});
},
// Multi-select input plug-in
initMultiselect: function(parent) {
if (typeof($.fn.multiselect) === 'undefined') {
return;
}
$('[data-ztfy-widget="multiselect"]', parent).each(function() {
var $this = $(this);
var data = $this.data();
var references = data.multiselectReferences || '{}';
if (typeof(references) === 'string') {
references = $.parseJSON(references.replace(/'/g, '"'));
}
$this.multiselect({
readonly: data.multiselectReadonly,
input_class: data.multiselectClass,
separator: data.multiselectSeparator || ',',
min_query_length: data.multiselectMinLength || 3,
input_references: references,
on_search: function(query) {
if (data.multiselectSearchCallback) {
var callback = $.ZTFY.getFunctionByName(data.multiselectSearchCallback);
var args = (data.multiselectSearchArgs || '').split(';');
if (args.length > 2) {
var index = args.length - 1;
var value = args[index];
if (value) {
args[index] = $.parseJSON(value.replace(/'/g, '"'));
}
}
args.splice(0, 0, query);
return callback.apply(window, args);
} else {
return '';
}
},
on_search_timeout: data.multiselectSearchTimeout || 300,
max_complete_results: data.multiselectMaxResults || 20,
enable_new_options: data.multiselectEnableNew,
complex_search: data.multiselectComplexSearch,
max_selection_length: data.multiselectMaxSelectionLength,
backspace_removes_last: data.multiselectBackspaceRemovesLast === false ? false : true
});
});
},
// Color input plug-in
initColors: function(parent) {
if (typeof($.fn.ColorPicker) === 'undefined') {
return;
}
$('[data-ztfy-widget="color-selector"]', parent).each(function() {
var $this = $(this);
var $input = $('INPUT', $this);
$('DIV', $this).css('background-color', '#' + $input.val());
if ($this.data('readonly') === undefined) {
$this.ColorPicker({
color: '#' + $input.val(),
onShow: function(picker) {
$(picker).fadeIn(500);
return false;
},
onHide: function(picker) {
$(picker).fadeOut(500);
return false;
},
onChange: function(hsb, hex, rgb) {
var element = $(this).data().colorpicker.el;
$('INPUT', element).val(hex);
$('DIV', element).css('background-color', '#' + hex);
},
onSubmit: function() {
$(this).ColorPickerHide();
}
});
}
});
},
// Info hints plug-in
initHints: function(parent) {
$.ZTFY.ajax.check($.fn.tipsy, '/--static--/ztfy.jqueryui/js/jquery-tipsy.min.js', function() {
var $form = $('DIV.form', $(parent));
if ($form.data('ztfy-inputs-hints') === true) {
$('INPUT[type!="hidden"]:not(.nohint), SELECT, TEXTAREA', $form).each(function(index, item) {
$(item).tipsy({
html: true,
fallback: $('A.hint', $(item).closest('DIV.row')).attr('title'),
gravity: 'nw'
});
$('A.hint:not(.nohide)', $(item).closest('DIV.row')).hide();
});
}
$('.hint', $form).tipsy({
gravity: function(element) {
return $(this).data('ztfy-hint-gravity') || 'sw';
},
offset: function(element) {
return $(this).data('ztfy-hint-offset') || 0;
}
});
});
},
// TinyMCE HTML editor plug-in
initTinyMCE: function(parent) {
if (typeof(tinyMCE) === 'undefined') {
return;
}
$('[data-ztfy-widget="TinyMCE"]', parent).each(function() {
var data = $(this).data();
var options = {
script_url: '/--static--/ztfy.jqueryui/js/tiny_mce/tiny_mce.js'
};
var new_options = data.tinymceOptions.split(';');
for (var index in new_options) {
if (!$.isNumeric(index)) { // IE indexOf !
continue;
}
var new_option = new_options[index].split('=');
switch (new_option[1]) {
case 'true':
options[new_option[0]] = true;
break;
case 'false':
options[new_option[0]] = false;
break;
default:
options[new_option[0]] = new_option[1];
}
}
if (!tinyMCE.settings) {
tinyMCE.init(options);
}
});
$('[data-ztfy-widget="TinyMCE"]', parent).click(function(element) {
if (element instanceof $.Event) {
element = element.srcElement || element.target;
}
if (tinyMCE.activeEditor) {
tinyMCE.execCommand('mceRemoveControl', false, tinyMCE.activeEditor.id);
}
tinyMCE.execCommand('mceAddControl', false, $(element).attr('id'));
});
},
// Fancybox plug-in
initFancybox: function(parent) {
if (typeof($.fn.fancybox) === 'undefined') {
return;
}
$('[data-ztfy-widget="fancybox"]', parent).each(function() {
var data = $(this).data();
var elements = $(data.fancyboxSelector || 'IMG', this);
if (data.fancyboxParent !== undefined) {
elements = elements.parents(data.fancyboxParent);
}
var options = {
type: data.fancyboxType || 'image',
titleShow: data.fancyboxShowTitle,
titlePosition: data.fancyboxTitlePosition || 'outside',
hideOnContentClick: data.fancyboxClickHide === undefined ? true : data.fancyboxClickHide,
overlayOpacity: data.fancyboxOverlayOpacity || 0.5,
padding: data.fancyboxPadding || 10,
margin: data.fancyboxMargin || 20,
transitionIn: data.fancyboxTransitionIn || 'elastic',
transitionOut: data.fancyboxTransitionOut || 'elastic'
};
if (data.fancyboxTitleFormat) {
options.titleFormat = $.ZTFY.getFunctionByName(data.fancyboxTitleFormat);
} else {
options.titleFormat = function (title, array, index, opts) {
if (title && title.length) {
var result = '<span id="fancybox-title-over"><strong>' + title + '</strong>';
var description = $(array[index]).data('fancybox-description');
if (description) {
result += '<br />' + description;
}
result += '</span>';
return result;
} else {
return null;
}
};
}
if (data.fancyboxComplete) {
options.onComplete = $.ZTFY.getFunctionByName(data.fancyboxComplete);
} else {
options.onComplete = function () {
$("#fancybox-wrap").hover(function () {
$("#fancybox-title").slideDown('slow');
}, function () {
$("#fancybox-title").slideUp('slow');
});
};
}
elements.fancybox(options);
});
}
}; /** $.ZTFY.widgets */
/**
* Dialogs management
*/
$.ZTFY.dialog = {
switchGroup: function(source, target) {
source = $(source);
target = $('DIV[id="group_' + target + '"]');
if (source.attr('type') === 'checkbox') {
if (source.is(':checked')) {
target.show();
} else {
target.hide();
}
} else {
if (source.attr('src').endsWith('pl.png')) {
target.show();
source.attr('src', '/--static--/ztfy.skin/img/mi.png');
} else {
target.hide();
source.attr('src', '/--static--/ztfy.skin/img/pl.png');
}
}
source.parents('FIELDSET:first').toggleClass('switched');
},
options: {
expose: {
maskId: 'mask',
color: '#444',
opacity: 0.6,
zIndex: 1000
},
top: '5%',
api: true,
oneInstance: false,
closeOnClick: false,
onBeforeLoad: function() {
var wrapper = this.getOverlay();
$.ZTFY.loader.start(wrapper);
var dialog = $.ZTFY.dialog.dialogs[$.ZTFY.dialog.getCount()-1];
wrapper.load(dialog.src, dialog.callback);
if ($.browser.msie && ($.browser.version < '7')) {
$('select').css('visibility', 'hidden');
}
},
onClose: function() {
$.ZTFY.dialog.onClose();
if ($.browser.msie && ($.browser.version < '7')) {
$('select').css('visibility', 'hidden');
}
}
},
dialogs: [],
getCount: function() {
return $.ZTFY.dialog.dialogs.length;
},
getCurrent: function() {
var count = $.ZTFY.dialog.getCount();
return $('#dialog_' + count);
},
open: function(src, event, callback) {
if (typeof($.fn.overlay) === 'undefined') {
jAlert($.ZTFY.I18n.MISSING_OVERLAY, $.ZTFY.I18n.ERROR_OCCURED);
return;
}
src = src.replace(/ /g, '%20');
/* Check for callback argument */
if ($.isFunction(event)) {
callback = event;
event = null;
}
/* Stop event ! */
event = typeof(window.event) !== 'undefined' ? window.event : event;
$.ZTFY.skin.stopEvent(event);
/* Init dialogs array */
if (!$.ZTFY.dialog.dialogs) {
$.ZTFY.dialog.dialogs = [];
}
var index = $.ZTFY.dialog.getCount() + 1;
var id = 'dialog_' + index;
var options = {};
var expose_options = {
maskId: 'mask_' + id,
color: '#444',
opacity: 0.6,
zIndex: $.ZTFY.dialog.options.expose.zIndex + index
};
$.extend(options, $.ZTFY.dialog.options, { expose: expose_options });
$.ZTFY.dialog.dialogs.push({
src: src,
callback: callback || $.ZTFY.dialog.openCallback,
body: $('<div class="overlay"></div>').attr('id', id)
.css('z-index', expose_options.zIndex+1)
.appendTo($('body'))
});
var dialog = $('#' + id);
dialog.empty()
.overlay(options)
.load();
if ($.fn.draggable) {
dialog.draggable({
handle: 'DIV[id="osx-container"], H1',
containment: 'window'
});
}
},
openCallback: function(response, status, result) {
if (status === 'error') {
$(this).html(response);
} else {
var dialog = $.ZTFY.dialog.getCurrent();
$.ZTFY.plugins.call(dialog);
$.ZTFY.plugins.callCustomPlugins(dialog);
var viewspace = $('DIV.viewspace', dialog);
var title = $('H1', dialog);
var legend = $('DIV.legend', dialog);
var help = $('DIV.form > FIELDSET > DIV.help', dialog);
var actions = $('DIV.actions', dialog);
if (viewspace.length > 0) {
/* Check scroll markers positions */
var maxheight = $(window).height() - title.height() - legend.height() - help.height() - actions.height() - 180;
var position = viewspace.position();
var barWidth = $.scrollbarWidth();
viewspace.css('max-height', maxheight);
if (viewspace.get(0).scrollHeight > maxheight) {
$('<div></div>').addClass('scrollmarker')
.addClass('top')
.css('width', viewspace.width() - barWidth/2)
.css('top', position.top)
.hide()
.appendTo(viewspace);
$('<div></div>').addClass('scrollmarker')
.addClass('bottom')
.css('width', viewspace.width() - barWidth/2)
.css('top', position.top + maxheight - 10)
.appendTo(viewspace);
viewspace.scroll(function(event) {
var source = event.srcElement || event.target;
var element = $(source);
var scroll_top = $('DIV.scrollmarker.top', element);
var top = element.scrollTop();
if (top > 0) {
scroll_top.show();
} else {
scroll_top.hide();
}
var scroll_bottom = $('DIV.scrollmarker.bottom', element);
var maxheight = parseInt(element.css('max-height'));
var target = maxheight + top - 10;
if (target >= source.scrollHeight-20) {
scroll_bottom.hide();
} else {
scroll_bottom.show();
}
});
}
/* Update JQuery-multiselect auto-complete widgets position */
viewspace.scroll(function(event) {
$('DIV.jquery-multiselect-autocomplete', viewspace).each(function(index, item) {
var body_top = $('BODY').scrollTop();
var widget = $(item).closest('.widget');
var offset = widget.offset();
var height = widget.height();
$(item).css('top', offset.top + height - body_top);
});
});
/* Redirect enter key to click on first button */
$(viewspace).on('keydown', 'INPUT', function(event) {
if (event.which === 13) {
event.preventDefault();
if ($(event.target).data('ztfy-widget') !== 'multiselect') {
$('INPUT[type=button]:first', actions).click();
}
}
});
/* Activate tooltips on dialog close icon */
$('A.close', dialog).tipsy({
gravity: 'e'
});
}
}
},
close: function() {
$('#dialog_' + $.ZTFY.dialog.getCount()).overlay().close();
},
onClose: function() {
if (typeof(tinyMCE) !== 'undefined') {
if (tinyMCE.activeEditor) {
tinyMCE.execCommand('mceRemoveControl', false, tinyMCE.activeEditor.id);
}
}
var count = $.ZTFY.dialog.getCount();
var id = 'dialog_' + count;
$('DIV.tipsy').remove();
$('#' + id).remove();
$('#mask_' + id).remove();
$.ZTFY.dialog.dialogs.pop();
}
}; /** $.ZTFY.dialog */
/**
* Forms managements
*/
$.ZTFY.form = {
check: function(callback) {
$.ZTFY.ajax.check($.fn.ajaxSubmit, '/--static--/ztfy.jqueryui/js/jquery-form.min.js', callback);
},
hideStatus: function() {
$('DIV.form DIV.status').animate({
'opacity': 0,
'height': 0,
'margin-top': 0,
'margin-bottom': 0,
'padding-top': 0,
'padding-bottom': 0
}, 2000, function() {
$(this).remove();
});
},
getSubmitCallbacks: function(form) {
var $form = $(form);
var callbacks = [];
var cb = $form.data('ztfy-submit-callback');
if (cb) {
callbacks.push([$form, cb]);
}
$('[data-ztfy-submit-callback]', $(form)).each(function() {
var input = $(this);
callbacks.push([input, input.data('ztfy-submit-callback')]);
});
return callbacks;
},
checkSubmitCallbacks: function(form) {
var callbacks = $.ZTFY.form.getSubmitCallbacks(form);
if (!callbacks.length) {
return true;
}
var output = [];
var callbacks_result = true;
for (var index in callbacks) {
if (!$.isNumeric(index)) { // IE indexOf !
continue;
}
var callback = callbacks[index];
var input = callback[0];
var funct = callback[1];
var result = $.ZTFY.executeFunctionByName(funct, undefined, form, input);
if ((result !== undefined) && (result !== true)) {
if (result === false) {
callbacks_result = false;
} else if (typeof(result) === 'string') {
output.push(result);
} else if (result.length && (result.length > 0)) {
output = output.concat(result);
}
}
}
if (output.length > 1) {
jAlert($.ZTFY.I18n.ERRORS_OCCURED + '\n' + output.join('\n'), $.ZTFY.I18n.WARNING);
return false;
} else if (output.length === 1) {
jAlert($.ZTFY.I18n.ERROR_OCCURED + '\n' + output.join('\n'), $.ZTFY.I18n.WARNING);
return false;
} else {
return callbacks_result;
}
},
submit: function(event) {
var $form = $(this);
if ($form.data('submitted') || !$.ZTFY.form.checkSubmitCallbacks(this)) {
$.ZTFY.skin.stopEvent(event);
return false;
}
if (!$form.data('ztfy-disable-submit-flag')) {
$form.data('submitted', true);
}
if ($('IFRAME.progress', $form).length > 0) {
$.ZTFY.ajax.check($.progressBar, '/--static--/ztfy.jqueryui/js/jquery-progressbar.min.js', function() {
if ($.progressBar) {
$.progressBar.submit($form);
}
});
}
},
reset: function(form) {
form.reset();
$('input:first', form).focus();
},
showErrors: function(result) {
var dialog = $.ZTFY.dialog.getCurrent();
var prev_height = $('DIV.status', dialog).outerHeight(true);
$('DIV.status', dialog).remove();
$('DIV.error', dialog).each(function(index, item) {
$('DIV.widget', $(item)).detach()
.insertAfter($(item));
$(item).remove();
});
var status = $('<div></div>').addClass('status error');
$('<div></div>').addClass('summary')
.text(result.errors.status)
.appendTo(status);
var errors = $('<ul></ul>').appendTo(status);
if (result.errors.errors) {
for (var i in result.errors.errors) {
if (!$.isNumeric(i)) { // IE indexOf !
continue;
}
var error = result.errors.errors[i];
if (error.widget) {
$('<li></li>').text(error.widget + ' : ' + error.message)
.appendTo(errors);
var widget = $('[id="' + error.id + '"]', dialog).parents('DIV.widget');
var row = $(widget).parents('DIV.row');
var div = $('<div></div>').addClass('error')
.append($('<div></div>').addClass('error')
.text(error.message))
.insertBefore(widget);
widget.detach().appendTo(div);
} else {
$('<li></li>').text(error.message)
.appendTo(errors);
}
}
}
var viewspace = $('DIV.viewspace', dialog);
status.insertBefore(viewspace);
var new_height = status.outerHeight(true);
if (new_height !== prev_height) {
viewspace.css('max-height', parseInt(viewspace.css('max-height')) - new_height + prev_height);
var marker = $('DIV.scrollmarker.top', dialog);
marker.css('top', parseInt(marker.css('top')) - prev_height + new_height);
}
$('FORM', dialog).data('submitted', false);
},
add: function(form, parent, callback, data, handler) {
var $form = $(form);
if ($form.data('submitted') || !$.ZTFY.form.checkSubmitCallbacks(form)) {
return false;
}
data = data || {};
$form.data('submitted', true);
$.ZTFY.form.check(function() {
if (typeof(tinyMCE) !== 'undefined') {
tinyMCE.triggerSave();
}
if (parent) {
data.parent = parent;
}
var action = $form.attr('action').replace(/\?X-Progress-ID=.*/, '');
var ajax_handler = '/@@ajax/' + (handler || 'ajaxCreate');
$($.ZTFY.form).data('add_action', action);
$.ZTFY.ajax.submit(form, action + ajax_handler, data, callback || $.ZTFY.form._addCallback, null, 'json');
});
return false;
},
_addCallback: function(result, status) {
if (status === 'success') {
if (typeof(result) === "string") {
result = $.parseJSON(result);
}
var output = result.output;
var message,
dialog;
switch (output) {
case 'ERRORS':
$.ZTFY.form.showErrors(result);
break;
case 'OK':
$.ZTFY.dialog.close();
$('DIV.status').remove();
message = result.message || $.ZTFY.I18n.DATA_UPDATED;
$('DIV.required-info').after('<div class="status success"><div class="summary">' + message + '</div></div>');
break;
case 'NONE':
$.ZTFY.dialog.close();
$('DIV.status').remove();
message = result.message || $.ZTFY.I18n.NO_UPDATE;
$('DIV.required-info').after('<div class="status warning"><div class="summary">' + message + '</div></div>');
break;
case 'MESSAGE':
jAlert(result.message, result.title || $.ZTFY.I18n.INFO);
dialog = $.ZTFY.dialog.getCurrent();
$('FORM', dialog).data('submitted', false);
break;
case 'PASS':
$.ZTFY.dialog.close();
$('DIV.status').remove();
break;
case 'RELOAD':
var ts = new Date().getTime();
if (window.location.href.indexOf('?') >= 0) {
var href;
var ts_value = $.ZTFY.getQueryVar(window.location.href, '_');
if (ts_value === false) {
href = window.location.href + '&_=' + ts;
} else {
href = window.location.href.replace(ts_value, ts);
}
window.location.href = href;
} else {
window.location.href = window.location.href + '?_=' + ts;
}
break;
case 'REDIRECT':
window.location.href = result.target;
break;
case 'CALLBACK':
if (result.close_dialog) {
$.ZTFY.dialog.close();
}
$.ZTFY.executeFunctionByName(result.callback, undefined, result.options);
break;
default:
if (output && output.startsWith('<!-- OK -->')) {
$.ZTFY.dialog.close();
$('DIV.form').replaceWith(output);
} else {
dialog = $.ZTFY.dialog.getCurrent();
$('DIV.dialog', dialog).replaceWith(output);
var form = $('FORM', dialog);
form.attr('action', $($.ZTFY.form).data('add_action'));
$('INPUT[id="'+form.attr('id')+'-buttons-add"]', dialog).bind('click', function(event) {
$.ZTFY.form.add(this.form, result.parent);
});
$('INPUT[id="'+form.attr('id')+'-buttons-cancel"]', dialog).bind('click', function(event) {
$.ZTFY.dialog.close();
});
$('#tabforms UL.tabs', dialog).tabs($(dialog).selector + ' DIV.panes > DIV');
}
}
if (output !== 'ERRORS') {
setTimeout($.ZTFY.form.hideStatus, 2000);
}
}
},
edit: function(form, base, callback, data, handler) {
var $form = $(form);
if ($form.data('submitted') || !$.ZTFY.form.checkSubmitCallbacks(form)) {
return false;
}
$form.data('submitted', true);
$.ZTFY.form.check(function() {
if (typeof(tinyMCE) !== 'undefined') {
tinyMCE.triggerSave();
}
var action = $form.attr('action').replace(/\?X-Progress-ID=.*/, '');
var ajax_handler = '/@@ajax/' + (handler || 'ajaxEdit');
$($.ZTFY.form).data('edit_action', action);
$.ZTFY.ajax.submit(form, action + ajax_handler, data || {}, callback || $.ZTFY.form._editCallback, null, 'json');
});
return false;
},
_editCallback: function(result, status, response) {
if (status === 'success') {
if (typeof(result) === "string") {
result = $.parseJSON(result);
}
var output = result.output;
var message,
dialog;
switch (output) {
case 'ERRORS':
$.ZTFY.form.showErrors(result);
break;
case 'OK':
$.ZTFY.dialog.close();
$('DIV.status').remove();
message = result.message || $.ZTFY.I18n.DATA_UPDATED;
$('DIV.required-info').after('<div class="status success"><div class="summary">' + message + '</div></div>');
break;
case 'NONE':
$.ZTFY.dialog.close();
$('DIV.status').remove();
message = result.message || $.ZTFY.I18n.NO_UPDATE;
$('DIV.required-info').after('<div class="status warning"><div class="summary">' + message + '</div></div>');
break;
case 'MESSAGE':
jAlert(result.message, result.title || $.ZTFY.I18n.INFO);
dialog = $.ZTFY.dialog.getCurrent();
$('FORM', dialog).data('submitted', false);
break;
case 'PASS':
$.ZTFY.dialog.close();
$('DIV.status').remove();
break;
case 'RELOAD':
var ts = new Date().getTime();
if (window.location.href.indexOf('?') >= 0) {
var href;
var ts_value = $.ZTFY.getQueryVar(window.location.href, '_');
if (ts_value === false) {
href = window.location.href + '&_=' + ts;
} else {
href = window.location.href.replace(ts_value, ts);
}
window.location.href = href;
} else {
window.location.href = window.location.href + '?_=' + ts;
}
break;
case 'REDIRECT':
window.location.href = result.target;
break;
case 'CALLBACK':
if (result.close_dialog) {
$.ZTFY.dialog.close();
}
$.ZTFY.executeFunctionByName(result.callback, undefined, result.options);
break;
default:
if (output && output.startsWith('<!-- OK -->')) {
$.ZTFY.dialog.close();
$('DIV.form').replaceWith(output);
} else {
dialog = $.ZTFY.dialog.getCurrent();
$('DIV.dialog', dialog).replaceWith(output);
var form = $('FORM', dialog);
form.attr('action', $($.ZTFY.form).data('edit_action'));
$('INPUT[id="'+form.attr('id')+'-buttons-dialog_submit"]', dialog).bind('click', function(event) {
$.ZTFY.form.edit(this.form);
});
$('INPUT[id="'+form.attr('id')+'-buttons-dialog_cancel"]', dialog).bind('click', function(event) {
$.ZTFY.dialog.close();
});
$('#tabforms UL.tabs', dialog).tabs($(dialog).selector + ' DIV.panes > DIV');
}
}
if (output !== 'ERRORS') {
setTimeout($.ZTFY.form.hideStatus, 2000);
}
}
},
remove: function(oid, source, callback, handler) {
jConfirm($.ZTFY.I18n.CONFIRM_REMOVE, $.ZTFY.I18n.CONFIRM, function(confirmed) {
if (confirmed) {
var data = {
id: oid
};
var base = $(source).closest('DIV.dialog').data('ztfy-url');
var target = base || window.location.href;
$.ZTFY.form.ajax_source = source;
var ajax_handler = '/@@ajax/' + (handler || 'ajaxRemove');
$.ZTFY.ajax.post(target + ajax_handler, data, callback || $.ZTFY.form._removeCallback, null, 'text');
}
});
},
_removeCallback: function(result, status) {
if ((status === 'success') && (result === 'OK')) {
$($.ZTFY.form.ajax_source).parents('TR').remove();
}
},
update: function(form, callback, handler) {
$.ZTFY.form.check(function() {
if (typeof(tinyMCE) !== 'undefined') {
tinyMCE.triggerSave();
}
var data = $(form).formToArray(true);
var ajax_handler = '/@@ajax/' + (handler || 'ajaxUpdate');
$.ZTFY.ajax.post($(form).attr('action') + ajax_handler, data, callback || $.ZTFY.form._updateCallback, null, 'text');
});
return false;
},
_updateCallback: function(result, status) {
if ((status === 'success') && (result === 'OK')) {
$('DIV.status').remove();
$('LEGEND').after('<div class="status success"><div class="summary">' + $.ZTFY.I18n.DATA_UPDATED + '</div></div>');
}
}
}; /** $.ZTFY.form */
/**
* Container management
*/
$.ZTFY.container = {
remove: function(oid, source, addr) {
var options = {
_source: source,
url: $.ZTFY.json.getAddr(addr),
type: 'POST',
method: 'remove',
params: {
id: oid
},
success: function(data, status) {
$(this._source).parents('BODY').css('cursor', 'default');
$(this._source).parents('TR').remove();
},
error: function(request, status, error) {
jAlert(request.responseText, $.ZTFY.I18n.ERROR_OCCURED, window.location.reload);
}
};
jConfirm($.ZTFY.I18n.CONFIRM_REMOVE, $.ZTFY.I18n.CONFIRM, function(confirmed) {
if (confirmed) {
$(source).parents('BODY').css('cursor', 'wait');
$.jsonRpc(options);
}
});
}
}; /** $.ZTFY.container */
/**
* Sortables management
*/
$.ZTFY.sortable = {
options: {
handle: 'IMG.handler',
axis: 'y',
containment: 'parent',
placeholder: 'sorting-holder',
stop: function(event, ui) {
var ids = [];
$('TD.id', this).each(function (i) {
ids[ids.length] = $(this).text();
});
var data = {
ids: ids
};
if (ids.length > 1) {
$.ZTFY.ajax.post(window.location.href + '/@@ajax/ajaxUpdateOrder', data, null, function(request, status, error) {
jAlert(request.responseText, $.ZTFY.I18n.ERROR_OCCURED, window.location.reload);
});
}
}
},
init: function(parent) {
if (typeof($.fn.sortable) === 'undefined') {
return;
}
$('TABLE.orderable TBODY', parent).sortable($.ZTFY.sortable.options);
}
}; /** $.ZTFY.sortable */
/**
* Treeviews management
*/
$.ZTFY.treeview = {
init: function(parent) {
if (typeof($.fn.treeTable) === 'undefined') {
return;
}
$('TABLE.treeview', parent).each(function() {
var $this = $(this);
var data = $this.data();
$this.treeTable({
treeColumn: data.treeColumn === undefined ? 1 : data.treeColumn,
initialState: data.initialState === undefined ? 'expanded' : data.initialState
});
});
},
changeParent: function(event,ui) {
var $dragged = $(ui.draggable.parents('TR'));
if ($dragged.appendBranchTo(this)) {
var source = $dragged.attr('id').substr('node-'.length);
var target = $(this).attr('id').substr('node-'.length);
var options = {
url: $.ZTFY.json.getAddr(),
type: 'POST',
method: 'changeParent',
params: {
source: parseInt(source),
target: parseInt(target)
},
error: function(request, status, error) {
jAlert(request.responseText, $.ZTFY.I18n.ERROR_OCCURED, window.location.reload);
}
};
$.jsonRpc(options);
}
}
}; /** $.ZTFY.treeview */
/**
* Internal references management
*/
$.ZTFY.reference = {
activate: function(selector) {
$('INPUT[name='+selector+']').attr('readonly','')
.val('')
.focus();
$('INPUT[name='+selector+']').prev().val('');
},
keyPressed: function(event) {
if (event.which === 13) {
$.ZTFY.reference.search(this);
return false;
}
},
search: function(query) {
var result;
var options = {
url: $.ZTFY.ajax.getAddr(),
type: 'POST',
method: 'searchByTitle',
async: false,
params: {
query: query
},
success: function(data, status) {
result = data.result;
},
error: function(request, status, error) {
jAlert(request.responseText, "Error !", window.location.reload);
}
};
$.jsonRpc(options);
return result;
},
select: function(oid, title) {
var source = $.ZTFY.reference.source;
$(source).prev().val(oid);
$(source).val(title + ' (OID: ' + oid + ')')
.attr('readonly', 'readonly');
$('#selector').overlay().close();
$('#selector').remove();
return false;
}
}; /** $.ZTFY.reference */
/**
* Small set of extra widgets defined in other packages
*/
$.ZTFY.extras = {
// File download helper
initDownloader: function(form, target, data) {
$.ZTFY.form.check(function() {
var action = $(form).attr('action');
var form_target = action + target;
var iframe = $('IFRAME[name="downloadFrame"]');
if (iframe.length === 0) {
iframe = $('<iframe></iframe>').hide()
.attr('name', 'downloadFrame')
.appendTo($('BODY'));
}
$(form).attr('action', form_target)
.attr('target', 'downloadFrame')
.ajaxSubmit({
data: data,
iframe: true,
iframeTarget: iframe
});
/** !! reset form action after submit !! */
$(form).attr('action', action)
.attr('target', null);
$.ZTFY.dialog.close();
$('BODY').css('cursor', 'auto');
});
},
// Init main container size
initContainerSize: function(element) {
$(element).css('min-height', $($(element).data('container-sizer')).height());
},
// Captcha from ZTFY.captcha package
initCaptcha: function(element) {
if (element instanceof $.Event) {
element = element.srcElement || element.target;
}
var data = $(element).data();
var now = new Date();
var target = '@@captcha.jpeg?id=' + data.captchaId + unescape('%26') + now.getTime();
$(element).attr('src', target)
.off('click')
.on('click', $.ZTFY.extras.initCaptcha);
}
};
/**
* Init I18n strings
*/
$.ZTFY.I18n = {
INFO: "Information",
WARNING: "!! WARNING !!",
ERROR_OCCURED: "An error occured!",
ERRORS_OCCURED: "Some errors occured!",
BAD_LOGIN_TITLE: "Bad login!",
BAD_LOGIN_MESSAGE: "Your anthentication credentials didn't allow you to open a session; please check your credentials or contact administrator.",
CONFIRM: "Confirm",
CONFIRM_REMOVE: "Removing this content can't be undone. Do you confirm?",
NO_UPDATE: "No changes were applied.",
DATA_UPDATED: "Data successfully updated.",
MISSING_OVERLAY: "JQuery « overlay » plug-in is required; please include JQuery-tools resources in your page!",
DATATABLE_sProcessing: "Processing...",
DATATABLE_sSearch: "Search:",
DATATABLE_sLengthMenu: "Show _MENU_ entries",
DATATABLE_sInfo: "Showing _START_ to _END_ of _TOTAL_ entrie",
DATATABLE_sInfoEmpty: "Showing 0 to 0 of 0 entries",
DATATABLE_sInfoFiltered: "(filtered from _MAX_ total entries))",
DATATABLE_sInfoPostFix: "",
DATATABLE_sLoadingRecords: "Loading...",
DATATABLE_sZeroRecords: "No matching records found",
DATATABLE_sEmptyTable: "No data available in table",
DATATABLE_oPaginate_sFirst: "First",
DATATABLE_oPaginate_sPrevious: "Previous",
DATATABLE_oPaginate_sNext: "Next",
DATATABLE_oPaginate_sLast: "Last",
DATATABLE_oAria_sSortAscending: ": sort ascending",
DATATABLE_oAria_sSortDescending: ": sort descending"
};
$.ZTFY.initPage = function(parent) {
// Call and register ZTFY inner plug-ins
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initTabs, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initDatatables, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initDates, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initMultiselect, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initHints, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initColors, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initTinyMCE, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.widgets.initFancybox, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.sortable.init, window, parent);
$.ZTFY.plugins.callAndRegister($.ZTFY.treeview.init, window, parent);
$.ZTFY.plugins.callCustomPlugins(parent);
// Register other common plug-ins
$('A[rel="external"]').attr('target', '_blank');
$(parent).on('submit', 'FORM', $.ZTFY.form.submit);
};
/**
* Initialize ZTFY plug-ins and events
*/
$(document).ready(function() {
// Init standard AJAX callbacks
$(document).ajaxStart(function () {
$('BODY').css('cursor', 'wait');
});
$(document).ajaxStop(function () {
$('BODY').css('cursor', 'auto');
});
var hasLayout = $('BODY').hasClass('layout');
if (hasLayout) {
$.ZTFY.initPage(document);
}
var lang = $('HTML').attr('lang') || $('HTML').attr('xml:lang');
if (lang && (lang !== 'en')) {
$.ZTFY.getScript('/--static--/ztfy.skin/js/i18n/' + lang + '.js', function () {
if (!hasLayout) {
$.ZTFY.initPage(document);
}
});
} else if (!hasLayout) {
$.ZTFY.initPage(document);
}
});
})(jQuery); | ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/src/ztfy/skin/resources/js/ztfy.skin.js | ztfy.skin.js |
=================
ztfy.skin package
=================
.. contents::
What is ztfy.skin ?
===================
ZTFY.skin is the first ZTFY-based management interface.
It's a set of base classes used by many ZTFY packages, mainly for management purpose.
Currently available classes include:
- ZTFY layer and skin
- add and edit forms, including AJAX dialogs
- date and datetime widgets
- viewlet manager
- menu and menu items
Most of ZTFY.skin base classes are based on z3c.* packages classes, including:
- z3c.form, z3c.formjs and z3c.formui
- z3c.template
- z3c.menu
- z3c.layer.pagelet
How to use ztfy.skin ?
======================
ztfy.skin usage is described via doctests in ztfy/skin/doctests/README.txt
| ztfy.skin | /ztfy.skin-0.6.23.tar.gz/ztfy.skin-0.6.23/docs/README.txt | README.txt |
# import standard packages
# import Zope3 interfaces
from zope.schema.interfaces import IVocabularyFactory
# import local interfaces
from ztfy.thesaurus.interfaces.extension import IThesaurusTermExtension
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus, IThesaurusExtracts
# import Zope3 packages
from zope.i18n import translate
from zope.interface import classProvides
from zope.component import getUtilitiesFor
from zope.componentvocabulary.vocabulary import UtilityVocabulary
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from zope.traversing.api import getName
# import local packages
from ztfy.utils.request import queryRequest
from ztfy.utils.traversing import getParent
from zope.component.interfaces import ComponentLookupError
class ThesaurusVocabulary(UtilityVocabulary):
"""Thesaurus utilities vocabulary"""
classProvides(IVocabularyFactory)
interface = IThesaurus
nameOnly = False
class ThesaurusNamesVocabulary(UtilityVocabulary):
"""Thesaurus names utilities vocabulary"""
classProvides(IVocabularyFactory)
interface = IThesaurus
nameOnly = True
class ThesaurusExtractsVocabulary(SimpleVocabulary):
"""Thesaurus extracts vocabulary"""
classProvides(IVocabularyFactory)
def __init__(self, context=None):
terms = []
if context is not None:
thesaurus = getParent(context, IThesaurus)
if thesaurus is not None:
extracts = IThesaurusExtracts(thesaurus)
terms = [ SimpleTerm(getName(extract), title=extract.name) for extract in extracts.values() ]
terms.sort(key=lambda x: x.title)
super(ThesaurusExtractsVocabulary, self).__init__(terms)
class ThesaurusTermExtensionsVocabulary(SimpleVocabulary):
"""Thesaurus term extensions vocabulary"""
classProvides(IVocabularyFactory)
interface = IThesaurusTermExtension
nameOnly = False
def __init__(self, context, **kw):
request = queryRequest()
try:
utils = getUtilitiesFor(self.interface, context)
terms = [ SimpleTerm(name, title=translate(util.label, context=request))
for name, util in utils ]
except ComponentLookupError:
terms = []
super(ThesaurusTermExtensionsVocabulary, self).__init__(terms) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/vocabulary.py | vocabulary.py |
# import standard packages
# import Zope3 interfaces
from zope.schema.interfaces import IObject, IList, SchemaNotProvided
# import local interfaces
# import Zope3 packages
from zope.interface import implements, Interface
from zope.schema import Object, List, Set, Choice, TextLine
# import local packages
from ztfy.thesaurus import _
class IThesaurusTermField(IObject):
"""Marker interface to define a thesaurus term field"""
thesaurus_name = TextLine(title=_("Thesaurus name"),
required=False)
extract_name = TextLine(title=_("Extract name"),
required=False)
class IThesaurusTermsListField(IList):
"""Marker interface to define a list of thesaurus terms"""
thesaurus_name = TextLine(title=_("Thesaurus name"),
required=False)
extract_name = TextLine(title=_("Extract name"),
required=False)
class ThesaurusTermField(Object):
"""Thesaurus term schema field"""
implements(IThesaurusTermField)
def __init__(self, schema=None, thesaurus_name=u'', extract_name=u'', **kw):
super(ThesaurusTermField, self).__init__(schema=Interface, **kw)
self.thesaurus_name = thesaurus_name
self.extract_name = extract_name
def _validate(self, value):
super(Object, self)._validate(value)
# schema has to be provided by value
if not self.schema.providedBy(value):
raise SchemaNotProvided
class ThesaurusTermsListField(List):
"""Thesaurus terms list schema field"""
implements(IThesaurusTermsListField)
def __init__(self, value_type=None, unique=False, thesaurus_name=u'', extract_name=u'', **kw):
super(ThesaurusTermsListField, self).__init__(value_type=Object(schema=Interface), unique=False, **kw)
self.thesaurus_name = thesaurus_name
self.extract_name = extract_name
class ValidatedSet(Set):
"""A set field validated when not bound to a context"""
def _validate(self, value):
#Don't try to validate with empty context !
if self.context is None:
return
super(ValidatedSet, self)._validate(value)
class ValidatedChoice(Choice):
"""An always validated choice field"""
def _validate(self, value):
pass | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/schema.py | schema.py |
__docformat__ = "restructuredtext"
# import standard packages
import transaction
# import Zope3 interfaces
from zope.catalog.interfaces import ICatalog
from zope.component.interfaces import IComponentRegistry, ISite
from zope.intid.interfaces import IIntIds
from zope.processlifetime import IDatabaseOpenedWithRoot
# import local interfaces
from ztfy.security.interfaces import ILocalRoleIndexer
from ztfy.utils.interfaces import INewSiteManagerEvent
# import Zope3 packages
from zc.catalog.catalogindex import SetIndex
from zope.app.publication.zopepublication import ZopePublication
from zope.catalog.catalog import Catalog
from zope.component import adapter, queryUtility
from zope.intid import IntIds
from zope.location import locate
from zope.site import hooks
# import local packages
from ztfy.utils.site import locateAndRegister
def updateDatabaseIfNeeded(context):
"""Check for missing utilities at application startup"""
try:
sm = context.getSiteManager()
except:
return
default = sm['default']
# Check for required IIntIds utility
intids = queryUtility(IIntIds)
if intids is None:
intids = default.get('IntIds')
if intids is None:
intids = IntIds()
locate(intids, default)
IComponentRegistry(sm).registerUtility(intids, IIntIds, '')
default['IntIds'] = intids
# Check for security catalog and indexes
catalog = default.get('SecurityCatalog')
if catalog is None:
catalog = Catalog()
locateAndRegister(catalog, default, 'SecurityCatalog', intids)
IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'SecurityCatalog')
if catalog is not None:
if 'ztfy.ThesaurusManager' not in catalog:
index = SetIndex('ztfy.ThesaurusManager', ILocalRoleIndexer, False)
locateAndRegister(index, catalog, 'ztfy.ThesaurusManager', intids)
if 'ztfy.ThesaurusContentManager' not in catalog:
index = SetIndex('ztfy.ThesaurusContentManager', ILocalRoleIndexer, False)
locateAndRegister(index, catalog, 'ztfy.ThesaurusContentManager', intids)
if 'ztfy.ThesaurusExtractManager' not in catalog:
index = SetIndex('ztfy.ThesaurusExtractManager', ILocalRoleIndexer, False)
locateAndRegister(index, catalog, 'ztfy.ThesaurusExtractManager', intids)
@adapter(IDatabaseOpenedWithRoot)
def handleOpenedDatabase(event):
db = event.database
connection = db.open()
root = connection.root()
root_folder = root.get(ZopePublication.root_name, None)
for site in root_folder.values():
if ISite(site, None) is not None:
hooks.setSite(site)
updateDatabaseIfNeeded(site)
transaction.commit()
@adapter(INewSiteManagerEvent)
def handleNewSiteManager(event):
updateDatabaseIfNeeded(event.object) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/database.py | database.py |
# import standard packages
from datetime import datetime
from persistent import Persistent
# import Zope3 interfaces
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
from ztfy.thesaurus.interfaces.extension import IThesaurusTermExtension
from ztfy.thesaurus.interfaces.thesaurus import IThesaurusExtractInfo
from ztfy.thesaurus.interfaces.term import IThesaurusTerm, IThesaurusLoaderTerm, STATUS_PUBLISHED
from ztfy.thesaurus.interfaces.tree import INode
# import Zope3 packages
from zope.component import adapts, queryUtility
from zope.container.contained import Contained
from zope.interface import implements, noLongerProvides, alsoProvides
from zope.schema.fieldproperty import FieldProperty
from zope.security.proxy import removeSecurityProxy
from zope.traversing.api import getName
# import local packages
from ztfy.utils.timezone import tztime
from ztfy.utils.unicode import translateString
REVERSE_LINK_ATTRIBUTES = {'generic': 'specifics',
'usage': 'used_for'}
REVERSE_LIST_ATTRIBUTES = {'specifics': 'generic',
'used_for': 'usage'}
class ThesaurusTerm(Persistent, Contained):
"""Thesaurus term content"""
implements(IThesaurusTerm)
label = FieldProperty(IThesaurusTerm['label'])
alt = FieldProperty(IThesaurusTerm['alt'])
definition = FieldProperty(IThesaurusTerm['definition'])
note = FieldProperty(IThesaurusTerm['note'])
_generic = FieldProperty(IThesaurusTerm['generic'])
_specifics = FieldProperty(IThesaurusTerm['specifics'])
_associations = FieldProperty(IThesaurusTerm['associations'])
_usage = FieldProperty(IThesaurusTerm['usage'])
_used_for = FieldProperty(IThesaurusTerm['used_for'])
_extracts = FieldProperty(IThesaurusTerm['extracts'])
_extensions = FieldProperty(IThesaurusTerm['extensions'])
status = FieldProperty(IThesaurusTerm['status'])
level = FieldProperty(IThesaurusTerm['level'])
micro_thesaurus = FieldProperty(IThesaurusTerm['micro_thesaurus'])
_parent = FieldProperty(IThesaurusTerm['parent'])
_created = FieldProperty(IThesaurusTerm['created'])
_modified = FieldProperty(IThesaurusTerm['modified'])
def __init__(self, label, alt=None, definition=None, note=None, generic=None, specifics=[], associations=[],
usage=None, used_for=[], created=None, modified=None):
self.label = label
self.alt = alt
self.definition = definition
self.note = note
self.generic = generic
self.specifics = specifics
self.associations = associations
self.usage = usage
self.used_for = used_for
self.created = created
self.modified = modified
def __eq__(self, other):
if other is None:
return False
else:
return isinstance(removeSecurityProxy(other), ThesaurusTerm) and (self.label == other.label)
@property
def base_label(self):
return translateString(self.label, escapeSlashes=True, forceLower=True, spaces=' ')
@property
def caption(self):
if self._usage:
label = self._usage.label
terms = [term.label for term in self._usage.used_for if term.status == STATUS_PUBLISHED]
elif self._used_for:
label = self.label
terms = [term.label for term in self._used_for if term.status == STATUS_PUBLISHED]
else:
label = self.label
terms = []
return label + (' [ %s ]' % ', '.join(terms) if terms else '')
@property
def generic(self):
return self._generic
@generic.setter
def generic(self, value):
self._generic = generic = removeSecurityProxy(value)
if generic is not None:
self.extracts = self.extracts & generic.extracts
@property
def specifics(self):
return self._specifics
@specifics.setter
def specifics(self, value):
self._specifics = [removeSecurityProxy(term) for term in value or ()]
@property
def associations(self):
return self._associations
@associations.setter
def associations(self, value):
self._associations = [removeSecurityProxy(term) for term in value or ()]
@property
def usage(self):
return self._usage
@usage.setter
def usage(self, value):
self._usage = usage = removeSecurityProxy(value)
if usage is not None:
self.generic = None
self.extracts = usage.extracts
@property
def used_for(self):
return self._used_for
@used_for.setter
def used_for(self, value):
self._used_for = [removeSecurityProxy(term) for term in value or ()]
@property
def extracts(self):
return self._extracts or set()
@extracts.setter
def extracts(self, value):
old_value = self._extracts or set()
new_value = value or set()
if self._generic is not None:
new_value = new_value & (self._generic.extracts or set())
if old_value != new_value:
removed = old_value - new_value
if removed:
for term in self.specifics:
term.extracts = (term.extracts or set()) - removed
self._extracts = removeSecurityProxy(new_value)
# Extracts selection also applies to term synonyms...
for term in self.used_for or ():
term.extracts = self.extracts
def addExtract(self, extract, check=True):
if IThesaurusExtractInfo.providedBy(extract):
extract = getName(extract)
if check:
self.extracts = (self.extracts or set()) | set((extract,))
else:
self._extracts = removeSecurityProxy((self._extracts or set()) | set((extract,)))
# Extracts selection also applies to term synonyms...
for term in self.used_for or ():
term.extracts = self.extracts
def removeExtract(self, extract, check=True):
if IThesaurusExtractInfo.providedBy(extract):
extract = getName(extract)
if check:
self.extracts = (self.extracts or set()) - set((extract,))
else:
self._extracts = removeSecurityProxy((self._extracts or set()) - set((extract,)))
# Extracts selection also applies to term synonyms...
for term in self.used_for or ():
term.extracts = self.extracts
@property
def extensions(self):
return self._extensions or set()
@extensions.setter
def extensions(self, value):
old_value = self._extensions or set()
new_value = value or set()
if old_value != new_value:
added = new_value - old_value
removed = old_value - new_value
for ext in removed:
extension = queryUtility(IThesaurusTermExtension, ext)
if extension is not None:
noLongerProvides(self, extension.target_interface)
for ext in added:
extension = queryUtility(IThesaurusTermExtension, ext)
if extension is not None:
alsoProvides(self, extension.target_interface)
self._extensions = removeSecurityProxy(new_value)
def queryExtensions(self):
return [ util for util in [ queryUtility(IThesaurusTermExtension, ext) for ext in self.extensions ]
if util is not None ]
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, value):
self._parent = removeSecurityProxy(value)
@property
def created(self):
if self._created is not None:
return self._created
dc = IZopeDublinCore(self, None)
if dc is not None:
return tztime(dc.created)
@created.setter
def created(self, value):
if isinstance(value, (str, unicode)):
if ' ' in value:
value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
else:
value = datetime.strptime(value, '%Y-%m-%d')
self._created = tztime(value)
@property
def modified(self):
if self._modified is not None:
return self._modified
dc = IZopeDublinCore(self, None)
if dc is not None:
return tztime(dc.modified)
@modified.setter
def modified(self, value):
if isinstance(value, (str, unicode)):
if ' ' in value:
value = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
else:
value = datetime.strptime(value, '%Y-%m-%d')
self._modified = tztime(value)
def getParents(self):
terms = []
parent = self.generic
while parent is not None:
terms.append(parent)
parent = parent.generic
return terms
@property
def level(self):
return len(self.getParents()) + 1
def getParentChilds(self):
terms = []
parent = self.generic
if parent is not None:
[terms.append(term) for term in parent.specifics if term is not self]
return terms
def getAllChilds(self, terms=None, with_synonyms=False):
if terms is None:
terms = []
if with_synonyms:
terms.extend(self.used_for)
terms.extend(self.specifics)
for term in self.specifics:
term.getAllChilds(terms, with_synonyms)
return terms
def merge(self, term, configuration):
# terms marked by IThesaurusLoaderTerm interface are used by custom loaders which only contains
# synonyms definitions; so they shouldn't alter terms properties
if term is None:
return
# assign basic attributes
if not IThesaurusLoaderTerm.providedBy(term):
for name in ('label', 'definition', 'note', 'status', 'micro_thesaurus', 'created', 'modified'):
setattr(self, name, getattr(term, name, None))
# for term references, we have to check if the target term is already
# in our parent thesaurus or not :
# - if yes => we target the term actually in the thesaurus
# - if not => we keep the same target, which will be included in the thesaurus after merging
terms = self.__parent__
if IThesaurusLoaderTerm.providedBy(term):
attrs = ('usage',)
else:
attrs = ('generic', 'usage')
for name in attrs:
target = getattr(term, name)
if target is None:
setattr(self, name, None)
else:
label = target.label
if configuration.conflict_suffix:
label = target.label + ' ' + configuration.conflict_suffix
if label not in terms:
label = target.label
if label in terms:
target_term = terms[label]
else:
target_term = target
setattr(self, name, target_term)
if name in REVERSE_LINK_ATTRIBUTES:
attribute = REVERSE_LINK_ATTRIBUTES[name]
setattr(target_term, attribute, set(getattr(target_term, attribute)) | set((self,)))
if IThesaurusLoaderTerm.providedBy(term):
attrs = ('used_for',)
else:
attrs = ('specifics', 'associations', 'used_for')
for name in attrs:
targets = getattr(term, name, [])
if not targets:
setattr(self, name, [])
else:
new_targets = []
for target in targets:
label = target.label
if configuration.conflict_suffix:
label = target.label + ' ' + configuration.conflict_suffix
if label not in terms:
label = target.label
if label in terms:
target_term = terms[label]
else:
target_term = target
new_targets.append(target_term)
if name in REVERSE_LIST_ATTRIBUTES:
attribute = REVERSE_LIST_ATTRIBUTES[name]
setattr(target_term, attribute, self)
setattr(self, name, new_targets)
class ThesaurusTermTreeAdapter(object):
"""Thesaurus term tree adapter"""
adapts(IThesaurusTerm)
implements(INode)
def __init__(self, context):
self.context = context
@property
def cssClass(self):
return self.context.status
@property
def label(self):
return self.context.label
def getLevel(self):
return self.context.level
def hasChildren(self):
return len(self.context.specifics) > 0
def getChildren(self):
return self.context.specifics | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/term.py | term.py |
# import standard packages
from persistent import Persistent
import BTrees.Length
import re
# import Zope3 interfaces
from hurry.query.interfaces import IQuery
from transaction.interfaces import ITransactionManager
from zc.catalog.interfaces import IValueIndex
from zope.annotation.interfaces import IAnnotations
from zope.catalog.interfaces import ICatalog
from zope.container.interfaces import IObjectAddedEvent, IObjectRemovedEvent
from zope.dublincore.interfaces import IZopeDublinCore
from zope.location.interfaces import ISublocations
from zopyx.txng3.core.interfaces.ting import ITingIndex
from zopyx.txng3.core.parsers.english import QueryParserError
# import local interfaces
from ztfy.thesaurus.interfaces.loader import IThesaurusLoader
from ztfy.thesaurus.interfaces.term import IThesaurusTermsContainer, IThesaurusTerm, IThesaurusLoaderTerm
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus, \
IThesaurusExtractInfo, \
IThesaurusExtracts
from ztfy.thesaurus.interfaces.tree import ITree
# import Zope3 packages
from hurry.query import And, Or
from hurry.query.value import Eq
from zc.catalog.catalogindex import ValueIndex
from zope.catalog.catalog import Catalog
from zope.component import adapter, adapts, getUtility, queryUtility, getSiteManager
from zope.container.contained import Contained
from zope.container.folder import Folder
from zope.interface import implementer, implements
from zope.location.location import locate
from zope.schema.fieldproperty import FieldProperty
from zope.security.proxy import removeSecurityProxy
from zope.traversing.api import getName
# import local packages
from ztfy.utils.catalog import indexObject, unindexObject
from ztfy.utils.catalog.index import TextIndexNG, Text as BaseTextSearch
from ztfy.security.property import RolePrincipalsProperty
from ztfy.utils.traversing import getParent
from ztfy.utils.unicode import translateString
CUSTOM_SEARCH = re.compile(r'\*|\"|\sAND\s|\sOR\s|\sNOT\s|\(|\)', re.IGNORECASE)
class ThesaurusIndexSearch(BaseTextSearch):
"""Custom text search index using catalog instance instead of name"""
def getIndex(self, context=None):
if ICatalog.providedBy(self.catalog_name):
catalog = self.catalog_name
else:
catalog = getUtility(ICatalog, self.catalog_name, context)
index = catalog[self.index_name]
assert ITingIndex.providedBy(index)
return index
class ThesaurusValueSearch(Eq):
"""Custom value search index using catalog instance instead of name"""
def getIndex(self, context=None):
if ICatalog.providedBy(self.catalog_name):
catalog = self.catalog_name
else:
catalog = getUtility(ICatalog, self.catalog_name, context)
index = catalog[self.index_name]
assert IValueIndex.providedBy(index)
return index
class ThesaurusTermsContainer(Folder):
"""Thesaurus terms container"""
implements(IThesaurusTermsContainer)
def __init__(self):
super(ThesaurusTermsContainer, self).__init__()
self._length = BTrees.Length.Length()
def __setitem__(self, name, term):
if name not in self.data:
self._length.change(1)
term = removeSecurityProxy(term)
self.data.__setitem__(name, term)
locate(term, self, name)
thesaurus = IThesaurus(self.__parent__, None)
if thesaurus is not None:
catalog = thesaurus.catalog
indexObject(term, catalog)
def __delitem__(self, name):
term = self.data[name]
thesaurus = IThesaurus(self.__parent__, None)
if thesaurus is not None:
catalog = thesaurus.catalog
unindexObject(term, catalog)
self.data.__delitem__(name)
self._length.change(-1)
def __len__(self):
return self._length()
def iterkeys(self):
return self.data.iterkeys()
def itervalues(self):
return self.data.itervalues()
def iteritems(self):
return self.data.iteritems()
class Thesaurus(Persistent, Contained):
"""Thesaurus utility"""
implements(IThesaurus, ISublocations)
__roles__ = ('ztfy.ThesaurusManager', 'ztfy.ThesaurusContentManager')
name = FieldProperty(IThesaurus['name'])
_title = FieldProperty(IThesaurus['title'])
subject = FieldProperty(IThesaurus['subject'])
description = FieldProperty(IThesaurus['description'])
creator = FieldProperty(IThesaurus['creator'])
publisher = FieldProperty(IThesaurus['publisher'])
created = FieldProperty(IThesaurus['created'])
language = FieldProperty(IThesaurus['language'])
terms = None
_top_terms = FieldProperty(IThesaurus['top_terms'])
catalog = FieldProperty(IThesaurus['catalog'])
administrators = RolePrincipalsProperty(IThesaurus['administrators'], role='ztfy.ThesaurusManager')
contributors = RolePrincipalsProperty(IThesaurus['contributors'], role='ztfy.ThesaurusContentManager')
def __init__(self, name=None, description=None, terms=None, top_terms=None):
if name:
self.name = name
if terms is None:
terms = []
if top_terms is None:
top_terms = []
if description:
self.title = description.title
self.subject = description.subject
self.description = description.description
self.creator = description.creator
self.publisher = description.publisher
self.created = description.created
self.language = description.language
if not IThesaurusTermsContainer.providedBy(terms):
terms = ThesaurusTermsContainer()
self.terms = terms
locate(terms, self, '++terms++')
self.resetTermsParent()
self.resetTopTerms()
@property
def title(self):
dc = IZopeDublinCore(self, None)
if dc is not None:
return dc.title
else:
return self._title
@title.setter
def title(self, value):
if value != self._title:
self._title = value
dc = IZopeDublinCore(self, None)
if dc is not None:
dc.title = value
def sublocations(self):
return (self.terms, self.catalog)
@property
def top_terms(self):
return self._top_terms
@top_terms.setter
def top_terms(self, value):
self._top_terms = [ removeSecurityProxy(term) for term in value or ()
if term.usage is None ]
def initCatalog(self):
catalog = self.catalog = Catalog()
locate(catalog, self, '++catalog++')
# init fulltext search catalog
index = TextIndexNG('label', IThesaurusTerm,
field_callable=False,
languages=self.language,
splitter='txng.splitters.default',
storage='txng.storages.term_frequencies',
dedicated_storage=False,
use_stopwords=True,
use_normalizer=True,
ranking=True)
locate(index, catalog, 'label')
catalog['label'] = index
# init stemmed search catalog
index = TextIndexNG('label', IThesaurusTerm,
field_callable=False,
languages=self.language,
splitter='txng.splitters.default',
storage='txng.storages.term_frequencies',
dedicated_storage=False,
use_stopwords=True,
use_normalizer=True,
use_stemmer=True,
ranking=True)
locate(index, catalog, 'stemm_label')
catalog['stemm_label'] = index
# init basic label catalog
index = ValueIndex('base_label', IThesaurusTerm, field_callable=False)
locate(index, catalog, 'base_label')
catalog['base_label'] = index
# index thesaurus terms
locate(self.terms, self, '++terms++')
for index, term in enumerate(self.terms.itervalues()):
indexObject(term, catalog)
if not index % 100:
try:
ITransactionManager(catalog).savepoint()
except TypeError:
# This method can fail if thesaurus is not stored yet...
pass
def delete(self):
manager = getSiteManager(self)
manager.unregisterUtility(self, IThesaurus, self.name)
default = manager['default']
name = 'Thesaurus::' + self.name
# re-parent thesaurus to site management folder
locate(self, default, name)
del default[name]
def clear(self):
self.terms.data.clear()
self.catalog.clear()
self.top_terms = []
def load(self, configuration):
loader = queryUtility(IThesaurusLoader, configuration.format)
if loader is not None:
result = loader.load(configuration.data)
self.merge(configuration, result)
def merge(self, configuration, thesaurus=None):
if thesaurus is None:
loader = queryUtility(IThesaurusLoader, configuration.format)
if loader is not None:
thesaurus = loader.load(configuration.data)
if thesaurus is not None:
# define or merge items from given thesaurus
terms = self.terms
for index, (key, term) in enumerate(thesaurus.terms.iteritems()):
# check for term conflict
if configuration.conflict_suffix:
suffixed_key = key + ' ' + configuration.conflict_suffix
if suffixed_key in terms:
key = suffixed_key
elif key in terms:
term.label = key
if key in terms:
terms[key].merge(term, configuration)
elif not IThesaurusLoaderTerm.providedBy(term):
terms[key] = term
if not index % 100:
try:
ITransactionManager(self).savepoint()
except TypeError:
# This method can fail if thesaurus is not stored yet...
pass
self.resetTermsParent()
self.resetTopTerms()
def resetTermsParent(self):
for index, term in enumerate(self.terms.itervalues()):
# reset generic/specifics attributes
generic = term.generic
if (generic is not None) and (term not in generic.specifics):
generic.specifics = generic.specifics + [term, ]
# reset term's first level parent
parent = term
while parent.generic is not None:
parent = parent.generic
term.parent = parent
if not index % 100:
try:
ITransactionManager(self).savepoint()
except TypeError:
# This method can fail if thesaurus is not stored yet...
pass
def resetTopTerms(self):
self.top_terms = [term for term in self.terms.itervalues()
if (not term.generic) and (not term.usage)]
def findTerms(self, query=None, extract=None, autoexpand='always', glob='end', limit=None,
exact=False, exact_only=False, stemmed=False):
assert exact or (not exact_only)
query_util = getUtility(IQuery)
terms = []
if exact:
search = ThesaurusValueSearch((self.catalog, 'base_label'),
translateString(query, escapeSlashes=True, forceLower=True, spaces=' '))
terms = list(query_util.searchResults(search))
if not exact_only:
searches = []
# check stemmed index
if stemmed and not re.search(r'\*', query):
index = (self.catalog, 'stemm_label')
searches.append(ThesaurusIndexSearch(index, {'query': u' '.join(m for m in query.split() if len(m) > 2),
'autoexpand': 'off',
'ranking': False}))
# check basic index
start = ''
end = ''
if CUSTOM_SEARCH.search(query):
query_text = query
autoexpand = 'off'
else:
if glob in ('start', 'both'):
start = u'*'
if glob in ('end', 'both'):
end = u'*'
query_text = u' '.join((u'%s%s%s' % (start, m, end) for m in query.split() if len(m) > 2))
index = (self.catalog, 'label')
searches.append(ThesaurusIndexSearch(index, {'query': query_text,
'autoexpand': autoexpand,
'ranking': False}))
try:
terms += sorted(query_util.searchResults(Or(*searches), limit=limit), key=lambda x: x.label)
except QueryParserError:
pass
if extract:
terms = [term for term in terms if extract in term.extracts]
return terms
@adapter(IThesaurus, IObjectAddedEvent)
def handleNewThesaurus(thesaurus, event):
"""Handle new thesaurus"""
thesaurus.initCatalog()
class ThesaurusTreeAdapter(object):
"""Thesaurus tree adapter"""
adapts(IThesaurus)
implements(ITree)
def __init__(self, context):
self.context = context
def getRootNodes(self):
return self.context.top_terms
#
# Thesaurus extracts
#
class ThesaurusExtract(Persistent, Contained):
"""Thesaurus extract"""
implements(IThesaurusExtractInfo)
__roles__ = ('ztfy.ThesaurusExtractManager',)
name = FieldProperty(IThesaurusExtractInfo['name'])
description = FieldProperty(IThesaurusExtractInfo['description'])
abbreviation = FieldProperty(IThesaurusExtractInfo['abbreviation'])
color = FieldProperty(IThesaurusExtractInfo['color'])
managers = RolePrincipalsProperty(IThesaurusExtractInfo['managers'], role='ztfy.ThesaurusExtractManager')
def addTerm(self, term):
term.addExtract(self)
def removeTerm(self, term):
term.removeExtract(self)
@adapter(IThesaurusExtractInfo, IObjectRemovedEvent)
def handleRemovedExtractInfo(extract, event):
thesaurus = getParent(extract, IThesaurus)
name = getName(extract)
for term in thesaurus.terms:
term.removeExtract(name, check=False)
class ThesaurusExtractsContainer(Folder):
"""Thesaurus extracts container"""
implements(IThesaurusExtracts)
THESAURUS_EXTRACTS_KEY = 'ztfy.thesaurus.extracts'
@adapter(IThesaurus)
@implementer(IThesaurusExtracts)
def ThesaurusExtractsFactory(context):
"""Thesaurus extracts adapter"""
annotations = IAnnotations(context)
extracts = annotations.get(THESAURUS_EXTRACTS_KEY)
if extracts is None:
extracts = annotations[THESAURUS_EXTRACTS_KEY] = ThesaurusExtractsContainer()
locate(extracts, context, '++extracts++')
return extracts | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/thesaurus.py | thesaurus.py |
# import standard packages
# import Zope3 interfaces
from zope.intid.interfaces import IIntIds
# import local interfaces
from ztfy.thesaurus.interfaces.index import IThesaurusTermFieldIndex, IThesaurusTermsListFieldIndex
# import Zope3 packages
from zc.catalog.catalogindex import SetIndex
from zc.catalog.index import SetIndex as SetIndexBase
from zope.component import getUtility
from zope.interface import implements
from zope.schema.fieldproperty import FieldProperty
# import local packages
def getIndexTerms(index, term):
terms = [term, ]
if index.include_parents:
terms.extend(term.getParents())
if index.include_synonyms:
if term.usage is not None:
terms.append(term.usage)
else:
terms.extend(term.used_for)
return terms
class ThesaurusTermFieldIndex(SetIndex):
"""Thesaurus term field index"""
implements(IThesaurusTermFieldIndex)
include_parents = FieldProperty(IThesaurusTermFieldIndex['include_parents'])
include_synonyms = FieldProperty(IThesaurusTermFieldIndex['include_synonyms'])
def index_doc(self, docid, object):
if self.interface is not None:
object = self.interface(object, None)
if object is None:
return None
value = getattr(object, self.field_name, None)
if value is not None and self.field_callable:
value = value()
if not value:
self.unindex_doc(docid)
return None
intids = getUtility(IIntIds)
value = [intids.register(term) for term in set(getIndexTerms(self, value))]
return SetIndexBase.index_doc(self, docid, value)
class ThesaurusTermsListFieldIndex(SetIndex):
"""Thesaurus terms list field index"""
implements(IThesaurusTermsListFieldIndex)
include_parents = FieldProperty(IThesaurusTermsListFieldIndex['include_parents'])
include_synonyms = FieldProperty(IThesaurusTermsListFieldIndex['include_synonyms'])
def index_doc(self, docid, object):
if self.interface is not None:
object = self.interface(object, None)
if object is None:
return None
value = getattr(object, self.field_name, None)
if value is not None and self.field_callable:
value = value()
if not value:
self.unindex_doc(docid)
return None
terms = []
[terms.extend(getIndexTerms(self, term)) for term in value]
intids = getUtility(IIntIds)
value = [intids.register(term) for term in set(terms)]
return SetIndexBase.index_doc(self, docid, value) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/index.py | index.py |
# import standard packages
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
from zope.interface import Interface, Attribute
from zope.schema import Bool, Choice, TextLine
# import local packages
from ztfy.file.schema import FileField
from ztfy.thesaurus.schema import ValidatedChoice
from ztfy.utils.encoding import EncodingField
from ztfy.thesaurus import _
class IThesaurusLoaderConfiguration(Interface):
"""Thesaurus loader configuration interface"""
name = TextLine(title=_("Thesaurus name"),
description=_("Name of the registered thesaurus"),
required=True)
data = FileField(title=_("loader-data-title", "Input data"),
description=_("loader-data-description", "Input file containing thesaurus data"),
required=True)
format = Choice(title=_("loader-format-title", "File format"),
description=_("loader-format-description", "This list contains available thesauri loaders"),
required=True,
vocabulary='ZTFY thesaurus loader formats')
import_synonyms = Bool(title=_("loader-synonyms-title", "Import synonyms?"),
description=_("loader-synonyms-description", "If 'No', synonyms will not be imported into loaded thesaurus"),
required=True,
default=True)
language = Choice(title=_("loader-language-title", "Content language"),
description=_("loader-language-description", "Select file language, for formats which don't provide it internally"),
required=False,
vocabulary='ZTFY base languages')
encoding = EncodingField(title=_("loader-encoding-title", "File encoding"),
description=_("loader-encoding-description", "Select file encoding, for formats which don't provide it internally"),
required=False,
default='utf-8')
class IThesaurusUpdaterConfiguration(IThesaurusLoaderConfiguration):
"""Thesaurus updater configuration interface"""
clear = Bool(title=_("updater-clear-title", "Clear before merge ?"),
description=_("updater-clear-description", "If 'Yes', thesaurus will be cleared before re-importing file contents"),
required=True,
default=False)
conflict_suffix = TextLine(title=_("updater-conflict-suffix-title", "Auto-added conflict suffix"),
description=_("updater-conflict-suffix-description",
"""If you want to prevent imports conflicts, you can provide """
"""a suffix which will be added automatically to conflicting terms"""),
required=False)
class IThesaurusLoaderHandler(Interface):
"""Thesaurus loader handler configuration"""
configuration = Attribute(_("Current handler configuration"))
def read(self, data, configuration=None):
"""Extract terms from given data"""
class IThesaurusLoader(Interface):
"""Thesaurus loader interface"""
handler = Attribute(_("Thesaurus handler class"))
def load(self, data, configuration=None):
"""Load thesaurus from data for the given loader configuration"""
class IThesaurusExporterConfiguration(Interface):
"""Thesaurus exporter configuration interface"""
filename = TextLine(title=_("export-filename-title", "Export file name"),
description=_("export-filename-description", "Full file name, including extension"),
required=False)
format = Choice(title=_("export-format-title", "Export file format"),
description=_("export-format-description", "This list contains available thesauri exporters"),
required=True,
vocabulary="ZTFY thesaurus exporter formats")
extract = ValidatedChoice(title=_("export-extract-title", "Extract to export"),
description=_("export-extract-description", "You can choose to export only an extract of the thesaurus"),
required=False,
vocabulary="ZTFY thesaurus extracts")
class IThesaurusExporterHandler(Interface):
"""Thesaurus exporter handler configuration"""
configuration = Attribute(_("Current handler configuration"))
def write(self, thesaurus, output, configuration=None):
"""Export terms of given thesaurus"""
class IThesaurusExporter(Interface):
"""Thesaurus exporter configuration"""
handler = Attribute(_("Thesaurus handler class"))
def export(self, thesaurus, configuration=None):
"""Export thesaurus terms with the given export configuration""" | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/interfaces/loader.py | loader.py |
# import standard packages
# import Zope3 interfaces
from zope.container.interfaces import IContainer
# import local interfaces
# import Zope3 packages
from zope.interface import Interface, Attribute, Invalid, invariant
from zope.schema import Text, TextLine, Bool, Choice, Int, Datetime, Set
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
# import local packages
from ztfy.thesaurus.schema import ThesaurusTermField, ThesaurusTermsListField, ValidatedSet
from ztfy.thesaurus import _
STATUS_CANDIDATE = u'candidate'
STATUS_PUBLISHED = u'published'
STATUS_ARCHIVED = u'archived'
THESAURUS_STATUS = (STATUS_CANDIDATE,
STATUS_PUBLISHED,
STATUS_ARCHIVED)
THESAURUS_STATUS_LABELS = (_("Candidate"),
_("Published"),
_("Archived"))
THESAURUS_STATUS_VOCABULARY = SimpleVocabulary([SimpleTerm(THESAURUS_STATUS[i], t, t) for i, t in enumerate(THESAURUS_STATUS_LABELS)])
class IThesaurusTermInfo(Interface):
"""Thesaurus term base interface"""
id = Attribute(_("term-id", "Internal ID"))
label = TextLine(title=_("term-label-title", "Term label"),
description=_("term-label-description", "Full keyword for the given term"),
required=True)
base_label = Attribute(_("Base label without uppercase or accentuated character"))
caption = Attribute(_("term-caption", "Term external caption"))
alt = TextLine(title=_("term-alt-title", "Alternate label"),
description=_("Not to be confused with synonyms 'usage' label, given below..."),
required=False)
definition = Text(title=_("term-definition-title", "Definition"),
description=_("term-definition-description", "Long definition, mostly for complicated terms"),
required=False)
note = Text(title=_("term-note-title", "Term's application note"),
description=_("term-note-description", "Application note for the given term"),
required=False)
generic = ThesaurusTermField(title=_("term-generic-title", "Generic term"),
description=_("term-generic-description", "Parent generic term of the current term"),
required=False)
specifics = ThesaurusTermsListField(title=_("term-specifics-title", "Specifics terms"),
description=_("term-specifics-description", "Child more specifics terms of the current term"),
required=False)
associations = ThesaurusTermsListField(title=_("term-associations-title", "Associated terms"),
description=_("term-associations-description", "Other terms associated to the current term"),
required=False)
usage = ThesaurusTermField(title=_("term-usage-title", "Usage"),
description=_("term-usage-description", "For synonyms, specify here the term's descriptor to use"),
required=False)
used_for = ThesaurusTermsListField(title=_("term-usedfor-title", "Synonyms"),
description=_("term-usedfor-description", "For a given allowed descriptor, specify here the list of synonyms"),
required=False)
extracts = ValidatedSet(title=_("term-extracts-title", "Extracts"),
description=_("term-extracts-description", "List of thesaurus extracts including this term"),
required=False,
value_type=Choice(vocabulary='ZTFY thesaurus extracts'))
extensions = Set(title=_("term-extensions-title", "Extensions"),
description=_(""),
required=False,
value_type=Choice(vocabulary='ZTFY thesaurus term extensions'))
status = Choice(title=_("term-status-title", "Status"),
description=_("term-status-description", "Term status"),
required=True,
vocabulary=THESAURUS_STATUS_VOCABULARY,
default=u'published')
level = Int(title=_("term-level-title", "Level"),
description=_("term-level-description", "Term's level in the thesaurus tree"),
required=True,
readonly=True,
default=1)
micro_thesaurus = Bool(title=_("term-miro-title", "Micro-thesaurus ?"),
description=_("term-micro-description", "Is the term part of a micro-thesaurus"),
required=False)
parent = ThesaurusTermField(title=_("term-parent-title", "First level parent"),
description=_("term-parent-description", "Parent at level 1 of the current term, or None"),
required=False,
schema=Interface)
created = Datetime(title=_("term-created-title", "Creation date"),
required=False)
modified = Datetime(title=_("term-modified-title", "Modification date"),
required=False)
def getParents(self):
"""Get list of term's parents"""
def getParentChilds(self):
"""Get 'brother's terms of current term"""
def getAllChilds(self, terms=None, with_synonyms=False):
"""Get full list of term's specifics"""
def queryExtensions(self):
"""Get list of extension utilities"""
@invariant
def checkLabel(self):
if '/' in self.label:
raise Invalid(_("'/' character is forbidden in term's label"))
@invariant
def checkSynonym(self):
if self.usage is not None:
if self.generic is not None:
raise Invalid(_("A term can't be a synonym and attached to a generic term"))
if self.used_for:
raise Invalid(_("A term used as synonym can't have it's own synonyms (all synonyms should be attached to the descriptor)"))
class IThesaurusTermWriter(Interface):
"""Thesaurus term writer interface"""
def merge(self, term, configuration):
"""Merge term attributes with given term, to avoid overwriting all entity"""
class IThesaurusTermExtractsWriter(Interface):
"""Thesaurus term extracts writer"""
def addExtract(self, extract, check=True):
"""Add given extract to the list of term extracts"""
def removeExtract(self, extract, check=True):
"""Remove given extract from the list of term extracts"""
class IThesaurusTerm(IThesaurusTermInfo, IThesaurusTermWriter, IThesaurusTermExtractsWriter):
"""Thesaurus term interface"""
class IThesaurusLoaderTerm(Interface):
"""Marker interface for temporary thesaurus loader terms"""
IThesaurusTermInfo['generic'].schema = IThesaurusTerm
IThesaurusTermInfo['usage'].schema = IThesaurusTerm
IThesaurusTermInfo['parent'].schema = IThesaurusTerm
class IThesaurusTermsIterable(Interface):
"""Thesaurus terms iterator interface"""
def iterkeys(self):
"Iterate over keys; equivalent to __iter__"
def itervalues(self):
"Iterate over values"
def iteritems(self):
"Iterate over items"
class IThesaurusTermsContainer(IContainer, IThesaurusTermsIterable):
"""Thesaurus terms container interface""" | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/interfaces/term.py | term.py |
# import standard packages
# import Zope3 interfaces
from zope.catalog.interfaces import ICatalog
from zope.container.interfaces import IContainer
# import local interfaces
from ztfy.security.interfaces import ILocalRoleManager
from ztfy.thesaurus.interfaces.term import IThesaurusTerm
# import Zope3 packages
from zope.container.constraints import contains
from zope.interface import Interface, Attribute
from zope.location.interfaces import IContained
from zope.schema import Text, TextLine, Choice, Object, List, Date
from ztfy.security.schema import PrincipalList
# import local packages
from ztfy.utils.schema import ColorField
from ztfy.thesaurus import _
class IThesaurusInfoBase(Interface):
"""Thesaurus base info"""
title = TextLine(title=_("thesaurus-title-title", "Title"),
description=_("thesaurus-title-description", "Long title for thie thesaurus"),
required=False)
subject = TextLine(title=_("thesaurus-subject-title", "Subject"),
required=False)
description = Text(title=_("thesaurus-description-title", "Description"),
required=False)
language = Choice(title=_("thesaurus-language-title", "Language"),
description=_("thesaurus-language-description", "Thesaurus's language"),
required=False,
default='fr',
vocabulary='ZTFY base languages')
creator = TextLine(title=_("thesaurus-creator-title", "Creator"),
required=False)
publisher = TextLine(title=_("thesaurus-publisher-title", "Publisher"),
required=False)
created = Date(title=_("thesaurus-created-title", "Creation date"),
required=False)
class IThesaurusInfo(IThesaurusInfoBase):
"""Main thesaurus infos"""
name = TextLine(title=_("thesaurus-name-title", "Name"),
description=_("thesaurus-name-description", "Thesaurus's name"),
required=True,
readonly=True)
terms = Attribute(_("thesaurus-terms-title", "Thesaurus terms"))
catalog = Object(title=_("thesaurus-catalog-title", "Thesaurus catalog"),
description=_("thesaurus-catalog-description",
"Inner thesaurus catalog, used for full-text indexing"),
schema=ICatalog)
def findTerms(self, query=None, extract=None, autoexpand='on_miss', glob='end', limit=None,
exact=False, exact_only=False, stemmed=False):
"""Get terms matching given query and parent
@param query: the text query
@param autoexpand: can be True, False on 'on_miss' (default)
@param glob: can be 'start' (default), 'end', 'both' or None
"""
class IThesaurusContentInfo(Interface):
"""Thesaurus content infos"""
top_terms = List(title=_("thesaurus-topterms-title", "Thesaurus top-terms"),
description=_("thesaurus-topterms-description",
"List of top thesaurus terms, placed at first level"),
required=False,
value_type=Object(schema=IThesaurusTerm))
class IThesaurusWriter(Interface):
"""Thesaurus update interface"""
def initCatalog(self):
"""Initialize thesaurus catalog"""
def delete(self):
"""Delete thesaurus"""
class IThesaurusContentWriter(Interface):
"""Thesaurus content update interface"""
def clear(self):
"""Clear thesaurus contents"""
def load(self, configuration):
"""Load contents from given configuration"""
def merge(self, configuration, thesaurus=None):
"""Merge current thesaurus with another one for given configuration"""
def resetTermsParent(self):
"""Reset thesaurus terms parent attribute"""
def resetTopTerms(self):
"""Reset thesaurus top terms"""
class IThesaurusAdminRole(Interface):
"""Thesaurus administrators roles interface"""
administrators = PrincipalList(title=_("Administrators"),
description=_("List of thesaurus's administrators"),
required=False)
class IThesaurusContribRole(Interface):
"""Thesaurus administrators roles interface"""
contributors = PrincipalList(title=_("Contents managers"),
description=_("List of thesaurus's contents contributors"),
required=False)
class IThesaurusRoles(IThesaurusAdminRole, IThesaurusContribRole):
"""Thesaurus roles interface"""
class IThesaurus(IThesaurusInfo, IThesaurusContentInfo, IThesaurusWriter, IThesaurusContentWriter,
IThesaurusRoles, IContained, ILocalRoleManager):
"""Thesaurus interface"""
class IThesaurusManagerTarget(Interface):
"""Marker interface for contents managing thesaurus"""
class IThesaurusTarget(Interface):
"""Marker interface for contents indexed on a thesaurus base"""
class IThesaurusExtractBaseInfo(Interface):
"""Thesaurus extract base info"""
name = TextLine(title=_("extract-title-title", "Extract name"),
description=_("extract-title-description", "Extract title"),
required=True)
description = Text(title=_("extract-description-title", "Description"),
required=False)
abbreviation = TextLine(title=_("extract-abbr-title", "Abbreviation"),
description=_("extract-abbr-description",
"Short abbreviation used to distinguish the extract"),
required=True,
max_length=3)
color = ColorField(title=_("Extract color"),
description=_("A color associated with this extract"),
required=True)
managers = PrincipalList(title=_("Extract managers"),
description=_("List of principals which can manage extract contents"),
required=False)
class IThesaurusExtractWriter(Interface):
"""Thesaurus extract writer"""
def addTerm(self, term):
"""Add a term to this extract"""
def removeTerm(self, term):
"""Remove a term from this extract"""
class IThesaurusExtractInfo(IThesaurusExtractBaseInfo, IThesaurusExtractWriter, ILocalRoleManager):
"""Thesaurus extract info"""
class IThesaurusExtracts(IContainer):
"""Thesaurus extracts container interface"""
contains(IThesaurusExtractInfo) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/interfaces/thesaurus.py | thesaurus.py |
# import standard packages
import chardet
from lxml import etree
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
# import local packages
from ztfy.thesaurus.loader import XMLThesaurusLoaderHandler, BaseThesaurusLoader, \
ThesaurusLoaderTerm, ThesaurusLoaderDescription, \
XMLThesaurusExporterHandler, BaseThesaurusExporter
from ztfy.utils.request import queryRequest
from zope.traversing.browser.absoluteurl import absoluteURL
# Namespaces definitions
XML = '{http://www.w3.org/XML/1998/namespace}'
RDF = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
RDFS = '{http://www.w3.org/2000/01/rdf-schema#}'
DC = '{http://purl.org/dc/elements/1.1/}'
DCT = '{http://purl.org/dc/terms/}'
MAP = '{http://www.w3c.rl.ac.uk/2003/11/21-skos-mapping#}'
SKOS = '{http://www.w3.org/2004/02/skos/core#}'
class SKOSThesaurusLoaderHandler(XMLThesaurusLoaderHandler):
"""SKOS format thesaurus handler"""
def read(self, data, configuration=None):
terms = {}
if configuration is None:
configuration = self.configuration
encoding = None
if configuration and configuration.encoding:
encoding = configuration.encoding
if (not encoding) and isinstance(data, (str, unicode)):
encoding = chardet.detect(data[:1000]).get('encoding', 'utf-8')
parser = etree.XMLParser(ns_clean=True, recover=True, encoding=encoding)
xml = etree.parse(data, parser=parser)
root = xml.getroot()
# check thesaurus scheme
description = ThesaurusLoaderDescription()
scheme = root.find('.//' + SKOS + 'ConceptScheme')
if scheme is not None:
for element in scheme.getchildren():
if element.tag == DC + 'title':
description.title = unicode(element.text)
elif element.tag == DC + 'creator':
description.creator = unicode(element.text)
elif element.tag == DC + 'subject':
description.subject = unicode(element.text)
elif element.tag == DC + 'description':
description.description = unicode(element.text)
elif element.tag == DC + 'publisher':
description.publisher = unicode(element.text)
elif element.tag == DC + 'date':
description.created = unicode(element.text)
elif element.tag == DC + 'language':
description.language = element.text
if configuration and not description.language:
description.language = configuration.language
# check thesaurus terms
for concept in root.findall(SKOS + 'Concept'):
key = concept.attrib.get(RDF + 'about')
label = None
alt = None
definition = None
note = None
generic = None
specifics = []
associations = []
usage = None
used_for = []
created = None
modified = None
for element in concept.getchildren():
if element.tag == SKOS + 'prefLabel':
label = unicode(element.text)
elif element.tag == SKOS + 'altLabel':
term = element.attrib.get(RDF + 'resource')
if term is not None:
# import synonyms ?
if not configuration.import_synonyms:
continue
# link to another synonym resource
used_for.append(term)
if term not in terms:
# initialize synonym with usage field
terms[term] = ThesaurusLoaderTerm(term, alt=u'', definition=u'', note=u'', generic=u'', specifics=u'',
associations=u'', usage=key, used_for=[])
else:
terms[term].usage = key
else:
# just an alternate label
alt = unicode(element.text)
elif element.tag == SKOS + 'definition':
definition = unicode(element.text)
elif element.tag in (SKOS + 'note', SKOS + 'scopeNote'):
note = unicode(element.text)
elif element.tag == SKOS + 'related':
associations.append(element.attrib[RDF + 'resource'])
elif element.tag == SKOS + 'broader':
generic = element.attrib[RDF + 'resource']
elif element.tag == SKOS + 'narrower':
specifics.append(element.attrib[RDF + 'resource'])
elif element.tag == DCT + 'created':
created = element.text
if key not in terms:
terms[key] = ThesaurusLoaderTerm(label, alt, definition, note, generic, specifics,
associations, usage, used_for, created, modified)
else:
# update an already initialized synonym
term = terms[key]
term.label = label
term.alt = alt
term.definition = definition
term.note = note
term.generic = generic
term.specifics = specifics
term.associations = associations
term.usage = usage
term.used_for = used_for
term.created = created
term.modified = modified
return description, terms
class SKOSThesaurusLoader(BaseThesaurusLoader):
"""SKOS format thesaurus loader"""
handler = SKOSThesaurusLoaderHandler
class SKOSThesaurusExporterHandler(XMLThesaurusExporterHandler):
"""SKOS/RDF format thesaurus export handler"""
def _write(self, thesaurus, configuration=None):
request = queryRequest()
thesaurus_url = absoluteURL(thesaurus, request)
nsmap = { 'rdf': RDF[1:-1],
'rdfs': RDFS[1:-1],
'dc': DC[1:-1],
'dct': DCT[1:-1],
'map': MAP[1:-1],
'skos': SKOS[1:-1] }
xml = etree.Element(RDF + 'RDF', nsmap=nsmap)
doc = etree.ElementTree(xml)
cs = etree.SubElement(xml, SKOS + 'ConceptScheme')
cs.attrib[RDF + 'about'] = thesaurus_url
etree.SubElement(cs, DC + 'title').text = thesaurus.title
etree.SubElement(cs, DC + 'creator').text = thesaurus.creator
etree.SubElement(cs, DC + 'subject').text = thesaurus.subject
if thesaurus.description:
etree.SubElement(cs, DC + 'description').text = etree.CDATA(thesaurus.description)
etree.SubElement(cs, DC + 'publisher').text = thesaurus.publisher
etree.SubElement(cs, DC + 'date').text = thesaurus.created.strftime('%Y-%m-%d')
etree.SubElement(cs, DC + 'language').text = thesaurus.language
extract = configuration and configuration.extract or None
for term in thesaurus.top_terms:
if extract and (extract not in (term.extracts or ())):
continue
etree.SubElement(cs, SKOS + 'hasTopConcept').attrib[RDF + 'resource'] = absoluteURL(term, request)
for term in thesaurus.terms.itervalues():
if extract and (extract not in (term.extracts or ())):
continue
concept = etree.SubElement(xml, SKOS + 'Concept')
concept.attrib[RDF + 'about'] = absoluteURL(term, request)
sub = etree.SubElement(concept, SKOS + 'prefLabel')
sub.attrib[XML + 'lang'] = thesaurus.language
sub.text = term.label
etree.SubElement(concept, SKOS + 'inScheme').attrib[RDF + 'resource'] = thesaurus_url
if term.definition:
sub = etree.SubElement(concept, SKOS + 'definition')
sub.attrib[XML + 'lang'] = thesaurus.language
sub.text = term.definition
if term.note:
sub = etree.SubElement(concept, SKOS + 'scopeNote')
sub.attrib[XML + 'lang'] = thesaurus.language
sub.text = etree.CDATA(term.note)
for subterm in term.associations:
if extract and (extract not in (subterm.extracts or ())):
continue
etree.SubElement(concept, SKOS + 'related').attrib[RDF + 'resource'] = absoluteURL(subterm, request)
if term.generic:
etree.SubElement(concept, SKOS + 'broader').attrib[RDF + 'resource'] = absoluteURL(term.generic, request)
for subterm in term.used_for:
if extract and (extract not in (subterm.extracts or ())):
continue
etree.SubElement(concept, SKOS + 'altLabel').attrib[RDF + 'resource'] = absoluteURL(subterm, request)
for subterm in term.specifics:
if extract and (extract not in (subterm.extracts or ())):
continue
etree.SubElement(concept, SKOS + 'narrower').attrib[RDF + 'resource'] = absoluteURL(subterm, request)
if term.created:
etree.SubElement(concept, DCT + 'created').text = term.created.strftime('%Y-%m-%d %H:%M:%S')
return doc
class SKOSThesaurusExporter(BaseThesaurusExporter):
"""SKOS/RDF format thesaurus exporter"""
handler = SKOSThesaurusExporterHandler | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/loader/skos.py | skos.py |
# import standard packages
# import Zope3 interfaces
# import local interfaces
from ztfy.thesaurus.interfaces.loader import IThesaurusLoaderConfiguration, IThesaurusUpdaterConfiguration, \
IThesaurusExporterConfiguration
# import Zope3 packages
from zope.interface import implements
from zope.schema.fieldproperty import FieldProperty
# import local packages
class ThesaurusLoaderConfiguration(object):
"""Thesaurus loader configuration"""
implements(IThesaurusLoaderConfiguration)
name = FieldProperty(IThesaurusLoaderConfiguration['name'])
data = FieldProperty(IThesaurusLoaderConfiguration['data'])
format = FieldProperty(IThesaurusLoaderConfiguration['format'])
import_synonyms = FieldProperty(IThesaurusLoaderConfiguration['import_synonyms'])
language = FieldProperty(IThesaurusLoaderConfiguration['language'])
encoding = FieldProperty(IThesaurusLoaderConfiguration['encoding'])
def __init__(self, data={}):
if data:
name = data.get('name')
if name:
self.name = name
self.data = data.get('data')
self.format = data.get('format')
self.import_synonyms = data.get('import_synonyms')
self.language = data.get('language')
self.encoding = data.get('encoding')
class ThesaurusUpdaterConfiguration(ThesaurusLoaderConfiguration):
"""Thesaurus updater configuration"""
implements(IThesaurusUpdaterConfiguration)
clear = FieldProperty(IThesaurusUpdaterConfiguration['clear'])
conflict_suffix = FieldProperty(IThesaurusUpdaterConfiguration['conflict_suffix'])
def __init__(self, data={}):
super(ThesaurusUpdaterConfiguration, self).__init__(data)
if data:
self.clear = data.get('clear')
self.conflict_suffix = data.get('conflict_suffix')
class ThesaurusExporterConfiguration(object):
"""Thesaurus exporter configuration"""
implements(IThesaurusExporterConfiguration)
filename = FieldProperty(IThesaurusExporterConfiguration['filename'])
format = FieldProperty(IThesaurusExporterConfiguration['format'])
extract = FieldProperty(IThesaurusExporterConfiguration['extract'])
def __init__(self, data={}):
if data:
self.filename = data.get('filename')
self.format = data.get('format')
self.extract = data.get('extract') | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/loader/config.py | config.py |
# import standard packages
from BTrees.OOBTree import OOBTree
from datetime import datetime
from tempfile import TemporaryFile
# import Zope3 interfaces
# import local interfaces
from ztfy.thesaurus.interfaces.loader import IThesaurusLoader, IThesaurusLoaderHandler, \
IThesaurusExporter, IThesaurusExporterHandler
from ztfy.thesaurus.interfaces.term import IThesaurusLoaderTerm
from ztfy.thesaurus.interfaces.thesaurus import IThesaurusInfoBase
# import Zope3 packages
from zope.interface import implements, alsoProvides
from zope.publisher.browser import FileUpload
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.thesaurus.term import ThesaurusTerm
from ztfy.thesaurus.thesaurus import Thesaurus, ThesaurusTermsContainer
from ztfy.utils.request import getRequest
from ztfy.utils.unicode import translateString
class ThesaurusLoaderDescription(object):
"""Thesaurus loader description"""
implements(IThesaurusInfoBase)
title = FieldProperty(IThesaurusInfoBase['title'])
subject = FieldProperty(IThesaurusInfoBase['subject'])
description = FieldProperty(IThesaurusInfoBase['description'])
creator = FieldProperty(IThesaurusInfoBase['creator'])
publisher = FieldProperty(IThesaurusInfoBase['publisher'])
_created = FieldProperty(IThesaurusInfoBase['created'])
language = FieldProperty(IThesaurusInfoBase['language'])
@property
def created(self):
return self._created
@created.setter
def created(self, value):
if isinstance(value, (str, unicode)):
try:
value = datetime.strptime(value, '%Y-%m-%d').date()
except ValueError:
value = datetime.today().date()
self._created = value
class ThesaurusLoaderTerm(object):
"""Base thesaurus loader term"""
def __init__(self, label, alt=None, definition=None, note=None, generic=None, specifics=None,
associations=None, usage=None, used_for=None, created=None, modified=None, weight=0, properties=None):
self.label = label
self.alt = alt
self.definition = definition
self.note = note
self.generic = generic
self.specifics = specifics or []
self.associations = associations or []
self.usage = usage
self.used_for = used_for or []
self.created = created
self.modified = modified
self.weight = int(weight)
self.properties = properties or {}
class BaseThesaurusLoaderHandler(object):
"""Base thesaurus loader handler"""
implements(IThesaurusLoaderHandler)
def __init__(self, configuration):
self.configuration = configuration
class XMLThesaurusLoaderHandler(BaseThesaurusLoaderHandler):
"""Base XML thesaurus loader handler"""
class BaseThesaurusLoader(object):
"""Base thesaurus loader"""
implements(IThesaurusLoader)
handler = None
def load(self, data, configuration=None):
handler = self.handler(configuration)
if isinstance(data, tuple):
data = data[0]
if isinstance(data, (file, FileUpload)):
data.seek(0)
description, terms = handler.read(data)
key_store = OOBTree()
store = ThesaurusTermsContainer()
# first loop to initialize terms
for key, term in terms.iteritems():
key_store[key] = store[term.label] = ThesaurusTerm(label=term.label, alt=term.alt, definition=term.definition, note=term.note,
created=term.created, modified=term.modified)
# second loop to update terms links
for key, term in terms.iteritems():
new_term = key_store[key]
if term.generic:
target = key_store.get(term.generic)
if target is None:
target = ThesaurusTerm(label=term.generic)
alsoProvides(target, IThesaurusLoaderTerm)
key_store[target.label] = store[target.label] = target
new_term.generic = target
if term.specifics:
for specific in term.specifics:
if key_store.get(specific) is None:
target = ThesaurusTerm(label=specific)
alsoProvides(target, IThesaurusLoaderTerm)
key_store[target.label] = store[target.label] = target
new_term.specifics = [key_store.get(specific) for specific in term.specifics]
for subterm in new_term.specifics:
subterm.generic = new_term
if term.associations:
for association in term.associations:
if key_store.get(association) is None:
target = ThesaurusTerm(label=association)
alsoProvides(target, IThesaurusLoaderTerm)
key_store[target.label] = store[target.label] = target
new_term.associations = [key_store.get(association) for association in term.associations]
if term.usage:
target = key_store.get(term.usage)
if target is None:
target = ThesaurusTerm(label=term.usage)
alsoProvides(target, IThesaurusLoaderTerm)
key_store[target.label] = store[target.label] = target
new_term.usage = target
target.used_for = set(target.used_for) | set((new_term,))
if term.used_for:
for used in term.used_for:
if key_store.get(used) is None:
target = ThesaurusTerm(label=used)
alsoProvides(target, IThesaurusLoaderTerm)
key_store[target.label] = store[target.label] = target
new_term.used_for = [key_store.get(used) for used in term.used_for]
for synonym in new_term.used_for:
synonym.usage = new_term
return Thesaurus(description=description, terms=store)
class BaseThesaurusExporterHandler(object):
"""Base thesaurus exporter handler"""
implements(IThesaurusExporterHandler)
def __init__(self, configuration):
self.configuration = configuration
class XMLThesaurusExporterHandler(BaseThesaurusExporterHandler):
"""Base XML thesaurus export handler"""
def _write(self, thesaurus, configuration=None):
raise NotImplementedError
def write(self, thesaurus, output, configuration=None):
doc = self._write(thesaurus, configuration)
doc.write(output, encoding='utf-8', xml_declaration=True, standalone=True, pretty_print=True)
return { 'Content-Type': 'text/xml; encoding=utf-8' }
class BaseThesaurusExporter(object):
"""Base thesaurus exporter"""
implements(IThesaurusExporter)
handler = None
def export(self, thesaurus, configuration=None):
handler = self.handler(configuration)
output = TemporaryFile()
result = handler.write(thesaurus, output, configuration)
request = getRequest()
if request is not None:
request.response.setHeader('Content-Type', result.get('Content-Type', 'text/plain'))
filename = translateString(configuration.filename or (thesaurus.name + '.xml'),
escapeSlashes=True, forceLower=False, spaces='-')
request.response.setHeader('Content-Disposition', 'attachment; filename="%s"' % filename)
return output | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/loader/__init__.py | __init__.py |
# import standard packages
import chardet
from datetime import datetime
from lxml import etree
# import Zope3 interfaces
from zope.intid.interfaces import IIntIds
# import local interfaces
# import Zope3 packages
from zope.component import getUtility
# import local packages
from ztfy.thesaurus.loader import BaseThesaurusLoader, XMLThesaurusLoaderHandler, \
BaseThesaurusExporter, XMLThesaurusExporterHandler, \
ThesaurusLoaderDescription, ThesaurusLoaderTerm
# namespaces definitions
INM = "{http://www.inmagic.com/webpublisher/query}"
class SuperdocThesaurusLoaderHandler(XMLThesaurusLoaderHandler):
"""SuperDoc format thesaurus load handler"""
def read(self, data, configuration=None):
terms = {}
if configuration is None:
configuration = self.configuration
encoding = None
if configuration and configuration.encoding:
encoding = configuration.encoding
if (not encoding) and isinstance(data, (str, unicode)):
encoding = chardet.detect(data[:1000]).get('encoding', 'utf-8')
parser = etree.XMLParser(ns_clean=True, recover=True, encoding=encoding)
xml = etree.parse(data, parser=parser)
root = xml.getroot()
# get thesaurus description
description = ThesaurusLoaderDescription()
# check thesaurus terms
for records in root.findall(INM + 'Recordset'):
for record in records.findall(INM + 'Record'):
key = None
label = None
alt = None
definition = None
note = None
generic = None
specifics = []
associations = []
usage = None
used_for = []
created = None
modified = None
for element in record.getchildren():
if element.text:
if element.tag == INM + 'Terme':
key = label = unicode(element.text)
elif element.tag == INM + 'NA':
definition = unicode(element.text)
elif element.tag == INM + 'TS':
specifics.append(unicode(element.text))
elif element.tag == INM + 'TG':
generic = unicode(element.text)
elif element.tag == INM + 'TA':
associations.append(unicode(element.text))
elif element.tag == INM + 'EM':
if configuration.import_synonyms:
usage = unicode(element.text)
elif element.tag == INM + 'EP':
if configuration.import_synonyms:
used_for.append(unicode(element.text))
elif element.tag == INM + 'Notes':
note = unicode(element.text)
elif element.tag == INM + 'DateCreation':
created = datetime.strptime(element.text, '%d/%m/%Y')
elif element.tag == INM + 'DateModification':
modified = datetime.strptime(element.text, '%d/%m/%Y')
if key:
terms[key] = ThesaurusLoaderTerm(label, alt, definition, note, generic, specifics,
associations, usage, used_for, created, modified)
return description, terms
class SuperdocThesaurusLoader(BaseThesaurusLoader):
"""SuperDoc export format thesaurus loader"""
handler = SuperdocThesaurusLoaderHandler
class SuperdocThesaurusExporterHandler(XMLThesaurusExporterHandler):
"""SuperDoc format thesaurus export handler"""
def _write(self, thesaurus, configuration=None):
intids = getUtility(IIntIds)
xml = etree.Element('Results', nsmap={ None: INM[1:-1] },
productTitle=u'ONF Thesaurus Manager', productVersion=u'0.1')
doc = etree.ElementTree(xml)
extract = configuration and configuration.extract or None
if extract:
terms = [ term for term in thesaurus.terms.itervalues() if extract in (term.extracts or set()) ]
else:
terms = thesaurus.terms
rs = etree.SubElement(xml, u'Recordset', setCount=str(len(terms)))
for index, term in enumerate(thesaurus.terms.itervalues()):
if extract and (extract not in (term.extracts or set())):
continue
rec = etree.SubElement(rs, u'Record', setEntry=str(index))
etree.SubElement(rec, u'ID').text = str(intids.queryId(term))
etree.SubElement(rec, u'Terme').text = term.label
etree.SubElement(rec, u'NA').text = term.note
added_subterms = False
if term.specifics:
for subterm in term.specifics:
if extract and (extract not in (subterm.extracts or ())):
continue
etree.SubElement(rec, u'TS').text = subterm.label
added_subterms = True
if not added_subterms:
etree.SubElement(rec, u'TS')
sub = etree.SubElement(rec, u'TG')
if term.generic:
sub.text = term.generic.label
added_subterms = False
if term.associations:
for subterm in term.associations:
if extract and (extract not in (subterm.extracts or ())):
continue
etree.SubElement(rec, u'TA').text = subterm.label
added_subterms = True
if not added_subterms:
etree.SubElement(rec, u'TA')
sub = etree.SubElement(rec, u'EM')
if term.usage:
sub.text = term.usage.label
added_subterms = False
if term.used_for:
for subterm in term.used_for:
if extract and (extract not in (subterm.extracts or ())):
continue
etree.SubElement(rec, u'EP').text = subterm.label
added_subterms = True
if not added_subterms:
etree.SubElement(rec, u'EP')
etree.SubElement(rec, u'Notes').text = term.definition
etree.SubElement(rec, u'Status').text = term.status
etree.SubElement(rec, u'DateCreation').text = term.created and term.created.strftime('%d/%m/%Y') or u''
etree.SubElement(rec, u'DateModification').text = term.modified and term.modified.strftime('%d/%m/%Y') or u''
etree.SubElement(rec, u'Niveau').text = str(term.level)
etree.SubElement(rec, u'MicroThes').text = term.micro_thesaurus and u'OUI' or u'NON'
etree.SubElement(rec, u'Terme0').text = (term.parent is None) and term.label or term.parent.label
return doc
class SuperdocThesaurusExporter(BaseThesaurusExporter):
"""SuperDoc format thesaurus exporter"""
handler = SuperdocThesaurusExporterHandler | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/loader/superdoc.py | superdoc.py |
# import standard packages
from HTMLParser import HTMLParser
# import Zope3 interfaces
from z3c.json.interfaces import IJSONWriter
from zope.publisher.interfaces import NotFound
# import local interfaces
from ztfy.thesaurus.browser.interfaces import IThesaurusView
from ztfy.thesaurus.browser.interfaces.term import IThesaurusTermAddFormMenuTarget
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus, IThesaurusExtracts
from ztfy.thesaurus.interfaces.tree import ITree, INode
# import Zope3 packages
from z3c.form import field, button
from z3c.formjs import ajax, jsaction
from zope.component import getUtility
from zope.i18n import translate
from zope.interface import implements, Interface
from zope.traversing.api import getName
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.i18n.property import translated
from ztfy.jqueryui import jquery_datetime, jquery_multiselect
from ztfy.skin.form import DialogDisplayForm, DialogEditForm
from ztfy.skin.menu import MenuItem
from ztfy.skin.page import BaseBackView, BaseTemplateBasedPage, TemplateBasedPage
from ztfy.thesaurus.browser import ztfy_thesaurus
from ztfy.utils.property import cached_property
from ztfy.utils.traversing import getParent
from ztfy.thesaurus import _
class ThesaurusTermsTreeViewMenuItem(MenuItem):
"""Thesaurus tree view menu item"""
title = _("Terms")
class ThesaurusTermsTreeView(BaseBackView, TemplateBasedPage, ajax.AJAXRequestHandler):
"""Thesaurus tree view"""
implements(IThesaurusView, IThesaurusTermAddFormMenuTarget)
legend = _("Thesaurus terms")
_parser = HTMLParser()
@property
def title(self):
return self.context.title
def update(self):
BaseBackView.update(self)
def render(self):
jquery_datetime.need()
jquery_multiselect.need()
ztfy_thesaurus.need()
return super(ThesaurusTermsTreeView, self).render()
output = render
@cached_property
def extracts(self):
return IThesaurusExtracts(self.context)
@property
def tree(self):
return sorted([INode(node) for node in ITree(self.context).getRootNodes()],
key=lambda x: x.label)
def _getNodes(self, term, result, subnodes=None):
extracts_container = IThesaurusExtracts(getParent(term, IThesaurus))
for child in INode(term).getChildren():
node = INode(child)
result.append({ 'label': node.label.replace("'", "'"),
'cssClass': node.cssClass,
'extracts': [ { 'name': name,
'title': extract.name,
'color': extract.color,
'used': name in (node.context.extracts or ()) } for name, extract in extracts_container.items() ],
'extensions': [ { 'title': translate(ext.label, context=self.request),
'icon': ext.icon,
'view': "%s/%s" % (absoluteURL(node.context, self.request),
ext.target_view) } for ext in node.context.queryExtensions() ],
'expand': node.hasChildren() })
if subnodes and (node.context.label in subnodes):
nodes = result[-1]['subnodes'] = []
self._getNodes(node.context, nodes, subnodes)
@ajax.handler
def getNodes(self):
label = self.request.form.get('term')
if label:
label = self._parser.unescape(label)
term = self.context.terms.get(label)
if term is None:
raise NotFound(self.context, label, self.request)
result = []
self._getNodes(term, result)
writer = getUtility(IJSONWriter)
return writer.write({ 'status': 'OK',
'term': label,
'nodes': sorted(result, key=lambda x: x['label']) })
@ajax.handler
def getParentNodes(self):
label = self.request.form.get('term')
if label:
label = self._parser.unescape(label)
term = self.context.terms.get(label)
if term is None:
raise NotFound(self.context, label, self.request)
if term.usage is not None:
term = term.usage
result = []
writer = getUtility(IJSONWriter)
parents = list(reversed(term.getParents()))
if parents:
self._getNodes(parents[0], result, [ t.label for t in parents ])
return writer.write({ 'status': 'OK',
'parent': parents[0].label,
'term': term.label,
'nodes': result })
else:
return writer.write({ 'status': 'OK',
'parent': term.label,
'term': term.label,
'nodes': result })
@ajax.handler
def switchExtract(self):
label = self.request.form.get('term')
if label:
label = self._parser.unescape(label)
term = self.context.terms.get(label)
if term is None:
raise NotFound(self.context, label, self.request)
name = self.request.form.get('extract')
if name is None:
raise NotFound(self.context, name, self.request)
extract = self.extracts.get(name)
if extract is None:
raise NotFound(self.context, name, self.request)
writer = getUtility(IJSONWriter)
if name in (term.extracts or set()):
extract.removeTerm(term)
return writer.write({ 'term': term.label,
'extract': name,
'used': False,
'color': 'white' })
else:
extract.addTerm(term)
return writer.write({ 'term': term.label,
'extract': name,
'used': True,
'color': extract.color })
class ThesaurusExtractTermsTreeView(DialogDisplayForm):
"""Thesaurus extract terms tree view"""
_parser = HTMLParser()
@property
def title(self):
return self.thesaurus.title
@property
def legend(self):
return translate(_("Terms for selected extract: %s"), context=self.request) % self.context.name
def update(self):
BaseBackView.update(self)
self.updateActions()
def render(self):
jquery_datetime.need()
jquery_multiselect.need()
ztfy_thesaurus.need()
return super(ThesaurusExtractTermsTreeView, self).render()
output = render
@cached_property
def thesaurus(self):
return getParent(self.context, IThesaurus)
@property
def tree(self):
extract = getName(self.context)
return sorted([INode(node) for node in ITree(self.thesaurus).getRootNodes()
if extract in (node.extracts or ()) ],
key=lambda x: x.label)
@ajax.handler
def getNodes(self):
label = self.request.form.get('term')
if label:
label = self._parser.unescape(label)
extract_only = getName(self.context)
term = self.thesaurus.terms.get(label)
if term is None:
raise NotFound(self.context, label, self.request)
result = []
for child in INode(term).getChildren():
node = INode(child)
if extract_only in (node.context.extracts or ()):
result.append({ 'label': node.label.replace("'", "'"),
'cssClass': node.cssClass,
'extracts': [],
'expand': node.hasChildren() })
writer = getUtility(IJSONWriter)
return writer.write({ 'term': term.label,
'nodes': sorted(result, key=lambda x: x['label']) })
#
# Thesaurus terms selector
#
class ISelectorDialogFormButtons(Interface):
"""Terms selector dialog form buttons"""
select = jsaction.JSButton(title=_("Select terms"))
cancel = jsaction.JSButton(title=_("Cancel"))
class ThesaurusTermsSelectorView(DialogEditForm):
"""Thesaurus terms selector tree view"""
fields = field.Fields(Interface)
buttons = button.Buttons(ISelectorDialogFormButtons)
@property
def title(self):
return self.context.title
@translated
def legend(self):
return _("Thesaurus terms selection")
@cached_property
def thesaurus(self):
return getParent(self.context, IThesaurus)
@property
def top_terms(self):
extract = self.request.form.get('extract')
return sorted([term for term in self.context.top_terms
if (not extract) or (extract in term.extracts) ],
key=lambda x: x.label)
@jsaction.handler(buttons['select'])
def add_handler(self, event, selector):
return '$.ZTFY.thesaurus.tree.openSelectorAction(this.form);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
class ThesaurusTermsSelectorNodeView(BaseTemplateBasedPage):
"""Thesaurus terms selector node view"""
@property
def sub_terms(self):
extract = self.request.form.get('extract')
return sorted([term for term in self.context.specifics
if (not extract) or (extract in term.extracts) ],
key=lambda x: x.label) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/tree.py | tree.py |
# import standard packages
# import Zope3 interfaces
from z3c.form.interfaces import DISPLAY_MODE, IErrorViewSnippet
# import local interfaces
from ztfy.thesaurus.interfaces.term import IThesaurusTermInfo
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus
# import Zope3 packages
from z3c.form import field
from zope.component import getMultiAdapter
from zope.interface import Invalid
from zope.security.proxy import removeSecurityProxy
from zope.traversing import api as traversing_api
# import local packages
from ztfy.skin.form import DialogAddForm, DialogEditForm
from ztfy.skin.menu import DialogMenuItem
from ztfy.thesaurus.browser.tree import ThesaurusTermsTreeView
from ztfy.thesaurus.term import ThesaurusTerm
from ztfy.utils.request import setRequestData, getRequestData
from ztfy.utils.traversing import getParent
from ztfy.thesaurus import _
class ThesaurusTermAddForm(DialogAddForm):
"""Thesaurus term add form"""
fields = field.Fields(IThesaurusTermInfo).select('label', 'alt', 'definition', 'note',
'generic', 'associations', 'usage',
'extensions', 'status', 'created')
legend = _("Add new term")
parent_interface = IThesaurus
parent_view = ThesaurusTermsTreeView
@property
def title(self):
return getParent(self.context, IThesaurus).title
def extractData(self, setErrors=True):
data, errors = super(ThesaurusTermAddForm, self).extractData(setErrors=setErrors)
if data.get('label') in IThesaurus(self.context).terms:
error = Invalid(_("New label already in use"))
widget = self.widgets['label']
view = getMultiAdapter((error, self.request, widget, widget.field, self, self.context),
IErrorViewSnippet)
view.update()
errors += (view,)
if setErrors:
widget.error = view
self.widgets.errors = errors
return data, errors
def create(self, data):
result = ThesaurusTerm(data.get('label'))
setRequestData('thesaurus.new_term', result, self.request)
return result
def add(self, term):
thesaurus = IThesaurus(self.context)
thesaurus.terms[term.label] = term
def updateContent(self, term, data):
super(ThesaurusTermAddForm, self).updateContent(term, data)
generic = term.generic
usage = term.usage
if (generic is None) and (usage is None):
thesaurus = IThesaurus(self.context)
thesaurus.top_terms = thesaurus.top_terms + [term, ]
else:
if generic is not None:
generic.specifics = generic.specifics + [term, ]
elif usage is not None:
usage.used_for = usage.used_for + [term, ]
def getOutput(self, writer, parent):
term = getRequestData('thesaurus.new_term', self.request)
if (term is None) or not term.generic:
return writer.write({ 'output': u'RELOAD' })
else:
return writer.write({ 'output': u'CALLBACK',
'callback': '$.ZTFY.thesaurus.tree.reloadTerm',
'options': { 'source': term.generic.label.replace("'", "'") } })
class ThesaurusTermAddMenuItem(DialogMenuItem):
"""Thesaurus term add menu item"""
title = _(":: Add term...")
target = ThesaurusTermAddForm
class ThesaurusTermEditForm(DialogEditForm):
"""Thesaurus term edit form"""
fields = field.Fields(IThesaurusTermInfo).select('label', 'alt', 'definition', 'note',
'generic', 'specifics', 'associations', 'usage', 'used_for',
'extracts', 'extensions', 'status', 'level',
'created', 'modified')
legend = _("Edit term properties")
parent_interface = IThesaurus
parent_view = ThesaurusTermsTreeView
@property
def title(self):
return getParent(self.context, IThesaurus).title
def updateWidgets(self):
super(ThesaurusTermEditForm, self).updateWidgets()
self.widgets['specifics'].mode = DISPLAY_MODE
self.widgets['used_for'].mode = DISPLAY_MODE
self.widgets['extracts'].mode = DISPLAY_MODE
self.widgets['created'].mode = DISPLAY_MODE
def extractData(self, setErrors=True):
data, errors = super(ThesaurusTermEditForm, self).extractData(setErrors=setErrors)
label = data.get('label')
if (label != self.context.label) and (data.get('label') in traversing_api.getParent(self.context)):
error = Invalid(_("New label already in use"))
widget = self.widgets['label']
view = getMultiAdapter((error, self.request, widget, widget.field, self, self.context),
IErrorViewSnippet)
view.update()
if setErrors:
widget.error = view
self.widgets.errors = errors
errors += (view,)
return data, errors
def applyChanges(self, data):
term = self.getContent()
thesaurus = getParent(term, IThesaurus)
old_label = term.label
old_generic = term.generic
old_usage = term.usage
changes = super(ThesaurusTermEditForm, self).applyChanges(data)
# Move term if label changed
# Don't use IObjectMover interface to avoid cataloging problems...
if 'label' in changes.get(IThesaurusTermInfo, []):
parent = traversing_api.getParent(term)
del parent[old_label]
parent[term.label] = term
# Check terms and thesaurus top terms if generic or usage changed
self._v_generic_changed = old_generic != term.generic
self._v_usage_changed = old_usage != term.usage
if self._v_generic_changed:
# Check previous value
if old_generic is not None:
# add a previous generic?
# remove term from list of previous generic's specifics
specifics = removeSecurityProxy(old_generic.specifics)
if term in specifics:
specifics.remove(term)
old_generic.specifics = specifics
else:
# didn't have a generic?
# may remove term from thesaurus top terms
top_terms = removeSecurityProxy(thesaurus.top_terms)
if term in top_terms:
top_terms.remove(term)
thesaurus.top_terms = top_terms
# Check new value
if term.generic is None:
# no generic and not a synonym?
# term should be added to thesaurus top terms
if (term.usage is None) and (term not in thesaurus.top_terms):
thesaurus.top_terms = thesaurus.top_terms + [term, ]
else:
# new generic ?
# add term to generic's specific terms
if term not in term.generic.specifics:
term.generic.specifics = term.generic.specifics + [term, ]
if self._v_usage_changed:
# Check previous value
if old_usage is not None:
# add a previous usage term?
used_for = removeSecurityProxy(old_usage.used_for)
if term in used_for:
used_for.remove(term)
old_usage.used_for = used_for
# Check new term usage
if term.usage is None:
# no usage? Maybe a top term...
if (term.generic is None) and (term not in thesaurus.top_terms):
thesaurus.top_terms = thesaurus.top_terms + [term, ]
else:
# term usage?
# remove term from top-terms...
top_terms = removeSecurityProxy(thesaurus.top_terms)
if term in top_terms:
top_terms.remove(term)
thesaurus.top_terms = top_terms
# add term to usage's synonyms
if term not in term.usage.used_for:
term.usage.used_for = term.usage.used_for + [term, ]
return changes
def getOutput(self, writer, parent, changes=()):
callback = None
options = None
if self._v_generic_changed:
status = u'RELOAD'
else:
term_changes = changes.get(IThesaurusTermInfo, [])
if ('label' in term_changes) or ('status' in term_changes):
term = self.getContent()
generic = term.generic
if generic is None:
status = u'RELOAD'
else:
status = u'CALLBACK'
callback = '$.ZTFY.thesaurus.tree.reloadTerm'
options = { 'source': generic.label.replace("'", "'"),
'status': term.status }
else:
status = changes and u'OK' or u'NONE'
return writer.write({ 'output': status,
'callback': callback,
'options': options }) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/term.py | term.py |
# import standard packages
import logging
logger = logging.getLogger('ztfy.thesaurus')
# import Zope3 interfaces
from z3c.form.interfaces import DISPLAY_MODE
from z3c.json.interfaces import IJSONWriter
from zope.copypastemove.interfaces import IObjectMover
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.schema.interfaces import IVocabularyFactory
from zope.size.interfaces import ISized
# import local interfaces
from ztfy.security.interfaces import ISecurityManager
from ztfy.skin.interfaces import IContainedDefaultView, IDefaultView
from ztfy.skin.interfaces.container import IContainerBaseView, ITitleColumn, IActionsColumn, \
IContainerTableViewTitleCell, IContainerTableViewActionsCell
from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer
from ztfy.thesaurus.browser.interfaces import IThesaurusView
from ztfy.thesaurus.browser.interfaces.thesaurus import IThesaurusAddFormMenuTarget, \
IThesaurusExtractAddFormMenuTarget
from ztfy.thesaurus.interfaces.loader import IThesaurusLoader, IThesaurusLoaderConfiguration, \
IThesaurusUpdaterConfiguration, \
IThesaurusExporter, IThesaurusExporterConfiguration
from ztfy.thesaurus.interfaces.thesaurus import IThesaurusInfoBase, IThesaurusInfo, \
IThesaurus, IThesaurusManagerTarget, \
IThesaurusRoles, \
IThesaurusExtracts, IThesaurusExtractBaseInfo, IThesaurusExtractInfo
# import Zope3 packages
from z3c.form import field, button
from z3c.form.browser.select import SelectWidget
from z3c.form.widget import FieldWidget
from z3c.formjs import ajax, jsaction
from z3c.table.column import Column
from z3c.template.template import getLayoutTemplate
from zope.component import adapts, getUtility, getSiteManager, queryUtility, queryMultiAdapter
from zope.dublincore.interfaces import IZopeDublinCore
from zope.i18n import translate
from zope.interface import implements, Interface
from zope.intid.interfaces import IIntIds
from zope.location import locate
from zope.schema import Bool
from zope.security.proxy import removeSecurityProxy
from zope.traversing import api as traversing_api
from zope.traversing.browser import absoluteURL
# import local packages
from ztfy.jqueryui import jquery_multiselect, jquery_colorpicker, jquery_datetime
from ztfy.security.browser.roles import RolesEditForm
from ztfy.skin.container import ContainerBaseView
from ztfy.skin.form import DialogAddForm, EditForm, DialogEditForm
from ztfy.skin.menu import MenuItem, DialogMenuItem
from ztfy.thesaurus.browser import ztfy_thesaurus
from ztfy.thesaurus.loader.config import ThesaurusLoaderConfiguration, \
ThesaurusUpdaterConfiguration, \
ThesaurusExporterConfiguration
from ztfy.thesaurus.thesaurus import ThesaurusExtract, Thesaurus
from ztfy.utils.container import getContentName
from ztfy.utils.list import unique
from ztfy.utils.traversing import getParent
from ztfy.thesaurus import _
class ThesaurusBackViewAdapter(object):
"""Default back-office URL adapter"""
adapts(IThesaurus, IZTFYBackLayer, Interface)
implements(IDefaultView)
viewname = '@@properties.html'
def __init__(self, context, request, view):
self.context = context
self.request = request
self.view = view
def getAbsoluteURL(self):
return '%s/%s' % (absoluteURL(self.context, self.request), self.viewname)
class ThesaurusManagerTargetBackViewAdapter(ThesaurusBackViewAdapter):
"""Thesaurus target default back-office view adapter"""
adapts(IThesaurusManagerTarget, IZTFYBackLayer, IThesaurusView)
viewname = '@@thesaurus.html'
class ThesaurusListViewMenu(MenuItem):
"""Thesaurus list view menu"""
title = _("Thesaurus")
class ThesaurusSizeAdapter(object):
adapts(IThesaurus)
implements(ISized)
def __init__(self, context):
self.context = context
def sizeForSorting(self):
return ('terms', len(self.context.terms))
def sizeForDisplay(self):
return _("${size} terms", mapping={'size': len(self.context.terms)})
class ThesaurusListViewTitleCellAdapter(object):
adapts(IThesaurus, IBrowserRequest, Interface)
implements(IContainedDefaultView)
viewname = ''
def __init__(self, context, request, view):
self.context = context
self.request = request
self.view = view
def getAbsoluteURL(self):
return '%s/@@properties.html' % absoluteURL(self.context, self.request)
class ThesaurusListView(ajax.AJAXRequestHandler, ContainerBaseView):
"""Actual list of available thesauri"""
implements(IThesaurusView, IThesaurusAddFormMenuTarget)
legend = _("List of registered thesauri")
output = ContainerBaseView.render
def update(self):
ContainerBaseView.update(self)
ztfy_thesaurus.need()
@property
def values(self):
factory = queryUtility(IVocabularyFactory, 'ZTFY thesaurus')
if factory is not None:
vocabulary = factory(self.context)
return unique([term.value for term in vocabulary])
@ajax.handler
def ajaxRemove(self):
oid = self.request.form.get('oid')
if oid is not None:
oid = int(oid)
intids = getUtility(IIntIds)
thesaurus = intids.queryObject(oid)
if IThesaurus.providedBy(thesaurus):
thesaurus.delete()
class ThesaurusListViewActionsCellAdapter(object):
adapts(IThesaurus, IBrowserRequest, ThesaurusListView, IActionsColumn)
implements(IContainerTableViewActionsCell)
def __init__(self, context, request, view, column):
self.context = context
self.request = request
self.view = view
self.column = column
@property
def content(self):
if not ISecurityManager(self.context).canUsePermission('ztfy.ManageThesaurus'):
return ''
klass = "ui-workflow icon icon-trash"
intids = getUtility(IIntIds)
return '''<span class="%s" title="%s" onclick="$.ZTFY.thesaurus.remove(%s,this);"></span>''' % (klass,
translate(_("Delete thesaurus"), context=self.request),
intids.register(self.context))
class ThesaurusAutomaticSelectWidget(SelectWidget):
noValueMessage = _("-- automatic selection -- (if provided by selected format)")
def ThesaurusAutomaticSelectWidgetFactory(field, request):
return FieldWidget(field, ThesaurusAutomaticSelectWidget(request))
class ThesaurusAddForm(DialogAddForm):
"""Thesaurus add form"""
legend = _("Adding a new empty thesaurus")
layout = getLayoutTemplate()
parent_interface = IThesaurusManagerTarget
parent_view = ThesaurusListView
fields = field.Fields(IThesaurusInfo).select('name', 'title', 'subject', 'description', 'language',
'creator', 'publisher', 'created')
resources = (jquery_datetime,)
def create(self, data):
thesaurus = Thesaurus()
thesaurus.name = data.get('name')
return thesaurus
def add(self, thesaurus):
manager = getSiteManager(self.context)
default = manager['default']
default['Thesaurus::' + thesaurus.name] = thesaurus
manager.registerUtility(removeSecurityProxy(thesaurus), IThesaurus, thesaurus.name)
locate(thesaurus, removeSecurityProxy(self.context), '++thesaurus++' + thesaurus.name)
class ThesaurusAddMenuItem(DialogMenuItem):
"""Thesaurus add menu item"""
title = _(":: Add empty thesaurus...")
target = ThesaurusAddForm
class ThesaurusImportForm(DialogAddForm):
"""Thesaurus import form"""
legend = _("Importing and registering a new thesaurus")
layout = getLayoutTemplate()
parent_interface = IThesaurusManagerTarget
parent_view = ThesaurusListView
fields = field.Fields(IThesaurusLoaderConfiguration)
fields['language'].widgetFactory = ThesaurusAutomaticSelectWidgetFactory
fields['encoding'].widgetFactory = ThesaurusAutomaticSelectWidgetFactory
def create(self, data):
configuration = ThesaurusLoaderConfiguration(data)
loader = getUtility(IThesaurusLoader, configuration.format)
thesaurus = loader.load(self.request.form.get(self.prefix + 'widgets.data'), configuration)
thesaurus.name = data.get('name')
if thesaurus.title:
IZopeDublinCore(thesaurus).title = thesaurus.title
else:
IZopeDublinCore(thesaurus).title = thesaurus.name
return thesaurus
def updateContent(self, object, data):
pass
def add(self, thesaurus):
manager = getSiteManager(self.context)
default = manager['default']
default['Thesaurus::' + thesaurus.name] = thesaurus
manager.registerUtility(removeSecurityProxy(thesaurus), IThesaurus, thesaurus.name)
locate(thesaurus, removeSecurityProxy(self.context), '++thesaurus++' + thesaurus.name)
class ThesaurusImportMenuItem(DialogMenuItem):
"""Thesaurus add menu item"""
title = _(":: Import thesaurus...")
target = ThesaurusImportForm
class ThesaurusEditForm(EditForm):
"""Thesaurus edit form"""
implements(IThesaurusView)
legend = _("Edit thesaurus properties")
fields = field.Fields(IThesaurusInfo).select('name', 'title', 'subject', 'description', 'language',
'creator', 'publisher', 'created')
@property
def title(self):
return self.context.title
def applyChanges(self, data):
thesaurus = self.getContent()
old_name = thesaurus.name
changes = super(ThesaurusEditForm, self).applyChanges(data)
if 'name' in changes.get(IThesaurusInfo, []):
old_parent = traversing_api.getParent(thesaurus)
IObjectMover(thesaurus).moveTo(traversing_api.getParent(thesaurus), 'Thesaurus::' + thesaurus.name)
manager = getSiteManager(thesaurus)
manager.unregisterUtility(removeSecurityProxy(thesaurus), IThesaurus, old_name)
manager.registerUtility(removeSecurityProxy(thesaurus), IThesaurus, thesaurus.name)
locate(thesaurus, old_parent, '++thesaurus++' + thesaurus.name)
if 'title' in changes.get(IThesaurusInfoBase, []):
if thesaurus.title:
IZopeDublinCore(thesaurus).title = thesaurus.title
else:
IZopeDublinCore(thesaurus).title = thesaurus.name
return changes
#
# Thesaurus roles menus and forms
#
class ThesaurusRolesEditForm(RolesEditForm):
"""Thesaurus roles edit form"""
interfaces = (IThesaurusRoles,)
layout = getLayoutTemplate()
parent_interface = IThesaurus
class ThesaurusRolesMenuItem(DialogMenuItem):
"""Thesaurus roles menu item"""
title = _(":: Roles...")
target = ThesaurusRolesEditForm
#
# Thesaurus extracts menus and forms
#
class ThesaurusExtractsMenuItem(MenuItem):
"""Thesaurus extract menu item"""
title = _("Extracts")
class ThesaurusExtractNameColumn(Column):
implements(ITitleColumn)
header = _("Name")
weight = 10
cssClasses = {}
def renderCell(self, item):
adapter = queryMultiAdapter((item, self.request, self.table, self), IContainerTableViewTitleCell)
prefix = (adapter is not None) and adapter.prefix or ''
before = (adapter is not None) and adapter.before or ''
after = (adapter is not None) and adapter.after or ''
suffix = (adapter is not None) and adapter.suffix or ''
title = item.name
result = "%s%s%s" % (before, title, after)
adapter = queryMultiAdapter((item, self.request, self.table), IContainedDefaultView)
if adapter is None:
adapter = queryMultiAdapter((item, self.request, self.table), IDefaultView)
if adapter is not None:
url = adapter.getAbsoluteURL()
if url:
result = '<a href="%s">%s</a>' % (url, result)
return '%s%s%s' % (prefix, result, suffix)
class ThesaurusExtractsListViewTitleCellAdapter(object):
adapts(IThesaurusExtractInfo, IBrowserRequest, Interface)
implements(IContainedDefaultView)
viewname = ''
def __init__(self, context, request, view):
self.context = context
self.request = request
self.view = view
def getAbsoluteURL(self):
return "javascript:$.ZTFY.dialog.open('%s/@@properties.html');" % absoluteURL(self.context, self.request)
class ThesaurusExtractsListViewCellActions(object):
adapts(IThesaurusExtractInfo, IZTFYBrowserLayer, IContainerBaseView, IActionsColumn)
implements(IContainerTableViewActionsCell)
def __init__(self, context, request, view, column):
self.context = context
self.request = request
self.view = view
self.column = column
@property
def content(self):
klass = "ui-workflow icon icon-trash"
intids = getUtility(IIntIds)
thesaurus = getParent(self.context, IThesaurus)
addr = absoluteURL(IThesaurusExtracts(thesaurus), self.request)
return '''<span class="%s" title="%s" onclick="$.ZTFY.container.remove(%s,this, '%s/');"></span>''' % (klass,
translate(_("Delete extract"), context=self.request),
intids.register(self.context),
addr)
class ThesaurusExtractsListView(ContainerBaseView):
"""Thesaurus extracts list view"""
implements(IThesaurusView, IThesaurusExtractAddFormMenuTarget)
legend = _("List of thesaurus extracts")
output = ContainerBaseView.render
cssClasses = { 'table': 'extracts' }
def render(self):
jquery_colorpicker.need()
jquery_multiselect.need()
ztfy_thesaurus.need()
return super(ThesaurusExtractsListView, self).render()
@property
def values(self):
return IThesaurusExtracts(self.context).values()
class IThesaurusExtractAddInfo(Interface):
"""Extra info for thesaurus extract add form"""
add_all_terms = Bool(title=_("Add all terms in extract ?"),
description=_("If 'Yes', all current thesaurus terms will be affected to this extract"),
required=True,
default=True)
class ThesaurusExtractAddForm(DialogAddForm):
"""Thesaurus extract add form"""
legend = _("Creating new thesaurus extract")
parent_interface = IThesaurus
parent_view = ThesaurusExtractsListView
fields = field.Fields(IThesaurusExtractBaseInfo) + \
field.Fields(IThesaurusExtractAddInfo)
@property
def title(self):
return self.context.title
def create(self, data):
extract = ThesaurusExtract()
extract.name = data.get('name')
return extract
def add(self, extract):
extracts = IThesaurusExtracts(self.context)
name = getContentName(extracts, extract.name)
extracts[name] = extract
def updateContent(self, extract, data):
add_all_terms = data.pop('add_all_terms', False)
result = super(ThesaurusExtractAddForm, self).updateContent(extract, data)
if add_all_terms:
thesaurus = IThesaurus(self.context)
for term in thesaurus.terms.itervalues():
try:
term.addExtract(extract, check=False)
except:
logger.warning('''Resetting extracts on term "%s"''' % term.label)
extracts = set([ traversing_api.getName(extract) for extract in IThesaurusExtracts(thesaurus).values() ])
term.extracts = ((term.extracts or set()) & extracts) | set((traversing_api.getName(extract),))
return result
class ThesaurusExtractAddFormMenuItem(DialogMenuItem):
"""Thesaurus extract add form menu item"""
title = _(":: Add extract...")
target = ThesaurusExtractAddForm
class ThesaurusExtractEditForm(DialogEditForm):
"""Thesaurus extract edit form"""
legend = _("Edit thesaurus extract properties")
fields = field.Fields(IThesaurusExtractBaseInfo)
@property
def title(self):
return translate(_('''%s: extract "%s"'''), context=self.request) % (getParent(self.context, IThesaurus).title,
self.context.name)
def updateWidgets(self):
super(ThesaurusExtractEditForm, self).updateWidgets()
self.widgets['name'].mode = DISPLAY_MODE
#
# Thesaurus merge menus and forms
#
class IMergeDialogFormButtons(Interface):
"""Export dialog form buttons"""
add = jsaction.JSButton(title=_("Merge"))
cancel = jsaction.JSButton(title=_("Cancel"))
class ThesaurusMergeEditForm(DialogAddForm):
"""Thesaurus merge editor"""
legend = _("Merge thesaurus terms")
layout = getLayoutTemplate()
parent_interface = IThesaurus
fields = field.Fields(IThesaurusUpdaterConfiguration).select('clear', 'conflict_suffix') + \
field.Fields(IThesaurusUpdaterConfiguration).omit('name', 'clear', 'conflict_suffix')
fields['language'].widgetFactory = ThesaurusAutomaticSelectWidgetFactory
fields['encoding'].widgetFactory = ThesaurusAutomaticSelectWidgetFactory
buttons = button.Buttons(IMergeDialogFormButtons)
@property
def title(self):
return self.context.title
@jsaction.handler(buttons['add'])
def add_handler(self, event, selector):
return '$.ZTFY.form.add(this.form);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
def create(self, data):
configuration = ThesaurusUpdaterConfiguration(data)
loader = getUtility(IThesaurusLoader, configuration.format)
thesaurus = loader.load(self.request.form.get(self.prefix + 'widgets.data'), configuration)
target = IThesaurus(self.getContent())
if configuration.clear:
target.clear()
target.merge(configuration, thesaurus)
def updateContent(self, object, data):
pass
def add(self, thesaurus):
pass
class ThesaurusMergeMenuItem(DialogMenuItem):
"""Thesaurus content edit menu item"""
title = _(":: Merge thesaurus...")
target = ThesaurusMergeEditForm
#
# Thesaurus exports menus and forms
#
class IExportDialogFormButtons(Interface):
"""Export dialog form buttons"""
download = jsaction.JSButton(title=_("Download"))
cancel = jsaction.JSButton(title=_("Cancel"))
class ThesaurusExportExtractSelectWidget(SelectWidget):
"""Thesaurus export extract select widget"""
noValueMessage = _("(export all terms)")
def ThesaurusExportExtractSelectWidgetFactory(field, request):
return FieldWidget(field, ThesaurusExportExtractSelectWidget(request))
class ThesaurusExportEditForm(DialogAddForm):
"""Thesaurus export editor"""
legend = _("Export thesaurus terms")
layout = getLayoutTemplate()
parent_interface = IThesaurus
buttons = button.Buttons(IExportDialogFormButtons)
fields = field.Fields(IThesaurusExporterConfiguration)
fields['extract'].widgetFactory = ThesaurusExportExtractSelectWidgetFactory
@property
def title(self):
return self.context.title
@jsaction.handler(buttons['download'])
def download_handler(self, event, selector):
return '$.ZTFY.thesaurus.download(this.form);'
@jsaction.handler(buttons['cancel'])
def cancel_handler(self, event, selector):
return '$.ZTFY.dialog.close();'
@ajax.handler
def ajaxDownload(self):
self.updateWidgets()
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
writer = getUtility(IJSONWriter)
return writer.write(self.getAjaxErrors())
configuration = ThesaurusExporterConfiguration(data)
exporter = getUtility(IThesaurusExporter, configuration.format)
return exporter.export(self.getContent(), configuration)
def create(self, data):
pass
def updateContent(self, object, data):
pass
def add(self, object):
pass
class ThesaurusExportMenuItem(DialogMenuItem):
"""Thesaurus export menu item"""
title = _(":: Export thesaurus...")
target = ThesaurusExportEditForm | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/thesaurus.py | thesaurus.py |
# import standard packages
# import Zope3 interfaces
# import local interfaces
from ztfy.thesaurus.browser.xmlrpc.interfaces import IThesaurusTargetInfosReader
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus
# import Zope3 packages
from zope.component import queryUtility
from zope.interface import implements
from zope.publisher.xmlrpc import XMLRPCView
from zope.schema.interfaces import IVocabularyFactory
from zope.traversing.browser.absoluteurl import absoluteURL
# import local packages
from ztfy.utils.date import unidate, datetodatetime
class XMLRPCThesaurusTargetView(XMLRPCView):
"""Thesaurus target XML-RPC view"""
implements(IThesaurusTargetInfosReader)
def getThesaurusList(self):
factory = queryUtility(IVocabularyFactory, 'ZTFY thesaurus')
if factory is not None:
vocabulary = factory(self.context)
return [{ 'name': term.token,
'url': absoluteURL(term.value, self.request) } for term in vocabulary]
def getThesaurusInfo(self, thesaurus):
thesaurus = queryUtility(IThesaurus, thesaurus)
if thesaurus is not None:
return { 'name': thesaurus.name,
'title': thesaurus.title,
'subject': thesaurus.subject,
'description': thesaurus.description,
'language': thesaurus.language,
'creator': thesaurus.creator,
'publisher': thesaurus.publisher,
'created': thesaurus.created and unidate(datetodatetime(thesaurus.created)) or None,
'length': len(thesaurus.terms),
'top_terms': [term.label for term in thesaurus.top_terms],
'url': absoluteURL(thesaurus, self.request) }
def search(self, query, extract=None, autoexpand='on_miss', glob='end', thesaurus=None):
if thesaurus:
thesaurus_list = [ queryUtility(IThesaurus, name) for name in thesaurus ]
else:
factory = queryUtility(IVocabularyFactory, 'ZTFY thesaurus')
if factory is not None:
vocabulary = factory(self.context)
thesaurus_list = [ term.value for term in vocabulary ]
else:
thesaurus_list = []
result = []
if thesaurus_list:
for thesaurus in thesaurus_list:
name = thesaurus.name
result.extend([ { 'thesaurus': name,
'label': term.label } for term in thesaurus.findTerms(query, extract, autoexpand, glob) ])
return result
class XMLRPCThesaurusView(XMLRPCView):
"""Thesaurus XML-RPC views"""
def search(self, query, extract=None, autoexpand='on_miss', glob='end'):
thesaurus = IThesaurus(self.context)
return [ term.label for term in thesaurus.findTerms(query, extract, autoexpand, glob) ]
def getTermInfo(self, term):
term = IThesaurus(self.context).terms.get(term)
if term is not None:
return { 'label': term.label,
'definition': term.definition,
'note': term.note,
'generic': term.generic and term.generic.label or None,
'specifics': [specific.label for specific in term.specifics],
'associations': [association.label for association in term.associations],
'usage': term.usage and term.usage.label or None,
'used_for': [used.label for used in term.used_for],
'status': term.status,
'level': term.level,
'created': unidate(term.created),
'modified': unidate(term.modified),
'url': absoluteURL(term, self.request) }
class XMLRPCThesaurusTermView(XMLRPCView):
"""Thesaurus term XML-RPC views""" | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/xmlrpc/thesaurus.py | thesaurus.py |
(function($) {
if (typeof($.ZTFY) == 'undefined') {
$.ZTFY = {}
}
$.ZTFY.thesaurus = {
/**
* Remove thesaurus
*/
remove: function(oid, source) {
jConfirm($.ZTFY.I18n.CONFIRM_REMOVE, $.ZTFY.I18n.CONFIRM, function(confirmed) {
if (confirmed) {
var data = {
oid: oid
}
$.ZTFY.ajax.post(window.location.href + '/@@ajax/ajaxRemove', data, function() {
window.location.reload();
}, function(request, status, error) {
jAlert(request.responseText, $.ZTFY.I18n.ERROR_OCCURED, window.location.reload);
});
}
});
},
/**
* Thesaurus tree management
*/
tree: {
// Show or hide an entire extract
showHideExtract: function(source) {
var source = this;
var extract = $(source).data('ztfy-extract-name');
if ($(source).hasClass('hide')) {
$('DIV.tree SPAN.square[data-ztfy-extract-name="' + extract + '"]').css('visibility', 'visible')
.each(function() {
if ($(this).hasClass('used')) {
$(this).css('background-color', '#'+$(source).data('ztfy-extract-color'))
.click(function() {
$.ZTFY.thesaurus.tree.switchExtract(this);
});
} else {
var source_div = $(this).parents('DIV').get(2);
if ($(source_div).hasClass('form') || $('SPAN[data-ztfy-extract-name="'+extract+'"]:first', source_div).hasClass('used')) {
$(this).css('background-color', 'white')
.click(function() {
$.ZTFY.thesaurus.tree.switchExtract(this);
});
} else {
$(this).css('background-color', 'silver');
}
}
});
$(source).css('background-image', "url('/--static--/ztfy.thesaurus/img/visible.gif')")
.removeClass('hide');
} else {
$('DIV.tree SPAN.square[data-ztfy-extract-name="' + extract + '"]').css('visibility', 'hidden')
.unbind('click');
$(source).css('background-image', "url('/--static--/ztfy.thesaurus/img/hidden.gif')")
.addClass('hide');
}
},
// Expand term node
_displayTermSubnodes: function(term, nodes) {
var source = $.data($.ZTFY.thesaurus.tree, 'source');
if (source) {
source = source[term];
} else {
source = $("A:econtains(" + term.replace(''','\'') + ")").siblings('IMG.plminus');
}
var source_div = $(source).closest('DIV').get(0);
var tree = $(source).closest('DIV.tree');
var show_links = tree.data('ztfy-tree-details') != 'off';
var $target = $('DIV.subnodes', $(source).closest('DIV').get(0));
$target.empty();
for (var index in nodes) {
var node = nodes[index];
var $div = $('<div></div>');
$('<img />').addClass('plminus')
.attr('src', node.expand ? '/--static--/ztfy.thesaurus/img/plus.png'
: '/--static--/ztfy.thesaurus/img/lline.png')
.click(function() {
$.ZTFY.thesaurus.tree.expand(this);
})
.appendTo($div);
$('<a></a>').addClass(show_links ? 'label' : '')
.addClass(node.cssClass)
.click(function() {
$.ZTFY.thesaurus.tree.openTerm(this);
})
.html(node.label).appendTo($div);
$('<span> </span>').appendTo($div);
for (var ind_ext in node.extensions) {
var extension = node.extensions[ind_ext];
$('<img />').addClass('extension')
.attr('src', extension.icon)
.data('ztfy-view', extension.view)
.click(function() {
$.ZTFY.thesaurus.tree.openExtension(this);
})
.appendTo($div);
}
node.extracts.reverse();
for (var ind_ext in node.extracts) {
var extract = node.extracts[ind_ext];
var checker = $('DIV.extract SPAN.showhide[data-ztfy-extract-name="' + extract.name + '"]');
var $span = $('<span></span>').addClass('square')
.addClass(extract.used ? 'used' : null)
.attr('title', extract.title)
.attr('data-ztfy-extract-name', extract.name);
if ($(checker).hasClass('hide')) {
$span.css('visibility', 'hidden');
} else if ($('SPAN[data-ztfy-extract-name="'+extract.name+'"]:first', source_div).hasClass('used')) {
$span.css('background-color', extract.used ? '#'+extract.color : 'white');
$span.click(function() {
$.ZTFY.thesaurus.tree.switchExtract(this);
});
} else {
$span.css('background-color', 'silver');
}
$span.appendTo($div);
}
$('<div></div>').addClass('subnodes').appendTo($div);
$div.appendTo($target);
if (node.subnodes) {
$.ZTFY.thesaurus.tree._displayTermSubnodes(node.label, node.subnodes);
}
}
$(source).attr('src', '/--static--/ztfy.thesaurus/img/minus.png');
},
expand: function(source) {
if ($(source).attr('src') == '/--static--/ztfy.thesaurus/img/plus.png') {
$(source).attr('src', '/--static--/ztfy.thesaurus/img/loader.gif');
var context = $(source).closest('DIV.tree').data('ztfy-base');
var term = $('A', $(source).closest('DIV').get(0)).text();
var data = $.data($.ZTFY.thesaurus.tree, 'source') || new Array();
data[term] = source;
$.data($.ZTFY.thesaurus.tree, 'source', data);
$.ZTFY.ajax.post(context + '/@@terms.html/@@ajax/getNodes', {'term': term}, $.ZTFY.thesaurus.tree._expandCallback);
} else {
$.ZTFY.thesaurus.tree.collapse(source);
}
},
_expandCallback: function(result, status) {
if (status == 'success') {
$.ZTFY.thesaurus.tree._displayTermSubnodes(result.term, result.nodes);
$.removeData($.ZTFY.thesaurus.tree, 'source');
}
},
// Collapse term node
collapse: function(source) {
$('DIV.subnodes', $(source).closest('DIV').get(0)).empty();
$(source).attr('src', '/--static--/ztfy.thesaurus/img/plus.png');
},
// Open term properties dialog
openTerm: function(source) {
var tree = $(source).closest('DIV.tree');
if (tree.data('ztfy-tree-details') == 'off') {
return;
}
var term = $(source).text().replace(/ /g, '%20')
.replace(/&/g, '%26');
if ($.browser.msie) {
term = $.UTF8.encode(term);
}
$.ZTFY.dialog.open('++terms++/' + term + '/@@properties.html');
},
// Open term properties from search engine
openTermFromSearch: function(source) {
if (source instanceof $.Event) {
var source = source.srcElement || source.target;
}
var term = $(source).text().replace(/ /g, '%20')
.replace(/&/g, '%26');
if (term) {
if ($.browser.msie) {
term = $.UTF8.encode(term);
}
$.ZTFY.dialog.open('++terms++/' + term + '/@@properties.html');
}
},
// Find term in terms tree
findTerm: function(source) {
if (source instanceof $.Event) {
var source = source.srcElement || source.target;
}
var term = $(source).siblings('INPUT').val();
if (term) {
if ($.browser.msie) {
term = $.UTF8.encode(term);
}
var context = $(source).parents('FIELDSET.search').siblings('DIV.tree').data('ztfy-base');
$.ZTFY.ajax.post(context + '/@@terms.html/@@ajax/getParentNodes', {'term': term}, $.ZTFY.thesaurus.tree._findCallback);
}
},
_findCallback: function(result, status) {
if (status == 'success') {
var status = result.status;
if (status == 'OK') {
$.ZTFY.thesaurus.tree._displayTermSubnodes(result.parent, result.nodes);
var element = $("A:econtains(" + result.term.replace(''','\'') + ")", 'DIV.tree');
$('html,body').animate({scrollTop: element.offset().top-100}, 1000);
element.css('background-color', 'yellow')
.on('mouseover', function() {
$(this).animate({'background-color': $.Color('white')}, 2000);
});
}
}
},
// Open term extension properties dialog
openExtension: function(source) {
var view = $(source).data('ztfy-view').replace('/ /g', '%20');
if ($.browser.msie) {
view = $.UTF8.encode(view);
}
$.ZTFY.dialog.open(view);
},
// Reload a term after properties change
reloadTerm: function(options) {
$.ZTFY.dialog.close();
var source = options.source;
var img = $('IMG.plminus:first', $("A:econtains(" + source.replace(''','\'') + ")").closest('DIV'));
$.ZTFY.thesaurus.tree.collapse(img);
$.ZTFY.thesaurus.tree.expand(img);
},
// Switch extract selection for a given term
switchExtract: function(source) {
if (source instanceof $.Event) {
$.ZTFY.skin.stopEvent(source);
var source = source.srcElement || source.target;
}
var extract = $(source).data('ztfy-extract-name');
var checker = $('DIV.extract SPAN.showhide[data-ztfy-extract-name="' + extract + '"]');
if (checker.data('ztfy-enabled') == false) {
return;
}
var label = $('A.label', $(source).closest('DIV')).get(0);
if ($.ZTFY.rgb2hex($(source).css('background-color')) == '#ffffff') {
/* Don't confirm when adding a term */
$.ZTFY.thesaurus.tree._switchExtract(label, extract);
} else {
if ($(label).closest('DIV').children('IMG').attr('src').endsWith('/lline.png')) {
/* Don't confirm if term don't have any specific term */
$.ZTFY.thesaurus.tree._switchExtract(label, extract);
} else {
jConfirm($.ZTFY.thesaurus.I18n.CONFIRM_UNSELECT_WITH_CHILD, $.ZTFY.I18n.CONFIRM, function(confirmed) {
if (confirmed) {
$.ZTFY.thesaurus.tree._switchExtract(label, extract);
}
});
}
}
},
_switchExtract: function(label, extract) {
var term = $(label).text();
$.ZTFY.ajax.post('@@terms.html/@@ajax/switchExtract',
{ 'term': term, 'extract': extract },
$.ZTFY.thesaurus.tree._switchExtractCallback);
},
_switchExtractCallback: function(result, status) {
if (status == 'success') {
var term = result.term;
var label = $('A.label:withtext(' + term + ')');
var div = $(label).closest('DIV').get(0);
if (result.used) {
$('DIV.subnodes:first > DIV', div).children('SPAN[data-ztfy-extract-name="'+result.extract+'"]', div)
.css('background-color', 'white')
.unbind('click')
.click(function() {
$.ZTFY.thesaurus.tree.switchExtract(this);
});
$('SPAN[data-ztfy-extract-name="'+result.extract+'"]:first', div).addClass('used')
.css('background-color', '#'+result.color);
} else {
$('SPAN[data-ztfy-extract-name="'+result.extract+'"]', div).removeClass('used')
.css('background-color', 'silver')
.off('click');
$('SPAN[data-ztfy-extract-name="'+result.extract+'"]:first', div).css('background-color', 'white')
.on('click', function() {
$.ZTFY.thesaurus.tree.switchExtract(this);
});
}
}
},
openSelector: function(target, source) {
$.ZTFY.dialog.open(target, function(response, status, result) {
$.ZTFY.dialog.openCallback(response, status, result);
var form = $('FORM', $.ZTFY.dialog.getCurrent());
form.data('thesaurus-selector-source', source);
var $source = $('INPUT[name="'+source+'"]');
$($source.val().split('|')).each(function() {
$('INPUT[type="checkbox"][value="'+this+'"]').attr('checked', true);
});
});
},
openSelectorAction: function(form) {
var source = $(form).data('thesaurus-selector-source');
var $source = $('INPUT[name="'+source+'"]');
var widget = $('DIV.jquery-multiselect', $source.closest('DIV.widget'));
var ms = $('A.bit-input INPUT', widget).data('multiselect');
$($source.val().split('|')).each(function() {
ms.remove([ String(this), String(this) ]);
});
$('INPUT[type="checkbox"]:checked', form).each(function() {
ms.add([ $(this).val(), $(this).val() ]);
});
$.ZTFY.dialog.close();
}
},
// Thesaurus terms search engine entry point
findTerms: function(query, thesaurus_name, extract_name) {
var result;
var options = {
url: $.ZTFY.ajax.getAddr(),
type: 'POST',
method: 'findTerms',
async: false,
params: {
query: query,
thesaurus_name: thesaurus_name || '',
extract_name: extract_name || ''
},
success: function(data, status) {
result = data.result;
},
error: function(request, status, error) {
jAlert(request.responseText, "Error !", window.location.reload);
}
}
$.jsonRpc(options);
return result;
},
// Thesaurus terms search engine entry point
findTermsWithLabel: function(query, thesaurus_name, extract_name) {
var result;
var options = {
url: $.ZTFY.ajax.getAddr(),
type: 'POST',
method: 'findTermsWithLabel',
async: false,
params: {
query: query,
thesaurus_name: thesaurus_name || '',
extract_name: extract_name || ''
},
success: function(data, status) {
result = data.result;
},
error: function(request, status, error) {
jAlert(request.responseText, "Error !", window.location.reload);
}
}
$.jsonRpc(options);
return result;
},
// Thesaurus download management
download: function(form) {
$.ZTFY.form.check(function() {
$.ZTFY.thesaurus._download(form);
});
return false;
},
_download: function(form) {
var action = $(form).attr('action');
var target = action + '/@@ajax/ajaxDownload';
var iframe = $('<iframe></iframe>').hide()
.attr('name', 'downloadFrame')
.appendTo($(form));
$(form).attr('action', target)
.attr('target', 'downloadFrame')
.ajaxSubmit({
iframe: true,
iframeTarget: iframe,
success: function() {
$.ZTFY.dialog.close();
}
});
/** !! reset form action after submit !! */
$(form).attr('action', action);
}
}
/**
* Init I18n strings
*/
$.ZTFY.thesaurus.I18n = {
CONFIRM_UNSELECT_WITH_CHILD: "Removing this term from this extract will also remove all it's specific terms and their synonyms. Are you sure?"
}
var lang = $('HTML').attr('lang') || $('HTML').attr('xml:lang');
if (lang && (lang != 'en'))
$.ZTFY.getScript('/--static--/ztfy.thesaurus/js/i18n/' + lang + '.js');
/**
* Initialize thesaurus events
*/
$(document).ready(function() {
$('DIV.extract').on('click', 'SPAN.showhide', $.ZTFY.thesaurus.tree.showHideExtract);
$('DIV.tree SPAN.square').click($.ZTFY.thesaurus.tree.switchExtract);
$('FIELDSET.search').on('click', 'A.bit-box', $.ZTFY.thesaurus.tree.openTermFromSearch);
});
})(jQuery); | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/resources/js/ztfy.thesaurus.js | ztfy.thesaurus.js |
(function(a){if(typeof(a.ZTFY)=="undefined"){a.ZTFY={}}a.ZTFY.thesaurus={remove:function(c,d){jConfirm(a.ZTFY.I18n.CONFIRM_REMOVE,a.ZTFY.I18n.CONFIRM,function(f){if(f){var e={oid:c};a.ZTFY.ajax.post(window.location.href+"/@@ajax/ajaxRemove",e,function(){window.location.reload()},function(i,g,h){jAlert(i.responseText,a.ZTFY.I18n.ERROR_OCCURED,window.location.reload)})}})},tree:{showHideExtract:function(d){var d=this;var c=a(d).data("ztfy-extract-name");if(a(d).hasClass("hide")){a('DIV.tree SPAN.square[data-ztfy-extract-name="'+c+'"]').css("visibility","visible").each(function(){if(a(this).hasClass("used")){a(this).css("background-color","#"+a(d).data("ztfy-extract-color")).click(function(){a.ZTFY.thesaurus.tree.switchExtract(this)})}else{var e=a(this).parents("DIV").get(2);if(a(e).hasClass("form")||a('SPAN[data-ztfy-extract-name="'+c+'"]:first',e).hasClass("used")){a(this).css("background-color","white").click(function(){a.ZTFY.thesaurus.tree.switchExtract(this)})}else{a(this).css("background-color","silver")}}});a(d).css("background-image","url('/--static--/ztfy.thesaurus/img/visible.gif')").removeClass("hide")}else{a('DIV.tree SPAN.square[data-ztfy-extract-name="'+c+'"]').css("visibility","hidden").unbind("click");a(d).css("background-image","url('/--static--/ztfy.thesaurus/img/hidden.gif')").addClass("hide")}},_displayTermSubnodes:function(i,d){var c=a.data(a.ZTFY.thesaurus.tree,"source");if(c){c=c[i]}else{c=a("A:econtains("+i.replace("'","'")+")").siblings("IMG.plminus")}var p=a(c).closest("DIV").get(0);var q=a(c).closest("DIV.tree");var o=q.data("ztfy-tree-details")!="off";var e=a("DIV.subnodes",a(c).closest("DIV").get(0));e.empty();for(var k in d){var g=d[k];var m=a("<div></div>");a("<img />").addClass("plminus").attr("src",g.expand?"/--static--/ztfy.thesaurus/img/plus.png":"/--static--/ztfy.thesaurus/img/lline.png").click(function(){a.ZTFY.thesaurus.tree.expand(this)}).appendTo(m);a("<a></a>").addClass(o?"label":"").addClass(g.cssClass).click(function(){a.ZTFY.thesaurus.tree.openTerm(this)}).html(g.label).appendTo(m);a("<span> </span>").appendTo(m);for(var h in g.extensions){var n=g.extensions[h];a("<img />").addClass("extension").attr("src",n.icon).data("ztfy-view",n.view).click(function(){a.ZTFY.thesaurus.tree.openExtension(this)}).appendTo(m)}g.extracts.reverse();for(var h in g.extracts){var j=g.extracts[h];var f=a('DIV.extract SPAN.showhide[data-ztfy-extract-name="'+j.name+'"]');var l=a("<span></span>").addClass("square").addClass(j.used?"used":null).attr("title",j.title).attr("data-ztfy-extract-name",j.name);if(a(f).hasClass("hide")){l.css("visibility","hidden")}else{if(a('SPAN[data-ztfy-extract-name="'+j.name+'"]:first',p).hasClass("used")){l.css("background-color",j.used?"#"+j.color:"white");l.click(function(){a.ZTFY.thesaurus.tree.switchExtract(this)})}else{l.css("background-color","silver")}}l.appendTo(m)}a("<div></div>").addClass("subnodes").appendTo(m);m.appendTo(e);if(g.subnodes){a.ZTFY.thesaurus.tree._displayTermSubnodes(g.label,g.subnodes)}}a(c).attr("src","/--static--/ztfy.thesaurus/img/minus.png")},expand:function(f){if(a(f).attr("src")=="/--static--/ztfy.thesaurus/img/plus.png"){a(f).attr("src","/--static--/ztfy.thesaurus/img/loader.gif");var d=a(f).closest("DIV.tree").data("ztfy-base");var c=a("A",a(f).closest("DIV").get(0)).text();var e=a.data(a.ZTFY.thesaurus.tree,"source")||new Array();e[c]=f;a.data(a.ZTFY.thesaurus.tree,"source",e);a.ZTFY.ajax.post(d+"/@@terms.html/@@ajax/getNodes",{term:c},a.ZTFY.thesaurus.tree._expandCallback)}else{a.ZTFY.thesaurus.tree.collapse(f)}},_expandCallback:function(c,d){if(d=="success"){a.ZTFY.thesaurus.tree._displayTermSubnodes(c.term,c.nodes);a.removeData(a.ZTFY.thesaurus.tree,"source")}},collapse:function(c){a("DIV.subnodes",a(c).closest("DIV").get(0)).empty();a(c).attr("src","/--static--/ztfy.thesaurus/img/plus.png")},openTerm:function(e){var c=a(e).closest("DIV.tree");if(c.data("ztfy-tree-details")=="off"){return}var d=a(e).text().replace(/ /g,"%20").replace(/&/g,"%26");if(a.browser.msie){d=a.UTF8.encode(d)}a.ZTFY.dialog.open("++terms++/"+d+"/@@properties.html")},openTermFromSearch:function(d){if(d instanceof a.Event){var d=d.srcElement||d.target}var c=a(d).text().replace(/ /g,"%20").replace(/&/g,"%26");if(c){if(a.browser.msie){c=a.UTF8.encode(c)}a.ZTFY.dialog.open("++terms++/"+c+"/@@properties.html")}},findTerm:function(e){if(e instanceof a.Event){var e=e.srcElement||e.target}var d=a(e).siblings("INPUT").val();if(d){if(a.browser.msie){d=a.UTF8.encode(d)}var c=a(e).parents("FIELDSET.search").siblings("DIV.tree").data("ztfy-base");a.ZTFY.ajax.post(c+"/@@terms.html/@@ajax/getParentNodes",{term:d},a.ZTFY.thesaurus.tree._findCallback)}},_findCallback:function(c,d){if(d=="success"){var d=c.status;if(d=="OK"){a.ZTFY.thesaurus.tree._displayTermSubnodes(c.parent,c.nodes);var e=a("A:econtains("+c.term.replace("'","'")+")","DIV.tree");a("html,body").animate({scrollTop:e.offset().top-100},1000);e.css("background-color","yellow").on("mouseover",function(){a(this).animate({"background-color":a.Color("white")},2000)})}}},openExtension:function(d){var c=a(d).data("ztfy-view").replace("/ /g","%20");if(a.browser.msie){c=a.UTF8.encode(c)}a.ZTFY.dialog.open(c)},reloadTerm:function(d){a.ZTFY.dialog.close();var e=d.source;var c=a("IMG.plminus:first",a("A:econtains("+e.replace("'","'")+")").closest("DIV"));a.ZTFY.thesaurus.tree.collapse(c);a.ZTFY.thesaurus.tree.expand(c)},switchExtract:function(f){if(f instanceof a.Event){a.ZTFY.skin.stopEvent(f);var f=f.srcElement||f.target}var e=a(f).data("ztfy-extract-name");var d=a('DIV.extract SPAN.showhide[data-ztfy-extract-name="'+e+'"]');if(d.data("ztfy-enabled")==false){return}var c=a("A.label",a(f).closest("DIV")).get(0);if(a.ZTFY.rgb2hex(a(f).css("background-color"))=="#ffffff"){a.ZTFY.thesaurus.tree._switchExtract(c,e)}else{if(a(c).closest("DIV").children("IMG").attr("src").endsWith("/lline.png")){a.ZTFY.thesaurus.tree._switchExtract(c,e)}else{jConfirm(a.ZTFY.thesaurus.I18n.CONFIRM_UNSELECT_WITH_CHILD,a.ZTFY.I18n.CONFIRM,function(g){if(g){a.ZTFY.thesaurus.tree._switchExtract(c,e)}})}}},_switchExtract:function(c,e){var d=a(c).text();a.ZTFY.ajax.post("@@terms.html/@@ajax/switchExtract",{term:d,extract:e},a.ZTFY.thesaurus.tree._switchExtractCallback)},_switchExtractCallback:function(c,d){if(d=="success"){var f=c.term;var e=a("A.label:withtext("+f+")");var g=a(e).closest("DIV").get(0);if(c.used){a("DIV.subnodes:first > DIV",g).children('SPAN[data-ztfy-extract-name="'+c.extract+'"]',g).css("background-color","white").unbind("click").click(function(){a.ZTFY.thesaurus.tree.switchExtract(this)});a('SPAN[data-ztfy-extract-name="'+c.extract+'"]:first',g).addClass("used").css("background-color","#"+c.color)}else{a('SPAN[data-ztfy-extract-name="'+c.extract+'"]',g).removeClass("used").css("background-color","silver").off("click");a('SPAN[data-ztfy-extract-name="'+c.extract+'"]:first',g).css("background-color","white").on("click",function(){a.ZTFY.thesaurus.tree.switchExtract(this)})}}},openSelector:function(d,c){a.ZTFY.dialog.open(d,function(g,f,e){a.ZTFY.dialog.openCallback(g,f,e);var h=a("FORM",a.ZTFY.dialog.getCurrent());h.data("thesaurus-selector-source",c);var i=a('INPUT[name="'+c+'"]');a(i.val().split("|")).each(function(){a('INPUT[type="checkbox"][value="'+this+'"]').attr("checked",true)})})},openSelectorAction:function(d){var f=a(d).data("thesaurus-selector-source");var g=a('INPUT[name="'+f+'"]');var e=a("DIV.jquery-multiselect",g.closest("DIV.widget"));var c=a("A.bit-input INPUT",e).data("multiselect");a(g.val().split("|")).each(function(){c.remove([String(this),String(this)])});a('INPUT[type="checkbox"]:checked',d).each(function(){c.add([a(this).val(),a(this).val()])});a.ZTFY.dialog.close()}},findTerms:function(g,d,f){var c;var e={url:a.ZTFY.ajax.getAddr(),type:"POST",method:"findTerms",async:false,params:{query:g,thesaurus_name:d||"",extract_name:f||""},success:function(i,h){c=i.result},error:function(j,h,i){jAlert(j.responseText,"Error !",window.location.reload)}};a.jsonRpc(e);return c},findTermsWithLabel:function(g,d,f){var c;var e={url:a.ZTFY.ajax.getAddr(),type:"POST",method:"findTermsWithLabel",async:false,params:{query:g,thesaurus_name:d||"",extract_name:f||""},success:function(i,h){c=i.result},error:function(j,h,i){jAlert(j.responseText,"Error !",window.location.reload)}};a.jsonRpc(e);return c},download:function(c){a.ZTFY.form.check(function(){a.ZTFY.thesaurus._download(c)});return false},_download:function(d){var e=a(d).attr("action");var f=e+"/@@ajax/ajaxDownload";var c=a("<iframe></iframe>").hide().attr("name","downloadFrame").appendTo(a(d));a(d).attr("action",f).attr("target","downloadFrame").ajaxSubmit({iframe:true,iframeTarget:c,success:function(){a.ZTFY.dialog.close()}});a(d).attr("action",e)}};a.ZTFY.thesaurus.I18n={CONFIRM_UNSELECT_WITH_CHILD:"Removing this term from this extract will also remove all it's specific terms and their synonyms. Are you sure?"};var b=a("HTML").attr("lang")||a("HTML").attr("xml:lang");if(b&&(b!="en")){a.ZTFY.getScript("/--static--/ztfy.thesaurus/js/i18n/"+b+".js")}a(document).ready(function(){a("DIV.extract").on("click","SPAN.showhide",a.ZTFY.thesaurus.tree.showHideExtract);a("DIV.tree SPAN.square").click(a.ZTFY.thesaurus.tree.switchExtract);a("FIELDSET.search").on("click","A.bit-box",a.ZTFY.thesaurus.tree.openTermFromSearch)})})(jQuery); | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/resources/js/ztfy.thesaurus.min.js | ztfy.thesaurus.min.js |
# import standard packages
import re
# import Zope3 interfaces
from z3c.form.interfaces import IFieldWidget, IWidget
from zope.schema.interfaces import IField
# import local interfaces
from ztfy.skin.layer import IZTFYBrowserLayer
from ztfy.thesaurus.browser.widget.interfaces import IThesaurusTermFieldWidget, \
IThesaurusTermsListFieldWidget
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus
from ztfy.thesaurus.schema import IThesaurusTermField, IThesaurusTermsListField
# import Zope3 packages
from z3c.form.browser.text import TextWidget
from z3c.form.converter import BaseDataConverter, SequenceDataConverter
from z3c.form.widget import FieldWidget
from zope.component import adapter, adapts, getUtility, queryUtility
from zope.interface import implementer, implementsOnly
from zope.schema.fieldproperty import FieldProperty
# import local packages
from ztfy.jqueryui import jquery_multiselect
from ztfy.thesaurus.browser import ztfy_thesaurus
from ztfy.utils.traversing import getParent
from ztfy.thesaurus.interfaces.term import IThesaurusTerm
from zope.traversing.browser.absoluteurl import absoluteURL
SYNONYM = re.compile('(.*)\ \[\ .*\ \]')
class ThesaurusTermFieldDataConverter(BaseDataConverter):
"""Thesaurus term data converter"""
adapts(IThesaurusTermField, IWidget)
def toWidgetValue(self, value):
if value is self.field.missing_value:
return u''
if IThesaurusTerm.providedBy(self.widget.context):
return unicode(value.label)
else:
return unicode(value.caption)
def toFieldValue(self, value):
if not value:
return self.field.missing_value
match = SYNONYM.match(value)
if match:
value = match.groups()[0]
thesaurus_name = self.widget.thesaurus_name or self.field.thesaurus_name
if thesaurus_name:
thesaurus = getUtility(IThesaurus, thesaurus_name)
else:
thesaurus = getParent(self.widget.context, IThesaurus)
if thesaurus is None:
thesaurus = queryUtility(IThesaurus)
if thesaurus is not None:
return thesaurus.terms.get(value)
else:
return None
class ThesaurusTermWidget(TextWidget):
"""Thesaurus term widget"""
implementsOnly(IThesaurusTermFieldWidget)
thesaurus_name = FieldProperty(IThesaurusTermFieldWidget['thesaurus_name'])
extract_name = FieldProperty(IThesaurusTermFieldWidget['extract_name'])
def update(self):
super(ThesaurusTermWidget, self).update()
self.thesaurus_name = self.field.thesaurus_name or u''
self.extract_name = self.field.extract_name or u''
def render(self):
jquery_multiselect.need()
ztfy_thesaurus.need()
return super(ThesaurusTermWidget, self).render()
@adapter(IField, IZTFYBrowserLayer)
@implementer(IFieldWidget)
def ThesaurusTermFieldWidget(field, request):
return FieldWidget(field, ThesaurusTermWidget(request))
class ThesaurusTermsListFieldDataConverter(SequenceDataConverter):
"""Thesaurus terms list data converter"""
adapts(IThesaurusTermsListField, IWidget)
def toWidgetValue(self, value):
if value is self.field.missing_value:
return []
if IThesaurusTerm.providedBy(self.widget.context):
return '|'.join([term.label for term in value])
else:
return '|'.join([term.caption for term in value])
def toFieldValue(self, value):
if not value:
return self.field.missing_value
value = value.split('|')
for idx, val in enumerate(value[:]):
match = SYNONYM.match(val)
if match:
value[idx] = match.groups()[0]
thesaurus_name = self.widget.thesaurus_name or self.field.thesaurus_name
if thesaurus_name:
thesaurus = getUtility(IThesaurus, thesaurus_name)
else:
thesaurus = getParent(self.widget.context, IThesaurus)
if thesaurus is None:
thesaurus = queryUtility(IThesaurus)
if thesaurus is not None:
terms = thesaurus.terms
return [terms[term] for term in value]
else:
return []
class ThesaurusTermsListWidget(TextWidget):
"""Thesaurus terms list widget"""
implementsOnly(IThesaurusTermsListFieldWidget)
thesaurus_name = FieldProperty(IThesaurusTermsListFieldWidget['thesaurus_name'])
extract_name = FieldProperty(IThesaurusTermsListFieldWidget['extract_name'])
display_terms_selector = FieldProperty(IThesaurusTermsListFieldWidget['display_terms_selector'])
backspace_removes_last = FieldProperty(IThesaurusTermsListFieldWidget['backspace_removes_last'])
size = 10
multiple = True
def update(self):
super(ThesaurusTermsListWidget, self).update()
self.thesaurus_name = self.field.thesaurus_name or u''
self.extract_name = self.field.extract_name or u''
def updateTerms(self):
self.terms = []
return self.terms
def getThesaurusURL(self):
thesaurus = queryUtility(IThesaurus, self.thesaurus_name)
if thesaurus is not None:
return absoluteURL(thesaurus, self.request)
def render(self):
jquery_multiselect.need()
ztfy_thesaurus.need()
return super(ThesaurusTermsListWidget, self).render()
@adapter(IField, IZTFYBrowserLayer)
@implementer(IFieldWidget)
def ThesaurusTermsListFieldWidget(field, request):
return FieldWidget(field, ThesaurusTermsListWidget(request)) | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/widget/term.py | term.py |
# import standard packages
# import Zope3 interfaces
# import local interfaces
from ztfy.thesaurus.interfaces.term import STATUS_ARCHIVED
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus
# import Zope3 packages
from z3c.jsonrpc.publisher import MethodPublisher
from zope.component import queryUtility
# import local packages
from ztfy.utils.list import unique
class ThesaurusTermsSearchView(MethodPublisher):
"""Thesaurus terms search view"""
def findTerms(self, query, thesaurus_name='', extract_name='',
autoexpand='on_miss', glob='end', limit=50):
allow_archives = True
if IThesaurus.providedBy(self.context):
thesaurus = self.context
else:
thesaurus = queryUtility(IThesaurus, thesaurus_name)
if thesaurus is None:
return []
allow_archives = False
return [{'value': term.caption,
'caption': term.caption}
for term in unique(thesaurus.findTerms(query, extract_name, autoexpand, glob, limit,
exact=True, stemmed=True),
idfun=lambda x: x.caption)
if allow_archives or (term.status != STATUS_ARCHIVED)]
def findTermsWithLabel(self, query, thesaurus_name='', extract_name='',
autoexpand='on_miss', glob='end', limit=50):
allow_archives = True
if IThesaurus.providedBy(self.context):
thesaurus = self.context
else:
thesaurus = queryUtility(IThesaurus, thesaurus_name)
if thesaurus is None:
return []
allow_archives = False
return [{'value': term.label,
'caption': term.label}
for term in unique(thesaurus.findTerms(query, extract_name, autoexpand, glob, limit,
exact=True, stemmed=True),
idfun=lambda x: x.label)
if allow_archives or (term.status != STATUS_ARCHIVED)] | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/browser/json/search.py | search.py |
# import standard packages
import logging
logger = logging.getLogger('ztfy.thesaurus')
# import Zope3 interfaces
from transaction.interfaces import ITransactionManager
from zope.component.interfaces import ISite
from zope.intid.interfaces import IIntIds
# import local interfaces
from ztfy.thesaurus.interfaces.term import IThesaurusTerm
from ztfy.thesaurus.interfaces.thesaurus import IThesaurus
# import Zope3 packages
from zope.app.publication.zopepublication import ZopePublication
from zope.component import getUtility, getUtilitiesFor
from zope.location import locate
from zope.site import hooks
# import local packages
from ztfy.utils.catalog import indexObject
from ztfy.utils.catalog.index import TextIndexNG
def evolve(context):
"""Create stemm_label index in each thesaurus"""
root_folder = context.connection.root().get(ZopePublication.root_name, None)
for site in root_folder.values():
if ISite(site, None) is not None:
hooks.setSite(site)
intids = getUtility(IIntIds)
for name, thesaurus in getUtilitiesFor(IThesaurus):
catalog = thesaurus.catalog
if 'stemm_label' not in catalog:
# create index
logger.info("Adding stemmed index in '%s' inner catalog..." % name)
index = TextIndexNG('label', IThesaurusTerm,
field_callable=False,
languages=thesaurus.language,
splitter='txng.splitters.default',
storage='txng.storages.term_frequencies',
dedicated_storage=False,
use_stopwords=True,
use_normalizer=True,
use_stemmer=True,
ranking=True)
locate(index, catalog, 'stemm_label')
catalog['stemm_label'] = index
# index terms in new index
logger.info("Indexing terms in '%s' inner catalog..." % name)
for index, term in enumerate(thesaurus.terms.itervalues()):
indexObject(term, catalog, 'stemm_label', intids=intids)
if not index % 100:
ITransactionManager(catalog).savepoint() | ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/src/ztfy/thesaurus/generations/evolve2.py | evolve2.py |
======================
ztfy.thesaurus package
======================
.. contents::
What is ztfy.thesaurus ?
========================
ztfy.thesaurus is a quite small package used to handle content's indexation
through the help of a structured and controlled vocabulary's thesaurus, which is
like a big hierarchic dictionary of terms linked together.
Several XML standards have emerged to handle such thesauri ; this package is mainly based
on a custom format but can import and export data in formats like SKOS (RDF) and SuperDoc.
How to use ztfy.thesaurus ?
===========================
A set of ztfy.thesaurus usages are given as doctests in ztfy/thesaurus/doctests/README.txt
| ztfy.thesaurus | /ztfy.thesaurus-0.2.16.1.tar.gz/ztfy.thesaurus-0.2.16.1/docs/README.txt | README.txt |
==================
ztfy.utils package
==================
You may find documentation in:
- Global README.txt: ztfy/utils/docs/README.txt
- General: ztfy/utils/docs
- Technical: ztfy/utils/doctests
More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available
on ZTFY.utils_.
This package is created and maintained by Thierry Florac_.
.. _Thierry Florac: mailto:[email protected]
.. _ZTFY.org: http://www.ztfy.org
.. _ZTFY.utils: http://trac.ztfy.org/ztfy.utils
| ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/README.txt | README.txt |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
__version__ = '2015-07-01'
# See zc.buildout's changelog if this version is up to date.
tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --buildout-version, "
"the bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
options, args = parser.parse_args()
if options.version:
print("bootstrap.py version %s" % __version__)
sys.exit(0)
######################################################################
# load/install setuptools
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
requirement = 'zc.buildout'
version = options.buildout_version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/bootstrap.py | bootstrap.py |
# import standard packages
from persistent.list import PersistentList
from persistent.dict import PersistentDict
# import Zope3 interfaces
from zope.authentication.interfaces import IAuthentication
from zope.pluggableauth.interfaces import IPrincipalInfo
# import local interfaces
# import Zope3 packages
from zc.set import Set
from zope.component import getUtility
from zope.deprecation.deprecation import deprecate
from zope.i18n import translate
from zope.interface import implements
from zope.security.proxy import removeSecurityProxy
# import local packages
from ztfy.utils.request import getRequest
from ztfy.utils import _
def unproxied(value):
"""Remove security proxies from given value ; if value is a list or dict, all elements are unproxied"""
if isinstance(value, (list, PersistentList)):
result = []
for v in value:
result.append(unproxied(v))
elif isinstance(value, (dict, PersistentDict)):
result = value.copy()
for v in value:
result[v] = unproxied(value[v])
elif isinstance(value, (set, Set)):
result = []
for v in value:
result.append(unproxied(v))
else:
result = removeSecurityProxy(value)
return result
@deprecate("ztfy.utils.security.MissingPrincipal is deprecated. Use ztfy.security.search.MissingPrincipal class instead.")
class MissingPrincipal(object):
implements(IPrincipalInfo)
def __init__(self, id):
self.id = id
self.request = getRequest()
@property
def title(self):
return translate(_("< missing principal %s >"), context=self.request) % self.id
@property
def description(self):
return translate(_("This principal can't be found in any authentication utility..."), context=self.request)
@deprecate("ztfy.utils.security.getPrincipal is deprecated. Use ztfy.security.search.getPrincipal function instead.")
def getPrincipal(uid):
principals = getUtility(IAuthentication)
try:
return principals.getPrincipal(uid)
except:
return MissingPrincipal(uid) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/security.py | security.py |
__author__ = "Marius Gedminas ([email protected])"
__copyright__ = "Copyright 2004-2006, Marius Gedminas"
__license__ = "MIT"
__version__ = "1.0"
__date__ = "2006-12-06"
import atexit
import inspect
import sys
import re
import cPickle as pickle
# For profiling
from profile import Profile
import pstats
# For hotshot profiling (inaccurate!)
import hotshot
import hotshot.stats
# For trace.py coverage
import trace
# For hotshot coverage (inaccurate!; uses undocumented APIs; might break)
import _hotshot
import hotshot.log
# For timecall
import time
def profile(fn=None, skip=0, filename=None, immediate=False):
"""Mark `fn` for profiling.
If `immediate` is False, profiling results will be printed to sys.stdout on
program termination. Otherwise results will be printed after each call.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `filename` is specified, the profile stats will be pickled and stored in
a file.
Usage:
def fn(...):
...
fn = profile(fn, skip=1)
If you are using Python 2.4, you should be able to use the decorator
syntax:
@profile(skip=3)
def fn(...):
...
or just
@profile
def fn(...):
...
"""
if fn is None: # @profile() syntax -- we are a decorator maker
def decorator(fn):
return profile(fn, skip=skip, filename=filename,
immediate=immediate)
return decorator
# @profile syntax -- we are a decorator.
fp = FuncProfile(fn, skip=skip, filename=filename, immediate=immediate)
# or HotShotFuncProfile
# We cannot return fp or fp.__call__ directly as that would break method
# definitions, instead we need to return a plain function.
def new_fn(*args, **kw):
return fp(*args, **kw)
new_fn.__doc__ = fn.__doc__
return new_fn
def coverage(fn):
"""Mark `fn` for line coverage analysis.
Results will be printed to sys.stdout on program termination.
Usage:
def fn(...):
...
fn = coverage(fn)
If you are using Python 2.4, you should be able to use the decorator
syntax:
@coverage
def fn(...):
...
"""
fp = TraceFuncCoverage(fn) # or HotShotFuncCoverage
# We cannot return fp or fp.__call__ directly as that would break method
# definitions, instead we need to return a plain function.
def new_fn(*args, **kw):
return fp(*args, **kw)
new_fn.__doc__ = fn.__doc__
return new_fn
def coverage_with_hotshot(fn):
"""Mark `fn` for line coverage analysis.
Uses the 'hotshot' module for fast coverage analysis.
BUG: Produces inaccurate results.
See the docstring of `coverage` for usage examples.
"""
fp = HotShotFuncCoverage(fn)
# We cannot return fp or fp.__call__ directly as that would break method
# definitions, instead we need to return a plain function.
def new_fn(*args, **kw):
return fp(*args, **kw)
new_fn.__doc__ = fn.__doc__
return new_fn
class FuncProfile:
"""Profiler for a function (uses profile)."""
# This flag is shared between all instances
in_profiler = False
def __init__(self, fn, skip=0, filename=None, immediate=False):
"""Creates a profiler for a function.
Every profiler has its own log file (the name of which is derived from
the function name).
HotShotFuncProfile registers an atexit handler that prints profiling
information to sys.stderr when the program terminates.
The log file is not removed and remains there to clutter the current
working directory.
"""
self.fn = fn
self.filename = filename
self.immediate = immediate
self.stats = pstats.Stats(Profile())
self.ncalls = 0
self.skip = skip
self.skipped = 0
atexit.register(self.atexit)
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
if self.skip > 0:
self.skip -= 1
self.skipped += 1
return self.fn(*args, **kw)
if FuncProfile.in_profiler:
# handle recursive calls
return self.fn(*args, **kw)
# You cannot reuse the same profiler for many calls and accumulate
# stats that way. :-/
profiler = Profile()
try:
FuncProfile.in_profiler = True
return profiler.runcall(self.fn, *args, **kw)
finally:
FuncProfile.in_profiler = False
self.stats.add(profiler)
if self.immediate:
self.print_stats()
self.reset_stats()
def print_stats(self):
"""Print profile information to sys.stdout."""
funcname = self.fn.__name__
filename = self.fn.func_code.co_filename
lineno = self.fn.func_code.co_firstlineno
print
print "*** PROFILER RESULTS ***"
print "%s (%s:%s)" % (funcname, filename, lineno)
print "function called %d times" % self.ncalls,
if self.skipped:
print "(%d calls not profiled)" % self.skipped
else:
print
print
stats = self.stats
if self.filename:
pickle.dump(stats, file(self.filename, 'w'))
stats.strip_dirs()
stats.sort_stats('cumulative', 'time', 'calls')
stats.print_stats(40)
def reset_stats(self):
"""Reset accumulated profiler statistics."""
self.stats = pstats.Stats(Profile())
self.ncalls = 0
self.skipped = 0
def atexit(self):
"""Stop profiling and print profile information to sys.stdout.
This function is registered as an atexit hook.
"""
if not self.immediate:
self.print_stats()
class HotShotFuncProfile:
"""Profiler for a function (uses hotshot)."""
# This flag is shared between all instances
in_profiler = False
def __init__(self, fn, skip=0, filename=None):
"""Creates a profiler for a function.
Every profiler has its own log file (the name of which is derived from
the function name).
HotShotFuncProfile registers an atexit handler that prints profiling
information to sys.stderr when the program terminates.
The log file is not removed and remains there to clutter the current
working directory.
"""
self.fn = fn
self.filename = filename
if self.filename:
self.logfilename = filename + ".raw"
else:
self.logfilename = fn.__name__ + ".prof"
self.profiler = hotshot.Profile(self.logfilename)
self.ncalls = 0
self.skip = skip
self.skipped = 0
atexit.register(self.atexit)
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
if self.skip > 0:
self.skip -= 1
self.skipped += 1
return self.fn(*args, **kw)
if HotShotFuncProfile.in_profiler:
# handle recursive calls
return self.fn(*args, **kw)
try:
HotShotFuncProfile.in_profiler = True
return self.profiler.runcall(self.fn, *args, **kw)
finally:
HotShotFuncProfile.in_profiler = False
def atexit(self):
"""Stop profiling and print profile information to sys.stderr.
This function is registered as an atexit hook.
"""
self.profiler.close()
funcname = self.fn.__name__
filename = self.fn.func_code.co_filename
lineno = self.fn.func_code.co_firstlineno
print
print "*** PROFILER RESULTS ***"
print "%s (%s:%s)" % (funcname, filename, lineno)
print "function called %d times" % self.ncalls,
if self.skipped:
print "(%d calls not profiled)" % self.skipped
else:
print
print
stats = hotshot.stats.load(self.logfilename)
# hotshot.stats.load takes ages, and the .prof file eats megabytes, but
# a pickled stats object is small and fast
if self.filename:
pickle.dump(stats, file(self.filename, 'w'))
# it is best to pickle before strip_dirs
stats.strip_dirs()
stats.sort_stats('cumulative', 'time', 'calls')
stats.print_stats(200)
class HotShotFuncCoverage:
"""Coverage analysis for a function (uses _hotshot).
HotShot coverage is reportedly faster than trace.py, but it appears to
have problems with exceptions; also line counts in coverage reports
are generally lower from line counts produced by TraceFuncCoverage.
Is this my bug, or is it a problem with _hotshot?
"""
def __init__(self, fn):
"""Creates a profiler for a function.
Every profiler has its own log file (the name of which is derived from
the function name).
HotShotFuncCoverage registers an atexit handler that prints profiling
information to sys.stderr when the program terminates.
The log file is not removed and remains there to clutter the current
working directory.
"""
self.fn = fn
self.logfilename = fn.__name__ + ".cprof"
self.profiler = _hotshot.coverage(self.logfilename)
self.ncalls = 0
atexit.register(self.atexit)
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
return self.profiler.runcall(self.fn, args, kw)
def atexit(self):
"""Stop profiling and print profile information to sys.stderr.
This function is registered as an atexit hook.
"""
self.profiler.close()
funcname = self.fn.__name__
filename = self.fn.func_code.co_filename
lineno = self.fn.func_code.co_firstlineno
print
print "*** COVERAGE RESULTS ***"
print "%s (%s:%s)" % (funcname, filename, lineno)
print "function called %d times" % self.ncalls
print
fs = FuncSource(self.fn)
reader = hotshot.log.LogReader(self.logfilename)
for what, (filename, lineno, funcname), tdelta in reader:
if filename != fs.filename:
continue
if what == hotshot.log.LINE:
fs.mark(lineno)
if what == hotshot.log.ENTER:
# hotshot gives us the line number of the function definition
# and never gives us a LINE event for the first statement in
# a function, so if we didn't perform this mapping, the first
# statement would be marked as never executed
if lineno == fs.firstlineno:
lineno = fs.firstcodelineno
fs.mark(lineno)
reader.close()
print fs
class TraceFuncCoverage:
"""Coverage analysis for a function (uses trace module).
HotShot coverage analysis is reportedly faster, but it appears to have
problems with exceptions.
"""
# Shared between all instances so that nested calls work
tracer = trace.Trace(count=True, trace=False,
ignoredirs=[sys.prefix, sys.exec_prefix])
# This flag is also shared between all instances
tracing = False
def __init__(self, fn):
"""Creates a profiler for a function.
Every profiler has its own log file (the name of which is derived from
the function name).
TraceFuncCoverage registers an atexit handler that prints profiling
information to sys.stderr when the program terminates.
The log file is not removed and remains there to clutter the current
working directory.
"""
self.fn = fn
self.logfilename = fn.__name__ + ".cprof"
self.ncalls = 0
atexit.register(self.atexit)
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
if TraceFuncCoverage.tracing:
return self.fn(*args, **kw)
try:
TraceFuncCoverage.tracing = True
return self.tracer.runfunc(self.fn, *args, **kw)
finally:
TraceFuncCoverage.tracing = False
def atexit(self):
"""Stop profiling and print profile information to sys.stderr.
This function is registered as an atexit hook.
"""
funcname = self.fn.__name__
filename = self.fn.func_code.co_filename
lineno = self.fn.func_code.co_firstlineno
print
print "*** COVERAGE RESULTS ***"
print "%s (%s:%s)" % (funcname, filename, lineno)
print "function called %d times" % self.ncalls
print
fs = FuncSource(self.fn)
for (filename, lineno), count in self.tracer.counts.items():
if filename != fs.filename:
continue
fs.mark(lineno, count)
print fs
never_executed = fs.count_never_executed()
if never_executed:
print "%d lines were not executed." % never_executed
class FuncSource:
"""Source code annotator for a function."""
blank_rx = re.compile(r"^\s*finally:\s*(#.*)?$")
def __init__(self, fn):
self.fn = fn
self.filename = inspect.getsourcefile(fn)
self.source, self.firstlineno = inspect.getsourcelines(fn)
self.sourcelines = {}
self.firstcodelineno = self.firstlineno
self.find_source_lines()
def find_source_lines(self):
"""Mark all executable source lines in fn as executed 0 times."""
strs = trace.find_strings(self.filename)
lines = trace.find_lines_from_code(self.fn.func_code, strs)
self.firstcodelineno = sys.maxint
for lineno in lines:
self.firstcodelineno = min(self.firstcodelineno, lineno)
self.sourcelines.setdefault(lineno, 0)
if self.firstcodelineno == sys.maxint:
self.firstcodelineno = self.firstlineno
def mark(self, lineno, count=1):
"""Mark a given source line as executed count times.
Multiple calls to mark for the same lineno add up.
"""
self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count
def count_never_executed(self):
"""Count statements that were never executed."""
lineno = self.firstlineno
counter = 0
for line in self.source:
if self.sourcelines.get(lineno) == 0:
if not self.blank_rx.match(line):
counter += 1
lineno += 1
return counter
def __str__(self):
"""Return annotated source code for the function."""
lines = []
lineno = self.firstlineno
for line in self.source:
counter = self.sourcelines.get(lineno)
if counter is None:
prefix = ' ' * 7
elif counter == 0:
if self.blank_rx.match(line):
prefix = ' ' * 7
else:
prefix = '>' * 6 + ' '
else:
prefix = '%5d: ' % counter
lines.append(prefix + line)
lineno += 1
return ''.join(lines)
def timecall(fn):
"""Wrap `fn` and print its execution time.
Example:
@timecall
def somefunc(x, y):
time.sleep(x * y)
somefunc(2, 3)
will print
somefunc: 6.0 seconds
"""
def new_fn(*args, **kw):
try:
start = time.time()
return fn(*args, **kw)
finally:
duration = time.time() - start
funcname = fn.__name__
filename = fn.func_code.co_filename
lineno = fn.func_code.co_firstlineno
print >> sys.stderr, "\n %s (%s:%s):\n %.3f seconds\n" % (
funcname, filename, lineno, duration)
new_fn.__doc__ = fn.__doc__
return new_fn | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/profilehooks.py | profilehooks.py |
__docformat__ = "restructuredtext"
# import standard packages
from sgmllib import SGMLParser
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
# import local packages
class HTMLParser(SGMLParser):
data = ''
entitydefs = { 'amp': '&', 'lt': '<', 'gt': '>',
'apos': "'", 'quot': '"',
'Agrave': 'À', 'Aacute': 'A', 'Acirc': 'Â', 'Atilde': 'A', 'Auml': 'Ä', 'Aring': 'A',
'AElig': 'AE',
'Ccedil': 'Ç',
'Egrave': 'É', 'Eacute': 'È', 'Ecirc': 'Ê', 'Euml': 'Ë',
'Igrave': 'I', 'Iacute': 'I', 'Icirc': 'I', 'Iuml': 'I',
'Ntilde': 'N',
'Ograve': 'O', 'Oacute': 'O', 'Ocirc': 'Ô', 'Otilde': 'O', 'Ouml': 'Ö', 'Oslash': 'O',
'Ugrave': 'Ù', 'Uacute': 'U', 'Ucirc': 'Û', 'Uuml': 'Ü',
'Yacute': 'Y',
'THORN': 'T',
'agrave': 'à', 'aacute': 'a', 'acirc': 'â', 'atilde': 'a', 'auml': 'ä', 'aring': 'a', 'aelig': 'ae',
'ccedil': 'ç',
'egrave': 'è', 'eacute': 'é', 'ecirc': 'ê', 'euml': 'ë',
'igrave': 'i', 'iacute': 'i', 'icirc': 'î', 'iuml': 'ï',
'ntilde': 'n',
'ograve': 'o', 'oacute': 'o', 'ocirc': 'ô', 'otilde': 'o', 'ouml': 'ö', 'oslash': 'o',
'ugrave': 'ù', 'uacute': 'u', 'ucirc': 'û', 'uuml': 'ü',
'yacute': 'y',
'thorn': 't',
'yuml': 'ÿ' }
charrefs = { 34 : '"', 38 : '&', 39 : "'",
60 : '<', 62 : '>',
192 : 'À', 193 : 'A', 194 : 'Â', 195 : 'A', 196 : 'Ä', 197 : 'A',
198 : 'AE',
199 : 'Ç',
200 : 'È', 201 : 'É', 202 : 'Ê', 203 : 'Ë',
204 : 'I', 205 : 'I', 206 : 'Î', 207 : 'Ï',
208 : 'D',
209 : 'N',
210 : 'O', 211 : 'O', 212 : 'Ô', 213 : 'O', 214 : 'Ö', 216 : 'O',
215 : 'x',
217 : 'Ù', 218 : 'U', 219 : 'Û', 220 : 'Ü',
221 : 'Y', 222 : 'T',
223 : 'sz',
224 : 'à', 225 : 'a', 226 : 'â', 227 : 'a', 228 : 'ä', 229 : 'a',
230 : 'ae',
231 : 'ç',
232 : 'è', 233 : 'é', 234 : 'ê', 235 : 'ë',
236 : 'i', 237 : 'i', 238 : 'î', 239 : 'ï',
240 : 'e',
241 : 'n',
242 : 'o', 243 : 'o', 244 : 'ô', 245 : 'o', 246 : 'ö', 248 : 'o',
249 : 'ù', 250 : 'u', 251 : 'û', 252 : 'ü',
253 : 'y', 255 : 'ÿ' }
def handle_data(self, data):
try:
self.data += data
except:
self.data += unicode(data, 'utf8')
def handle_charref(self, name):
try:
n = int(name)
except ValueError:
self.unknown_charref(name)
return
if not 0 <= n <= 255:
self.unknown_charref(name)
return
self.handle_data(self.charrefs.get(n) or unicode(chr(n), 'latin1'))
def start_td(self, attributes):
self.data += ' '
def start_p(self, attributes):
pass
def end_p(self):
self.data += '\n'
def htmlToText(value):
"""Utility function to extract text content from HTML"""
if value is None:
return ''
parser = HTMLParser()
parser.feed(value)
parser.close()
return parser.data | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/html.py | html.py |
# import standard packages
import codecs
import string
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
# import local packages
_unicodeTransTable = {}
def _fillUnicodeTransTable():
_corresp = [
(u"A", [0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x0100, 0x0102, 0x0104]),
(u"AE", [0x00C6]),
(u"a", [0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x0101, 0x0103, 0x0105]),
(u"ae", [0x00E6]),
(u"C", [0x00C7, 0x0106, 0x0108, 0x010A, 0x010C]),
(u"c", [0x00E7, 0x0107, 0x0109, 0x010B, 0x010D]),
(u"D", [0x00D0, 0x010E, 0x0110]),
(u"d", [0x00F0, 0x010F, 0x0111]),
(u"E", [0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0112, 0x0114, 0x0116, 0x0118, 0x011A]),
(u"e", [0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0113, 0x0115, 0x0117, 0x0119, 0x011B]),
(u"G", [0x011C, 0x011E, 0x0120, 0x0122]),
(u"g", [0x011D, 0x011F, 0x0121, 0x0123]),
(u"H", [0x0124, 0x0126]),
(u"h", [0x0125, 0x0127]),
(u"I", [0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x0128, 0x012A, 0x012C, 0x012E, 0x0130]),
(u"i", [0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x0129, 0x012B, 0x012D, 0x012F, 0x0131]),
(u"IJ", [0x0132]),
(u"ij", [0x0133]),
(u"J", [0x0134]),
(u"j", [0x0135]),
(u"K", [0x0136]),
(u"k", [0x0137, 0x0138]),
(u"L", [0x0139, 0x013B, 0x013D, 0x013F, 0x0141]),
(u"l", [0x013A, 0x013C, 0x013E, 0x0140, 0x0142]),
(u"N", [0x00D1, 0x0143, 0x0145, 0x0147, 0x014A]),
(u"n", [0x00F1, 0x0144, 0x0146, 0x0148, 0x0149, 0x014B]),
(u"O", [0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D8, 0x014C, 0x014E, 0x0150]),
(u"o", [0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F8, 0x014D, 0x014F, 0x0151]),
(u"OE", [0x0152]),
(u"oe", [0x0153]),
(u"R", [0x0154, 0x0156, 0x0158]),
(u"r", [0x0155, 0x0157, 0x0159]),
(u"S", [0x015A, 0x015C, 0x015E, 0x0160]),
(u"s", [0x015B, 0x015D, 0x015F, 0x01610, 0x017F]),
(u"T", [0x0162, 0x0164, 0x0166]),
(u"t", [0x0163, 0x0165, 0x0167]),
(u"U", [0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x0168, 0x016A, 0x016C, 0x016E, 0x0170, 0x172]),
(u"u", [0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0169, 0x016B, 0x016D, 0x016F, 0x0171]),
(u"W", [0x0174]),
(u"w", [0x0175]),
(u"Y", [0x00DD, 0x0176, 0x0178]),
(u"y", [0x00FD, 0x00FF, 0x0177]),
(u"Z", [0x0179, 0x017B, 0x017D]),
(u"z", [0x017A, 0x017C, 0x017E])
]
for char, codes in _corresp:
for code in codes :
_unicodeTransTable[code] = char
_fillUnicodeTransTable()
def translateString(s, escapeSlashes=False, forceLower=True, spaces=' ', keep_chars='_-.'):
"""Remove extended characters from string and replace them with 'basic' ones
@param s: text to be cleaned.
@type s: str or unicode
@param escapeSlashes: if True, slashes are also converted
@type escapeSlashes: boolean
@param forceLower: if True, result is automatically converted to lower case
@type forceLower: boolean
@return: text without diacritics
@rtype: unicode
"""
if escapeSlashes:
s = string.replace(s, "\\", "/").split("/")[-1]
s = s.strip()
if isinstance(s, str):
s = unicode(s, "utf8", "replace")
s = s.translate(_unicodeTransTable)
s = ''.join([a for a in s.translate(_unicodeTransTable)
if a.replace(' ', '-') in (string.ascii_letters + string.digits + (keep_chars or ''))])
if forceLower:
s = s.lower()
if spaces != ' ':
s = s.replace(' ', spaces)
return s
def nvl(value, default=''):
"""Get specified value, or an empty string if value is empty
@param value: text to be checked
@param default: default value
@return: value, or default if value is empty
"""
return value or default
def uninvl(value, default=u''):
"""Get specified value converted to unicode, or an empty unicode string if value is empty
@param value: text to be checked
@type value: str or unicode
@param default: default value
@return: value, or default if value is empty
@rtype: unicode
"""
try:
if isinstance(value, unicode):
return value
return codecs.decode(value or default)
except:
return codecs.decode(value or default, 'latin1')
def unidict(value):
"""Get specified dict with values converted to unicode
@param value: input dict of strings which may be converted to unicode
@type value: dict
@return: input dict converted to unicode
@rtype: dict
"""
result = {}
for key in value:
result[key] = uninvl(value[key])
return result
def unilist(value):
"""Get specified list with values converted to unicode
@param value: input list of strings which may be converted to unicode
@type value: list
@return: input list converted to unicode
@rtype: list
"""
if not isinstance(value, (list, tuple)):
return uninvl(value)
return [uninvl(v) for v in value]
def encode(value, encoding='utf-8'):
"""Encode given value with encoding"""
return value.encode(encoding) if isinstance(value, unicode) else value
def utf8(value):
"""Encode given value tu UTF-8"""
return encode(value, 'utf-8')
def decode(value, encoding='utf-8'):
"""Decode given value with encoding"""
return value.decode(encoding) if isinstance(value, str) else value | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/unicode.py | unicode.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.component.interfaces import IObjectEvent
# import local interfaces
# import Zope3 packages
from zope.interface import Interface, Attribute
from zope.schema import TextLine, Int, Password, Bool
# import local packages
from ztfy.utils import _
class INewSiteManagerEvent(IObjectEvent):
"""Event interface for new site manager event"""
#
# Generic list interface
#
class IListInfo(Interface):
"""Custom interface used to handle list-like components"""
def count(self):
"""Get list items count"""
def index(self):
"""Get position of the given item"""
def __contains__(self, value):
"""Check if given value is in list"""
def __getitem__(self, index):
"""Return item at given position"""
def __iter__(self):
"""Iterator over list items"""
class IListWriter(Interface):
"""Writer interface for list-like components"""
def append(self, value):
"""Append value to list"""
def extend(self, values):
"""Extend list with given items"""
def insert(self, index, value):
"""Insert item to given index"""
def pop(self):
"""Pop item from list and returns it"""
def remove(self, value):
"""Remove given item from list"""
def reverse(self):
"""Sort list in reverse order"""
def sort(self):
"""Sort list"""
class IList(IListInfo, IListWriter):
"""Marker interface for list-like components"""
#
# Generic dict interface
#
class IDictInfo(Interface):
"""Custom interface used to handle dict-like components"""
def keys(self):
"""Get list of keys for the dict"""
def has_key(self, key):
"""Check to know if dict includes the given key"""
def get(self, key, default=None):
"""Get given key or default from dict"""
def copy(self,):
"""Duplicate content of dict"""
def __contains__(self, key):
"""Check if given key is in dict"""
def __getitem__(self, key):
"""Get given key value from dict"""
def __iter__(self):
"""Iterator over dictionnary keys"""
class IDictWriter(Interface):
"""Writer interface for dict-like components"""
def clear(self):
"""Clear dict"""
def update(self, b):
"""Update dict with given values"""
def setdefault(self, key, failobj=None):
"""Create value for given key if missing"""
def pop(self, key, *args):
"""Remove and return given key from dict"""
def popitem(self, item):
"""Pop item from dict"""
def __setitem__(self, key, value):
"""Update given key with given value"""
def __delitem__(self, key):
"""Remove selected key from dict"""
class IDict(IDictInfo, IDictWriter):
"""Marker interface for dict-like components"""
#
# Generic set interfaces
#
class ISetInfo(Interface):
"""Set-like interfaces"""
def copy(self, *args, **kwargs):
""" Return a shallow copy of a set. """
def difference(self, *args, **kwargs):
"""Return the difference of two or more sets as a new set"""
def intersection(self, *args, **kwargs):
"""Return the intersection of two or more sets as a new set"""
def isdisjoint(self, *args, **kwargs):
""" Return True if two sets have a null intersection. """
def issubset(self, *args, **kwargs):
""" Report whether another set contains this set. """
def issuperset(self, *args, **kwargs):
""" Report whether this set contains another set. """
def symmetric_difference(self, *args, **kwargs):
"""Return the symmetric difference of two sets as a new set"""
def union(self, *args, **kwargs):
"""Return the union of sets as a new set"""
def __and__(self, y):
""" x.__and__(y) <==> x&y """
def __cmp__(self, y):
""" x.__cmp__(y) <==> cmp(x,y) """
def __contains__(self, y):
""" x.__contains__(y) <==> y in x. """
def __eq__(self, y):
""" x.__eq__(y) <==> x==y """
def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
def __ge__(self, y):
""" x.__ge__(y) <==> x>=y """
def __gt__(self, y):
""" x.__gt__(y) <==> x>y """
def __hash__(self):
"""Compute hash value"""
def __iter__(self):
""" x.__iter__() <==> iter(x) """
def __len__(self):
""" x.__len__() <==> len(x) """
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
def __or__(self, y): # real signature unknown; restored from __doc__
""" x.__or__(y) <==> x|y """
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
def __rand__(self, y):
""" x.__rand__(y) <==> y&x """
def __ror__(self, y):
""" x.__ror__(y) <==> y|x """
def __rsub__(self, y):
""" x.__rsub__(y) <==> y-x """
def __rxor__(self, y):
""" x.__rxor__(y) <==> y^x """
def __sizeof__(self):
""" S.__sizeof__() -> size of S in memory, in bytes """
def __sub__(self, y):
""" x.__sub__(y) <==> x-y """
def __xor__(self, y):
""" x.__xor__(y) <==> x^y """
class ISetWriter(Interface):
"""Set-like writer interface"""
def add(self, *args, **kwargs):
"""Add an element to set"""
def clear(self, *args, **kwargs):
""" Remove all elements from this set. """
def difference_update(self, *args, **kwargs):
""" Remove all elements of another set from this set. """
def discard(self, *args, **kwargs):
"""Remove an element from a set if it is a member"""
def intersection_update(self, *args, **kwargs):
""" Update a set with the intersection of itself and another. """
def pop(self, *args, **kwargs):
"""Remove and return an arbitrary set element"""
def remove(self, *args, **kwargs):
"""Remove an element from a set; it must be a member"""
def symmetric_difference_update(self, *args, **kwargs):
""" Update a set with the symmetric difference of itself and another """
def update(self, *args, **kwargs):
""" Update a set with the union of itself and others. """
def __iand__(self, y):
""" x.__iand__(y) <==> x&=y """
def __ior__(self, y):
""" x.__ior__(y) <==> x|=y """
def __isub__(self, y):
""" x.__isub__(y) <==> x-=y """
def __ixor__(self, y):
""" x.__ixor__(y) <==> x^=y """
class ISet(ISetInfo, ISetWriter):
"""Marker interface for set-like components"""
#
# ZEO connection settings interface
#
class IZEOConnection(Interface):
"""ZEO connection settings interface"""
server_name = TextLine(title=_("ZEO server name"),
description=_("Hostname of ZEO server"),
required=True,
default=u'localhost')
server_port = Int(title=_("ZEO server port"),
description=_("Port number of ZEO server"),
required=True,
default=8100)
storage = TextLine(title=_("ZEO server storage"),
description=_("Storage name on ZEO server"),
required=True,
default=u'1')
username = TextLine(title=_("ZEO user name"),
description=_("User name on ZEO server"),
required=False)
password = Password(title=_("ZEO password"),
description=_("User password on ZEO server"),
required=False)
server_realm = TextLine(title=_("ZEO server realm"),
description=_("Realm name on ZEO server"),
required=False)
blob_dir = TextLine(title=_("BLOBs directory"),
description=_("Directory path for blob data"),
required=False)
shared_blob_dir = Bool(title=_("Shared BLOBs directory ?"),
description=_("""Flag whether the blob_dir is a server-shared filesystem """
"""that should be used instead of transferring blob data over zrpc."""),
required=True,
default=False)
connection = Attribute(_("Opened ZEO connection"))
def getSettings(self):
"""Get ZEO connection setting as a JSON dict"""
def update(self, settings):
"""Update internal fields with given settings dict"""
def getConnection(self, wait=False, get_storage=False):
"""Open ZEO connection with given settings""" | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/interfaces.py | interfaces.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.schema.interfaces import IVocabularyFactory, IChoice
# import local interfaces
# import Zope3 packages
from zope.i18n import translate
from zope.interface import classProvides, implements
from zope.schema import Choice
from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary
# import local packages
from ztfy.utils.request import queryRequest
from ztfy.utils import _
ENCODINGS = {
'ascii': _('English (ASCII)'),
'big5': _('Traditional Chinese (big5)'),
'big5hkscs': _('Traditional Chinese (big5hkscs)'),
'cp037': _('English (cp037)'),
'cp424': _('Hebrew (cp424)'),
'cp437': _('English (cp437)'),
'cp500': _('Western Europe (cp500)'),
'cp720': _('Arabic (cp720)'),
'cp737': _('Greek (cp737)'),
'cp775': _('Baltic languages (cp775)'),
'cp850': _('Western Europe (cp850)'),
'cp852': _('Central and Eastern Europe (cp852)'),
'cp855': _('Bulgarian, Byelorussian, Macedonian, Russian, Serbian (cp855)'),
'cp856': _('Hebrew (cp856)'),
'cp857': _('Turkish (cp857)'),
'cp858': _('Western Europe (cp858)'),
'cp860': _('Portuguese (cp860)'),
'cp861': _('Icelandic (cp861)'),
'cp862': _('Hebrew (cp862)'),
'cp863': _('Canadian (cp863)'),
'cp864': _('Arabic (cp864)'),
'cp865': _('Danish, Norwegian (cp865)'),
'cp866': _('Russian (cp866)'),
'cp869': _('Greek (cp869)'),
'cp874': _('Thai (cp874)'),
'cp875': _('Greek (cp875)'),
'cp932': _('Japanese (cp932)'),
'cp949': _('Korean (cp949)'),
'cp950': _('Traditional Chinese (cp950)'),
'cp1006': _('Urdu (cp1006)'),
'cp1026': _('Turkish (cp1026)'),
'cp1140': _('Western Europe (cp1140)'),
'cp1250': _('Central and Eastern Europe (cp1250)'),
'cp1251': _('Bulgarian, Byelorussian, Macedonian, Russian, Serbian (cp1251)'),
'cp1252': _('Western Europe (cp1252)'),
'cp1253': _('Greek (cp1253)'),
'cp1254': _('Turkish (cp1254)'),
'cp1255': _('Hebrew (cp1255)'),
'cp1256': _('Arabic (cp1256)'),
'cp1257': _('Baltic languages (cp1257)'),
'cp1258': _('Vietnamese (cp1258)'),
'euc_jp': _('Japanese (euc_jp)'),
'euc_jis_2004': _('Japanese (euc_jis_2004)'),
'euc_jisx0213': _('Japanese (euc_jisx0213)'),
'euc_kr': _('Korean (euc_kr)'),
'gb2312': _('Simplified Chinese (gb2312)'),
'gbk': _('Unified Chinese (gbk)'),
'gb18030': _('Unified Chinese (gb18030)'),
'hz': _('Simplified Chinese (hz)'),
'iso2022_jp': _('Japanese (iso2022_jp)'),
'iso2022_jp_1': _('Japanese (iso2022_jp_1)'),
'iso2022_jp_2': _('Japanese, Korean, Simplified Chinese, Western Europe, Greek (iso2022_jp_2)'),
'iso2022_jp_2004': _('Japanese (iso2022_jp_2004)'),
'iso2022_jp_3': _('Japanese (iso2022_jp_3)'),
'iso2022_jp_ext': _('Japanese (iso2022_jp_ext)'),
'iso2022_kr': _('Korean (iso2022_kr)'),
'latin_1': _('West Europe (latin_1)'),
'iso8859_2': _('Central and Eastern Europe (iso8859_2)'),
'iso8859_3': _('Esperanto, Maltese (iso8859_3)'),
'iso8859_4': _('Baltic languages (iso8859_4)'),
'iso8859_5': _('Bulgarian, Byelorussian, Macedonian, Russian, Serbian (iso8859_5)'),
'iso8859_6': _('Arabic (iso8859_6)'),
'iso8859_7': _('Greek (iso8859_7)'),
'iso8859_8': _('Hebrew (iso8859_8)'),
'iso8859_9': _('Turkish (iso8859_9)'),
'iso8859_10': _('Nordic languages (iso8859_10)'),
'iso8859_13': _('Baltic languages (iso8859_13)'),
'iso8859_14': _('Celtic languages (iso8859_14)'),
'iso8859_15': _('Western Europe (iso8859_15)'),
'iso8859_16': _('South-Eastern Europe (iso8859_16)'),
'johab': _('Korean (johab)'),
'koi8_r': _('Russian (koi8_r)'),
'koi8_u': _('Ukrainian (koi8_u)'),
'mac_cyrillic': _('Bulgarian, Byelorussian, Macedonian, Russian, Serbian (mac_cyrillic)'),
'mac_greek': _('Greek (mac_greek)'),
'mac_iceland': _('Icelandic (mac_iceland)'),
'mac_latin2': _('Central and Eastern Europe (mac_latin2)'),
'mac_roman': _('Western Europe (mac_roman)'),
'mac_turkish': _('Turkish (mac_turkish)'),
'ptcp154': _('Kazakh (ptcp154)'),
'shift_jis': _('Japanese (shift_jis)'),
'shift_jis_2004': _('Japanese (shift_jis_2004)'),
'shift_jisx0213': _('Japanese (shift_jisx0213)'),
'utf_32': _('all languages (utf_32)'),
'utf_32_be': _('all languages (utf_32_be)'),
'utf_32_le': _('all languages (utf_32_le)'),
'utf_16': _('all languages (utf_16)'),
'utf_16_be': _('all languages (BMP only - utf_16_be)'),
'utf_16_le': _('all languages (BMP only - utf_16_le)'),
'utf_7': _('all languages (utf_7)'),
'utf_8': _('all languages (utf_8)'),
'utf_8_sig': _('all languages (utf_8_sig)'),
}
class EncodingsVocabulary(SimpleVocabulary):
classProvides(IVocabularyFactory)
def __init__(self, terms, *interfaces):
request = queryRequest()
terms = [SimpleTerm(unicode(v), title=translate(t, context=request)) for v, t in ENCODINGS.iteritems()]
terms.sort(key=lambda x: x.title)
super(EncodingsVocabulary, self).__init__(terms, *interfaces)
class IEncodingField(IChoice):
"""Encoding field interface"""
class EncodingField(Choice):
"""Encoding field"""
implements(IEncodingField)
def __init__(self, values=None, vocabulary='ZTFY encodings', source=None, **kw):
if 'values' in kw:
del kw['values']
if 'source' in kw:
del kw['source']
kw['vocabulary'] = vocabulary
super(EncodingField, self).__init__(**kw) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/encoding.py | encoding.py |
# import standard packages
import decimal
import string
# import Zope3 interfaces
from z3c.form.interfaces import IWidget
from zope.schema.interfaces import ITextLine, IDecimal, IList, ITuple
# import local interfaces
# import Zope3 packages
from z3c.form.converter import BaseDataConverter, FormatterValidationError
from zope.component import adapts
from zope.interface import implements
from zope.schema import TextLine, Decimal, List, Tuple
from zope.schema._bootstrapfields import InvalidValue
# import local packages
from ztfy.utils import _
class StringLine(TextLine):
"""String line field"""
_type = str
def fromUnicode(self, value):
return str(value)
#
# Color field
#
class IColorField(ITextLine):
"""Marker interface for color fields"""
class ColorField(TextLine):
"""Color field"""
implements(IColorField)
def __init__(self, *args, **kw):
super(ColorField, self).__init__(max_length=6, *args, **kw)
def _validate(self, value):
if len(value) not in (3, 6):
raise InvalidValue, _("Color length must be 3 or 6 characters")
for v in value:
if v not in string.hexdigits:
raise InvalidValue, _("Color value must contain only valid color codes (numbers or letters between 'A' end 'F')")
super(ColorField, self)._validate(value)
#
# Pointed decimal field
#
class IDottedDecimalField(IDecimal):
"""Marker interface for dotted decimal fields"""
class DottedDecimalField(Decimal):
"""Dotted decimal field"""
implements(IDottedDecimalField)
class DottedDecimalDataConverter(BaseDataConverter):
"""Dotted decimal field data converter"""
adapts(IDottedDecimalField, IWidget)
errorMessage = _('The entered value is not a valid decimal literal.')
def __init__(self, field, widget):
super(DottedDecimalDataConverter, self).__init__(field, widget)
def toWidgetValue(self, value):
if not value:
return self.field.missing_value
return str(value)
def toFieldValue(self, value):
if value is self.field.missing_value:
return u''
if not value:
return None
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
raise FormatterValidationError(self.errorMessage, value)
#
# Dates range field
#
class IDatesRangeField(ITuple):
"""Marker interface for dates range fields"""
class DatesRangeField(Tuple):
"""Dates range field"""
implements(IDatesRangeField)
def __init__(self, value_type=None, unique=False, **kw):
super(DatesRangeField, self).__init__(value_type=None, unique=False,
min_length=2, max_length=2, **kw)
#
# TextLine list field
#
class ITextLineListField(IList):
"""Marker interface for textline list field"""
class TextLineListField(List):
"""TextLine list field"""
implements(ITextLineListField)
def __init__(self, value_type=None, unique=False, **kw):
super(TextLineListField, self).__init__(value_type=TextLine(), unique=True, **kw) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/schema.py | schema.py |
# import standard packages
from datetime import datetime
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
from zope.datetime import parseDatetimetz
from zope.i18n import translate
# import local packages
from ztfy.utils.request import queryRequest
from ztfy.utils.timezone import gmtime, tztime
from ztfy.utils import _
def unidate(value):
"""Get specified date converted to unicode ISO format
Dates are always assumed to be stored in GMT timezone
@param value: input date to convert to unicode
@type value: date or datetime
@return: input date converted to unicode
@rtype: unicode
"""
if value is not None:
value = gmtime(value)
return unicode(value.isoformat('T'), 'ascii')
return None
def parsedate(value):
"""Get date specified in unicode ISO format to Python datetime object
Dates are always assumed to be stored in GMT timezone
@param value: unicode date to be parsed
@type value: unicode
@return: the specified value, converted to datetime
@rtype: datetime
"""
if value is not None:
return gmtime(parseDatetimetz(value))
return None
def datetodatetime(value):
"""Get datetime value converted from a date or datetime object
@param value: a date or datetime value to convert
@type value: date or datetime
@return: input value converted to datetime
@rtype: datetime
"""
if type(value) is datetime:
return value
return datetime(value.year, value.month, value.day)
SH_DATE_FORMAT = _("%d/%m/%Y")
SH_DATETIME_FORMAT = _("%d/%m/%Y - %H:%M")
EXT_DATE_FORMAT = _("on %d/%m/%Y")
EXT_DATETIME_FORMAT = _("on %d/%m/%Y at %H:%M")
def formatDate(value, format=EXT_DATE_FORMAT, request=None):
if request is None:
request = queryRequest()
if value.year >= 1900:
return datetime.strftime(tztime(value), translate(format, context=request).encode('utf-8')).decode('utf-8')
else:
return format.replace('%d', str(value.day)) \
.replace('%m', str(value.month)) \
.replace('%Y', str(value.year))
def formatDatetime(value, format=EXT_DATETIME_FORMAT, request=None):
return formatDate(value, format, request)
def getAge(value):
"""Get age of a given datetime (including timezone) compared to current datetime (in UTC)
@param value: a datetime value, including timezone
@type value: datetime
@return: string representing value age
@rtype: gettext translated string
"""
now = gmtime(datetime.utcnow())
delta = now - value
if delta.days > 60:
return translate(_("%d months ago")) % int(round(delta.days * 1.0 / 30))
elif delta.days > 10:
return translate(_("%d weeks ago")) % int(round(delta.days * 1.0 / 7))
elif delta.days > 2:
return translate(_("%d days ago")) % delta.days
elif delta.days == 2:
return translate(_("the day before yesterday"))
elif delta.days == 1:
return translate(_("yesterday"))
else:
hours = int(round(delta.seconds * 1.0 / 3600))
if hours > 1:
return translate(_("%d hours ago")) % hours
elif delta.seconds > 300:
return translate(_("%d minutes ago")) % int(round(delta.seconds * 1.0 / 60))
else:
return translate(_("less than 5 minutes ago"))
def getDuration(v1, v2=None):
"""Get delta between two dates"""
if v2 is None:
v2 = datetime.utcnow()
assert isinstance(v1, datetime) and isinstance(v2, datetime)
v1, v2 = min(v1, v2), max(v1, v2)
delta = v2 - v1
if delta.days > 60:
return translate(_("%d months")) % int(round(delta.days * 1.0 / 30))
elif delta.days > 10:
return translate(_("%d weeks")) % int(round(delta.days * 1.0 / 7))
elif delta.days >= 2:
return translate(_("%d days")) % delta.days
else:
hours = int(round(delta.seconds * 1.0 / 3600))
if delta.days == 1:
return translate(_("%d day and %d hours")) % (delta.days, hours)
else:
if hours > 2:
return translate(_("%d hours")) % hours
else:
minutes = int(round(delta.seconds * 1.0 / 60))
if minutes > 2:
return translate(_("%d minutes")) % minutes
else:
return translate(_("%d seconds")) % delta.seconds | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/date.py | date.py |
__docformat__ = "restructuredtext"
# import standard packages
from persistent import Persistent
from persistent.interfaces import IPersistent
from transaction.interfaces import ITransactionManager
# import Zope3 interfaces
from ZODB.interfaces import IConnection
from zope.schema.interfaces import IVocabularyFactory
# import local interfaces
from ztfy.utils.interfaces import IZEOConnection
# import Zope3 packages
from ZEO import ClientStorage
from ZODB import DB
from zope.component import adapter
from zope.componentvocabulary.vocabulary import UtilityVocabulary
from zope.container.contained import Contained
from zope.interface import implementer, implements, classProvides
from zope.schema import getFieldNames
from zope.schema.fieldproperty import FieldProperty
from zope.security.proxy import removeSecurityProxy
# import local packages
class ZEOConnectionInfo(object):
"""ZEO connection info
Provides a context manager which directly returns
ZEO connection root
"""
implements(IZEOConnection)
_storage = None
_db = None
_connection = None
server_name = FieldProperty(IZEOConnection['server_name'])
server_port = FieldProperty(IZEOConnection['server_port'])
storage = FieldProperty(IZEOConnection['storage'])
username = FieldProperty(IZEOConnection['username'])
password = FieldProperty(IZEOConnection['password'])
server_realm = FieldProperty(IZEOConnection['server_realm'])
blob_dir = FieldProperty(IZEOConnection['blob_dir'])
shared_blob_dir = FieldProperty(IZEOConnection['shared_blob_dir'])
def getSettings(self):
result = {}
for name in getFieldNames(IZEOConnection):
result[name] = getattr(self, name)
return result
def update(self, settings):
names = getFieldNames(IZEOConnection)
for k, v in settings.items():
if k in names:
setattr(self, k, unicode(v) if isinstance(v, str) else v)
def getConnection(self, wait=False, get_storage=False):
"""Get a tuple made of storage and DB connection for given settings"""
storage = ClientStorage.ClientStorage((str(self.server_name), self.server_port),
storage=self.storage,
username=self.username or '',
password=self.password or '',
realm=self.server_realm,
blob_dir=self.blob_dir,
shared_blob_dir=self.shared_blob_dir,
wait=wait)
db = DB(storage)
return (storage, db) if get_storage else db
@property
def connection(self):
return self._connection
# Context management methods
def __enter__(self):
self._storage, self._db = self.getConnection(get_storage=True)
self._connection = self._db.open()
return self._connection.root()
def __exit__(self, exc_type, exc_value, traceback):
if self._connection is not None:
self._connection.close()
if self._storage is not None:
self._storage.close()
class ZEOConnectionUtility(ZEOConnectionInfo, Persistent, Contained):
"""Persistent ZEO connection settings utility"""
class ZEOConnectionVocabulary(UtilityVocabulary):
"""ZEO connections vocabulary"""
classProvides(IVocabularyFactory)
interface = IZEOConnection
nameOnly = True
# IPersistent adapters copied from zc.twist package
# also register this for adapting from IConnection
@adapter(IPersistent)
@implementer(ITransactionManager)
def transactionManager(obj):
conn = IConnection(removeSecurityProxy(obj)) # typically this will be
# zope.app.keyreference.persistent.connectionOfPersistent
try:
return conn.transaction_manager
except AttributeError:
return conn._txn_mgr
# or else we give up; who knows. transaction_manager is the more
# recent spelling. | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/zodb.py | zodb.py |
# import standard packages
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
# import local packages
from ztfy.utils.request import queryRequest, getRequestData, setRequestData
from ztfy.utils.session import getSessionData, setSessionData
class cached(object):
"""Custom property decorator to define a property or function
which is calculated only once
When applied on a function, caching is based on input arguments
"""
def __init__(self, function):
self._function = function
self._cache = {}
def __call__(self, *args):
try:
return self._cache[args]
except KeyError:
self._cache[args] = self._function(*args)
return self._cache[args]
def expire(self, *args):
del self._cache[args]
class cached_property(object):
"""A read-only @property decorator that is only evaluated once. The value is cached
on the object itself rather than the function or class; this should prevent
memory leakage.
"""
def __init__(self, fget, doc=None):
self.fget = fget
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
self.__module__ = fget.__module__
def __get__(self, obj, cls):
if obj is None:
return self
obj.__dict__[self.__name__] = result = self.fget(obj)
return result
_marker = object()
def request_property(key):
"""Define a method decorator used to store result into request's annotations
`key` is a required argument; if None, the key will be the method's object
"""
def request_decorator(func):
def wrapper(obj, key, *args, **kwargs):
request = queryRequest()
if callable(key):
key = key(obj)
if not key:
key = '{0!r}'.format(obj)
data = getRequestData(key, request, _marker)
if data is _marker:
data = func
if callable(data):
data = data(obj, *args, **kwargs)
setRequestData(key, data, request)
return data
return lambda x: wrapper(x, key=key)
return request_decorator
class session_property(object):
"""Define a property for which computed value is stored into session"""
def __init__(self, fget, app, key=None):
self.fget = fget
self.app = app
if key is None:
key = "%s.%s" % (fget.__module__, fget.__name__)
self.key = key
def __get__(self, obj, cls):
if obj is None:
return self
request = queryRequest()
data = getSessionData(request, self.app, self.key, _marker)
if data is _marker:
data = self.fget(obj)
setSessionData(request, self.app, self.key, data)
return data | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/property.py | property.py |
# import standard packages
from cStringIO import StringIO
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.publisher.interfaces import IRequest
from zope.security.interfaces import NoInteraction, IParticipation, IPrincipal
# import local interfaces
# import Zope3 packages
from zope.interface import implements
from zope.publisher.http import HTTPRequest
from zope.security.management import getInteraction, newInteraction, endInteraction
# import local packages
from ztfy.utils import _
#
# Participations functions
#
class Principal(object):
"""Basic principal"""
implements(IPrincipal)
def __init__(self, id, title=u'', description=u''):
self.id = id
self.title = title
self.description = description
class Participation(HTTPRequest):
"""Basic participation"""
implements(IParticipation)
def __init__(self, principal):
super(Participation, self).__init__(StringIO(), {})
self.setPrincipal(principal)
self.interaction = None
def newParticipation(principal, title=u'', description=u''):
principal = Principal(principal)
newInteraction(Participation(principal))
def endParticipation():
endInteraction()
#
# Request handling functions
#
def getRequest():
"""Extract request from current interaction"""
interaction = getInteraction()
for participation in interaction.participations:
if IRequest.providedBy(participation):
return participation
raise RuntimeError, _("No Request in interaction !")
def queryRequest():
try:
return getRequest()
except NoInteraction: # No current interaction
return None
except RuntimeError: # No request in interaction
return None
def getRequestPrincipal(request=None):
"""Get principal from given request"""
if request is None:
request = getRequest()
return request.principal
getPrincipal = getRequestPrincipal
def getRequestAnnotations(request=None):
"""Get annotations from given request"""
if request is None:
request = getRequest()
return IAnnotations(request)
getAnnotations = getRequestAnnotations
def getRequestData(key, request=None, default=None):
"""Get request data, stored into request annotations"""
try:
annotations = getRequestAnnotations(request)
return annotations.get(key, default)
except:
return default
getData = getRequestData
def setRequestData(key, data, request=None):
"""Define request data, stored into request annotations"""
annotations = getRequestAnnotations(request)
annotations[key] = data
setData = setRequestData | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/request.py | request.py |
__docformat__ = "restructuredtext"
# import standard packages
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.app.file.interfaces import IFile
from zope.catalog.interfaces import ICatalog
from zope.container.interfaces import IContainer
from zope.intid.interfaces import IIntIds
# import local interfaces
# import Zope3 packages
from zope.component import queryUtility, getAllUtilitiesRegisteredFor
# import local packages
from ztfy.utils import request as request_utils
#
# IntIds utility functions
#
def getIntIdUtility(name='', request=None, context=None):
"""Look for a named IIntIds utility"""
intids = None
if request is None:
request = request_utils.queryRequest()
if request is not None:
intids = request_utils.getRequestData('IntIdsUtility::' + name, request)
if intids is None:
intids = queryUtility(IIntIds, name, context=context)
if (request is not None) and (intids is not None):
request_utils.setRequestData('IntIdsUtility::' + name, intids, request)
return intids
def getObjectId(object, intids_name='', request=None, context=None):
"""Look for an object Id as recorded by given IIntIds utility"""
if object is None:
return None
if request is None:
request = request_utils.queryRequest()
intids = getIntIdUtility(intids_name, request, context)
if intids is not None:
return intids.queryId(object)
return None
def getObject(id, intids_name='', request=None, context=None):
"""Look for an object recorded by given IIntIds utility and id"""
if id is None:
return None
if request is None:
request = request_utils.queryRequest()
intids = getIntIdUtility(intids_name, request, context)
if intids is not None:
return intids.queryObject(id)
return None
#
# Catalog utility functions
#
def queryCatalog(name='', context=None):
"""Look for a registered catalog"""
return queryUtility(ICatalog, name, context=context)
def indexObject(object, catalog_name='', index_name='', request=None, context=None, intids=None):
"""Index object into a registered catalog"""
if intids is None:
if request is None:
request = request_utils.queryRequest()
intids = getIntIdUtility('', request, context)
if intids is not None:
if ICatalog.providedBy(catalog_name):
catalog = catalog_name
else:
catalog = queryCatalog(catalog_name, context)
if catalog is not None:
id = intids.register(object)
if index_name:
catalog[index_name].index_doc(id, object)
else:
catalog.index_doc(id, object)
return True
return False
def unindexObject(object, catalog_name='', index_name='', request=None, context=None):
"""Remove object from a registered catalog"""
if request is None:
request = request_utils.getRequest()
id = getObjectId(object, '', request, context)
if id is not None:
if ICatalog.providedBy(catalog_name):
catalog = catalog_name
else:
catalog = queryCatalog(catalog_name, context)
if catalog is not None:
if index_name:
catalog[index_name].unindex_doc(id)
else:
catalog.unindex_doc(id)
return True
return False
def _indexObject(object, intids, catalogs):
"""Index object data into given set of catalogs"""
id = intids.register(object)
for catalog in catalogs:
catalog.index_doc(id, object)
def _indexObjectValues(object, intids, catalogs):
"""Index object values into given set of catalogs"""
container = IContainer(object, None)
if container is not None:
for subobject in container.values():
_indexAllObject(subobject, intids, catalogs)
def _indexObjectAnnotations(object, intids, catalogs):
"""Index object annotations into given set of catalogs"""
annotations = IAnnotations(object, None)
if annotations is not None:
keys = annotations.keys()
for key in keys:
_indexAllObject(annotations[key], intids, catalogs)
file = IFile(annotations[key], None)
if file is not None:
_indexObject(file, intids, catalogs)
def _indexAllObject(object, intids, catalogs):
"""Index object, object values and annotations into given set of catalogs"""
_indexObject(object, intids, catalogs)
_indexObjectValues(object, intids, catalogs)
_indexObjectAnnotations(object, intids, catalogs)
def indexAllObjectValues(object, context=None):
"""Reindex a whole container properties and contents (including annotations) into site's catalogs"""
if context is None:
context = object
intids = queryUtility(IIntIds, context=context)
if intids is not None:
catalogs = getAllUtilitiesRegisteredFor(ICatalog, context)
if catalogs:
_indexAllObject(object, intids, catalogs) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/catalog/__init__.py | __init__.py |
__docformat__ = "restructuredtext"
# import standard packages
import re
from persistent import Persistent
from BTrees import IFBTree
# import Zope3 interfaces
from zope.index.interfaces import IInjection, IStatistics, IIndexSearch
from zopyx.txng3.core.interfaces import IStorageWithTermFrequency
from zopyx.txng3.core.interfaces.ting import ITingIndex
# import local interfaces
# import Zope3 packages
from zope.catalog.attribute import AttributeIndex
from zope.component import createObject
from zope.container.contained import Contained
from zope.interface import implements
from zopyx.txng3.core import config
from zopyx.txng3.core.index import Index
# import local packages
from hurry.query.query import IndexTerm
class TextIndexNG(AttributeIndex, Persistent, Contained):
"""Adaptation of zopyx.txng3.core for use zope.catalog index"""
implements(IInjection, IStatistics, IIndexSearch, ITingIndex)
def __init__(self,
field_name=None,
interface=None,
field_callable=False,
use_stemmer=config.defaults['use_stemmer'],
dedicated_storage=config.defaults['dedicated_storage'],
ranking=config.defaults['ranking'],
use_normalizer=config.defaults['use_normalizer'],
languages=config.DEFAULT_LANGUAGE,
use_stopwords=config.defaults['use_stopwords'],
autoexpand_limit=config.defaults['autoexpand_limit'],
splitter=config.DEFAULT_SPLITTER,
index_unknown_languages=config.defaults['index_unknown_languages'],
query_parser=config.DEFAULT_PARSER,
lexicon=config.DEFAULT_LEXICON,
splitter_additional_chars=config.defaults['splitter_additional_chars'],
storage=config.DEFAULT_STORAGE,
splitter_casefolding=config.defaults['splitter_casefolding']):
spaces = re.compile(r'\s+')
if ranking:
util = createObject(storage)
if not IStorageWithTermFrequency.providedBy(util):
raise ValueError("This storage cannot be used for ranking")
_fields = spaces.split(field_name)
AttributeIndex.__init__(self, _fields[0], interface, field_callable)
if len(_fields) < 2:
dedicated_storage = False
self._index = Index(fields=_fields,
languages=spaces.split(languages),
use_stemmer=use_stemmer,
dedicated_storage=dedicated_storage,
ranking=ranking,
use_normalizer=use_normalizer,
use_stopwords=use_stopwords,
storage=storage,
autoexpand_limit=autoexpand_limit,
splitter=splitter,
lexicon=lexicon,
index_unknown_languages=index_unknown_languages,
query_parser=query_parser,
splitter_additional_chars=splitter_additional_chars,
splitter_casefolding=splitter_casefolding)
self.languages = languages
self.use_stemmer = use_stemmer
self.dedicated_storage = dedicated_storage
self.ranking = ranking
self.use_normalizer = use_normalizer
self.use_stopwords = use_stopwords
self.interface = interface
self.storage = storage
self.autoexpand_limit = autoexpand_limit
self.default_field = _fields[0]
self._fields = _fields
self.splitter = splitter
self.lexicon = lexicon
self.index_unknown_languages = index_unknown_languages
self.query_parser = query_parser
self.splitter_additional_chars = splitter_additional_chars
self.splitter_casefolding = splitter_casefolding
def clear(self):
self._index.clear()
def documentCount(self):
"""See interface IStatistics"""
return len(self._index.getStorage(self.default_field))
def wordCount(self):
"""See interface IStatistics"""
return len(self._index.getLexicon())
def index_doc(self, docid, value):
"""See interface IInjection"""
self.unindex_doc(docid)
v = self.interface(value, None)
if v is not None:
self._index.index_object(v, docid)
def unindex_doc(self, docid):
"""See interface IInjection"""
self._index.unindex_object(docid)
def apply(self, query):
if isinstance(query, dict):
kw = query
query = kw['query']
del kw['query']
ting_rr = self._index.search(query, **kw)
return ting_rr.getDocids().keys()
class Text(IndexTerm):
"""hurry.query search term"""
def __init__(self, index_id, text):
super(Text, self).__init__(index_id)
self.text = text
def getIndex(self, context=None):
index = super(Text, self).getIndex(context)
assert ITingIndex.providedBy(index)
return index
def apply(self, context=None):
index = self.getIndex(context)
return IFBTree.IFSet(index.apply(self.text)) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/catalog/index.py | index.py |
# import standard packages
import base64
import cookielib
import httplib
import socket
import urllib2
import xmlrpclib
# import Zope3 interfaces
# import local interfaces
# import Zope3 packages
# import local packages
class TimeoutHTTP(httplib.HTTP):
def __init__(self, host='', port=None, strict=None, timeout=None):
if port == 0:
port = None
self._setup(self._connection_class(host, port, strict, timeout))
class TimeoutHTTPS(httplib.HTTPS):
def __init__(self, host='', port=None, strict=None, timeout=None):
if port == 0:
port = None
self._setup(self._connection_class(host, port, strict, timeout))
class XMLRPCCookieAuthTransport(xmlrpclib.Transport):
"""An XML-RPC transport handling authentication via cookies"""
_http_connection = httplib.HTTPConnection
_http_connection_compat = TimeoutHTTP
def __init__(self, user_agent, credentials=(), cookies=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, headers=None):
xmlrpclib.Transport.__init__(self)
self.user_agent = user_agent
self.credentials = credentials
self.cookies = cookies
self.timeout = timeout
self.headers = headers
if self._connection_required_compat():
self.make_connection = self._make_connection_compat
self.get_response = self._get_response_compat
def _connection_required_compat(self):
# Compatibility code copied from EULExistDB (https://github.com/emory-libraries/eulexistdb)
# UGLY HACK ALERT. Python 2.7 xmlrpclib caches connection objects in
# self._connection (and sets self._connection in __init__). Python
# 2.6 and earlier has no such cache. Thus, if self._connection
# exists, we're running the newer-style, and if it doesn't then
# we're running older-style and thus need compatibility mode.
try:
self._connection
return False
except AttributeError:
return True
def make_connection(self, host):
# This is the make_connection that runs under Python 2.7 and newer.
# The code is pulled straight from 2.7 xmlrpclib, except replacing
# HTTPConnection with self._http_connection
if self._connection and host == self._connection[0]:
return self._connection[1]
chost, self._extra_headers, _x509 = self.get_host_info(host)
self._connection = host, self._http_connection(chost, timeout=self.timeout)
return self._connection[1]
def _make_connection_compat(self, host):
# This method runs as make_connection under Python 2.6 and older.
# __init__ detects which version we need and pastes this method
# directly into self.make_connection if necessary.
host, _extra_headers, _x509 = self.get_host_info(host)
return self._http_connection_compat(host, timeout=self.timeout)
# override the send_host hook to also send authentication info
def send_host(self, connection, host):
xmlrpclib.Transport.send_host(self, connection, host)
if (self.cookies is not None) and (len(self.cookies) > 0):
for cookie in self.cookies:
connection.putheader('Cookie', '%s=%s' % (cookie.name, cookie.value))
elif self.credentials:
auth = 'Basic %s' % base64.encodestring("%s:%s" % self.credentials).strip()
connection.putheader('Authorization', auth)
# send custom headers
def send_headers(self, connection):
for k, v in (self.headers or {}).iteritems():
connection.putheader(k, v)
# dummy request class for extracting cookies
class CookieRequest(urllib2.Request):
pass
# dummy response info headers helper
class CookieResponseHelper:
def __init__(self, response):
self.response = response
def getheaders(self, header):
return self.response.msg.getallmatchingheaders(header)
# dummy response class for extracting cookies
class CookieResponse:
def __init__(self, response):
self.response = response
def info(self):
return XMLRPCCookieAuthTransport.CookieResponseHelper(self.response)
# dummy compat response class for extracting cookies
class CompatCookieResponse:
def __init__(self, headers):
self.headers = headers
def info(self):
return self.headers
def request(self, host, handler, request_body, verbose=False):
# issue XML-RPC request
connection = self.make_connection(host)
self.verbose = verbose
if verbose:
connection.set_debuglevel(1)
self.send_request(connection, handler, request_body)
self.send_host(connection, host)
self.send_user_agent(connection)
self.send_headers(connection)
self.send_content(connection, request_body)
# get response
return self.get_response(connection, host, handler)
def get_response(self, connection, host, handler):
response = connection.getresponse()
# extract cookies from response headers
if self.cookies is not None:
crequest = XMLRPCCookieAuthTransport.CookieRequest('http://%s/' % host)
cresponse = XMLRPCCookieAuthTransport.CookieResponse(response)
for cookie in self.cookies.make_cookies(cresponse, crequest):
if cookie.name.startswith('Set-Cookie'):
cookie.name = cookie.name.split(': ', 1)[1]
self.cookies.set_cookie(cookie)
if response.status != 200:
raise xmlrpclib.ProtocolError(host + handler, response.status, response.reason, response.getheaders())
return self.parse_response(response)
def _get_response_compat(self, connection, host, handler):
errcode, errmsg, headers = connection.getreply()
# extract cookies from response headers
if self.cookies is not None:
crequest = XMLRPCCookieAuthTransport.CookieRequest('http://%s/' % host)
cresponse = XMLRPCCookieAuthTransport.CompatCookieResponse(headers)
self.cookies.extract_cookies(cresponse, crequest)
if errcode != 200:
raise xmlrpclib.ProtocolError(host + handler, errcode, errmsg, headers)
try:
sock = connection._conn.sock
except AttributeError:
sock = None
return self._parse_response(connection.getfile(), sock)
class SecureXMLRPCCookieAuthTransport(XMLRPCCookieAuthTransport):
"""Secure XML-RPC transport"""
_http_connection = httplib.HTTPSConnection
_http_connection_compat = TimeoutHTTPS
def getClient(uri, credentials=(), verbose=False, allow_none=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, headers=None):
"""Get an XML-RPC client which supports basic authentication"""
if uri.startswith('https:'):
transport = SecureXMLRPCCookieAuthTransport('Python XML-RPC Client/0.1 (ZTFY secure transport)', credentials, timeout=timeout, headers=headers)
else:
transport = XMLRPCCookieAuthTransport('Python XML-RPC Client/0.1 (ZTFY basic transport)', credentials, timeout=timeout, headers=headers)
return xmlrpclib.Server(uri, transport=transport, verbose=verbose, allow_none=allow_none)
def getClientWithCookies(uri, credentials=(), verbose=False, allow_none=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
headers=None, cookies=None):
"""Get an XML-RPC client which supports authentication through cookies"""
if cookies is None:
cookies = cookielib.CookieJar()
if uri.startswith('https:'):
transport = SecureXMLRPCCookieAuthTransport('Python XML-RPC Client/0.1 (ZTFY secure cookie transport)',
credentials, cookies, timeout, headers)
else:
transport = XMLRPCCookieAuthTransport('Python XML-RPC Client/0.1 (ZTFY basic cookie transport)',
credentials, cookies, timeout, headers)
return xmlrpclib.Server(uri, transport=transport, verbose=verbose, allow_none=allow_none) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/protocol/xmlrpc.py | xmlrpc.py |
import urllib
import urlparse
import httplib2
class HTTPClient(object):
"""HTTP client"""
def __init__(self, method, protocol, servername, url, params={}, credentials=(),
proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None,
disable_ssl_verification=False):
"""Intialize HTTP connection"""
self.connection = None
self.method = method
self.protocol = protocol
self.servername = servername
self.url = url
self.params = params
self.location = None
self.credentials = credentials
self.proxy = proxy
self.rdns = rdns
self.proxy_auth = proxy_auth
self.timeout = timeout
self.headers = headers or {}
self.disable_ssl_verification = disable_ssl_verification
if 'User-Agent' not in headers:
self.headers['User-Agent'] = 'ZTFY HTTP Client/1.0'
def getResponse(self):
"""Common HTTP request"""
if self.proxy:
proxy_info = httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP,
proxy_host=self.proxy[0],
proxy_port=self.proxy[1],
proxy_rdns=self.rdns,
proxy_user=self.proxy_auth and self.proxy_auth[0] or None,
proxy_pass=self.proxy_auth and self.proxy_auth[1] or None)
else:
proxy_info = None
http = httplib2.Http(timeout=self.timeout, proxy_info=proxy_info,
disable_ssl_certificate_validation=self.disable_ssl_verification)
if self.credentials:
http.add_credentials(self.credentials[0], self.credentials[1])
uri = '%s://%s%s' % (self.protocol, self.servername, self.url)
if self.params:
uri += '?' + urllib.urlencode(self.params)
response, content = http.request(uri, self.method, headers=self.headers)
return response, content
def getClient(method, protocol, servername, url, params=None, credentials=(), proxy=(),
rdns=True, proxy_auth=(), timeout=None, headers=None, disable_ssl_verification=False):
"""HTTP client factory"""
return HTTPClient(method, protocol, servername, url, params or {}, credentials, proxy,
rdns, proxy_auth, timeout, headers or {},
disable_ssl_verification)
def getClientFromURL(url, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None,
headers=None, disable_ssl_verification=False):
"""HTTP client factory from URL"""
elements = urlparse.urlparse(url)
return HTTPClient('GET', elements.scheme, elements.netloc, elements.path, elements.params,
credentials, proxy, rdns, proxy_auth, timeout, headers or {},
disable_ssl_verification) | ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/src/ztfy/utils/protocol/http.py | http.py |
==================
ztfy.utils package
==================
.. contents::
What is ztfy.utils ?
====================
ztfy.utils is a set of classes and functions which can be used to handle many small operations.
Internal sub-packages include :
- date : convert dates to unicode ISO format, parse ISO datetime, convert date to datetime
- request : get current request, get request annotations, get and set request data via annotations
- security : get unproxied value of a given object ; can be applied to lists or dicts
- timezone : convert datetime to a given timezone ; provides a server default timezone utility
- traversing : get object parents until a given interface is implemented
- unicode : convert any text to unicode for easy storage
- protocol : utility functions and modules for several nerwork protocols
- catalog : TextIndexNG index for Zope catalog and hurry.query "Text" query item
- text : simple text operations and text to HTML conversion
- html : HTML parser and HTML to text converter
- file : file upload data converter
- tal : text and HTML conversions for use from within TAL
How to use ztfy.utils ?
=======================
A set of ztfy.utils usage are given as doctests in ztfy/utils/doctests/README.txt
| ztfy.utils | /ztfy.utils-0.4.16.tar.gz/ztfy.utils-0.4.16/docs/README.txt | README.txt |
.. contents:: Table of Contents
:depth: 2
ZTFY.webapp
***********
Introduction
------------
ZTFY.webapp is mainly based on BlueBream concepts and packages, but
introduces a few changes and a set of new functionalities ; it's main goal
is to provide a Paster template to create a new ZTFY.blog based web site
in just a few seconds.
More informations about ZTFY packages can be found on
`ZTFY home page <http://www.ztfy.org>`_.
The "webapp" is nothing more than a "configuration container", which
references and configures all packages needed to handle a web site ;
it doesn't provide any real functionality in itself, except those required
to handle the web server in itself.
`BlueBream <http://bluebream.zope.org>`_ -- formerly known as **Zope
3** -- is a web framework written in the Python programming language.
BlueBream is free/open source software, owned by the `Zope Foundation
<http://foundation.zope.org>`_, licensed under the `Zope Public
License <http://foundation.zope.org/agreements/ZPL_2.1.pdf>`_ (BSD
like, GPL compatible license).
Features
--------
Here are the features distinguishing BlueBream from other Python web frameworks:
- BlueBream is built on top of the `Zope Toolkit
<http://docs.zope.org/zopetoolkit>`_ (ZTK), which has many years of
experience proving it meets the demanding requirements for stable,
scalable software.
- BlueBream uses the powerful and familiar Buildout_ building system written in
Python.
- BlueBream employs the Zope Object Database ZODB_, a transactional
object database, providing extremely powerful and easy to use
persistence.
- BlueBream registers components with Zope Component Markup Language
(`ZCML <http://www.muthukadan.net/docs/zca.html#zcml>`_), an XML
based configuration language, providing limitless flexibility.
- BlueBream features the `Zope Component Architecture
<http://muthukadan.net/docs/zca.html>`_ (ZCA) which implements
*Separation of concerns* to create highly cohesive reusable
components (zope.component_).
- BlueBream implements the `WSGI` specification (`Web Server Gateway Interface
<http://www.wsgi.org/wsgi>`_) with the help of `PasteDeploy
<http://pythonpaste.org/deploy>`_.
- BlueBream includes a number of well tested components to implement
common activities. A few of these are:
- zope.publisher_ publishes Python objects on the web, emphasizing
`WSGI <http://www.wsgi.org/wsgi>`_ compatibility
- zope.security_ provides a generic mechanism for pluggable
security policies
- zope.testing_ and zope.testbrowser_ offer unit and functional testing
frameworks
- zope.pagetemplate_ is an XHTML-compliant language for developing
templates
- zope.schema_ is a schema engine to describe your data models
- zope.formlib_ is a tool for automatically generating forms from your schemas
.. _Buildout: http://www.buildout.org
.. _ZODB: http://www.zodb.org
.. _zope.component: http://pypi.python.org/pypi/zope.component
.. _zope.publisher: http://pypi.python.org/pypi/zope.publisher
.. _zope.security: http://pypi.python.org/pypi/zope.security
.. _zope.testing: http://pypi.python.org/pypi/zope.testing
.. _zope.testbrowser: http://pypi.python.org/pypi/zope.testbrowser
.. _zope.pagetemplate: http://pypi.python.org/pypi/zope.pagetemplate
.. _zope.schema: http://pypi.python.org/pypi/zope.schema
.. _zope.formlib: http://pypi.python.org/pypi/zope.formlib
On top of this, ZTFY provides a few set of additional packages, which allows you
to manage a full web site in just a few minutes, including :
- a complete content management interface (based on z3c.form_)
- an alternate ZMI
- a structured web site, containing sections and articles, blog(s), topics...
- images galleries
- and many more little features, described on `ZTFY home page <http://www.ztfy.org>`_.
You will also find on this web page all informations required to know how
to create and setup a new web site using these packages.
Three simple skins are provided in the default setup, and a "nearly ready to use"
configuration file for Apache2 mod_wsgi_ module is also provided.
.. _z3c.form: http://pypi.python.org/pypi/z3c.form
.. _mod_wsgi: http://code.google.com/p/modwsgi/
Installation
------------
If you have installed `setuptools
<http://pypi.python.org/pypi/setuptools>`_ or `distribute
<http://pypi.python.org/pypi/distribute>`_ an ``easy_install``
command will be available. Then, you can install ZTFY.webapp using
``easy_install`` command like this::
$ easy_install ztfy.webapp
Internet access to `PyPI <http://pypi.python.org/pypi>`_ is required
to perform installation of ZTFY.webapp.
The ``ZTFY.webapp`` distribution provides a quick project
creation tool based on PasteScript templates. Once ZTFY.webapp is installed,
run ``paster`` command to create the project directory structure.
The ``create`` sub-command provided by paster will show a wizard to
create the project directory structure.
::
$ paster create -t ztfy.webapp
This will bring a wizard asking details about your new project. If you provide
a package name and version number, you will get a working application which can
be modified further. The project name will be used as the egg name. You can
also change the values provided later.
The project name can be given as a command line argument::
$ paster create -t ztfy.webapp sampleproject
If you provide an option from the command line, it will not be
prompted by the wizard. The other variables are given below, you can
give the values from the command line, if required:
- ``interpreter`` -- Name of the custom Python interpreter
- ``release`` -- The version of ZTFY.webapp
- ``version`` -- The version of your project (eg:- 0.1)
- ``description`` -- One-line description of the package
- ``long_description`` -- Multi-line description (in reStructuredText)
- ``keywords`` -- Space-separated keywords/tags
- ``author`` -- Author name
- ``author_email`` -- Author email
- ``url`` -- URL of the homepage
- ``license_name`` -- License name
If you are in a hurry, you can simply press *Enter/Return* key and
change the values later. But it would be a good idea, if you provide
a good name for your project.
Usage
-----
The generated package is bundled with Buildout configuration and the
Buildout bootstrap script (``bootstrap.py``). First you need to
bootstrap the buildout itself::
$ cd sampleproject
$ python bootstrap.py
The bootstrap script will install the ``zc.buildout`` and ``distribute``
packages. Also, it will create the basic directory structure. Next step is
building the application. To build the application, run the buildout::
$ ./bin/buidout
The buildout script will download all dependencies and setup the
environment to run your application.
The most common thing you need while developing an application is
running the server. ZTFY.webapp uses the ``paster`` command provided by
PasteScript to run the WSGI server. To run the server, you can pass
the PasteDeploy configuration file as the argument to ``serve``
sub-command as given here::
$ ./bin/paster serve debug.ini
Once you run the server, you can access it here:
http://localhost:8080/ . The port number (``8080``) can be changed
from the PasteDeploy configuration file (``debug.ini``).
The second most common thing must be running the test cases.
ZTFY.webapp creates a testrunner using the ``zc.recipe.testrunner``
Buildout recipe. You can see a ``test`` command inside the ``bin``
directory. To run test cases, just run this command::
$ ./bin/test
Sometimes you may want to get the debug shell. ZTFY.webapp provides a
Python prompt with your application object. You can invoke the debug
shell like this::
$ ./bin/paster shell debug.ini
More about the test runner and debug shell will be explained in the
BlueBream Manual. You can continue reading about BlueBream from the
`documentation site <http://bluebream.zope.org>`_.
Resources
---------
- `ZTFY home page <http://www.ztfy.org>`_
- `Website with documentation <http://bluebream.zope.org>`_
- `Project blog <http://bluebream.posterous.com>`_
- The bugs and issues are tracked at `launchpad
<https://launchpad.net/bluebream>`_.
- `BlueBream Wiki <http://wiki.zope.org/bluebream>`_
- `PyPI Home <http://pypi.python.org/pypi/bluebream>`_
- `Twitter <http://twitter.com/bluebream>`_
- `Mailing list <https://mail.zope.org/mailman/listinfo/bluebream>`_
- IRC Channel: `#bluebream at irc.freenode.net <http://webchat.freenode.net/?randomnick=1&channels=bluebream>`_
- `Buildbot <http://buildbot.afpy.org/bluebream>`_
- The source code is managed at `Zope reposistory
<http://svn.zope.org/bluebream>`_. You can perform a read-only
checkout of trunk code like this (Anonymous access)::
svn co svn://svn.zope.org/repos/main/bluebream/trunk bluebream
You can also `become a source code contributor (committer) after signing a
contributor agreement
<http://docs.zope.org/developer/becoming-a-committer.html>`_
You can see `more details about contributing in wiki
<http://wiki.zope.org/bluebream/ContributingToBlueBream>`_.
| ztfy.webapp | /ztfy.webapp-1.1.5.tar.gz/ztfy.webapp-1.1.5/README.txt | README.txt |
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=True,
help="For backward compatibility. "
"Distribute is used by default.")
parser.add_option("--setuptools",
action="store_false", dest="distribute", default=True,
help="Use Setuptools rather than Distribute.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
try:
import pkg_resources
import setuptools
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
reload(sys.modules['pkg_resources'])
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | ztfy.webapp | /ztfy.webapp-1.1.5.tar.gz/ztfy.webapp-1.1.5/bootstrap.py | bootstrap.py |
import os
from paste.script import pluginlib
from paste.script.pluginlib import egg_name
from paste.script import create_distro
from paste.script import copydir
def egg_info_dir(base_dir, dist_name):
all = []
for dir_extension in ['.'] + os.listdir(base_dir):
full = os.path.join(base_dir, dir_extension,
egg_name(dist_name)+'.egg-info')
all.append(full)
if os.path.exists(full):
return full
return ''
pluginlib.egg_info_dir = egg_info_dir
def command(self):
if self.options.list_templates:
return self.list_templates()
asked_tmpls = self.options.templates or ['basic_package']
templates = []
for tmpl_name in asked_tmpls:
self.extend_templates(templates, tmpl_name)
if self.options.list_variables:
return self.list_variables(templates)
if self.verbose:
print 'Selected and implied templates:'
max_tmpl_name = max([len(tmpl_name) for tmpl_name, tmpl in templates])
for tmpl_name, tmpl in templates:
print ' %s%s %s' % (
tmpl_name, ' '*(max_tmpl_name-len(tmpl_name)),
tmpl.summary)
print
if not self.args:
if self.interactive:
dist_name = self.challenge('Enter project name')
else:
raise BadCommand('You must provide a PACKAGE_NAME')
else:
dist_name = self.args[0].lstrip(os.path.sep)
templates = [tmpl for name, tmpl in templates]
output_dir = os.path.join(self.options.output_dir, dist_name)
pkg_name = self._bad_chars_re.sub('', dist_name.lower())
vars = {'project': dist_name,
'package': pkg_name,
'egg': pluginlib.egg_name(dist_name),
}
vars.update(self.parse_vars(self.args[1:]))
if self.options.config and os.path.exists(self.options.config):
for key, value in self.read_vars(self.options.config).items():
vars.setdefault(key, value)
if self.verbose: # @@: > 1?
self.display_vars(vars)
if self.options.inspect_files:
self.inspect_files(
output_dir, templates, vars)
return
if not os.path.exists(output_dir):
# We want to avoid asking questions in copydir if the path
# doesn't exist yet
copydir.all_answer = 'y'
if self.options.svn_repository:
self.setup_svn_repository(output_dir, dist_name)
# First we want to make sure all the templates get a chance to
# set their variables, all at once, with the most specialized
# template going first (the last template is the most
# specialized)...
for template in templates[::-1]:
vars = template.check_vars(vars, self)
# Gather all the templates egg_plugins into one var
egg_plugins = set()
for template in templates:
egg_plugins.update(template.egg_plugins)
egg_plugins = list(egg_plugins)
egg_plugins.sort()
vars['egg_plugins'] = egg_plugins
for template in templates:
self.create_template(
template, output_dir, vars)
found_setup_py = False
paster_plugins_mtime = None
package_dir = vars.get('package_dir', None)
if package_dir:
output_dir = os.path.join(output_dir, package_dir)
# With no setup.py this doesn't make sense:
if found_setup_py:
# Only write paster_plugins.txt if it wasn't written by
# egg_info (the correct way). leaving us to do it is
# deprecated and you'll get warned
egg_info_dir = pluginlib.egg_info_dir(output_dir, dist_name)
plugins_path = os.path.join(egg_info_dir, 'paster_plugins.txt')
if len(egg_plugins) and (not os.path.exists(plugins_path) or \
os.path.getmtime(plugins_path) == paster_plugins_mtime):
if self.verbose:
print >> sys.stderr, \
('Manually creating paster_plugins.txt (deprecated! '
'pass a paster_plugins keyword to setup() instead)')
for plugin in egg_plugins:
if self.verbose:
print 'Adding %s to paster_plugins.txt' % plugin
if not self.simulate:
pluginlib.add_plugin(egg_info_dir, plugin)
if self.options.svn_repository:
self.add_svn_repository(vars, output_dir)
if self.options.config:
write_vars = vars.copy()
del write_vars['project']
del write_vars['package']
self.write_vars(self.options.config, write_vars)
create_distro.CreateDistroCommand.command = command | ztfy.webapp | /ztfy.webapp-1.1.5.tar.gz/ztfy.webapp-1.1.5/src/ztfy/webapp/webapp_base/paste_script_patch.py | paste_script_patch.py |
from HTMLParser import HTMLParser
from paste.script import templates
from paste.script.templates import var
from urllib2 import urlopen
import pkg_resources
import re, os, sys
DOWNLOAD_URL = 'http://download.ztfy.org/webapp/'
class FindLatest(HTMLParser):
"""html parser used to find the latest version file on download.zope.org
"""
def reset(self):
"""initialize a regexp and a version set"""
HTMLParser.reset(self)
self.regexp = re.compile('.*ztfy.webapp-(.*).cfg$')
self.versions = set()
def handle_starttag(self, tag, attrs):
"""extract the version from each link"""
if tag != 'a':
return
for attr in attrs:
if attr[0] == 'href' and self.regexp.match(attr[1]):
self.versions.add(self.regexp.sub('\\1', attr[1]))
class Webapp(templates.Template):
""" The main paster template for ZTFY.webapp
"""
_template_dir = 'webapp_template'
summary = "A ZTFY webapp project, referencing all ZTFY packages"
vars = [
var('python_package',
u'Main Python package (without namespace)'),
var('interpreter',
u'Name of custom Python interpreter',
default='ztpy'),
var('release', (u'Which release of ZTFY.webapp?\n'
u'Check on %s' % DOWNLOAD_URL)),
var('version', u'Version of your project', default='0.1'),
var('description', u'One-line description of the package'),
var('long_description', u'Multi-line description (in reST)'),
var('keywords', u'Space-separated keywords/tags'),
var('author', u'Author name'),
var('author_email', u'Author email'),
var('url', u'URL of homepage'),
var('license_name', u'License name'),
]
def check_vars(self, vars, cmd):
"""This method checks the variables and ask for missing ones
"""
# Find the latest versions.cfg online
current = pkg_resources.get_distribution('ztfy.webapp').version
latest = current
try:
if 'offline' not in vars: #offline is used in tests
sys.stdout.write('Searching the latest version... ')
sys.stdout.flush()
parse_version = pkg_resources.parse_version
# download and parse the html page and store versions
parser = FindLatest()
parser.feed(urlopen(DOWNLOAD_URL).read())
# return the highest minor version
if not len(parser.versions):
raise IOError('No versions found')
all_versions = sorted(parser.versions,
key=lambda v: parse_version(v),
reverse=True)
for v in all_versions:
trunked_v = [x for x in parse_version(v)[:2] if not x.startswith('*')]
trunked_current = [x for x in parse_version(current)[:2] if not x.startswith('*')]
while len(trunked_v) < 2:
trunked_v.append('00000000')
while len(trunked_current) < 2:
trunked_current.append('00000000')
if trunked_v > trunked_current:
continue
latest = v
break
print str(latest) + '\n'
# warn the user if there is a change in the latest template
last_change = '1.1.0' # feature introduced for 1.0b4
for line in urlopen(DOWNLOAD_URL
+ 'ztfy.webapp-%s.cfg' % latest).readlines():
if 'LAST_TEMPLATE_CHANGE' in line:
last_change = line.split('=')[1].strip()
break
if parse_version(last_change) > parse_version(current):
print ('**WARNING**: the project template for ZTFY.webapp '
'has changed since version %s.\n'
'You should upgrade to this version.\n' % last_change)
except IOError:
# if something wrong occurs, we keep the current version
print u'**WARNING**: error while getting the latest version online'
print u'Please check that you can access %s\n' % DOWNLOAD_URL
# suggest what Paste chose
for var in self.vars:
if var.name == 'release':
var.default = latest
if var.name == 'python_package':
var.default = vars['package']
# but keep the user's input if there are dots in the middle
if '.' in vars['project'][1:-1]:
var.default = re.sub('[^A-Za-z0-9.]+', '_',
vars['project']).lower()
# ask remaining variables
vars = templates.Template.check_vars(self, vars, cmd)
# replace Paste default choice with ours
vars['package'] = vars['python_package']
# check for bad python package names
if vars['package'] in ('bluebream', 'bream', 'zope'):
print
print "Error: The chosen project name results in an invalid " \
"package name: %s." % vars['package']
print "Please choose a different project name."
sys.exit(1)
vars['zip_safe'] = False
# remember the version of bluebream used to create the project
vars['created_with'] = current
return vars
def pre(self, command, output_dir, vars):
"""Detect namespaces in the project name
"""
if not command.options.verbose:
command.verbose = 0
self.ns_split = vars['package'].split('.')
vars['package'] = self.ns_split[-1]
vars['namespace_packages'] = list(reversed([
vars['python_package'].rsplit('.', i)[0]
for i in range(1, len(self.ns_split))]))
vars['ns_prefix'] = '.'.join(self.ns_split[:-1]) + '.'
if len(self.ns_split) == 1:
vars['ns_prefix'] = ''
vars['basedir'] = os.getcwd()
def post(self, command, output_dir, vars):
"""Add nested namespace levels
and move the main package to the last level
"""
# if we have a namespace package
if len(self.ns_split) > 1:
package_dir = os.path.join(output_dir, 'src', vars['package'])
tmp_dir = package_dir + '.tmp'
os.rename(package_dir, tmp_dir)
# create the intermediate namespace packages
target_dir = os.path.join(output_dir, 'src',
os.path.join(*self.ns_split[:-1]))
os.makedirs(target_dir)
# create each __init__.py with namespace declaration
ns_decl = "__import__('pkg_resources').declare_namespace(__name__)"
for i, namespace_package in enumerate(self.ns_split[:-1]):
init_file = os.path.join(output_dir, 'src',
os.path.join(*self.ns_split[:i + 1]),
'__init__.py')
open(init_file, 'w').write(ns_decl)
# move the (renamed) main package to the last namespace
os.rename(tmp_dir,
os.path.join(target_dir, os.path.basename(package_dir,)))
print("\nYour project has been created! Now, you want to:\n"
"1) put the generated files under version control\n"
"2) run: python bootstrap.py\n"
"3) run: ./bin/buildout\n"
) | ztfy.webapp | /ztfy.webapp-1.1.5.tar.gz/ztfy.webapp-1.1.5/src/ztfy/webapp/webapp_base/template.py | template.py |
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=True,
help="For backward compatibility. "
"Distribute is used by default.")
parser.add_option("--setuptools",
action="store_false", dest="distribute", default=True,
help="Use Setuptools rather than Distribute.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
try:
import pkg_resources
import setuptools
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
reload(sys.modules['pkg_resources'])
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | ztfy.webapp | /ztfy.webapp-1.1.5.tar.gz/ztfy.webapp-1.1.5/src/ztfy/webapp/webapp_base/webapp_template/bootstrap.py | bootstrap.py |
=====================
ztfy.workflow package
=====================
You may find documentation in:
- Global README.txt: ztfy/workflow/docs/README.txt
- General: ztfy/workflow/docs
- Technical: ztfy/workflow/doctest
More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available
on ZTFY.workflow_.
This package is created and maintained by Thierry Florac_.
.. _Thierry Florac: mailto:[email protected]
.. _ZTFY.org: http://www.ztfy.org
.. _ZTFY.workflow: http://trac.ztfy.org/ztfy.workflow
| ztfy.workflow | /ztfy.workflow-0.2.9.tar.gz/ztfy.workflow-0.2.9/README.txt | README.txt |
from datetime import datetime
from persistent.dict import PersistentDict
import pytz
# import Zope3 interfaces
from zope.annotation.interfaces import IAnnotations
from zope.dublincore.interfaces import IZopeDublinCore
# import local interfaces
# import Zope3 packages
from zope.component import adapts, queryUtility
from zope.interface import implements
# import local packages
from hurry.workflow.interfaces import IWorkflowState
from ztfy.security.security import getSecurityManager
from ztfy.utils.date import unidate, parsedate
from ztfy.utils.traversing import getParent
from ztfy.workflow.interfaces import IWorkflow, IWorkflowTarget, IWorkflowContent
WORKFLOW_CONTENT_KEY = 'ztfy.workflow.content'
GMT = pytz.timezone('GMT')
class WorkflowContentAdapter(object):
adapts(IWorkflowTarget)
implements(IWorkflowContent)
def __init__(self, context):
self.context = context
annotations = IAnnotations(self.context)
data = annotations.get(WORKFLOW_CONTENT_KEY)
if data is None:
data = annotations[WORKFLOW_CONTENT_KEY] = PersistentDict()
self.data = data
def _getStateDate(self):
return parsedate(self.data.get('state_date')) or IZopeDublinCore(self.context).created
def _setStateDate(self, date):
if date and not date.tzinfo:
date = GMT.localize(date)
self.data['state_date'] = unidate(date)
state_date = property(_getStateDate, _setStateDate)
def _getStatePrincipal(self):
return self.data.get('state_principal') or IZopeDublinCore(self.context).creators[0]
def _setStatePrincipal(self, principal):
self.data['state_principal'] = principal
state_principal = property(_getStatePrincipal, _setStatePrincipal)
def _getPublicationDate(self):
return parsedate(self.data.get('publication_date'))
def _setPublicationDate(self, date):
if date and not date.tzinfo:
date = GMT.localize(date)
self.data['publication_date'] = unidate(date)
publication_date = property(_getPublicationDate, _setPublicationDate)
def _getFirstPublicationDate(self):
return parsedate(self.data.get('first_publication_date'))
def _setFirstPublicationDate(self, date):
if date and not date.tzinfo:
date = GMT.localize(date)
self.data['first_publication_date'] = unidate(date)
first_publication_date = property(_getFirstPublicationDate, _setFirstPublicationDate)
def _getEffectiveDate(self):
return IZopeDublinCore(self.context).effective
def _setEffectiveDate(self, date):
if date:
if not date.tzinfo:
date = GMT.localize(date)
IZopeDublinCore(self.context).effective = date
if (self.first_publication_date is None) or (self.first_publication_date > date):
self.first_publication_date = date
else:
if self.first_publication_date == self.publication_effective_date:
self.first_publication_date = None
if self.publication_effective_date:
del IZopeDublinCore(self.context)._mapping['Date.Effective']
publication_effective_date = property(_getEffectiveDate, _setEffectiveDate)
def _getExpirationDate(self):
return IZopeDublinCore(self.context).expires
def _setExpirationDate(self, date):
if date:
if not date.tzinfo:
date = GMT.localize(date)
IZopeDublinCore(self.context).expires = date
else:
if self.publication_expiration_date:
del IZopeDublinCore(self.context)._mapping['Date.Expires']
publication_expiration_date = property(_getExpirationDate, _setExpirationDate)
def isPublished(self):
parent = getParent(self.context, IWorkflowTarget, allow_context=False)
if (parent is not None) and (not IWorkflowContent(parent).isPublished()):
return False
workflow_name = IWorkflowTarget(self.context).workflow_name
if not workflow_name:
return True
workflow = queryUtility(IWorkflow, workflow_name)
if (workflow is None) or (not workflow.published_states):
return False
if IWorkflowState(self.context).getState() not in workflow.published_states:
return False
now = datetime.now(pytz.UTC)
return (self.publication_effective_date is not None) and \
(self.publication_effective_date <= now) and \
((self.publication_expiration_date is None) or \
(self.publication_expiration_date >= now))
def isVisible(self):
result = True
sm = getSecurityManager(self.context)
if sm is not None:
result = sm.canView()
return result and self.isPublished() | ztfy.workflow | /ztfy.workflow-0.2.9.tar.gz/ztfy.workflow-0.2.9/src/ztfy/workflow/content.py | content.py |
# import Zope3 interfaces
from zope.schema.interfaces import IVocabularyTokenized
# import local interfaces
from hurry.workflow.interfaces import IWorkflow as IWorkflowBase
from ztfy.comment.interfaces import ICommentable
# import Zope3 packages
from zope.interface import Interface, invariant, Invalid
from zope.schema import Datetime, Choice, Tuple, TextLine, Object
# import local packages
from ztfy.security.schema import Principal
from ztfy.workflow import _
class IWorkflow(IWorkflowBase):
"""Marker interface for custom workflows extending IWorkflow"""
states = Object(schema=IVocabularyTokenized)
published_states = Tuple(title=_("Published states"),
description=_("Tuple of published and potentially visible workflow states"),
required=False,
value_type=TextLine())
class IWorkflowTarget(ICommentable):
"""Marker interface for contents handled by a workflow"""
workflow_name = Choice(title=_("Workflow name"),
description=_("Name of a registered workflow utility used by this workflow"),
required=True,
vocabulary="ZTFY workflows")
class IWorkflowContentInfo(Interface):
"""Interface used to define common workflow properties"""
state_date = Datetime(title=_("State date"),
description=_("Date when the current state was defined"))
state_principal = Principal(title=_("State principal"),
description=_("Name of the principal who defined the current state"))
publication_date = Datetime(title=_("Publication date"),
description=_("Date when content was accepted to publication by the publisher, entered in ISO format"),
required=False)
first_publication_date = Datetime(title=_("First publication date"),
description=_("Date when content was accepted to publication by the publisher for the first time"),
required=False)
publication_effective_date = Datetime(title=_("Publication start date and time"),
description=_("Date and time from which content will be visible"),
required=True,
default=None)
publication_expiration_date = Datetime(title=_("Publication end date and time"),
description=_("Date and time until which content will be visible"),
required=False,
default=None)
@invariant
def expireAfterEffective(self):
if self.publication_expiration_date is not None:
if self.publication_effective_date is None:
raise Invalid(_("Can't define publication end date without publication start date"))
if self.publication_expiration_date <= self.publication_effective_date:
raise Invalid(_("Publication end date must be null or defined after publication's start date"))
def isPublished():
"""Is the context published or not ?"""
def isVisible():
"""Is the context visible according to current workflow state and security context ?"""
class IWorkflowContent(IWorkflowContentInfo):
"""Marker interface for workflow contents"""
class ITransition(Interface):
"""Marker interface for standard transitions"""
class ITransitionTarget(Interface):
"""Get transition link target"""
def absoluteURL():
"""Get absolute URL for adapted context and request""" | ztfy.workflow | /ztfy.workflow-0.2.9.tar.gz/ztfy.workflow-0.2.9/src/ztfy/workflow/interfaces.py | interfaces.py |
Subsets and Splits