Ejemplo n.º 1
0
def cb_renderer(args):
    request = args['request']
    config = request.get_configuration()
    http = request.get_http()
    form = http['form']

    # intercept ajax requests with our renderer
    if 'ajax' in form and http.get('REQUEST_METHOD', '') == 'POST':
        data = '&'.join(['%s=%s' % (arg.name, arg.value) for arg in form.list])
        tools.get_logger().info('AJAX request: %s' % data)
        return AjaxRenderer(request, request.get_data())
Ejemplo n.º 2
0
def readfile(filename, request):
    logger = tools.get_logger()
    logger.info("Calling readfile for %s", filename)
    entry_data = {}
    lines = open(filename).readlines()

    if len(lines) == 0:
        return {"title": "", "body": ""}

    title = lines.pop(0).strip()

    # absorb meta data
    while lines and lines[0].startswith("#"):
        meta = lines.pop(0)
        # remove the hash
        meta = meta[1:].strip()
        meta = meta.split(" ", 1)
        # if there's no value, we append a 1
        if len(meta) == 1:
            meta.append("1")
        entry_data[meta[0].strip()] = meta[1].strip()

    body = parse("".join(lines), request)
    entry_data["title"] = title
    entry_data["body"] = body

    # Call the postformat callbacks
    tools.run_callback("postformat", {"request": request,
                                      "entry_data": entry_data})
    logger.info("Returning %r", entry_data)
    return entry_data
Ejemplo n.º 3
0
    def __init__(self, url = '', pybloxsom_config = None):
#{{{Init method for the MoinMoinEntryParser class
        '''
        init method for MoinMoinEntryParser Object
        '''
        self.PREFORMATTER_ID = PREFORMATTER_ID

        # New MoinMoin request
        self.request = MoinMoinScriptContext(url)
        self.logger = PyblosxomTools.get_logger()
        self.url = url
        self.entryfile=''
        self.entrytitle = ''
        self.page_name = ''

        # Initial parser configuration if config is usable
        if pybloxsom_config is not None:
            self.pybloxsom_config = pybloxsom_config
            # Use moinmoin cache
            self.request.cacheable = self.request.use_cache = self.pybloxsom_config.get('moinmoin_use_cache', '0') == '1'
            #self.request.cacheable = self.request.use_cache = False

            # moinmoin encoding 
            self.output_charset = self.pybloxsom_config.get('blog_encoding', 'utf-8')
        # We don't have the config, using default
        else:
            self.request.cacheable = False
            self.output_charset = 'utf-8'
#}}}
        self.logger.debug('Moinmoin parser Object created')
Ejemplo n.º 4
0
def readfile(filename, request):
    '''This may never be used'''
    logger = tools.get_logger()
    logger.info("Calling readfile for %s", filename)
    entry_data = {}
    lines = open(filename).readlines()

    if len(lines) == 0:
        return {"title": "", "body": ""}

    title = lines.pop(0).strip()

    # absorb meta data
    meta = {}
    while lines and lines[0].startswith("#"):
        m = re.match("#([^:]+):\s*(.*)\s*")
        if m and m.group(2):
            entry_data[m.group(1)] = m.group(2)
        elif m:
            entry_data[m.group(1)] = "1"
        lines.pop(0)

    body = parse("".join(lines), request)
    entry_data["title"] = title
    entry_data["body"] = body

    # Call the postformat callbacks
    tools.run_callback("postformat", {"request": request,
                                      "entry_data": entry_data})
    logger.info("Returning %r", entry_data)
    return entry_data
Ejemplo n.º 5
0
def build_acronyms(lines):
    acronyms = []
    for line in lines:
        line = line.split("=", 1)
        firstpart = line[0].strip()

        try:
            firstpartre = re.compile("(\\b" + firstpart + "\\b)")
        except re.error:
            logger = tools.get_logger()
            logger.error("acronyms: '%s' is not a regular expression",
                         firstpart)
            continue

        secondpart = line[1].strip()
        secondpart = secondpart.replace("\"", """)

        if (secondpart.startswith("abbr|") or firstpart.endswith(".")):
            if secondpart.startswith("abbr|"):
                secondpart = secondpart[5:]
            repl = "<abbr title=\"%s\">\\1</abbr>" % secondpart
        else:
            if secondpart.startswith("acronym|"):
                secondpart = secondpart[8:]
            repl = "<acronym title=\"%s\">\\1</acronym>" % secondpart

        acronyms.append((firstpartre, repl))
    return acronyms
Ejemplo n.º 6
0
def cb_comment_reject(args):
    request = args["request"]
    config = request.get_configuration()
    http = request.get_http()
    form = http["form"]

    if "secretToken" in form and form["secretToken"].value == config["blog_title"]:
        return False

    dump = "\n".join(["%s: %s" % (arg.name, arg.value) for arg in dict(form).values()])
    logger = tools.get_logger()
    logger.info("Comment rejected from %s:\n%s" % (http["REMOTE_ADDR"], dump))
    return True
Ejemplo n.º 7
0
def cb_prepare(args):
    request = args['request']
    config = request.get_configuration()
    base_url = config['base_url']
    if not base_url:
        base_url = ''
    data = request.get_data()
    logger = tools.get_logger()
    logger.debug(data['url'])
    if data['url'] == "%s/index.html" % base_url:
        for categoryName in config["newslists"].keys():
            key = categoryName.lower()
            cfg = config["newslists"][categoryName]
            data[key] = GetNewsList(config, categoryName, cfg['itemCount'], cfg['useLink'], cfg['useDate'])
def cb_comment_reject(args):
  request = args["request"]
  config = request.get_configuration()
  http = request.get_http()
  form = http['form']

  if ('secretToken' in form and
      form['secretToken'].value == config['blog_title']):
    return 0
  else:
    dump = '\n'.join(['%s: %s' % (arg.name, arg.value)
                      for arg in dict(form).values()])
    logger = tools.get_logger()
    logger.info('Comment rejected from %s:\n%s' % (http['REMOTE_ADDR'], dump))
    return 1
Ejemplo n.º 9
0
def cb_comment_reject(args):
    req = args["request"]
    comment = args["comment"]
    blog_config = req.get_configuration()

    max_age = blog_config.get('no_old_comments_max_age', 2419200)

    data = req.get_data()
    entry = data['entry_list'][0]

    logger = tools.get_logger()

    logger.debug('%s -> %s', entry['mtime'], comment)

    if ((time.time() - entry['mtime']) >= max_age):
        logger.info('Entry too old, comment not posted!')
        return 1

    logger.info('Entry ok, comment posted!')
    return 0
Ejemplo n.º 10
0
def cb_comment_reject(args):
    req = args["request"]
    comment = args["comment"]
    blog_config = req.get_configuration()

    max_age = blog_config.get("no_old_comments_max_age", 2419200)

    data = req.get_data()
    entry = data["entry_list"][0]

    logger = tools.get_logger()

    logger.debug("%s -> %s", entry["mtime"], comment)

    if (time.time() - entry["mtime"]) >= max_age:
        logger.info("Entry too old, comment not posted!")
        return 1

    logger.info("Entry ok, comment posted!")
    return 0
Ejemplo n.º 11
0
def cb_comment_reject(args):
    req = args["request"]
    comment = args["comment"]
    blog_config = req.get_configuration()

    max_age = blog_config.get('no_old_comments_max_age', 2419200)

    data = req.get_data()
    entry = data['entry_list'][0]

    logger = tools.get_logger()

    logger.debug('%s -> %s', entry['mtime'], comment)

    if ((time.time() - entry['mtime']) >= max_age):
        logger.info('Entry too old, comment not posted!')
        return 1

    logger.info('Entry ok, comment posted!')
    return 0
Ejemplo n.º 12
0
def write_comment(request, config, data, comment, encoding):
    """
    Write a comment

    @param config: dict containing pyblosxom config info
    @type  config: dict

    @param data: dict containing entry info
    @type  data: dict

    @param comment: dict containing comment info
    @type  comment: dict

    @return: The success or failure of creating the comment.
    @rtype: string
    """
    entry_list = data.get("entry_list", [])
    if not entry_list:
        return "No such entry exists."

    entry = data['entry_list'][0]
    cdir = os.path.join(config['comment_dir'], entry['absolute_path'])
    cdir = os.path.normpath(cdir)
    if not os.path.isdir(cdir):
        os.makedirs(cdir)

    cfn = os.path.join(
        cdir, entry['fn'] + "-" + comment['pubDate'] + "." +
        config['comment_draft_ext'])

    def make_xml_field(name, field):
        return "<" + name + ">" + cgi.escape(field.get(
            name, "")) + "</" + name + ">\n"

    filedata = '<?xml version="1.0" encoding="%s"?>\n' % encoding
    filedata += "<item>\n"
    for key in comment:
        filedata += make_xml_field(key, comment)
    filedata += "</item>\n"

    try:
        cfile = codecs.open(cfn, "w", encoding)
    except IOError:
        logger = tools.get_logger()
        logger.error("couldn't open comment file '%s' for writing" % cfn)
        return "Internal error: Your comment could not be saved."

    cfile.write(filedata)
    cfile.close()

    # write latest pickle
    latest = None
    latest_filename = os.path.join(config['comment_dir'], LATEST_PICKLE_FILE)
    try:
        latest = open(latest_filename, "w")
    except IOError:
        logger = tools.get_logger()
        logger.error("couldn't open latest comment pickle for writing")
        return "Couldn't open latest comment pickle for writing."
    else:
        mod_time = float(comment['pubDate'])

    try:
        cPickle.dump(mod_time, latest)
        latest.close()
    except IOError:
        if latest:
            latest.close()

        logger = tools.get_logger()
        logger.error("comment may not have been saved to pickle file.")
        return "Internal error: Your comment may not have been saved."

    if ((('comment_mta_cmd' in config or 'comment_smtp_server' in config)
         and 'comment_smtp_to' in config)):
        # FIXME - removed grabbing send_email's return error message
        # so there's no way to know if email is getting sent or not.
        send_email(config, entry, comment, cdir, cfn)

    # figure out if the comment was submitted as a draft
    if config["comment_ext"] != config["comment_draft_ext"]:
        return "Comment was submitted for approval.  Thanks!"

    return "Comment submitted.  Thanks!"
Ejemplo n.º 13
0
"""
__author__      = "Ian Wienand"
__version__     = "1.0"
__url__         = "git://github.com/ianw/Pyblosxom-Recaptcha-plugin.git"
__description__ = "Recaptcha.net plugin for Pyblosxom"

import sys
import time

import urllib, urllib2
import encodings

from Pyblosxom import tools

logger = tools.get_logger()

def verify_installation(request):
  config = request.getConfiguration()

  if not config.has_key("recaptcha_api_key"):
    print >>sys.stderr, "Please set recaptcha_api_key"
    return False

  return True

def cb_comment_reject(args):
    
    request = args['request']
    comment = args['comment']
    config = request.get_configuration()
Ejemplo n.º 14
0
def pingback(request, source, target):
    logger = tools.get_logger()
    logger.info("pingback started")
    source_file = urllib.urlopen(source.split('#')[0])
    if source_file.headers.get('error', '') == '404':
        raise Fault(0x0010, "Target %s not exists" % target)
    source_page = parser()
    source_page.feed(source_file.read())
    source_file.close()

    if source_page.title == "":
        source_page.title = source

    if not target in source_page.hrefs:
        raise Fault(0x0011, "%s does not point to %s" % (source, target))

    target_entry = fileFor(request, target)

    body = ''
    try:
        from rssfinder import getFeeds
        from rssparser import parse

        baseurl = source.split("#")[0]
        for feed in getFeeds(baseurl):
            for item in parse(feed)['items']:
                if item['link'] == source:
                    if 'title' in item:
                        source_page.title = item['title']
                    if 'content_encoded' in item:
                        body = item['content_encoded'].strip()
                    if 'description' in item:
                        body = item['description'].strip() or body
                    body = re.compile('<.*?>', re.S).sub('', body)
                    body = re.sub('\s+', ' ', body)
                    body = body[:body.rfind(' ', 0, 250)][:250] + " ...<br />"
    except:
        pass

    cmt = {'title': source_page.title,
           'author': 'Pingback from %s' % source_page.title,
           'pubDate': str(time.time()),
           'link': source,
           'source': '',
           'description': body}

    # run anti-spam plugins
    argdict = {"request": request, "comment": cmt}
    reject = tools.run_callback("trackback_reject",
                                argdict,
                                donefunc=lambda x: x != 0)
    if isinstance(reject, (tuple, list)) and len(reject) == 2:
        reject_code, reject_message = reject
    else:
        reject_code, reject_message = reject, "Pingback rejected."
    if reject_code == 1:
        raise Fault(0x0031, reject_message)

    from comments import writeComment
    config = request.get_configuration()
    data = request.get_data()
    data['entry_list'] = [target_entry]

    # TODO: Check if comment from the URL exists
    writeComment(request, config, data, cmt, config['blog_encoding'])

    return "success pinging %s from %s\n" % (target, source)
Ejemplo n.º 15
0
def send_email(config, entry, comment, comment_dir, comment_filename):
    """Send an email to the blog owner on a new comment

    @param config: configuration as parsed by Pyblosxom
    @type config: dictionary

    @param entry: a file entry
    @type config: dictionary

    @param comment: comment as generated by read_comments
    @type comment: dictionary

    @param comment_dir: the comment directory
    @type comment_dir: string

    @param comment_filename: file name of current comment
    @type comment_filename: string
    """
    import smtplib
    # import the formatdate function which is in a different
    # place in Python 2.3 and up.
    try:
        from email.Utils import formatdate
    except ImportError:
        from rfc822 import formatdate
    from socket import gethostbyaddr

    author = escape_smtp_commands(clean_author(comment['author']))
    description = escape_smtp_commands(comment['description'])
    ipaddress = escape_smtp_commands(comment.get('ipaddress', '?'))

    if 'comment_smtp_from' in config:
        email = config['comment_smtp_from']
    else:
        email = escape_smtp_commands(clean_author(comment['email']))

    try:
        curl = "%s/%s" % (config['base_url'],
                          tools.urlencode_text(entry['file_path']))
        comment_dir = os.path.join(config['comment_dir'], entry['absolute_path'])

        # create the message
        message = []
        message.append("Name: %s" % author)
        if 'email' in comment:
            message.append("Email: %s" % comment['email'])
        if 'link' in comment:
            message.append("URL: %s" % comment['link'])
        try:
            host_name = gethostbyaddr(ipaddress)[0]
            message.append("Hostname: %s (%s)" % (host_name, ipaddress))
        # FIXME - bare except here--bad!
        except:
            message.append("IP: %s" % ipaddress)
        message.append("Entry URL: %s" % curl)
        message.append("Comment location: %s" % comment_filename)
        message.append("\n\n%s" % description)
 
        if 'comment_mta_cmd' in config:
            # set the message headers
            message.insert(0, "")
            message.insert(0, "Subject: comment on %s" % curl)
            message.insert(0, "Date: %s" % formatdate(float(comment['pubDate'])))
            message.insert(0, "To: %s" % config["comment_smtp_to"])
            message.insert(0, "From: %s" % email)

            body = '\n'.join(message).encode('utf-8')

            argv = [config['comment_mta_cmd'],
                    '-s',
                    '"comment on %s"' % curl,
                    config['comment_smtp_to']]
            # FIXME - switch to subprocess when we can require python 2.4
            process = popen2.Popen3(argv, capturestderr=True)
            process.tochild.write(body)
            process.tochild.close()
            process.wait()
            stdout = process.fromchild.read()
            stderr = process.childerr.read()
            tools.get_logger().debug('Ran MTA command: ' + ' '.join(argv))
            tools.get_logger().debug('Received stdout: ' + stdout)
            tools.get_logger().debug('Received stderr: ' + stderr)
            # the except clause below will catch this
            assert stderr == '', stderr

        else:
            assert 'comment_smtp_server' in config
            server = smtplib.SMTP(config['comment_smtp_server'])
            mimemsg = MIMEText("\n".join(message).encode("utf-8"), 'plain', 'utf-8')

            # set the message headers
            mimemsg["From"] = email
            mimemsg["To"] = config["comment_smtp_to"]
            mimemsg["Date"] = formatdate(float(comment["pubDate"]))
            mimemsg["Subject"] = ("comment on %s" % curl)

            # send the message via smtp
            server.sendmail(from_addr=email,
                            to_addrs=config['comment_smtp_to'], 
                            msg=mimemsg.as_string())
            server.quit()

    except Exception, e:
        tools.get_logger().error("error sending email: %s" %
                                traceback.format_exception(*sys.exc_info()))
Ejemplo n.º 16
0
def write_comment(request, config, data, comment, encoding):
    """
    Write a comment
    
    @param config: dict containing pyblosxom config info
    @type  config: dict
    
    @param data: dict containing entry info
    @type  data: dict
    
    @param comment: dict containing comment info
    @type  comment: dict

    @return: The success or failure of creating the comment.
    @rtype: string
    """
    entry_list = data.get("entry_list", [])
    if not entry_list:
        return "No such entry exists."

    entry = data['entry_list'][0]
    cdir = os.path.join(config['comment_dir'], entry['absolute_path'])
    cdir = os.path.normpath(cdir)
    if not os.path.isdir(cdir):
        os.makedirs(cdir)

    cfn = os.path.join(cdir, entry['fn'] + "-" + comment['pubDate'] + "." + config['comment_draft_ext'])

    def make_xml_field(name, field):
        return "<" + name + ">" + cgi.escape(field.get(name, "")) + "</"+name+">\n";

    filedata = '<?xml version="1.0" encoding="%s"?>\n' % encoding
    filedata += "<item>\n"
    for key in comment:
        filedata += make_xml_field(key, comment)
    filedata += "</item>\n"

    try :
        cfile = codecs.open(cfn, "w", encoding)
    except IOError:
        logger = tools.get_logger()
        logger.error("couldn't open comment file '%s' for writing" % cfn)
        return "Internal error: Your comment could not be saved."
 
    cfile.write(filedata)
    cfile.close()
 
    # write latest pickle
    latest = None
    latest_filename = os.path.join(config['comment_dir'], LATEST_PICKLE_FILE)
    try:
        latest = open(latest_filename, "w")
    except IOError:
        logger = tools.get_logger()
        logger.error("couldn't open latest comment pickle for writing")
        return "Couldn't open latest comment pickle for writing."
    else:
        mod_time = float(comment['pubDate'])

    try:
        cPickle.dump(mod_time, latest)
        latest.close()
    except IOError:
        if latest:
            latest.close()

        logger = tools.get_logger()
        logger.error("comment may not have been saved to pickle file.")
        return "Internal error: Your comment may not have been saved."

    if ((('comment_mta_cmd' in config
          or 'comment_smtp_server' in config)
         and 'comment_smtp_to' in config)):
        # FIXME - removed grabbing send_email's return error message
        # so there's no way to know if email is getting sent or not.
        send_email(config, entry, comment, cdir, cfn)

    # figure out if the comment was submitted as a draft
    if config["comment_ext"] != config["comment_draft_ext"]:
       return "Comment was submitted for approval.  Thanks!"

    return "Comment submitted.  Thanks!"
Ejemplo n.º 17
0
def read_file(filename, config):
    """
    Read comment(s) from filename
    
    @param filename: filename containing comment(s)
    @type filename: string

    @param config: the pyblosxom configuration settings
    @type config: dictionary
    
    @returns: a list of comment dicts
    """
    from xml.sax import make_parser, SAXException
    from xml.sax.handler import feature_namespaces, ContentHandler

    class cmt_handler(ContentHandler):
        def __init__(self, cmts):
            self.cmts = cmts
        def startElement(self, name, atts):
            if name == 'item':
                self.cur_cmt = {}
            self._data = ""
        def endElement(self, name):
            self.cur_cmt['cmt_' + name] = self._data
            if name == 'item':
                self.cmts.append(self.cur_cmt)
        def characters(self, content):
            self._data += content

    cmts = []
    
    try:
        parser = make_parser()
        parser.setFeature(feature_namespaces, 0)
        handler = cmt_handler(cmts)
        parser.setContentHandler(handler)
        parser.parse(filename)
        
    # FIXME - bare except here--bad!
    except:
        logger = tools.get_logger()
        logger.error("bad comment file: %s\nerror was: %s" %
                     (filename, traceback.format_exception(*sys.exc_info())))
        return []

    for cmt in cmts:
        # time.time()
        cmt['cmt_time'] = float(cmt['cmt_pubDate'])
        # pretty time
        cmt['cmt_pubDate'] = time.ctime(float(cmt['cmt_pubDate']))
        cmt['cmt_w3cdate'] = time.strftime('%Y-%m-%dT%H:%M:%SZ',
                                           time.gmtime(cmt['cmt_time']))
        cmt['cmt_date'] = time.strftime('%a %d %b %Y',
                                        time.gmtime(cmt['cmt_time']))
        if cmt['cmt_link']:
            link = add_dont_follow('<a href="%s">%s</a>' %
                                   (cmt['cmt_link'], cmt['cmt_author']),
                                   config)
            cmt['cmt_optionally_linked_author'] = link
        else:
            cmt['cmt_optionally_linked_author'] = cmt['cmt_author']

    return cmts
Ejemplo n.º 18
0
def send_email(config, entry, comment, comment_dir, comment_filename):
    """Send an email to the blog owner on a new comment

    @param config: configuration as parsed by Pyblosxom
    @type config: dictionary

    @param entry: a file entry
    @type config: dictionary

    @param comment: comment as generated by read_comments
    @type comment: dictionary

    @param comment_dir: the comment directory
    @type comment_dir: string

    @param comment_filename: file name of current comment
    @type comment_filename: string
    """
    import smtplib
    # import the formatdate function which is in a different
    # place in Python 2.3 and up.
    try:
        from email.Utils import formatdate
    except ImportError:
        from rfc822 import formatdate
    from socket import gethostbyaddr

    author = escape_smtp_commands(clean_author(comment['author']))
    description = escape_smtp_commands(comment['description'])
    ipaddress = escape_smtp_commands(comment.get('ipaddress', '?'))

    if 'comment_smtp_from' in config:
        email = config['comment_smtp_from']
    else:
        email = escape_smtp_commands(clean_author(comment['email']))

    try:
        curl = "%s/%s" % (config['base_url'],
                          tools.urlencode_text(entry['file_path']))
        comment_dir = os.path.join(config['comment_dir'],
                                   entry['absolute_path'])

        # create the message
        message = []
        message.append("Name: %s" % author)
        if 'email' in comment:
            message.append("Email: %s" % comment['email'])
        if 'link' in comment:
            message.append("URL: %s" % comment['link'])
        try:
            host_name = gethostbyaddr(ipaddress)[0]
            message.append("Hostname: %s (%s)" % (host_name, ipaddress))
        # FIXME - bare except here--bad!
        except:
            message.append("IP: %s" % ipaddress)
        message.append("Entry URL: %s" % curl)
        message.append("Comment location: %s" % comment_filename)
        message.append("\n\n%s" % description)

        if 'comment_mta_cmd' in config:
            # set the message headers
            message.insert(0, "")
            message.insert(0, "Subject: comment on %s" % curl)
            message.insert(0,
                           "Date: %s" % formatdate(float(comment['pubDate'])))
            message.insert(0, "To: %s" % config["comment_smtp_to"])
            message.insert(0, "From: %s" % email)

            body = '\n'.join(message).encode('utf-8')

            argv = [
                config['comment_mta_cmd'], '-s',
                '"comment on %s"' % curl, config['comment_smtp_to']
            ]

            process = subprocess.Popen(argv,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            process.stdin.write(body)
            process.stdin.close()
            process.wait()
            stdout = process.stdout.read()
            stderr = process.stderr.read()
            tools.get_logger().debug('Ran MTA command: ' + ' '.join(argv))
            tools.get_logger().debug('Received stdout: ' + stdout)
            tools.get_logger().debug('Received stderr: ' + stderr)
            # the except clause below will catch this
            assert stderr == '', stderr

        else:
            assert 'comment_smtp_server' in config
            server = smtplib.SMTP(config['comment_smtp_server'])
            mimemsg = MIMEText("\n".join(message).encode("utf-8"), 'plain',
                               'utf-8')

            # set the message headers
            mimemsg["From"] = email
            mimemsg["To"] = config["comment_smtp_to"]
            mimemsg["Date"] = formatdate(float(comment["pubDate"]))
            mimemsg["Subject"] = ("comment on %s" % curl)

            # send the message via smtp
            server.sendmail(from_addr=email,
                            to_addrs=config['comment_smtp_to'],
                            msg=mimemsg.as_string())
            server.quit()

    except Exception, e:
        tools.get_logger().error("error sending email: %s" %
                                 traceback.format_exception(*sys.exc_info()))
Ejemplo n.º 19
0
def cb_handle(args):
    request = args["request"]
    pyhttp = request.get_http()
    config = request.get_configuration()

    urltrigger = config.get("trackback_urltrigger", "/trackback")

    logger = tools.get_logger()

    path_info = pyhttp["PATH_INFO"]
    if path_info.startswith(urltrigger):
        response = request.get_response()
        response.add_header("Content-type", "text/xml")

        form = request.get_form()

        message = (
            "A trackback must have at least a URL field (see " "http://www.sixapart.com/pronet/docs/trackback_spec)"
        )

        if "url" in form:
            from comments import decode_form

            encoding = config.get("blog_encoding", "iso-8859-1")
            decode_form(form, encoding)
            import time

            cdict = {
                "title": form.getvalue("title", ""),
                "author": form.getvalue("blog_name", ""),
                "pubDate": str(time.time()),
                "link": form["url"].value,
                "source": form.getvalue("blog_name", ""),
                "description": form.getvalue("excerpt", ""),
                "ipaddress": pyhttp.get("REMOTE_ADDR", ""),
                "type": "trackback",
            }
            argdict = {"request": request, "comment": cdict}
            reject = tools.run_callback("trackback_reject", argdict, donefunc=lambda x: x != 0)
            if isinstance(reject, (tuple, list)) and len(reject) == 2:
                reject_code, reject_message = reject
            else:
                reject_code, reject_message = reject, "Trackback rejected."

            if reject_code == 1:
                print >> response, tb_bad_response % reject_message
                return 1

            from Pyblosxom.entries.fileentry import FileEntry

            datadir = config["datadir"]

            from comments import writeComment

            try:
                import os

                pi = path_info.replace(urltrigger, "")
                path = os.path.join(datadir, pi[1:])
                data = request.get_data()
                ext = tools.what_ext(data["extensions"].keys(), path)
                entry = FileEntry(request, "%s.%s" % (path, ext), datadir)
                data = {}
                data["entry_list"] = [entry]
                # Format Author
                cdict["author"] = "Trackback from %s" % form.getvalue("blog_name", "")
                writeComment(request, config, data, cdict, encoding)
                print >> response, tb_good_response
            except OSError:
                message = "URI " + path_info + " doesn't exist"
                logger.error(message)
                print >> response, tb_bad_response % message

        else:
            logger.error(message)
            print >> response, tb_bad_response % message

        # no further handling is needed
        return 1
    return 0
Ejemplo n.º 20
0
def read_file(filename, config):
    """
    Read comment(s) from filename

    @param filename: filename containing comment(s)
    @type filename: string

    @param config: the pyblosxom configuration settings
    @type config: dictionary

    @returns: a list of comment dicts
    """
    from xml.sax import make_parser, SAXException
    from xml.sax.handler import feature_namespaces, ContentHandler

    class cmt_handler(ContentHandler):
        def __init__(self, cmts):
            self.cmts = cmts

        def startElement(self, name, atts):
            if name == 'item':
                self.cur_cmt = {}
            self._data = ""

        def endElement(self, name):
            self.cur_cmt['cmt_' + name] = self._data
            if name == 'item':
                self.cmts.append(self.cur_cmt)

        def characters(self, content):
            self._data += content

    cmts = []

    try:
        parser = make_parser()
        parser.setFeature(feature_namespaces, 0)
        handler = cmt_handler(cmts)
        parser.setContentHandler(handler)
        parser.parse(filename)

    # FIXME - bare except here--bad!
    except:
        logger = tools.get_logger()
        logger.error("bad comment file: %s\nerror was: %s" %
                     (filename, traceback.format_exception(*sys.exc_info())))
        return []

    for cmt in cmts:
        # time.time()
        cmt['cmt_time'] = float(cmt['cmt_pubDate'])
        # pretty time
        cmt['cmt_pubDate'] = time.ctime(float(cmt['cmt_pubDate']))
        cmt['cmt_w3cdate'] = time.strftime('%Y-%m-%dT%H:%M:%SZ',
                                           time.gmtime(cmt['cmt_time']))
        cmt['cmt_date'] = time.strftime('%a %d %b %Y',
                                        time.gmtime(cmt['cmt_time']))
        if cmt['cmt_link']:
            link = add_dont_follow(
                '<a href="%s">%s</a>' % (cmt['cmt_link'], cmt['cmt_author']),
                config)
            cmt['cmt_optionally_linked_author'] = link
        else:
            cmt['cmt_optionally_linked_author'] = cmt['cmt_author']

    return cmts
Ejemplo n.º 21
0
def pingback(request, source, target):
    logger = tools.get_logger()
    logger.info("pingback started")
    source_file = urllib.urlopen(source.split('#')[0])
    if source_file.headers.get('error', '') == '404':
        raise Fault(0x0010, "Target %s not exists" % target)
    source_page = parser()
    source_page.feed(source_file.read())
    source_file.close()

    if source_page.title == "":
        source_page.title = source

    if not target in source_page.hrefs:
        raise Fault(0x0011, "%s does not point to %s" % (source, target))

    target_entry = fileFor(request, target)

    body = ''
    try:
        from rssfinder import getFeeds
        from rssparser import parse

        baseurl = source.split("#")[0]
        for feed in getFeeds(baseurl):
            for item in parse(feed)['items']:
                if item['link'] == source:
                    if 'title' in item:
                        source_page.title = item['title']
                    if 'content_encoded' in item:
                        body = item['content_encoded'].strip()
                    if 'description' in item:
                        body = item['description'].strip() or body
                    body = re.compile('<.*?>', re.S).sub('', body)
                    body = re.sub('\s+', ' ', body)
                    body = body[:body.rfind(' ', 0, 250)][:250] + " ...<br />"
    except:
        pass

    cmt = {'title': source_page.title,
           'author': 'Pingback from %s' % source_page.title,
           'pubDate': str(time.time()),
           'link': source,
           'source': '',
           'description': body}

    # run anti-spam plugins
    argdict = {"request": request, "comment": cmt}
    reject = tools.run_callback("trackback_reject",
                                argdict,
                                donefunc=lambda x: x != 0)
    if isinstance(reject, (tuple, list)) and len(reject) == 2:
        reject_code, reject_message = reject
    else:
        reject_code, reject_message = reject, "Pingback rejected."
    if reject_code == 1:
        raise Fault(0x0031, reject_message)

    from comments import writeComment
    config = request.get_configuration()
    data = request.get_data()
    data['entry_list'] = [target_entry]

    # TODO: Check if comment from the URL exists
    writeComment(request, config, data, cmt, config['blog_encoding'])

    return "success pinging %s from %s\n" % (target, source)
Ejemplo n.º 22
0
def cb_handle(args):
    request = args['request']
    pyhttp = request.get_http()
    config = request.get_configuration()

    urltrigger = config.get('trackback_urltrigger', '/trackback')

    logger = tools.get_logger()

    path_info = pyhttp['PATH_INFO']
    if path_info.startswith(urltrigger):
        response = request.get_response()
        response.add_header("Content-type", "text/xml")

        form = request.get_form()

        message = ("A trackback must have at least a URL field (see "
                   "http://www.sixapart.com/pronet/docs/trackback_spec)")

        if "url" in form:
            from comments import decode_form
            encoding = config.get('blog_encoding', 'iso-8859-1')
            decode_form(form, encoding)
            import time
            cdict = {'title': form.getvalue('title', ''),
                     'author': form.getvalue('blog_name', ''),
                     'pubDate': str(time.time()),
                     'link': form['url'].value,
                     'source': form.getvalue('blog_name', ''),
                     'description': form.getvalue('excerpt', ''),
                     'ipaddress': pyhttp.get('REMOTE_ADDR', ''),
                     'type': 'trackback'
                     }
            argdict = {"request": request, "comment": cdict}
            reject = tools.run_callback("trackback_reject",
                                        argdict,
                                        donefunc=lambda x: x != 0)
            if isinstance(reject, (tuple, list)) and len(reject) == 2:
                reject_code, reject_message = reject
            else:
                reject_code, reject_message = reject, "Trackback rejected."

            if reject_code == 1:
                print >> response, tb_bad_response % reject_message
                return 1

            from Pyblosxom.entries.fileentry import FileEntry

            datadir = config['datadir']

            from comments import writeComment
            try:
                import os
                pi = path_info.replace(urltrigger, '')
                path = os.path.join(datadir, pi[1:])
                data = request.get_data()
                ext = tools.what_ext(data['extensions'].keys(), path)
                entry = FileEntry(request, '%s.%s' % (path, ext), datadir)
                data = {}
                data['entry_list'] = [entry]
                # Format Author
                cdict['author'] = (
                    'Trackback from %s' % form.getvalue('blog_name', ''))
                writeComment(request, config, data, cdict, encoding)
                print >> response, tb_good_response
            except OSError:
                message = 'URI ' + path_info + " doesn't exist"
                logger.error(message)
                print >> response, tb_bad_response % message

        else:
            logger.error(message)
            print >> response, tb_bad_response % message

        # no further handling is needed
        return 1
    return 0