Пример #1
0
def authenticated_memberid(context):
    """ the last modified author is set on an annotation """
    from opencore.project.browser.metadata import ANNOT_KEY
    from Missing import Value as MissingValue
    annot = IAnnotations(context)
    annot = annot.get(ANNOT_KEY, {})

    val = annot.get('lastModifiedAuthor')
    if val:
        return val

    # @@ adapters must return something or code must expect component
    # errors
    return MissingValue
Пример #2
0
class GEOLocated(object):
    """ geolocation
    """
    implements(IGEOLocated)

    def __init__(self, context):
        """ init  """
        self.annotations = IAnnotations(context)
        self.geolocation = self.annotations.get(GEOLOCATION_KEY, None)
        if self.geolocation == None:
            self.annotations[GEOLOCATION_KEY] = PersistentMapping()
            self.geolocation = self.annotations[GEOLOCATION_KEY]
            self.geolocation['latitude']  = None
            self.geolocation['longitude'] = None

    def getLongitude(self): 
        """ return longtitude """
        return self.geolocation['longitude']

    def getLatitude(self):
        """ return latitude """
        return self.geolocation['latitude']

    def setLongitude(self, value):
        """ set longtitude """
        self.geolocation['longitude'] = float(value)

    def setLatitude(self, value):
        """ set latitutde """
        self.geolocation['latitude'] = float(value)

    def setLocation(self, latitude, longitude):
        """ set location """
        self.geolocation['longitude'] = float(longitude)
        self.geolocation['latitude'] = float(latitude)
Пример #3
0
    def migrate(self):
        if self.is_updated(): 
            return 'already migrated'
        
        # set the appropriate list type based on the previous settings
        # this may need to mark the appropriate interface on the mailing
        # list as well
        if self.context.moderated:
            self.context.list_type = PostModeratedListTypeDefinition
        elif self.context.closed:
            self.context.list_type = MembershipModeratedListTypeDefinition
        else:
            self.context.list_type = PublicListTypeDefinition

        # copy over the membership stuff
        annot = IAnnotations(self.context)
        listen_annot = annot.get('listen', {})
        old_subscribers = listen_annot.get('subscribers', [])

        # create the new annotations by using current adapters
        mem_list = IWriteMembershipList(self.context)
        for subscriber in old_subscribers:
            mem_list.subscribe(subscriber)

        # unsubscribe (but leave as allowed senders) those who don't 
        # receive mail
        nomail = listen_annot.get('norecvmail', [])
        for allowed_sender in nomail:
            mem_list.unsubscribe(allowed_sender)

        # copy over the moderation messages
        self.mod_post_pending_list = getAdapter(self.context, IPostPendingList, 'pending_pmod_post')
        for i in self.context.mqueue.objectIds():
            (header, body) = splitMail(self.context.mqueue[i])
            post = {'header':header, 'body':body}
            (user_name, user_email) = parseaddr(header.get('from', ''))
            self.mod_post_pending_list.add(user_email, user_name=user_name, post=post)

        # creates list managers from moderators and list owner
        managers = []
        managers.append(self.context.list_owner)
        for moderator in self.context.moderators:
            managers.append(moderator)
        self.context.managers = tuple(managers)
        convert_manager_emails_to_memberids(self.context)

        # translate archived vocabulary
        if self.context.archived == 'not archived':
            self.context.archived = 2
        elif self.context.archived == 'plain text':
            self.context.archived = 1
        elif self.context.archived == 'with attachments':
            self.context.archived = 0
        else:
            return 'error translating archive option'

        # annotate the list to say the migration completed
        self.migration_annot.append('policy_migration')

        return 'successfully migrated'
Пример #4
0
class GEOMap(object):
    """ geomap
    """
    implements(IGEOMap)

    def __init__(self, context):
        """ init  """
        self.annotations = IAnnotations(context)
        self.geomap = self.annotations.get(GEOMAP_KEY, None)
        if self.geomap == None:
            self.annotations[GEOMAP_KEY] = PersistentMapping()
            self.geomap = self.annotations[GEOMAP_KEY]
            self.geomap['mapcenter'] = None
            self.geomap['mapzoom']   = None
            self.geomap['maptype']   = None

    def getMapCenter(self):
        """ return map center """
        return self.geomap['mapcenter']

    def getMapZoom(self):
        """ return map zoom """
        return self.geomap['mapzoom']

    def getMapType(self):
        """ return map type """
        return self.geomap['maptype']


    def setMap(self, mapcenter, mapzoom, maptype):
        """ set map options """
        self.geomap['mapcenter'] = mapcenter
        self.geomap['mapzoom'] = mapzoom
        self.geomap['maptype'] = maptype
Пример #5
0
 def __init__(self, context):
     self.context = context
     annot = IAnnotations(context)
     req_annot = annot.get(annot_key, None)
     if req_annot is None:
         req_annot = set()
         annot[annot_key] = req_annot
     self._req_store = req_annot
Пример #6
0
    def __init__(self, context):
        annotations = IAnnotations(context)
        dcdata = annotations.get(DCkey)
        if dcdata is None:
            self.annotations = annotations
            dcdata = ZDCAnnotationData()

        super(ZDCAnnotatableAdapter, self).__init__(dcdata)
Пример #7
0
 def __init__(self, context):
     self.context = context
     annot = IAnnotations(context)
     wiki_annot = annot.get(annot_key, None)
     if wiki_annot is None:
         wiki_annot = IOBTree()
         annot[annot_key] = wiki_annot
     self.annot = wiki_annot
Пример #8
0
 def __init__(self, context):
     self.context = context
     annot = IAnnotations(context)
     homepage_annot = annot.get(self.KEY, None)
     if homepage_annot is None:
         homepage_annot = OOBTree()
         annot['opencore.project.browser.home_page'] = homepage_annot
     self.annot = homepage_annot
Пример #9
0
 def clearMemoCache(self):
     # from the request
     req = self.portal.REQUEST
     annotations = IAnnotations(req)
     cache = annotations.get(ViewMemo.key, None)
     if cache is not None:
         annotations[ViewMemo.key] = dict()
     # from the timestamp cache
     opencore.utils.timestamp_cache.clear()
Пример #10
0
 def __init__(self, requester, folder):
     self.requester = requester
     self.folder = folder
     annot = IAnnotations(requester)
     req_annot = annot.get(annot_key, None)
     if req_annot is None:
         req_annot = PersistentDict()
         annot[annot_key] = req_annot
     self._req_store = req_annot
Пример #11
0
 def __init__(self, context):
     _ATCTFileAudio.__init__(self, context)
     annotations = IAnnotations(context)
     self.encoding_data = annotations.get(self.ENCODING_KEY, None)
     if self.encoding_data == None:
         self.encoding_data = PersistentDict()
         annotations[self.ENCODING_KEY] = self.encoding_data
         self.encoding_data['encoding'] = ""
         self.encoding_data['original_encoding'] = ""
Пример #12
0
 def addPath(self, path):
     path = self._make_relative(path)
     annotations = IAnnotations(self.context)
     old = annotations.get(self.key, ())
     fixed = map(self._make_relative, old)
     if path not in fixed:
         fixed.append(path)
     new = tuple(fixed)
     if new != old:
         annotations[self.key] = new
Пример #13
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     annotations = IAnnotations(context.getCanonical())
     mapping = annotations.get(KEY)
     if mapping is None:
         mapping = annotations[KEY] = PersistentDict({
             'page_background': None,
         })
     self.mapping = mapping
    def capture(self, order, amount):
        annotations = IAnnotations(order)
        trans_id = annotations[interfaces.keys.processor_txn_id]
        if annotations.has_key(APPROVAL_KEY):
            annotation = IAnnotations( order )
            if annotation.get( interfaces.keys.capture_amount ) is None:
                annotation[ interfaces.keys.capture_amount ] = amount
            else:
                annotation[ interfaces.keys.capture_amount ] += amount            
            return interfaces.keys.results_success

        return result.response_reason
Пример #15
0
    def save_import_history(self):
        annot = IAnnotations(self.context)
        listen_annot = annot.get(PROJECTNAME)
        if listen_annot is None:
            annot[PROJECTNAME] = listen_annot = OOBTree()
        import_annot = listen_annot.get('import')
        if import_annot is None:
            listen_annot['import'] = import_annot = OOBTree()

        now = str(time.time())
        data = dict(msgids=self.msgids, filename=self.filename)
        import_annot[now] = OOBTree(data)
 def save_import_history(self):
     annot = IAnnotations(self.context)
     listen_annot = annot.get(PROJECTNAME)
     if listen_annot is None:
         annot[PROJECTNAME] = listen_annot = OOBTree()
     import_annot = listen_annot.get('import')
     if import_annot is None:
         listen_annot['import'] = import_annot = OOBTree()
         
     now = str(time.time())
     data = dict(msgids=self.msgids,
                 filename=self.filename)
     import_annot[now] = OOBTree(data)
Пример #17
0
 def removePath(self, path):
     path = self._make_relative(path)
     annotations = IAnnotations(self.context)
     old = annotations.get(self.key, ())
     if old:
         fixed = map(self._make_relative, old)
         fixed = [loc for loc in fixed if loc != path]
         new = tuple(fixed)
         if new != old:
             if new:
                 annotations[self.key] = new
             else:
                 del annotations[self.key]
Пример #18
0
class Point(object):
    implements(IPoint)

    def __init__(self, context):
        """ init  """
        self.annotations = IAnnotations(context)
        self.point = self.annotations.get(GEOLOCATION_KEY, None)
        if self.point == None:
            self.annotations[GEOLOCATION_KEY] = PersistentMapping()
            self.point = self.annotations[GEOLOCATION_KEY]
            self.point['targetId'] = ''
            self.point['extrude'] = 0
            self.point['tessellate'] = 0
            self.point['altitudeMode'] = 'clampToGround'
            self.point['coordinates']  = (0,0,0)

    def getCoordinates(self):
        return self.point['coordinates']

    def setCoordinates(self, coordinates):
        self.point['coordinates'] = coordinates

    def getAltitudeMode(self):
        return self.point['altitudeMode']

    def setAltitudeMode(self, altitudeMode):
        self.point['altitudeMode'] = altitudeMode

    def getTessellate(self):
        return self.point['tessellate']

    def setTessellate(self, tessellate):
        self.point['tessellate'] = tessellate

    def getExtrude(self):
        return self.point['extrude']

    def setExtrude(self, extrude):
        self.point['extrude'] = extrude

    def getTargetId(self):
        return self.point['targetId']

    def setTargetId(self, targetId):
        self.point['targetId'] = targetId

    coordinates = property(getCoordinates, setCoordinates, """ see interface """)
    altitudeMode = property(getAltitudeMode, setAltitudeMode, """ see interface """)
    tessellate = property(getTessellate, setTessellate, """ see interface """)
    extrude = property(getExtrude, setExtrude, """ see interface """)
    targetId = property(getTargetId, setTargetId, """ see interface """)
Пример #19
0
    def _extractQueryIndexMap(self):
        fragment = self._doc.createDocumentFragment()
        annots = IAnnotations(self.context)
        query_index_map = annots.get(QIM_ANNOT_KEY)
        if query_index_map is not None:
            child = self._doc.createElement('query_index_map')
            
            for key, value in query_index_map.items():
                sub = self._doc.createElement('index')
                sub.setAttribute('name', key)
                inner = self._doc.createTextNode(value)
                sub.appendChild(inner)
                child.appendChild(sub)

            fragment.appendChild(child)
        return fragment
Пример #20
0
 def capture(self, order, amount):
     #AC - Authorization and Mark for Capture
     annotation = IAnnotations(order)
     trans_ref_num = annotation[interfaces.keys.processor_txn_id]
     data = createCaptureXMLFile(self.options, order, trans_ref_num, amount)
     
     result = self.process(data, timeout=None)
     
     if result.proc_status == "0":
         if annotation.get(interfaces.keys.capture_amount) is None:
             annotation[interfaces.keys.capture_amount] = amount
         else:
             annotation[interfaces.keys.capture_amount] += amount            
         return interfaces.keys.results_success
     else:
         return result.status_msg
Пример #21
0
    def post_validate(self, REQUEST, errors):
        form = REQUEST.form
        if form.has_key("password") or form.has_key("confirmPassword"):
            password = form.get("password", None)
            confirm = form.get("confirmPassword", None)

            annotations = IAnnotations(self)
            passwordDigest = annotations.get(PASSWORD_KEY, None)

            if not passwordDigest:
                if not password and not confirm:
                    errors["password"] = u"An initial password must be set"
                    return
            if password or confirm:
                if password != confirm:
                    errors["password"] = errors["confirmPassword"] = u"Passwords do not match"
Пример #22
0
    def post_validate(self, REQUEST, errors):
        form = REQUEST.form
        if form.has_key('password') or form.has_key('confirmPassword'):
            password = form.get('password', None)
            confirm = form.get('confirmPassword', None)

            annotations = IAnnotations(self)
            passwordDigest = annotations.get(PASSWORD_KEY, None)

            if not passwordDigest:
                if not password and not confirm:
                    errors['password'] = u'An initial password must be set'
                    return
            if password or confirm:
                if password != confirm:
                    errors['password'] = errors[
                        'confirmPassword'] = u'Passwords do not match'
Пример #23
0
    def verifyCredentials(self, credentials):
        """Authenticate against the password stored via attribute on this person,
        or pass authentication on to the next PAS plugin
        """
        login = credentials.get('login', None)
        password = credentials.get('password', None)
        logger.info("Adapting an igcPerson... %s %s" % (login,password))
        
        if login is None or password is None:
            return False

#TODO: with a line of code, we can have here login as anyone, for testing
#        gcommons_tool = getToolByName(self.context,FSD_TOOL)
#        if (password == gcommons_tool.getUseInternalPassword()( return true
        
        digest = sha(password).digest()
        annotations = IAnnotations(self.context)
        passwordDigest = annotations.get(PASSWORD_KEY, None)
        return (login == self.getUserName() and digest == passwordDigest)
Пример #24
0
    def verifyCredentials(self, credentials):
        """Authenticate against the password stored via attribute on this person,
        or pass authentication on to the next PAS plugin
        """
        login = credentials.get('login', None)
        password = credentials.get('password', None)
        logger.info("Adapting an igcPerson... %s %s" % (login, password))

        if login is None or password is None:
            return False


#TODO: with a line of code, we can have here login as anyone, for testing
#        gcommons_tool = getToolByName(self.context,FSD_TOOL)
#        if (password == gcommons_tool.getUseInternalPassword()( return true

        digest = sha(password).digest()
        annotations = IAnnotations(self.context)
        passwordDigest = annotations.get(PASSWORD_KEY, None)
        return (login == self.getUserName() and digest == passwordDigest)
Пример #25
0
 def getInfo(self):
     """ retrieve additional info """
     annotations = IAnnotations(self.context)
     info = annotations.get(self.annotation_key, {})
     info['eMail'] = self.context.email
     userid = info.get('userid', None)
     if userid:
         mdtool = getToolByName(self.context, 'portal_memberdata')
         user = mdtool[userid]
         vocab = user.Vocabulary('salutation')[0].getValue
         info.update({
             'firstName': user.getFirstName(),
             'lastName': user.getLastName(),
             'salutation': vocab(user.getSalutation()),
             'terms_and_conditions': bool(user.getTerms_and_conditions()),
         })
     relative = getToolByName(self.context, 'portal_url').getRelativeContentURL
     info['editURL'] = relative(self.context) + '/Subscriber_editForm'
     info['salutation'] = self.context.translate(info.get('salutation', ''), target_language='de')
     return info
Пример #26
0
    def _initQueryIndexMap(self, node):
        for child in node.childNodes:
            if child.nodeName != 'query_index_map':
                continue

            annots = IAnnotations(self.context)
            query_index_map = annots.get(QIM_ANNOT_KEY)
            if query_index_map is None:
                query_index_map = annots[QIM_ANNOT_KEY] = PersistentMapping()

            for sub in child.childNodes:
                if sub.nodeName != 'index':
                    continue
                key = str(sub.getAttribute('name'))
                value = ''
                for inner in sub.childNodes:
                    if inner.nodeType == inner.TEXT_NODE:
                        value = str(inner.nodeValue)
                        break
                if value:
                    query_index_map[key] = value
Пример #27
0
 def getCacheId(self):
     annotations = IAnnotations(self._context)
     return annotations.get(annotation_key, None)
Пример #28
0
 def _purgeQueryIndexMap(self):
     annots = IAnnotations(self.context)
     if annots.get(QIM_ANNOT_KEY) is not None:
         del annots[QIM_ANNOT_KEY]
Пример #29
0
 def getPaths(self):
     annotations = IAnnotations(self.context)
     locs = annotations.get(self.key, ())
     return tuple(map(self._make_absolute, locs))
Пример #30
0
    def save_list_archives(self):
        self.status.progress_descr = _(u'Saving mailing lists')
        try:
            listfol = self.context['lists']
        except KeyError:
            logger.error("No lists subfolder on %s" % self.context.getId())
            return

        real_site = getSite()
        for mlistid, mlist in listfol.objectItems(): # XXX filter more?
            logger.info("exporting %s" % mlistid)
            setSite(mlist)  # Needed to get the export adapter.
            mlistid = badchars.sub('_', mlistid)
            # Cargo-culted from listen/browser/import_export.py
            em = getAdapter(mlist, IMailingListMessageExport, name='mbox')
            # Nooo don't do it all in memory, we have seen some huge archives.
            #file_data = em.export_messages() or ''
            #self.zipfile.writestr('%s/lists/%s.mbox' % (self.context_dirname, mlistid),
            #                     file_data)
            tmpfd, tmpname = em.export_messages_to_tempfile()
            self.zipfile.write(tmpname,
                               '%s/lists/%s/archive.mbox' % (self.context_dirname, mlistid))
            os.unlink(tmpname)
            del(tmpfd)

            # Now the list subscribers.
            logger.info("exporting subscribers.csv for %s" % mlistid)
            es = getAdapter(mlist, IMailingListSubscriberExport, name='csv')
            file_data = es.export_subscribers(
                include_allowed_senders=True) or ''
            csv_path = '%s/lists/%s/subscribers.csv' % (self.context_dirname, mlistid)
            self.zipfile.writestr(csv_path, file_data)

            # And the pending subscriptions, unsubscriptions, and posts.
            from zope.annotation import IAnnotations
            import simplejson as json
            annot = IAnnotations(mlist).get('listen', {})

            this_annot = annot.get("pending_a_s_mod_email", {})
            this_annot_json = {}
            for mem_email in this_annot:
                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": this_annot[mem_email].get("user_name"),
                    }
            self.zipfile.writestr(
                '%s/lists/%s/pending_a_s_mod_email.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))

            this_annot = annot.get("a_s_pending_sub_email", {})
            this_annot_json = {}
            for mem_email in this_annot:
                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": this_annot[mem_email].get("user_name"),
                    }
            self.zipfile.writestr(
                '%s/lists/%s/a_s_pending_sub_email.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))

            this_annot = annot.get("pending_sub_email", {})
            this_annot_json = {}
            for mem_email in this_annot:
                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": this_annot[mem_email].get("user_name"),
                    }
            self.zipfile.writestr(
                '%s/lists/%s/pending_sub_email.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))

            this_annot = annot.get("pending_sub_mod_email", {})
            this_annot_json = {}
            for mem_email in this_annot:
                user_name = this_annot[mem_email].get("user_name")
                if isinstance(user_name, str):
                    try:
                        user_name = user_name.decode("utf8")
                    except UnicodeDecodeError:
                        user_name = user_name.decode("ISO-8859-1")
                if user_name:
                    user_name = user_name.encode("utf8")
                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": user_name,
                    }
            self.zipfile.writestr(
                '%s/lists/%s/pending_sub_mod_email.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))

            this_annot = annot.get("pending_unsub_email", {})
            this_annot_json = {}
            for mem_email in this_annot:
                user_name = this_annot[mem_email].get("user_name")
                if isinstance(user_name, str):
                    try:
                        user_name = user_name.decode("utf8")
                    except UnicodeDecodeError:
                        user_name = user_name.decode("ISO-8859-1")
                if user_name:
                    user_name = user_name.encode("utf8")
                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": user_name,
                    }
            self.zipfile.writestr(
                '%s/lists/%s/pending_unsub_email.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))
                        
            this_annot = annot.get("pending_mod_post", {})
            this_annot_json = {}
            for mem_email in this_annot:
                user_name = this_annot[mem_email].get("user_name")
                if isinstance(user_name, str):
                    try:
                        user_name = user_name.decode("utf8")
                    except UnicodeDecodeError:
                        user_name = user_name.decode("ISO-8859-1")
                if user_name:
                    user_name = user_name.encode("utf8")

                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": user_name,
                    "post": {},
                    }
                posts = this_annot[mem_email].get("post")
                for post_id in posts:
                    body = posts[post_id]['body']
                    header = posts[post_id]['header']
                    try:
                        body = body.decode("utf8").encode("utf8")
                    except UnicodeDecodeError:
                        try:
                            body = body.decode("ISO-8859-1").encode("utf8")
                        except UnicodeDecodeError:
                            body = body.decode("ascii").encode("utf8")
                    for header_name in header:
                        if header_name in header:
                            val = header[header_name]
                            try:
                                val = val.decode("utf8").encode("utf8")
                            except UnicodeDecodeError:
                                val = val.decode("ISO-8859-1").encode("utf8")
                            header[header_name] = val
                    this_annot_json[mem_email]['post'][post_id] = {
                        'header': header,
                        'body': body,
                        'postid': posts[post_id]['postid'],
                        }
            
            self.zipfile.writestr(
                '%s/lists/%s/pending_mod_post.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))

            this_annot = annot.get("pending_pmod_post", {})
            this_annot_json = {}
            for mem_email in this_annot:
                user_name = this_annot[mem_email].get("user_name")
                if isinstance(user_name, str):
                    try:
                        user_name = user_name.decode("utf8")
                    except UnicodeDecodeError:
                        user_name = user_name.decode("ISO-8859-1")
                if user_name:
                    user_name = user_name.encode("utf8")

                this_annot_json[mem_email] = {
                    "pin": this_annot[mem_email].get("pin"),
                    "time": this_annot[mem_email].get("time"),
                    "subscriber": this_annot[mem_email].get("subscriber"),
                    "user_name": user_name,
                    "post": {},
                    }
                posts = this_annot[mem_email].get("post")
                for post_id in posts:
                    body = posts[post_id]['body']
                    header = posts[post_id]['header']
                    try:
                        body = body.decode("utf8").encode("utf8")
                    except UnicodeDecodeError:
                        try:
                            body = body.decode("ISO-8859-1").encode("utf8")
                        except UnicodeDecodeError:
                            body = body.decode("ascii").encode("utf8")
                    for header_name in header:
                        if header_name in header:
                            val = header[header_name]
                            try:
                                val = val.decode("utf8").encode("utf8")
                            except UnicodeDecodeError:
                                val = val.decode("ISO-8859-1").encode("utf8")
                            header[header_name] = val
                    this_annot_json[mem_email]['post'][post_id] = {
                        'header': header,
                        'body': body,
                        'postid': posts[post_id]['postid'],
                        }

            self.zipfile.writestr(
                '%s/lists/%s/pending_pmod_post.json' % (self.context_dirname, mlistid),
                json.dumps(this_annot_json))
                        
            # Now the metadata and preferences.
            logger.info("exporting settings.ini for %s" % mlistid)
            list_info = {
                'id': mlist.getId(),
                'type': mlist_type_to_workflow(mlist),
                'mailto': mlist.mailto,
                'managers': mlist.managers,
                'archive_setting': mlist_archive_policy(mlist),
                'title': mlist.Title(),
                'description': mlist.Description(),
                'creation_date': str(mlist.created()),
                'modification_date': str(mlist.modified()),
                'creator': mlist.Creator(),
                'sync_with_project': ISyncWithProjectMembership.providedBy(mlist),
                'context': self.context.getId(),
                'private_archives': mlist.private_archives,
                }
            conf_path = '%s/lists/%s/settings.ini' % (self.context_dirname, mlistid)
            self.zipfile.writestr(conf_path, mlist_conf(list_info))

            setSite(real_site)
            logger.info("finished %s" % mlistid)
class ToPreviewableObject( object ):
    
    implements( IPreviewable )
    
    _re_imgsrc = re.compile('<[iI][mM][gG]([^>]*) [sS][rR][cC]="([^">]*)"([^>]*)>')
    
    class _replacer(object):
        
        def __init__(self, sublist, instance):
            self.sublist = sublist
            self.instance = instance
        
        def __call__(self, match):
            prefix = match.group(1)
            inside = match.group(2)
            postfix = match.group(3)
            # patch inside
            if inside.startswith('./'):
                # some .swt are converted with this prefix
                inside = inside[2:]
            if inside in self.sublist:
                # convert elems that are known images 
                inside = '%s/@@preview_provider/%s' % (self.instance.getId(), inside)
            result = '<img%s src="%s"%s>' % (prefix, inside, postfix)
            return result
    
    def __init__(self, context):
        self.key         = 'htmlpreview'
        self.context     = context
        self.annotations = IAnnotations(context)
        if not self.annotations.get(self.key, None):
            self.annotations[self.key] = OOBTree()
        if not self.annotations[self.key].get('html', None):
            self.annotations[self.key]['html'] = ""
        if not self.annotations[self.key].get('subobjects', None):
            self.annotations[self.key]['subobjects'] = OOBTree()
    
    def hasPreview(self):
        return bool(len(self.annotations[self.key]['html']))
    
    def setPreview(self, preview):
        self.annotations[self.key]['html'] = preview
        self.context.reindexObject()
    
    def getPreview(self, mimetype="text/html"):
        data = self.annotations[self.key]['html']
        if mimetype!="text/html" and data is not None and data != '' :
            transforms = getToolByName(self.context, 'portal_transforms')
            filename = self.context.getPrimaryField().getAccessor(self.context)().filename+".html"
            return str(transforms.convertTo(mimetype, data.encode('utf-8'), mimetype="text/html", filename = filename)).decode('utf-8')
        return data
    
    def setSubObject(self, name, data):
        mtr = self.context.mimetypes_registry
        mime = mtr.classify(data, filename=name)
        mime = str(mime) or 'application/octet-stream'
        self.annotations[self.key]['subobjects'][name] = (data, mime)
    
    def getSubObject(self, id):
        if id in self.annotations[self.key]['subobjects'].keys():
            return self.annotations[self.key]['subobjects'][id]
        else:
            raise AttributeError
    
    def clearSubObjects(self):
        self.annotations[self.key]['subobjects'] = OOBTree()
    
    def buildAndStorePreview(self):
        self.clearSubObjects()
        transforms = getToolByName(self.context, 'portal_transforms')
        file = self.context.getPrimaryField().getAccessor(self.context)()
        data = transforms.convertTo('text/html', self.context.get_data(), filename=file.filename)
        
        if data is None:
            self.setPreview(u"")
            return
        
        #get the html code
        html_converted = data.getData()
        #update internal links
        #remove bad character '\xef\x81\xac' from HTMLPreview
        html_converted = re.sub('\xef\x81\xac', "", html_converted)
        # patch image sources since html base is that of our parent
        subobjs = data.getSubObjects()
        if len(subobjs)>0:
            for id, data in subobjs.items():
                self.setSubObject(id, data)
            html_converted = self._re_imgsrc.sub(self._replacer(subobjs.keys(), self.context), html_converted)
        #store the html in the HTMLPreview field for preview
        self.setPreview(html_converted.decode('utf-8'))
	self.context.reindexObject()
Пример #32
0
 def get_import_annot(self):
     annot = IAnnotations(self.context)
     listen_annot = annot.get(PROJECTNAME)
     if listen_annot:
         return listen_annot.get('import')
    def migrate(self):
        if self.is_updated():
            return _(u'already migrated')

        # set the appropriate list type based on the previous settings
        # this may need to mark the appropriate interface on the mailing
        # list as well
        if self.context.moderated:
            self.context.list_type = PostModeratedListTypeDefinition
        elif self.context.closed:
            self.context.list_type = MembershipModeratedListTypeDefinition
        else:
            self.context.list_type = PublicListTypeDefinition

        # copy over the membership stuff
        annot = IAnnotations(self.context)
        listen_annot = annot.get('listen', {})
        old_subscribers = listen_annot.get('subscribers', [])

        # create the new annotations by using current adapters
        mem_list = IWriteMembershipList(self.context)
        for subscriber in old_subscribers:
            mem_list.subscribe(subscriber)

        # unsubscribe (but leave as allowed senders) those who don't
        # receive mail
        nomail = listen_annot.get('norecvmail', [])
        for allowed_sender in nomail:
            mem_list.unsubscribe(allowed_sender)

        # copy over the moderation messages
        self.mod_post_pending_list = getAdapter(self.context, IPostPendingList,
                                                'pending_pmod_post')
        for i in self.context.mqueue.objectIds():
            (header, body) = splitMail(self.context.mqueue[i])
            post = {'header': header, 'body': body}
            (user_name, user_email) = parseaddr(header.get('from', ''))
            self.mod_post_pending_list.add(user_email,
                                           user_name=user_name,
                                           post=post)

        # creates list managers from moderators and list owner
        managers = []
        managers.append(self.context.list_owner)
        for moderator in self.context.moderators:
            managers.append(moderator)
        self.context.managers = tuple(managers)
        convert_manager_emails_to_memberids(self.context)

        # translate archived vocabulary
        if self.context.archived == 'not archived':
            self.context.archived = 2
        elif self.context.archived == 'plain text':
            self.context.archived = 1
        elif self.context.archived == 'with attachments':
            self.context.archived = 0
        else:
            return _(u'error translating archive option')

        # annotate the list to say the migration completed
        self.migration_annot.append('policy_migration')

        return _(u'successfully migrated')
 def get_import_annot(self):
     annot = IAnnotations(self.context)
     listen_annot = annot.get(PROJECTNAME)
     if listen_annot:
         return listen_annot.get('import')