示例#1
0
    def show(self):
        """Returns file handle for efficient streaming."""
        
        if self.request is not None:
            self.request.response.setHeader('Content-Type',
                                            self.context.contentType)
            self.request.response.setHeader('Content-Length',
                                            self.context.getSize())
        try:
            modified = IZopeDublinCore(self.context).modified
        except TypeError:
            modified = None
        if modified is None or not isinstance(modified, datetime):
            return self.context.openDetached()

        header= self.request.getHeader('If-Modified-Since', None)
        lmt = zope.datetime.time(modified.isoformat())
        if header is not None:
            header = header.split(';')[0]
            try:
                mod_since = long(zope.datetime.time(header))
            except:
                mod_since = None
            if mod_since is not None:
                if lmt <= mod_since:
                    self.request.response.setStatus(304)
                    return ''

        self.request.response.setHeader('Last-Modified', zope.datetime.rfc1123_date(lmt))

        return self.context.openDetached()
示例#2
0
    def modified(self):
        """Provide a callable to return the modification time of content items.

        So stored image scales can be invalidated.
        """
        dc = IZopeDublinCore(self.context)
        return dc.ModificationDate()
示例#3
0
def created(context):
        created = IZopeDublinCore(context).created
        created = unicode(created)
        created = created.split(u'.')
        created.reverse()
        created = created.pop()
        return created
示例#4
0
def ModifiedAnnotator(event):
    dc = IZopeDublinCore(event.object, None)
    if dc is not None:
        # Principals that can modify objects do not necessary have permissions
        # to arbitrarily modify DC data, see issue 373
        dc = removeSecurityProxy(dc)
        dc.modified = datetime.now(pytz.utc)
示例#5
0
    def edit(self):
        try:
            dc = IZopeDublinCore(self.context)
        except TypeError:
            return None

        request = self.request
        formatter = self.request.locale.dates.getFormatter(
            'dateTime', 'medium')
        message = ''

        if 'dctitle' in request:
            dc.title = unicode(request['dctitle'])
            dc.description = unicode(request['dcdescription'])
            description = Attributes(IZopeDublinCore, 'title', 'description')
            notify(ObjectModifiedEvent(self.context, description))
            message = "Changed data %s" % formatter.format(datetime.utcnow())

        return {'message': message,
                'dctitle': dc.title,
                'dcdescription': dc.description,
                'modified': (dc.modified or dc.created) and \
                    formatter.format(dc.modified or dc.created) or '',
                'created': dc.created and formatter.format(dc.created) or '',
                'creators': dc.creators}
def ModifiedAnnotator(event):
    dc = IZopeDublinCore(event.object, None)
    if dc is not None:
        # Principals that can modify objects do not necessary have permissions
        # to arbitrarily modify DC data, see issue 373
        dc = removeSecurityProxy(dc)
        dc.modified = datetime.now(pytz.utc)
示例#7
0
    def test_inplace_change_title(self):
        root = self.getRootFolder()
        root['foo'] = File()
        transaction.commit()
        self.assert_('foo' in root)
        dc = IZopeDublinCore(root['foo'])
        self.assert_(dc.title == '')

        response = self.publish('/@@contents.html',
                                basic='mgr:mgrpw',
                                form={'retitle_id': u'foo'})
        body = ' '.join(response.getBody().split())
        self.assert_(body.find('type="hidden" name="retitle_id"') >= 0)
        self.assert_(body.find('input name="new_value"') >= 0)
        self.assert_(
            body.find('type="submit" name="container_cancel_button"') >= 0)
        self.assert_(
            body.find('type="submit" name="container_rename_button"') < 0)

        response = self.publish('/@@contents.html',
                                basic='mgr:mgrpw',
                                form={
                                    'retitle_id': u'foo',
                                    'new_value': u'test title'
                                })
        self.assertEqual(response.getStatus(), 302)
        self.assertEqual(response.getHeader('Location'),
                         'http://localhost/@@contents.html')

        root._p_jar.sync()
        self.assert_('foo' in root)
        dc = IZopeDublinCore(root['foo'])
        self.assert_(dc.title == 'test title')
示例#8
0
def getModifiedDate(item, formatter):
    """Modified Date for Overview in Web-Browser"""
    if type(item) is dict:
        item = item["obj"]
    try:
        userTZ = getUserTimezone()
        my_formatter = formatter.request.locale.dates.getFormatter(
            'dateTime', 'short')
        timeString = my_formatter.format(userTZ.fromutc(
            IZopeDublinCore(item).modified))
        timeStringHTML = timeString.replace(" ", "&nbsp;")
        my_formatter = formatter.request.locale.dates.getFormatter(
            'dateTime', 'long')
        longTimeString = my_formatter.format(
            userTZ.fromutc(IZopeDublinCore(item).modified))
        #ttid = u"id" + str(abs(hash(timeString)))
        ttid = u"modt" + item.getObjectId()
        tooltip = u"<script type=\"text/javascript\">tt_%s = new YAHOO." \
                u"widget.Tooltip('tt_%s', { autodismissdelay:'15000', " \
                u"context:'%s', text:'%s' });</script>" \
                % (ttid, ttid, ttid, longTimeString)
        resString = u'<span id="%s">%s</span>' % (ttid, timeStringHTML)
    except AttributeError:
        resString = u"---"
        tooltip = u""
    except TypeError:
        resString = u"---"
        tooltip = u""
    return resString + tooltip
示例#9
0
    def modified(self):
        """Provide a callable to return the modification time of content items.

        So stored image scales can be invalidated.
        """
        unecure_context = removeSecurityProxy(self.context.context)
        # dc = IZopeDublinCore(self.context.context)
        dc = IZopeDublinCore(unecure_context)
        return dc.ModificationDate()
示例#10
0
 def publication_expiration_date(self, value):
     """Publication expiration date setter"""
     value = gmtime(value)
     dc = IZopeDublinCore(self.__parent__, None)  # pylint: disable=invalid-name
     if dc is not None:
         if value:
             dc.expires = value
         elif self._publication_expiration_date:
             del dc._mapping['Date.Expires']  # pylint: disable=protected-access
     self._publication_expiration_date = value
示例#11
0
def ModifiedAnnotator(object, event=None):
    if event is None:
        # annotator was only called the event as only argument
        object = object.object
    dc = IZopeDublinCore(object, None)
    if dc is not None:
        # Principals that can modify objects do not necessary have permissions
        # to arbitrarily modify DC data, see issue 373
        dc = removeSecurityProxy(dc)
        dc.modified = _now()
示例#12
0
文件: setup.py 项目: ilshad/tackle
def setup_local(e):
    sm = e.manager
    site = sm.__parent__ # root folder

    intids = IntIds()
    sm[u'intids'] = intids
    sm.registerUtility(intids, IIntIds)

    catalog = Catalog()
    sm[u'catalog'] = catalog
    sm.registerUtility(catalog, ICatalog)

    catalog[u'fulltext'] = TextIndex(interface=ISearchableText,
                                     field_name='getSearchableText',
                                     field_callable=True)

    auth = PluggableAuthentication()
    sm[u'authentication'] = auth
    sm.registerUtility(auth, IAuthentication)

    pfolder = principalfolder.PrincipalFolder(prefix='principal.')
    auth[u'principalfolder'] = pfolder
 
    gfolder = groupfolder.GroupFolder(prefix='group.')
    auth[u'groupfolder'] = gfolder

    auth.credentialsPlugins += (u'Session Credentials',)
    auth.authenticatorPlugins += (u'principalfolder', u'groupfolder')

    pran = PrincipalAnnotationUtility()
    sm[u'principalannotation'] = pran
    sm.registerUtility(pran, IPrincipalAnnotationUtility)

    pwdreset = PasswordResetUtility()
    sm[u'passwordreset'] = pwdreset
    sm.registerUtility(pwdreset, IPasswordResetUtility)

    # default bootstrap admin
    login = u"manager"
    password = "******"
    pfolder[login] = principalfolder.InternalPrincipal(login, password, login, u"", "SSHA")
    principal_id = pfolder.prefix + login

    prinrole = IPrincipalRoleManager(site)
    prinrole.assignRoleToPrincipal('tackle.SystemManager', principal_id)

    # all authenticated users are guests by default
    prinrole.assignRoleToPrincipal('tackle.Guest', 'zope.Authenticated')

    # site title
    dc = IZopeDublinCore(site)
    dc.title = u"Tackle"

    # custom local setup
    notify(NewLocalSite(sm))
示例#13
0
def updateSuperclassDCTitle(ikObject, event):
    """
    Update an object's Dublin Core Title and back
    """
    for i in event.descriptions:
        if ISuperclass.isEqualOrExtendedBy(i.interface):
            dcore = IWriteZopeDublinCore(ikObject)
            dcore.title = ikObject.ikName
        if IZopeDublinCore.isEqualOrExtendedBy(i.interface):
            dcore = IZopeDublinCore(ikObject)
            ikObject.ikName = dcore.title
示例#14
0
 def render(self, *args, **kw):
     site = getSite()
     base = IZopeDublinCore(site).title
     try:
         if checkPermission('zope.View', self.context):
             dc_title = IZopeDublinCore(self.context).title
             if dc_title:
                 return base + u" :: " + dc_title
     except AttributeError:
         pass
     except TypeError:
         pass
     return base
示例#15
0
 def publication_effective_date(self, value):
     """Publication effective date setter"""
     value = gmtime(value)
     dc = IZopeDublinCore(self.__parent__, None)  # pylint: disable=invalid-name
     if value:
         if (self._first_publication_date is
                 None) or (self._first_publication_date > value):
             self._first_publication_date = value
         if dc is not None:
             dc.effective = value
     elif self._publication_effective_date:
         if dc is not None:
             del dc._mapping['Date.Effective']  # pylint: disable=protected-access
     self._publication_effective_date = value
示例#16
0
 def __post_init__(self, **data):
     """
     triggerd after constructor has been finished
     """
     newEntry = Entry(u"Object created", self, level=u"info")
     newEntry.setObjVersion(self.ikRevision)
     self.history.append(newEntry)
     self.connectToEventXbar()
     newEntry = Entry(u"Object connected to event crossbar", self, level=u"info")
     newEntry.setObjVersion(self.ikRevision)
     self.history.append(newEntry)
     dc = IZopeDublinCore(self, None)
     if dc is not None:
         now = datetime.now(pytz.utc)
         dc.created = now
         dc.modified = now
示例#17
0
文件: metas.py 项目: Py-AMS/pyams-zmi
 def get_metas(self):
     """Metas getter"""
     config = IZMIConfiguration(self.request.root, None)
     if (config is not None) and (config.favicon is not None):
         icon = config.favicon
         icon_url = absolute_url(icon, self.request)
         icon_size = icon.get_image_size()[0]  # pylint: disable=no-member
         dc = IZopeDublinCore(icon)  # pylint: disable=invalid-name
         timestamp = datetime.timestamp(tztime(dc.modified))
         for size in (180, 144, 114, 72, 32, 16):
             if icon_size >= size:
                 yield LinkMeta(
                     'apple-touch-icon',
                     type=icon.content_type,  # pylint: disable=no-member
                     href=THUMB_HREF_STR.format(icon_url, size, size,
                                                timestamp),
                     sizes='{0}x{0}'.format(size))
         for size in (128, 124, 32):
             if icon_size >= size:
                 yield LinkMeta(
                     'icon',
                     type=icon.content_type,  # pylint: disable=no-member
                     href=THUMB_HREF_STR.format(icon_url, size, size,
                                                timestamp),
                     sizes='{0}x{0}'.format(size))
         yield LinkMeta('shortcut-icon',
                        type=icon.content_type,
                        href=icon_url)  # pylint: disable=no-member
示例#18
0
def password_reset_request(event):
    user = get_profile(event.principal_id, "basic")
    f = open_file('mail/password_reset_request.tmpl', __file__)

    site = hooks.getSite()
    site_url = absoluteURL(site, event.req)
    page_link = u'%s/password_reset' % site_url
    full_link = u'%s?login=%s&code=%s' % (page_link, event.login, event.code)
    dc = IZopeDublinCore(site)

    data = {
        'name': user.name,
        'code': event.code,
        'page_link': page_link,
        'full_link': full_link,
        'site_title': dc.title,
        'site_url': site_url
    }

    message = Template(file=f, searchList=[data])

    subject = u'Password reset request'
    send_mail(message,
              subject,
              user.email,
              subtype='html',
              from_header=dc.title,
              to_header=user.name)
示例#19
0
    def test_deny_dublincore_view(self):
        """Tests the denial of dublincore view permissions to anonymous.

        Users who can view a folder contents page but cannot view dublin core
        should still be able to see the folder items' names, but not their
        title, modified, and created info.
        """
        # add an item that can be viewed from the root folder
        obj = OrderedContainer()
        alsoProvides(obj, IAttributeAnnotatable)

        self.getRootFolder()['obj'] = obj
        IZopeDublinCore(obj).title = u'My object'

        # deny zope.app.dublincore.view to zope.Anonymous
        prm = IRolePermissionManager(self.getRootFolder())
        prm.denyPermissionToRole('zope.dublincore.view', 'zope.Anonymous')
        # Try both spellings just in case we are used with an older zope.dc
        prm.denyPermissionToRole('zope.app.dublincore.view', 'zope.Anonymous')
        transaction.commit()

        response = self.publish('/')
        self.assertEquals(response.getStatus(), 200)
        body = response.getBody()

        # confirm we can see the file name
        self.assert_(body.find('<a href="obj">obj</a>') != -1)

        # confirm we *cannot* see the metadata title
        self.assert_(body.find('My object') == -1)
示例#20
0
 def about(self):
     about = {}
     dc = IZopeDublinCore(self)
     about['creator'] = dc.creators and dc.creators[0] or 'Unknown user'
     about['created'] = dc.created.astimezone(tz)
     about['status'] = IWorkflowState(self).getState()
     return about
示例#21
0
 def renderCell(self, item):
     formatter = self.getFormatter()
     dc = IZopeDublinCore(item, None)
     value = self.getValue(dc)
     if value:
         value = formatter.format(value)
     return value
示例#22
0
def createLocalSystem(root_folder):
    dateNow = datetime.utcnow()
    newHost = createObject(u'org.ict_ok.components.host.host.Host')
    notify(ObjectCreatedEvent(newHost))
    root_folder.__setitem__(newHost.getObjectId(), newHost)
    dcore = IZopeDublinCore(newHost, None)
    dcore.creators = [u'first bootstrap']
    newHost.ikComment += u"bootstrap on %s" % (dateNow)
    newHost.__setattr__("ikName", u'Local System')
    newHost.__setattr__("hostname", u'Local System')
    dcore.title = u'Local System'
    newHost.__setattr__("ikDesc", u'this is the ict-ok.org management-system')
    newHost.__setattr__("manufacturer", u'see ict-ok.org')
    newHost.__setattr__("vendor", u'see ict-ok.org')
    newHost.__setattr__("genNagios", True)
    dcore.created = dateNow
示例#23
0
 def getItemTitle(self, item):
     """ """
     title = getattr(item, 'title', None)
     if title is None:
         dc = IZopeDublinCore(item)
         title = dc.title or u''
     return title
示例#24
0
 def getTitle(self):
     """ """
     title = getattr(self.context, 'title', None)
     if title is None:
         dc = IZopeDublinCore(self.context)
         title = dc.title or u''
     return title
示例#25
0
文件: edit.py 项目: ilshad/tackle
 def handleBack(self, action):
     context = self.context.context
     quote = lambda x: urllib.quote(x.encode("utf-8"))
     self.request.response.redirect(
         u"%s/select_group?context=%s&title=%s" %
         (absoluteURL(hooks.getSiteManager(),
                      self.request), absoluteURL(context, self.request),
          quote(IZopeDublinCore(context).title or context.__name__)))
示例#26
0
 def render_cell(self, item):
     """Render column cell"""
     zdc = IZopeDublinCore(item, None)
     if zdc is not None:
         value = self.get_value(zdc)
         if value:
             value = self.get_formatted_value(value)
         return value
     return ''
示例#27
0
 def title(self):
     # Sometimes you need to reimplement this method in subclass,
     # mostly if an object does not uses Dublin Core metadata
     try:
         title = IZopeDublinCore(self.context).title
         if title:
             return u'[ ' + title + ' ]'
     except TypeError:
         pass
     return u''
示例#28
0
def bootStrapSubscriber(event):
    """initialisation of IntId utility on first database startup
    """
    if appsetup.getConfigContext().hasFeature('devmode'):
        logger.info(u"starting bootStrapSubscriberDatabase (org.ict_ok...)")
    dummy_db, connection, dummy_root, root_folder = \
            getInformationFromEvent(event)
    # search in global component registry
    sitem = root_folder.getSiteManager()
    # search for ICatalog
    utils = [
        util for util in sitem.registeredUtilities()
        if util.provided.isOrExtends(ICatalog)
    ]
    instUtilityICatalog = utils[0].component
    if not "script_oid_index" in instUtilityICatalog.keys():
        script_oid_index = KeywordIndex(interface=ISearchableText,
                                        field_name='getSearchableScriptOid',
                                        field_callable=True)
        instUtilityICatalog['script_oid_index'] = script_oid_index
        # search for IAdmUtilSupervisor
        utils = [
            util for util in sitem.registeredUtilities()
            if util.provided.isOrExtends(IAdmUtilSupervisor)
        ]
        instAdmUtilSupervisor = utils[0].component
        instAdmUtilSupervisor.appendEventHistory(\
            u" bootstrap: ICatalog - create index for entry type 'script'")

    folderName = u"MobilePhones"
    if folderName not in root_folder.keys():
        #newFolder = TestComponentFolder()
        newFolder = createObject(
            u'org.ict_ok.components.mobilephone.mobilephone.MobilePhoneFolder')
        root_folder[folderName] = newFolder
        dcore = IZopeDublinCore(newFolder, None)
        #dcore.creators = [u'ikportscan']
        #newFolder.ikComment += u"scanner: %s" % (dateNow)
        newFolder.__setattr__("ikName", folderName)
        dcore.title = folderName

    transaction.get().commit()
    connection.close()
示例#29
0
def get_timestamp(context, formatting=None):
    """Get timestamp matching context modification date"""
    if formatting == 'iso':
        format_func = datetime.isoformat
    else:
        format_func = datetime.timestamp
    zdc = IZopeDublinCore(context, None)
    if zdc is not None:
        return format_func(tztime(zdc.modified))
    return format_func(tztime(datetime.utcnow()))
示例#30
0
 def modified_time(self):
     context = self.context
     if isinstance(context, Proxy):
         context = removeSecurityProxy(context)
     try:
         dc = IZopeDublinCore(context)
     except Exception:
         return None
     else:
         return dc.modified
示例#31
0
 def __set__(self, inst, value):
     name = self.__name
     inst = IZopeDublinCore(inst)
     field = IZopeDublinCore[name].bind(inst)
     if isinstance(field, schema.Tuple):
         value = tuple(value)
     field.validate(value)
     if field.readonly and inst.__dict__.has_key(name):
         raise ValueError(name, 'field is readonly')
     setattr(inst, name, value)
示例#32
0
文件: lib.py 项目: mleist/ict-ok.org
def ensureComponentFolderOnBootstrap(interface, folderName, factoryId,
                                     root_folder, siteManager):
    allSubFolders = [folder for folder in root_folder.values()
                     if interface.providedBy(folder)]
    utils = [ util for util in siteManager.registeredUtilities()
              if util.provided.isOrExtends(IIntIds)]
    instUtilityIIntIds = utils[0].component
    if len(allSubFolders) < 1: # there is no subfolder
        newFolder = createObject(factoryId)
        root_folder[folderName] = newFolder
        dcore = IZopeDublinCore(newFolder, None)
        #dcore.creators = [u'ikportscan']
        #newFolder.ikComment += u"scanner: %s" % (dateNow)
        newFolder.__setattr__("ikName", folderName)
        dcore.title = folderName
        instUtilityIIntIds.register(newFolder)
    else:
        for obj in allSubFolders:
            instUtilityIIntIds.register(obj)
示例#33
0
文件: item.py 项目: ilshad/tackle
 def render(self, selected=False):
     try:
         dc = IZopeDublinCore(self.context)
         title = dc.title
     except TypeError:
         title = None
     return u'<a href="%s" class="%s%s">%s%s</a>' % (
         absoluteURL(self.context, self.request), selected and u"selected "
         or u"", self.css_class, self.type_title, title
         or self.context.__name__)
示例#34
0
    def _extractContentInfo(self, item):
        request = self.request

        rename_ids = {}
        if "container_rename_button" in request:
            for rename_id in request.get('ids', ()):
                rename_ids[rename_id] = rename_id
        elif "rename_ids" in request:
            for rename_id in request.get('rename_ids', ()):
                rename_ids[rename_id] = rename_id

        retitle_id = request.get('retitle_id')

        id, obj = item
        info = {}
        info['id'] = info['cb_id'] = id
        info['object'] = obj

        info['url'] = urllib.quote(id.encode('utf-8'))
        info['rename'] = rename_ids.get(id)
        info['retitle'] = id == retitle_id

        zmi_icon = queryMultiAdapter((obj, self.request), name='zmi_icon')
        if zmi_icon is None:
            info['icon'] = None
        else:
            info['icon'] = zmi_icon()

        dc = IZopeDublinCore(obj, None)
        if dc is not None:
            info['retitleable'] = canWrite(dc, 'title')
            info['plaintitle'] = not info['retitleable']

            title = self.safe_getattr(dc, 'title', None)
            if title:
                info['title'] = title

            formatter = self.request.locale.dates.getFormatter(
                'dateTime', 'short')

            created = self.safe_getattr(dc, 'created', None)
            if created is not None:
                info['created'] = formatter.format(created)

            modified = self.safe_getattr(dc, 'modified', None)
            if modified is not None:
                info['modified'] = formatter.format(modified)
        else:
            info['retitleable'] = 0
            info['plaintitle'] = 1

        sized_adapter = ISized(obj, None)
        if sized_adapter is not None:
            info['size'] = sized_adapter
        return info
示例#35
0
def NetScannerInstances(dummy_context):
    """Which types of network scanners are there
    """
    #print "NetScannerInstances   ################"
    utilList = [util for name, util in zapi.getUtilitiesFor(IScanner)]
    #prefixes = [u'dot', u'neato', u'twopi', u'circo', u'fdp']
    terms = [SimpleTerm(util.__name__,
                        str(util.__name__),
                        IZopeDublinCore(util).title) \
             for util in utilList]
    return SimpleVocabulary(terms)
示例#36
0
def CreatorAnnotator(event):
    """Update Dublin-Core creator property"""
    dc = IZopeDublinCore(event.object, None)
    # Principals that can create objects do not necessarily have
    # 'zope.app.dublincore.change' permission.
    # https://bugs.launchpad.net/zope3/+bug/98124
    dc = removeSecurityProxy(dc)
    if dc is None:
        return

    # Try to find a principal for that one. If there
    # is no principal then we don't touch the list
    # of creators.
    interaction = queryInteraction()
    if interaction is not None:
        for participation in interaction.participations:
            if participation.principal is None:
                continue
            principalid = participation.principal.id
            if not principalid in dc.creators:
                dc.creators = dc.creators + (unicode(principalid), )
示例#37
0
    def edit(self):
        request = self.request
        formatter = self.request.locale.dates.getFormatter("dateTime", "medium")
        dc = IZopeDublinCore(self.context)
        message = ""

        if "dctitle" in request:
            dc.title = unicode(request["dctitle"])
            dc.description = unicode(request["dcdescription"])
            description = Attributes(IZopeDublinCore, "title", "description")
            notify(ObjectModifiedEvent(self.context, description))
            message = _("Changed data ${datetime}", mapping={"datetime": formatter.format(datetime.utcnow())})

        return {
            "message": message,
            "dctitle": dc.title,
            "dcdescription": dc.description,
            "modified": (dc.modified or dc.created) and formatter.format(dc.modified or dc.created) or "",
            "created": dc.created and formatter.format(dc.created) or "",
            "creators": dc.creators,
        }
示例#38
0
    def edit(self):
        request = self.request
        formatter = self.request.locale.dates.getFormatter('dateTime', 'medium')
        dc = IZopeDublinCore(self.context)
        message=''

        if 'dctitle' in request:
            dc.title = unicode(request['dctitle'])
            dc.description = unicode(request['dcdescription'])
            description = Attributes(IZopeDublinCore, 'title', 'description')
            notify(ObjectModifiedEvent(self.context, description))
            message = _("Changed data ${datetime}",
                        mapping={'datetime': formatter.format(datetime.utcnow())})

        return {
            'message': message,
            'dctitle': dc.title,
            'dcdescription': dc.description,
            'modified': (dc.modified or dc.created) and \
                        formatter.format(dc.modified or dc.created) or '',
            'created': dc.created and formatter.format(dc.created) or '',
            'creators': dc.creators
            }
示例#39
0
 def gimmeURL(self):
     cat = getUtility(IQreatureCatalog, context=self.context)
     int_ids = getUtility(IQreatureIntIds, context=self.context)
     quizes = cat['quizes'].apply((None,None))
     quizes = [int_ids.getObject(quiz) for quiz in quizes]
     for quiz in quizes:
         if IPublished.providedBy(quiz):
             loc = absoluteURL(quiz,self.request) + '/go.html'
             loc = loc[:7] + 'www.' + loc[7:]
             created = IZopeDublinCore(quiz).created
             created = unicode(created)
             created = created.split(u'.')
             created.reverse()
             created = created.pop()
             created = created.split(u' ')
             created.reverse()
             lastmod = created.pop()
             changefreq= "weekly"
             priority="0.5"
             yield {'loc':loc,'lastmod':lastmod,'changefreq':changefreq,'priority':priority}
示例#40
0
文件: add.py 项目: ilshad/tackle
    def handleAdd(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return
        factory = getUtility(IFactory, name=data['factory'])
        ob = factory()
        title = data.get('title')
        if title:
            dc = IZopeDublinCore(ob)
            dc.title = title
        notify(ObjectCreatedEvent(ob))
        name = data['name']
        if name not in self.context:
            self.context[name] = ob
        else:
            self.status = u"Identifier already used"
            return

        installed = getObject(IInstalledContent(self.context))
        installed.contents += (name,)
        notify(ObjectModifiedEvent(installed))

        self.request.response.redirect(self.request.URL)
示例#41
0
 def renderImage(self, image):
     self.request.response.setHeader('Content-Type', image.mimeType)
     self.request.response.setHeader('Content-Length', image.size)
     try:
         modified = IZopeDublinCore(self.context).modified
     except TypeError:
         modified=None
     if modified is not None and isinstance(modified, datetime.datetime):
         header= self.request.getHeader('If-Modified-Since', None)
         lmt = long(time.mktime(modified.timetuple()))
         if header is not None:
             header = header.split(';')[0]
             try:
                 mod_since=long(time(header))
             except:
                 mod_since=None
             if mod_since is not None:
                 if lmt <= mod_since:
                     self.request.response.setStatus(304)
                     return ''
         self.request.response.setHeader(
             'Last-Modified', zope.datetime.rfc1123_date(lmt))
     result = image.openDetached()
     return result
示例#42
0
 def __call__(self, data):
     dc = IZopeDublinCore(self.context)
     dc.title = data.get('arg')
示例#43
0
 def __call__(self, data):
     dc = IZopeDublinCore(self.context)
     dc.description = data.get('arg')