##############################################################################  
#   
# This software is released under the Zope Public License (ZPL) Version 1.0
#
# Copyright (c) Digital Creations.  All rights reserved.  
# Portions Copyright (c) 1999 by Butch Landingin.
# Portions Copyright (c) 2000-2001 by Chris Withers.
#   
##############################################################################  
     
import re    
from Globals import HTMLFile, MessageDialog
import Globals
from time import time, localtime, strftime, gmtime
from string import strip,split,atoi
from types import IntType
from urllib import quote
from DocumentTemplate.DT_Util import html_quote
from Squishfile import Squishfile
from StringIO import StringIO
from Products.PythonScripts.PythonScript import manage_addPythonScript

# Some handy regular expression
CRLF=re.compile('\r\n|\n\r')    
tagRegex = re.compile("<.*?>")

# where we exist on the file system
file_path = Globals.package_home(globals())
    
def sameday(n, m):     
    n = localtime(n)     
    m = localtime(m)     
    if m[0] == n[0] and m[1] == n[1] and m[2] == n[2]:     
        return 1     
    else:     
        return 0     
     
def addPythonScript(obj,id,file):
    f=open(file_path+'/'+file+'.py')     
    file=f.read()     
    f.close()     
    manage_addPythonScript(obj,id)
    obj._getOb(id).write(file)
    return getattr(obj,id)     

def addDTML(obj,id,title,file):     
    f=open(file_path+'/'+file+'.dtml')     
    file=f.read()     
    f.close()     
    obj.manage_addDTMLMethod(id,title,file)     
    return getattr(obj,id)     
     
def addImage(obj,id,file):     
    f=open(file_path+'/'+file,'rb')     
       
    contents=f.read()     
    f.close()     
    title=''     
    tlen = len(contents)     
    new_id = obj.manage_addImage(id,contents,title=title)   
    img_obj = obj.__getitem__(new_id)  
    img_obj.content_type = 'image/gif'  
    
     
def addTable(obj,addmethod,id,fname):     
    file=open(file_path+'/'+fname+'.tbl')     
    cols=file.readline()     
    cols=cols[:-1] # takeout newline     
    fcontent=file.read()     
    file.close()     
    title=''
    getattr(obj,addmethod)(id,title,cols)
    tbl=getattr(obj,id)     
    tbl.manage_editData(fcontent)     
     
def addArt(obj,file):
    f=open(file_path+'/'+file)     
    file=''
    REQUEST=obj.REQUEST
    REQUEST['title'] = f.readline()[:-1] # removes newline char     
    REQUEST['subject'] = f.readline()[:-1]     
    REQUEST['author'] = f.readline()[:-1]     
    REQUEST['email'] = f.readline()[:-1]     
    REQUEST['notify']= f.readline()[:-1]     
    REQUEST['dept']=f.readline()[:-1]
    
    summary=''     
    currline=f.readline()     
    while strip(currline) <> '%%' and currline <> '':     
        summary = summary + currline     
        currline=f.readline()
    REQUEST['summary']=summary
    
    body=''     
    currline=f.readline()     
    while strip(currline) <> '%%' and currline <> '':     
        body = body + currline     
        currline=f.readline()
    REQUEST['body']=body
    
    f.close()
    id =  obj.addPosting(file,REQUEST,index=0)     
    msg = obj.data[id]     
    msg.reviewed = 1
    return id     
     
PATH_SEP=re.compile('[\\/]')      
    
def createUploadable(filename):
    filename=file_path+'/'+filename
    f=open(filename,'rb')
    # extra step 'cos we can't set attributes on files
    s=StringIO(f.read())
    s.filename=filename
    return s
    
def addFile(posting,file):
    f  = createUploadable(file)
    sf = Squishfile(f)
    posting.file = sf
    setattr(posting,sf.file_name(),sf)
    
htmlhead =  '''<html><head><title>%s</title></head>  
<body><pre>    
'''    
    
htmlend = '''   
</pre></body></html>    
'''    
    
def addText(file,title):    
    global htmlhead, htmlend     
    try:     
        f=open(file_path+'/'+file,'rb')     
    except:     
        return htmlhead + htmlend         
    s = f.read()     
    f.close()     
    return (htmlhead % title) + html_quote(s) + htmlend

def doAddPosting(self, file, REQUEST,RESPONSE,moderated,message,klass,index=1):     
        """ add a posting """
        moderated = getattr(self,moderated)
        comment = klass.meta_type=='Comment'
        # This sets reviewed if comments aren't moderated and leaves it at 0 if they are.
        reviewed = not moderated
        
        id=self.createId()     
     
        msg=klass(id, [], self.level+1, reviewed).__of__(self)     

        error = msg.edit(REQUEST,None,'delete attachment',file,reviewed,index=0)
        if error:
            return error

        # setup thread
        thread=msg.thread   
        map(thread.append, self.thread)

        # tweaks if we're a comment
        if comment:
            thread.append(atoi(self.id))     
            msg.subject = self.subject

        # increase reply counts or moderation counts as appropriate
        for t in thread:     
            obj=self.data[t]     
            obj.modified=id     
            if not reviewed:     
                obj.revsub=obj.revsub+1     
            else:     
                obj.reply_cnt = obj.reply_cnt+1     

        self.setItem(id, msg, index=index)     
        self.expire_items()     
          
        if RESPONSE:
            if hasattr(self,'doNotify'):
                self.doNotify(msg,REQUEST)
            
            if comment and self.mail_replies or klass.meta_type=='Article' and self.mail_articles:
                self.sendEmail(msg,self.admin_address,REQUEST,manage_notify=1)

            gtime = gmtime(id)     
            glist = list(gtime)     
            glist[0] = glist[0] + 1 # add 1 year to expiry date     
            glist[1] = 12     
            glist[2] = 31     
            glist[3] = 23     
            glist[4] = 59     
            glist[5] = 59     
            glist[6] = 0     
            glist[7] = 365     
            glist[8] = 0     
            gtime = tuple(glist)     
            e = strftime('%A, %d-%b-%y %H:%M:%S GMT',gtime)     
            author = quote(msg.author)    
            RESPONSE.setCookie('_suggest_author',author,expires=e,path='/')     
            email = quote(msg.email)    
            RESPONSE.setCookie('_suggest_email',email,expires=e,path='/')     
            RESPONSE.setCookie('suggest_notify',msg.notify,expires=e,path='/')
            
            path = self.absolute_url()            
            if not moderated:
                path = path + '/%s' % id

            return self.showMessage(self, REQUEST=REQUEST, title='%s Posted' % klass.meta_type,     
                                 message=message,     
                                 action=path     
                                )

        return id


def getitem(self,id):
    """ Get a posting from the SquishSite data store """

    # make sure id is an integer
    try:
        if not isinstance(id,IntType):
            id=atoi(id)
    except ValueError:
        raise KeyError, id

    # make sure it's in our list of children
    if not self.ids.has_key(id):
        raise KeyError, id
        
    # return the posting
    return self.data[id].__of__(self)

# figure out what crap STX is gonna throw at us
from StructuredText import html_with_references
from zLOG import LOG, WARNING
crap = str(html_with_references('', level=3))
if   crap=='<html>\n<body>\n</body>\n</html>\n':
    stx_min=14
    stx_max=-16
elif crap=='<p>\012<TABLE BORDER=1 CELLPADDING=2>\012</TABLE></p>\012\012':
    stx_min=0
    stx_max=-2
else:
    stx_min=0
    stx_max=100000
    LOG('Squishdot',
        WARNING,
        'STX has decided to throw out unexpected crap:',
        crap)
