[Zope-dev] Confera fix

Jon Franz jfranz@one.net
Tue, 27 Jun 2000 16:52:11 -0400


This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.

------_=_NextPart_000_01BFE079.913694E2
Content-Type: text/plain;
	charset="iso-8859-1"

Attached is a slightly modified Confera.py that does not require the
ts_regex
python package (something I do not have on my system and cant seem to 
find - and yet something Confera will choke on during message posting if 
it doesn't exist)

I've put the moded Confera.py up in my member folder at:
http://www.zope.org/Members/Coventry/Confera_Fix

Anyone who has problems utilizing Confera due to no ts_regex may find this 
useful.

Does anyone know where to find ts_regex by itself?

If its not readily available (I cannot find it) I'd suggest making a minor
point 
release of Confera that does not need it.

 <<Confera.py>> 

------_=_NextPart_000_01BFE079.913694E2
Content-Type: application/octet-stream;
	name="Confera.py"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
	filename="Confera.py"

########################################################################=
######
#=20
# Zope Public License (ZPL) Version 0.9.7
# ---------------------------------------
#=20
# Copyright (c) Digital Creations.  All rights reserved.
#=20
# This license has been certified as Open Source(tm).
#=20
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions =
are
# met:
#=20
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
#=20
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#=20
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
#=20
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
#=20
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#=20
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
#=20
# 5. Names associated with Zope or Digital Creations must not be used =
to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
#=20
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
#=20
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
#=20
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
#=20
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be =
clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
#=20
#=20
# Disclaimer
#=20
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
#=20
#=20
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
#=20
########################################################################=
######
"""Confera - a web-based discussion system."""

__version__=3D'$Revision: 1.2 $'[11:-2]

#import sys, ts_regex, regsub
import sys, regsub
from Globals import Persistent
from Globals import PersistentMapping
from Globals import HTMLFile ,MessageDialog
from OFS.ObjectManager import ObjectManager
from AccessControl.Role import RoleManager
from SearchIndex.TextIndex import TextIndex
from SearchIndex.Index import Index
from IOBTree import BTree
from intSet import intSet
from FileObject import FileObject
from OFS.Folder import Folder
from Acquisition import Implicit
from time import time, localtime
from string import strip,split,join
from string import lower,rfind,atoi


#crlf=3Dts_regex.compile('\r\n\|\n\r')
#dpat=3Dts_regex.compile('[\\/]')





class Topic(Folder, RoleManager):
    """ """
    meta_type  =3D'Confera Topic'
    description=3D'Confera Topic'

    icon       =3D'misc_/Confera/topic.gif'
    root       =3D1

    _properties=3D({'id':'title', 'type':'string'},
                )

    manage_messages=3DHTMLFile('Topic_manage_messages', globals())
    manage_editForm=3DHTMLFile('Topic_editForm', globals())

    manage_options=3D({'label':'Contents', 'icon':icon,
                     'action':'manage_main', 'target':'manage_main'},
                    {'label':'Messages', 'icon':'',
                     'action':'manage_messages', =
'target':'manage_main'},
                    {'label':'Options', 'icon':'',
                     'action':'manage_editForm', =
'target':'manage_main'},
                    {'label':'Properties', 'icon':'',
                     'action':'manage_propertiesForm', =
'target':'manage_main'},
                    {'label':'Security', 'icon':'',
                     'action':'manage_access', 'target':'manage_main'},
                    {'label':'Undo', 'icon':'',
                     =
'action':'manage_UndoForm','target':'manage_main'},
                    )

    __ac_permissions__=3DFolder.__ac_permissions__+(
        ('Manage messages', ['manage_edit', 'manage_delete']),
        ('Add messages', ['addMessage'], ('Anonymous', 'Manager')),
        )
  =20

    def __init__(self, id, title, mhost, exp, mod, default):
        t=3Dtime()
        self.id       =3Did
        self.title    =3Dtitle
        self.created  =3Dt
        self.modified =3Dt
        self.mail_host=3Dmhost
        self.expire   =3Dexp
        self.moderated=3Dmod
        self.data     =3DBTree()  # id -> Message
        self.ids      =3DintSet() # ids of children

        self.indices=3DPersistentMapping({'author': Index(),
                                        'body'  : TextIndex(),
                                       }
                                      )
        for k in self.indices.keys():
            self.indices[k]._init(self.data,None,k)

        if default:
            self.defaultDocFile('index_html','Topic Homepage',
                                'Confera/Topic_index_html')
            self.defaultDocFile('message_html','Message',
                                'Confera/Topic_message_html')
            self.defaultDocFile('searchForm','Search Form',
                                'Confera/Topic_searchForm')
            self.defaultDocFile('searchResults','Search Results',
                                'Confera/Topic_searchResults')
            self.defaultDocFile('mail_html','Notification Email',
                                'Confera/Topic_mail_html')
            self.defaultDocFile('addMessageForm','Add Message Form',
                                'Confera/addMessageForm')

    def __len__(self): return 1

    def __getitem__(self,n):
        try:    id=3Datoi(n)
        except: raise AttributeError, n
        if self.ids.has_key(id):
            return self.data[id].__of__(self)
        raise AttributeError, n

    def setItem(self,id,obj):
        # Make sure the object we store is not wrapped with
        # an acquisition wrapper, since we will be wrapping
        # it again manually in __getitem__ when it is needed.
        if hasattr(obj, 'aq_base'):
            obj=3Dobj.aq_base
        self.ids.insert(id)
        self.data[id]=3Dobj
        for k in self.indices.keys():
            self.indices[k].index_item(id)

    def delItem(self,id):
        data=3Dself.data
        item=3Ddata[id]
        if self.ids.has_key(id): self.ids.remove(id)
        else: data[item.thread[-1]].ids.remove(id)
        if self.moderated:
            if not item.reviewed:
                for t in item.thread:
                    obj=3Dself.data[t]
                    if obj.revsub > 0: obj.revsub=3Dobj.revsub-1
        ids=3DintSet()
        ids.insert(id)
        ids=3Ditem.sub_ids(ids,data)
        item=3DNone
        for index in self.indices.values():
            for id in ids:
                try:    index.unindex_item(id)
                except: pass
        for id in ids:
            del data[id]

    def createId(self):
        id=3Dint(time())
        while 1:
            try:    o=3Dself.data[id]
            except: break
            id=3Did+1
        return id

    def defaultDocFile(self,id,title,file):
        f=3Dopen('%s/Products/%s.dtml' % (SOFTWARE_HOME,file))
        file=3Df.read()
        f.close()
        self.manage_addDTMLMethod(id,title,file)

    def messageValues(self):
        """ """
        return map(lambda x, p=3Dself: x.__of__(p), =
self.data.map(self.ids))


    def tpId(self):
        return self.id

    def tpURL(self):
        return self.id

    def this(self):
        return self

    def topic(self):
        return (self,)

    def topic_url(self):
        return self.REQUEST['URL1']

    def has_items(self):
        return len(self.ids)

    def item_count(self):
        return len(self.data)

    def mailhost_list(self):
        try:    return self.superValues(('Mail Host',))
        except: return []

    def expire_items(self):
        if self.expire:
            d=3Dself.data
            t=3Dint(time()-(self.expire * 86400.0))
            ids=3D[]
            for id in d.keys():
                if d[id].modified < t:
                    ids.append(id)
            for id in ids:
                try:    self.delItem(id)
                except: pass
        return ''

    def =
addMessage(self,title,author,body,email=3D'',notify=3D'',file=3D'',
                   submit=3D'Cancel',REQUEST=3DNone,RESPONSE=3DNone):
        """ """
        if submit=3D=3D'Cancel':
            RESPONSE.redirect('%s/index_html' % self.topic_url())
        title =3Dstrip(title)
        author=3Dstrip(author)
        email =3Dstrip(email)
	# workaround by JMF
        body=3Dregsub.gsub('\n\r', '\n', body)
	body=3Dregsub.gsub('\r\n', '\n', body)
	body =3D split(body,'\n')
	#body  =3Dsplit(regsub.gsub(crlf,'\n',body),'\n')
        notify=3Dnotify
        reviewed=3D(not self.moderated) and 1 or 0

        try:    file=3DFileObject(file)
        except: file=3D''

        if notify and not email:
            return MessageDialog(
                   title=3D'Data Missing',
                   message=3D'You must enter an email address for =
notification!',
                   action=3DREQUEST['URL1']+'/addMessageForm')

        if not title or not author or not body:
            return MessageDialog(
                   title=3D'Data Missing',
                   message=3D'You must enter a title, author and =
body!',
                   action=3DREQUEST['URL1']+'/addMessageForm')

        id=3Dself.createId()
        =
msg=3DMessage(id,intSet(),title,author,body,email,notify,reviewed,file)
        msg=3Dmsg.__of__(self)

        self.setItem(id,msg)
        self.expire_items()

        if REQUEST:
            p=3D'%s%s' % (REQUEST['SCRIPT_NAME'],REQUEST['PATH_INFO'])
            t=3Dself.id
            p=3Dp[:(rfind(p,t)+len(t))]
            e=3D'Friday, 31-Dec-99 23:59:59 GMT'
            resp=3DREQUEST['RESPONSE']
            =
resp.setCookie('suggest_author',author,path=3Dp,expires=3De)
            resp.setCookie('suggest_email',email,path=3Dp,expires=3De)
            =
resp.setCookie('suggest_notify',notify,path=3Dp,expires=3De)
            return MessageDialog(title=3D'Message Posted',
                                 message=3D'Your message has been =
posted',
                                 action=3DREQUEST['URL1'])

    def search(self,REQUEST):
        """ """
        sr=3Dself.__call__(REQUEST,1)
        rc=3Dlen(sr)
        return self.searchResults(self,REQUEST,search_results=3Dsr,
                                  result_count=3Drc)

    def =
manage_edit(self,mailhost=3D'',exp=3D0,expire=3D'0',moderated=3D0,
                    REQUEST=3DNone):
        """ """
        if exp: expire=3Datoi(expire)
        else:   expire=3D0
        if mailhost:
            try:    v=3Dgetattr(self, mailhost)
            except: return MessageDialog(title=3D'Invalid Mail Host',
                           message=3D'Cannot find the named mail =
host!',
                           action=3DREQUEST['URL']+'/manage_main')
        self.mail_host=3Dmailhost
        self.expire   =3Dexpire
        self.moderated=3Dmoderated
        return self.manage_main(self, REQUEST)

    def manage_delete(self,REQUEST,ids=3D[],):
        """ """
        ids=3Dmap(atoi, ids)
        while ids:
            self.delItem(ids[-1])
            del ids[-1]
        return self.manage_messages(self, REQUEST)


    # Searchable interface

    def __call__(self, REQUEST=3DNone, internal=3D0):
        if REQUEST is None: REQUEST=3Dself.REQUEST
        myid=3Dself.id
        rset=3DNone
        used=3D{}
        for i in self.indices.values():
            try:
                r=3Di._apply_index(REQUEST,myid)
                if r is not None:
                    r,u=3Dr
                    for n in u: used[n]=3D1
                    if rset is None: rset=3Dr
                    else: rset=3Drs.intersection(r)
            except: pass

        if rset is None:
            r=3D[]
        else:
            r=3Dself.data.map(rset)
            if self.moderated:
                r=3Dfilter(lambda x: x.reviewed, r)
            r=3Dmap(lambda x, p=3Dself: x.__of__(p), r)

        if internal: return r
        return ResultSet(r)

    def _searchable_result_columns(self):
        return ({'name':'title', 'type':'s'},
                {'name':'author','type':'s'},
                {'name':'body',  'type':'s'},
                {'name':'email', 'type':'s'},
               )

    def _searchable_arguments(self):
        return {'author': {'type':'string', 'optional':1, 'indexed':1},
                'body':   {'type':'string', 'optional':0, 'indexed':1},
               }



class ResultItem:
    def __init__(self,data):
        self._data=3Ddata

    _schema=3D['title','author','body','email']

    def __getattr__(self,key):
        if key=3D=3D'body':
            return join(self._data.body,'<BR>')
        return getattr(self._data, key)

    def __getitem__(self,key,inttype=3Dtype(0)):
        try:
            if type(key) is inttype:
                return getattr(self._data,self._schema[key])
            return getattr(self._data, key)
        except (IndexError, KeyError):
            raise AttributeError, key

    def __len__(self):
        return len(self._schema)



class ResultSet:
    def __init__(self,data):
        self._data=3Dmap(ResultItem, data)

    def __getitem__(self,index):
        return self._data[index]
   =20
    def __len__(self):
        return len(self._data)

    def __getslice__(self,i1,i2):
        return self._data[i1:i2]

    slice=3D__getslice__
    _searchable_result_columns=3DTopic._searchable_result_columns



class Message(Persistent, Implicit):
    """ """
    manage_editForm=3DHTMLFile('editMessageForm', globals())
    manage         =3Dmanage_editForm
    manage_main    =3Dmanage_editForm

    meta_type=3D'Message'
    icon   =3D'misc_/Confera/message.gif'
    root=3D0

    def __init__(self, id, thread, title, author, body,
                 email, notify, reviewed, file):
        self.id      =3Dstr(id)
        self.ids     =3DintSet()
        self.thread  =3Dthread
        self.title   =3Dtitle
        self.author  =3Dauthor
        self.body    =3Dbody
        self.email   =3Demail
        self.notify  =3Dnotify
        self.created =3Did
        self.modified=3Did
        self.reviewed=3Dreviewed
        if file:
            setattr(self,file._name,file)
            self.file=3Dfile
        else:
            self.file=3D''
        self.revsub  =3D0

    def __len__(self): return 1

    def __getitem__(self,n):
        try:    id=3Datoi(n)
        except: raise AttributeError, n
        if self.ids.has_key(id):
            return self.data[id].__of__(self)
        raise AttributeError, n

    def setItem(self,id,obj):
        # Make sure the object we store is not wrapped with
        # an acquisition wrapper, since we will be wrapping
        # it again manually in __getitem__ when it is needed.
        if hasattr(obj, 'aq_base'):
            obj=3Dobj.aq_base

        self.ids.insert(id)
        self.data[id]=3Dobj
        for k in self.indices.keys():
            self.indices[k].index_item(id)

    def messageValues(self):
        return map(lambda x, p=3Dself: x.__of__(p), =
self.data.map(self.ids))

    def tpId(self):
        return self.id

    def tpURL(self):
        return self.id

    def this(self): return self

    def has_items(self):
        return len(self.ids)

    def sub_ids(self,ids,data):
        map(ids.insert, self.ids)
        for item in data.map(self.ids):
            ids=3Ditem.sub_ids(ids,data)
        return ids

    def date_created(self):
        t=3Dlocaltime(self.created)
        return '%d/%d/%d' % (t[1],t[2],t[0])

    def time_created(self):
        t=3Dlocaltime(self.created)
        return '%02d:%02d' % (t[3],t[4])

    def attachment(self):
        file=3Dself.file
        return file and (file,) or None

    def suggest_title(self):
        t=3Dself.title
        return (lower(t[:3])=3D=3D're:') and t or 'Re: %s' % t

    def topic_url(self):
        req=3Dself.REQUEST
        par=3Dreq['PARENTS']
        for p in par:
            if p.root:
                return req['URL%d' % (par.index(p)+1)]
        return ''

    def thread_path(self):
        return join(map(lambda x: '/%s' % x, self.thread), '')

    def index_html(self,REQUEST):
        """ """
        return self.message_html(self,REQUEST)

    def doNotify(self, msg, REQUEST):
        if self.notify and self.email and self.mail_host:
            mail =3Dself.mail_html(self, REQUEST, newItem=3D(msg,))
            mhost=3Dgetattr(self,self.mail_host)
            mhost.send(mail)

    def cancelNotify(self, REQUEST):
        """ """
        self.notify=3D''
        return MessageDialog(title=3D'Cancelled Notification',
                             message=3D'You will no longer be notified =
of ' \
                                     'replies to this message',
                             action=3Dself.topic_url())

    def =
addMessage(self,title,author,body,email=3D'',notify=3D'',file=3D'',
                   submit=3D'Cancel', REQUEST=3DNone,RESPONSE=3DNone):
        """ """
        if submit=3D=3D'Cancel':
            RESPONSE.redirect('%s/index_html' % self.topic_url())
        title   =3Dstrip(title)
        author  =3Dstrip(author)
        email   =3Dstrip(email)
		# workaround by JMF
        body=3Dregsub.gsub('\n\r', '\n', body)
	body=3Dregsub.gsub('\r\n', '\n', body)
	body =3D split(body,'\n')
	#body  =3Dsplit(regsub.gsub(crlf,'\n',body),'\n')

#        body    =3Dsplit(regsub.gsub(crlf,'\n',body),'\n')
        notify  =3Dnotify
        reviewed=3D(not self.moderated) and 1 or 0

        try:    file=3DFileObject(file)
        except: file=3D''

        if notify and not email:
            return MessageDialog(
                   title=3D'Data Missing',
                   message=3D'You must enter an email address for =
notification!',
                   action=3DREQUEST['URL1']+'/addMessageForm')

        if not title or not author or not body:
            return MessageDialog(
                   title=3D'Data Missing',
                   message=3D'You must enter a title, author and =
body!',
                   action=3DREQUEST['URL1']+'/addMessageForm')

        id=3Dself.createId()
        thread=3DintSet()
        map(thread.insert, self.thread)
        thread.insert(atoi(self.id))
        for t in thread:
            obj=3Dself.data[t]
            obj.modified=3Did
            if not reviewed:
                obj.revsub=3Dobj.revsub+1

        msg=3DReply(id, thread, title, author, body, email, notify,
                  reviewed, file)
        msg=3Dmsg.__of__(self)
        self.setItem(id, msg)

        if REQUEST:
            try:    self.doNotify(msg,REQUEST)
            except: pass

            p=3D'%s%s' % (REQUEST['SCRIPT_NAME'],REQUEST['PATH_INFO'])
            t=3Dself.topic()[0].id
            p=3Dp[:(rfind(p,t)+len(t))]
            e=3D'Friday, 31-Dec-99 23:59:59 GMT'
            resp=3DREQUEST['RESPONSE']
            =
resp.setCookie('suggest_author',author,path=3Dp,expires=3De)
            resp.setCookie('suggest_email',email,path=3Dp,expires=3De)
            =
resp.setCookie('suggest_notify',notify,path=3Dp,expires=3De)
            return MessageDialog(title=3D'Message Posted',
                                 message=3D'Your message has been =
posted',
                                 action=3Dp)

    def =
manage_edit(self,title,author,body,email=3D'',notify=3D'',reviewed=3D'',=

                    REQUEST=3DNone,RESPONSE=3DNone):
        """ """
        if not title or not author or not body:
            return MessageDialog(
                   title=3D'Data Missing',
                   message=3D'You must enter a title, author and =
body!',
                   action=3DREQUEST['URL1']+'/manage_editForm')
        if notify and not email:
            return MessageDialog(
                   title=3D'Data Missing',
                   message=3D'You must enter an email address for =
notification!',
                   action=3DREQUEST['URL1']+'/manage_editForm')
        self.title =3Dstrip(title)
        self.author=3Dstrip(author)
        self.email =3Dstrip(email)
		# workaround by JMF
        body=3Dregsub.gsub('\n\r', '\n', body)
	body=3Dregsub.gsub('\r\n', '\n', body)
	self.body =3D split(body,'\n')
	#body  =3Dsplit(regsub.gsub(crlf,'\n',body),'\n')

        #self.body  =3Dsplit(regsub.gsub(crlf,'\n',body),'\n')
        self.notify=3Dnotify

        if self.moderated and (not self.reviewed) and reviewed:
            self.reviewed=3D1
            for t in self.thread:
                obj=3Dself.data[t]
                if obj.revsub > 0: obj.revsub=3Dobj.revsub-1
        if RESPONSE:
            RESPONSE.redirect('%s/manage_messages' % self.topic_url())


class Reply(Message):
    """ """
    meta_type  =3D'Reply'
    icon       =3D'misc_/Confera/reply.gif'





def =
manage_addConferaTopic(self,id,title=3D'',mailhost=3D'',exp=3D0,expire=3D=
'0',
                              moderated=3D0, default=3D1, =
REQUEST=3DNone):
    """Create Confera topic"""
    if exp:
        try:    expire=3Datoi(expire)
        except: expire=3D0
    else:   expire=3D0
    if mailhost:
        try:    v=3Dgetattr(self, mailhost)
        except: return MessageDialog(title=3D'Invalid Mail Host',
                       message=3D'Cannot find the named mail host!',
                       action=3DREQUEST['URL1']+'/manage_main')
    ob=3DTopic(id,title,mailhost,expire,moderated,default)
    self._setObject(id, ob)
    if REQUEST: return self.manage_main(self,REQUEST,update_menu=3D1)

------_=_NextPart_000_01BFE079.913694E2--