Пример #1
0
def verify_installation(request):
    config = request.get_configuration()

    if not config.has_key('disqus_shortname'):
        pwrap_error("missing required config property 'disqus_shortname' which"
                    "is necessary to determine which disqus site to link to.")
        return False

    return True
Пример #2
0
def verify_installation(request):
    config = request.get_configuration()

    if not config.has_key('disqus_shortname'):
        pwrap_error(
            "missing required config property 'disqus_shortname' which"
            "is necessary to determine which disqus site to link to.")
        return False

    return True
Пример #3
0
def verify_installation(request):
    config = request.get_configuration()
    if config.get("num_entries", 0) == 0:
        pwrap_error(
            "Missing config property 'num_entries'.  paginate won't do "
            "anything without num_entries set.  Either set num_entries "
            "to a positive integer, or disable the paginate plugin."
            "See the documentation at the top of the paginate plugin "
            "code file for more details.")
        return False
    return True
Пример #4
0
def verify_installation(request):
    config = request.get_configuration()
    if config.get("num_entries", 0) == 0:
        pwrap_error(
            "Missing config property 'num_entries'.  paginate won't do "
            "anything without num_entries set.  Either set num_entries "
            "to a positive integer, or disable the paginate plugin."
            "See the documentation at the top of the paginate plugin "
            "code file for more details.")
        return False
    return True
Пример #5
0
def verify_installation(request):
    config = request.get_configuration()
    filename = get_acronym_file(config)
    if not os.path.exists(filename):
        pwrap_error("There is no acronym file at %s." % filename)
        pwrap_error(
            "You should create one.  Refer to documentation for examples.")
        return False

    try:
        fp = open(filename, "r")
    except IOError:
        pwrap_error(
            "Your acronyms file %s cannot be opened for reading.  Please "
            "adjust the permissions." % filename)
        return False

    malformed = False

    # FIXME - this is a repeat of build_acronyms
    for line in fp.readlines():
        line = line.strip()
        firstpart = line.split("=", 1)[0]
        firstpart = "(\\b" + firstpart.strip() + "\\b)"
        try:
            re.compile(firstpart)
        except re.error, s:
            pwrap_error("- '%s' is not a properly formed regexp.  (%s)" %
                        (line, s))
            malformed = True
Пример #6
0
def verify_installation(request):
    config = request.get_configuration()
    filename = get_acronym_file(config)
    if not os.path.exists(filename):
        pwrap_error("There is no acronym file at %s." % filename)
        pwrap_error(
            "You should create one.  Refer to documentation for examples.")
        return False

    try:
        fp = open(filename, "r")
    except IOError:
        pwrap_error(
            "Your acronyms file %s cannot be opened for reading.  Please "
            "adjust the permissions." % filename)
        return False

    malformed = False

    # FIXME - this is a repeat of build_acronyms
    for line in fp.readlines():
        line = line.strip()
        firstpart = line.split("=", 1)[0]
        firstpart = "(\\b" + firstpart.strip() + "\\b)"
        try:
            re.compile(firstpart)
        except re.error, s:
            pwrap_error("- '%s' is not a properly formed regexp.  (%s)" %
                        (line, s))
            malformed = True
Пример #7
0
def verify_installation(req):
    config = req.get_configuration()

    retval = True

    if not 'pagesdir' in config:
        pwrap_error("'pagesdir' property is not set in the config file.")
        retval = False
    elif not os.path.isdir(config["pagesdir"]):
        pwrap_error("'pagesdir' directory does not exist. %s" %
                    config["pagesdir"])
        retval = False

    return retval
Пример #8
0
def verify_installation(req):
    config = req.get_configuration()

    retval = True

    if not 'pagesdir' in config:
        pwrap_error("'pagesdir' property is not set in the config file.")
        retval = False
    elif not os.path.isdir(config["pagesdir"]):
        pwrap_error(
            "'pagesdir' directory does not exist. %s" % config["pagesdir"])
        retval = False

    return retval
Пример #9
0
def build_pyblosxom():
    """Imports config.py and builds an empty Pyblosxom object.
    """
    pwrap("Trying to import the config module....")
    try:
        from config import py as cfg
    except StandardError:
        h, t = os.path.split(sys.argv[0])
        scriptname = t or h

        pwrap_error("ERROR: Cannot find your config.py file.  Please execute "
                    "%s in the directory with the config.py file in it or use "
                    "the --config flag.\n\n"
                    "See \"%s --help\" for more details." % (scriptname,
                                                             scriptname))
        return None

    return Pyblosxom(cfg, {})
Пример #10
0
def verify_installation(request):
    config = request.get_configuration()
    if not "comment_rejected_words" in config:
        pwrap_error(
            "The \"comment_rejected_words\" property must be set in your "
            "config.py file.  It takes a list of strings as a value.  "
            "Refer to the documentation for more details.")
        return False

    crw = config["comment_rejected_words"]
    if not isinstance(crw, (list, tuple)):
        pwrap_error(
            "The \"comment_rejected_words\" property is incorrectly set in "
            "your config.py file.  It takes a list of strings as a value.  "
            "Refer to the documentation at the top of the comment_blacklist "
            "plugin for more details.")
        return False
    return True
Пример #11
0
def build_pyblosxom():
    """Imports config.py and builds an empty Pyblosxom object.
    """
    pwrap("Trying to import the config module....")
    try:
        from config import py as cfg
    except StandardError:
        h, t = os.path.split(sys.argv[0])
        scriptname = t or h

        pwrap_error("ERROR: Cannot find your config.py file.  Please execute "
                    "%s in the directory with the config.py file in it or use "
                    "the --config flag.\n\n"
                    "See \"%s --help\" for more details." %
                    (scriptname, scriptname))
        return None

    return Pyblosxom(cfg, {})
Пример #12
0
def verify_installation(request):
    config = request.get_configuration()

    retval = True

    if 'comment_dir' in config and not os.path.isdir(config['comment_dir']):
        pwrap_error(
            'The "comment_dir" property in the config file must refer '
            'to a directory')
        retval = False

    smtp_keys_defined = []
    smtp_keys=[
        'comment_smtp_server',
        'comment_smtp_from',
        'comment_smtp_to']
    for k in smtp_keys:
        if k in config:
            smtp_keys_defined.append(k)

    if smtp_keys_defined:
        for i in smtp_keys:
            if i not in smtp_keys_defined:
                pwrap_error("Missing comment SMTP property: '%s'" % i)
                retval = False

    optional_keys = [
        'comment_dir',
        'comment_ext',
        'comment_draft_ext',
        'comment_nofollow',
        'comment_disable_after_x_days']
    for i in optional_keys:
        if not i in config:
            pwrap("missing optional property: '%s'" % i)

    if 'comment_disable_after_x_days' in config:
        if ((not isinstance(config['comment_disable_after_x_days'], int) or
             config['comment_disable_after_x_days'] <= 0)):
            pwrap("comment_disable_after_x_days has a non-positive "
                  "integer value.")

    return retval
Пример #13
0
def verify_installation(request):
    config = request.get_configuration()

    retval = True

    if 'comment_dir' in config and not os.path.isdir(config['comment_dir']):
        pwrap_error('The "comment_dir" property in the config file must refer '
                    'to a directory')
        retval = False

    smtp_keys_defined = []
    smtp_keys = ['comment_smtp_server', 'comment_smtp_from', 'comment_smtp_to']
    for k in smtp_keys:
        if k in config:
            smtp_keys_defined.append(k)

    if smtp_keys_defined:
        for i in smtp_keys:
            if i not in smtp_keys_defined:
                pwrap_error("Missing comment SMTP property: '%s'" % i)
                retval = False

    optional_keys = [
        'comment_dir', 'comment_ext', 'comment_draft_ext', 'comment_nofollow',
        'comment_disable_after_x_days'
    ]
    for i in optional_keys:
        if not i in config:
            pwrap("missing optional property: '%s'" % i)

    if 'comment_disable_after_x_days' in config:
        if ((not isinstance(config['comment_disable_after_x_days'], int)
             or config['comment_disable_after_x_days'] <= 0)):
            pwrap("comment_disable_after_x_days has a non-positive "
                  "integer value.")

    return retval
Пример #14
0
def verify_installation(request):
    config = request.get_configuration()

    status = True
    if not 'mw_question' in config:
        pwrap_error("Missing required property: mw_question")
        status = False

    if not 'mw_answer' in config:
        pwrap_error("Missing required property: mw_answer")
        return False

    a = config["mw_answer"]
    if a != a.strip().lower():
        pwrap_error("mw_answer must be lowercase, without leading "
                    "or trailing whitespace")
        return False

    return status
Пример #15
0
def verify_installation(request):
    config = request.get_configuration()

    status = True
    if not 'mw_question' in config:
        pwrap_error("Missing required property: mw_question")
        status = False

    if not 'mw_answer' in config:
        pwrap_error("Missing required property: mw_answer")
        return False

    a = config["mw_answer"]
    if a != a.strip().lower():
        pwrap_error("mw_answer must be lowercase, without leading "
                    "or trailing whitespace")
        return False

    return status
Пример #16
0
def verify_installation(request):
    try:
        from akismet import Akismet
    except ImportError:
        pwrap_error(
            "Missing module 'akismet'.  See documentation for getting it.")
        return False

    config = request.get_configuration()

    # try to check to se make sure that the config file has a key
    if not "akismet_api_key" in config:
        pwrap_error("Missing required configuration value 'akismet_key'")
        return False

    a = Akismet(config['akismet_api_key'], config['base_url'],
                agent='Pyblosxom/1.3')
    if not a.verify_key():
        pwrap_error("Could not verify akismet API key.")
        return False

    return True
Пример #17
0
def verify_installation(request):
    try:
        from akismet import Akismet
    except ImportError:
        pwrap_error(
            "Missing module 'akismet'.  See documentation for getting it.")
        return False

    config = request.get_configuration()

    # try to check to se make sure that the config file has a key
    if not "akismet_api_key" in config:
        pwrap_error("Missing required configuration value 'akismet_key'")
        return False

    a = Akismet(config['akismet_api_key'],
                config['base_url'],
                agent='Pyblosxom/1.3')
    if not a.verify_key():
        pwrap_error("Could not verify akismet API key.")
        return False

    return True
Пример #18
0
def command_line_handler(scriptname, argv):
    if "--silent" in argv:
        sys.stdout = open(os.devnull, "w")
        argv.remove("--silent")

    print "%s version %s" % (scriptname, __version__)

    # slurp off the config file setting and add it to sys.path.
    # this needs to be first to pick up plugin-based command handlers.
    configdir = None
    for i, mem in enumerate(argv):
        if mem.startswith("--config"):
            if "=" in mem:
                _, configdir = mem.split("=")
                break
            else:
                try:
                    configdir = argv[i + 1]
                    break
                except IndexError:
                    pwrap_error("Error: no config file argument specified.")
                    pwrap_error("Exiting.")
                    return 1

    if configdir is not None:
        if configdir.endswith("config.py"):
            configdir = configdir[0:-9]

        if not os.path.exists(configdir):
            pwrap_error("ERROR: '%s' does not exist--cannot find config.py "
                        "file." % configdir)
            pwrap_error("Exiting.")
            return 1

        if not "config.py" in os.listdir(configdir):
            pwrap_error("Error: config.py not in '%s'.  "
                        "Cannot find config.py file." % configdir)
            pwrap_error("Exiting.")
            return 1

        sys.path.insert(0, configdir)
        print "Inserting %s to beginning of sys.path...." % configdir

    handlers = get_handlers()

    if len(argv) == 1 or (len(argv) == 2 and argv[1] in ("-h", "--help")):
        parser = build_parser("[command]")
        parser.print_help()
        print ""
        print "Commands:"
        for command_str, _, command_help in handlers:
            print "    %-14s %s" % (command_str, command_help)
        return 0

    if argv[1] == "--version":
        return 0

    # then we execute the named command with options, or print help
    if argv[1].startswith("-"):
        pwrap_error("Command '%s' does not exist." % argv[1])
        pwrap_error('')
        pwrap_error("Commands:")
        for command_str, _, command_help in handlers:
            pwrap_error("    %-14s %s" % (command_str, command_help))
        return 1

    command = argv.pop(1)
    for (c, f, h) in handlers:
        if c == command:
            return f(command, argv)

    pwrap_error("Command '%s' does not exist." % command)
    for command_str, command_func, command_help in handlers:
        pwrap_error("    %-14s %s" % (command_str, command_help))
    return 1
Пример #19
0
def test_installation(command, argv):
    """
    This function gets called when someone starts up pyblosxom.cgi
    from the command line with no REQUEST_METHOD environment variable.
    It:

    1. verifies config.py file properties
    2. initializes all the plugins they have installed
    3. runs ``cb_verify_installation``--plugins can print out whether
       they are installed correctly (i.e. have valid config property
       settings and can read/write to data files)

    The goal is to be as useful and informative to the user as we can
    be without being overly verbose and confusing.

    This is designed to make it easier for a user to verify their
    Pyblosxom installation is working and also to install new plugins
    and verify that their configuration is correct.
    """
    parser = build_parser("%prog test [options]")
    parser.parse_args()

    p = build_pyblosxom()
    if not p:
        return 0

    request = p.get_request()
    config = request.config

    pwrap("System Information")
    pwrap("==================")
    pwrap("")

    pwrap("- pyblosxom:    %s" % __version__)
    pwrap("- sys.version:  %s" % sys.version.replace("\n", " "))
    pwrap("- os.name:      %s" % os.name)
    codebase = os.path.dirname(os.path.dirname(__file__))
    pwrap("- codebase:     %s" % config.get("codebase", codebase))
    pwrap("")

    pwrap("Checking config.py file")
    pwrap("=======================")
    pwrap("- properties set: %s" % len(config))

    config_keys = config.keys()

    if "datadir" not in config_keys:
        pwrap_error("- ERROR: 'datadir' must be set.  Refer to installation "
                    "documentation.")

    elif not os.path.isdir(config["datadir"]):
        pwrap_error("- ERROR: datadir '%s' does not exist."
                    "  You need to create your datadir and give it "
                    " appropriate permissions." % config["datadir"])
    else:
        pwrap("- datadir '%s' exists." % config["datadir"])

    if "flavourdir" not in config_keys:
        pwrap("- WARNING: You should consider setting flavourdir and putting "
              "your flavour templates there.  See the documentation for "
              "more details.")
    elif not os.path.isdir(config["flavourdir"]):
        pwrap_error("- ERROR: flavourdir '%s' does not exist."
                    "  You need to create your flavourdir and give it "
                    " appropriate permissions." % config["flavourdir"])
    else:
        pwrap("- flavourdir '%s' exists." % config["flavourdir"])

    if (("blog_encoding" in config_keys
         and config["blog_encoding"].lower() != "utf-8")):
        pwrap_error("- WARNING: 'blog_encoding' is set to something other "
                    "than 'utf-8'.  As of Pyblosxom 1.5, "
                    "this isn't a good idea unless you're absolutely certain "
                    "it's going to work for your blog.")
    pwrap("")

    pwrap("Checking plugin configuration")
    pwrap("=============================")

    import traceback

    no_verification_support = []

    if len(plugin_utils.plugins) + len(plugin_utils.bad_plugins) == 0:
        pwrap(" - There are no plugins installed.")

    else:
        if len(plugin_utils.bad_plugins) > 0:
            pwrap("- Some plugins failed to load.")
            pwrap("")
            pwrap("----")
            for mem in plugin_utils.bad_plugins:
                pwrap("plugin:  %s" % mem[0])
                print "%s" % mem[1]
                pwrap("----")

        if len(plugin_utils.plugins) > 0:
            pwrap("- This goes through your plugins and asks each of them "
                  "to verify configuration and installation.")
            pwrap("")
            pwrap("----")
            for mem in plugin_utils.plugins:
                if hasattr(mem, "verify_installation"):
                    pwrap("plugin:  %s" % mem.__name__)
                    print "file:    %s" % mem.__file__
                    print "version: %s" % (str(getattr(mem, "__version__")))

                    try:
                        if mem.verify_installation(request) == 1:
                            pwrap("PASS")
                        else:
                            pwrap_error("FAIL")
                    except StandardError:
                        pwrap_error("FAIL: Exception thrown:")
                        traceback.print_exc(file=sys.stdout)

                    pwrap("----")
                else:
                    mn = mem.__name__
                    mf = mem.__file__
                    no_verification_support.append("'%s' (%s)" % (mn, mf))

            if len(no_verification_support) > 0:
                pwrap("")
                pwrap("The following plugins do not support installation "
                      "verification:")
                no_verification_support.sort()
                for mem in no_verification_support:
                    print "- %s" % mem

    pwrap("")
    pwrap("Verification complete.  Correct any errors and warnings above.")
Пример #20
0
def generate_entries(command, argv):
    """
    This function is primarily for testing purposes.  It creates
    a bunch of blog entries with random text in them.
    """
    parser = build_parser("%prog entries [options] <num_entries>")
    (options, args) = parser.parse_args()

    if args:
        try:
            num_entries = int(args[0])
            assert num_entries > 0
        except ValueError:
            pwrap_error("ERROR: num_entries must be a positive integer.")
            return 0
    else:
        num_entries = 5

    verbose = options.verbose

    p = build_pyblosxom()
    if not p:
        return 0

    datadir = p.get_request().config["datadir"]

    sm_para = "<p>Lorem ipsum dolor sit amet.</p>"
    med_para = """<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
  in mi lacus, sed interdum nisi. Vestibulum commodo urna et libero
  vestibulum gravida. Vivamus hendrerit justo quis lorem auctor
  consectetur. Aenean ornare, tortor in sollicitudin imperdiet, neque
  diam pellentesque risus, vitae.
</p>"""
    lg_para = """<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
  dictum tortor orci. Lorem ipsum dolor sit amet, consectetur
  adipiscing elit. Etiam quis lectus vel odio convallis tincidunt sed
  et magna. Suspendisse at dolor suscipit eros ullamcorper iaculis. In
  aliquet ornare libero eget rhoncus. Sed ac ipsum eget eros fringilla
  aliquet ut eget velit. Curabitur dui nibh, eleifend non suscipit at,
  laoreet ac purus. Morbi id sem diam. Cras sit amet ante lacus, nec
  euismod urna. Curabitur iaculis, lorem at fringilla malesuada, nunc
  ligula eleifend nisi, at bibendum libero est quis
  tellus. Pellentesque habitant morbi tristique senectus et netus et
  malesuada.
</p>"""
    paras = [sm_para, med_para, lg_para]

    if verbose:
        print "Creating %d entries" % num_entries

    now = time.time()

    for i in range(num_entries):
        title = "post number %d\n" % (i + 1)
        body = []
        for _ in range(random.randrange(1, 6)):
            body.append(random.choice(paras))

        fn = os.path.join(datadir, "post%d.txt" % (i + 1))
        f = open(fn, "w")
        f.write(title)
        f.write("\n".join(body))
        f.close()

        mtime = now - ((num_entries - i) * 3600)
        os.utime(fn, (mtime, mtime))
        
        if verbose:
            print "Creating '%s'..." % fn

    if verbose:
        print "Done!"
    return 0
Пример #21
0
def command_line_handler(scriptname, argv):
    if "--silent" in argv:
        sys.stdout = open(os.devnull, "w")
        argv.remove("--silent")

    print "%s version %s" % (scriptname, __version__)

    # slurp off the config file setting and add it to sys.path.
    # this needs to be first to pick up plugin-based command handlers.
    configdir = None
    for i, mem in enumerate(argv):
        if mem.startswith("--config"):
            if "=" in mem:
                _, configdir = mem.split("=")
                break
            else:
                try:
                    configdir = argv[i+1]
                    break
                except IndexError:
                    pwrap_error("Error: no config file argument specified.")
                    pwrap_error("Exiting.")
                    return 1

    if configdir is not None:
        if configdir.endswith("config.py"):
            configdir = configdir[0:-9]

        if not os.path.exists(configdir):
            pwrap_error("ERROR: '%s' does not exist--cannot find config.py "
                        "file." % configdir)
            pwrap_error("Exiting.")
            return 1

        if not "config.py" in os.listdir(configdir):
            pwrap_error("Error: config.py not in '%s'.  "
                        "Cannot find config.py file." % configdir)
            pwrap_error("Exiting.")
            return 1

        sys.path.insert(0, configdir)
        print "Inserting %s to beginning of sys.path...." % configdir

    handlers = get_handlers()

    if len(argv) == 1 or (len(argv) == 2 and argv[1] in ("-h", "--help")):
        parser = build_parser("[command]")
        parser.print_help()
        print ""
        print "Commands:"
        for command_str, _, command_help in handlers:
            print "    %-14s %s" % (command_str, command_help)
        return 0

    if argv[1] == "--version":
        return 0

    # then we execute the named command with options, or print help
    if argv[1].startswith("-"):
        pwrap_error ( "Command '%s' does not exist." % argv[1])
        pwrap_error ('')
        pwrap_error ( "Commands:")
        for command_str, _, command_help in handlers:
            pwrap_error ( "    %-14s %s" % (command_str, command_help))
        return 1

    command = argv.pop(1)
    for (c, f, h) in handlers:
        if c == command:
            return f(command, argv)

    pwrap_error ( "Command '%s' does not exist." % command)
    for command_str, command_func, command_help in handlers:
        pwrap_error ( "    %-14s %s" % (command_str, command_help))
    return 1
Пример #22
0
def create_blog(command, argv):
    """
    Creates a blog in the specified directory.  Mostly this involves
    copying things over, but there are a few cases where we expand
    template variables.
    """
    parser = build_parser("%prog create [options] <dir>")
    (options, args) = parser.parse_args()

    if args:
        d = args[0]
    else:
        d = "."

    if d == ".":
        d = "." + os.sep + "blog"

    d = os.path.abspath(d)

    verbose = options.verbose

    if os.path.isfile(d) or os.path.isdir(d):
        pwrap_error("ERROR: Cannot create '%s'--something is in the way." % d)
        return 0

    def _mkdir(d):
        if verbose:
            print "Creating '%s'..." % d
        os.makedirs(d)

    _mkdir(d)
    _mkdir(os.path.join(d, "entries"))
    _mkdir(os.path.join(d, "plugins"))

    source = os.path.join(os.path.dirname(__file__), "flavours")

    for root, dirs, files in os.walk(source):
        if ".svn" in root:
            continue

        dest = os.path.join(d, "flavours", root[len(source) + 1:])
        if not os.path.isdir(dest):
            if verbose:
                print "Creating '%s'..." % dest
            os.mkdir(dest)

        for mem in files:
            if verbose:
                print "Creating file '%s'..." % os.path.join(dest, mem)
            fpin = open(os.path.join(root, mem), "r")
            fpout = open(os.path.join(dest, mem), "w")

            fpout.write(fpin.read())

            fpout.close()
            fpin.close()

    def _copyfile(frompath, topath, fn, fix=False):
        if verbose:
            print "Creating file '%s'..." % os.path.join(topath, fn)
        fp = open(os.path.join(frompath, fn), "r")
        filedata = fp.readlines()
        fp.close()

        if fix:
            basedir = topath
            if not basedir.endswith(os.sep):
                basedir = basedir + os.sep
            if os.sep == "\\":
                basedir = basedir.replace(os.sep, os.sep + os.sep)
            datamap = {
                "basedir": basedir,
                "codedir": os.path.dirname(os.path.dirname(__file__))
            }
            filedata = [line % datamap for line in filedata]

        fp = open(os.path.join(topath, fn), "w")
        fp.write("".join(filedata))
        fp.close()

    source = os.path.join(os.path.dirname(__file__), "data")

    _copyfile(source, d, "config.py", fix=True)
    _copyfile(source, d, "blog.ini", fix=True)
    _copyfile(source, d, "pyblosxom.cgi", fix=True)

    datadir = os.path.join(d, "entries")
    firstpost = os.path.join(datadir, "firstpost.txt")
    if verbose:
        print "Creating file '%s'..." % firstpost
    fp = open(firstpost, "w")
    fp.write("""First post!
<p>
  This is your first post!  If you can see this with a web-browser,
  then it's likely that everything's working nicely!
</p>
""")
    fp.close()

    if verbose:
        print "Done!"
    return 0
Пример #23
0
def create_blog(command, argv):
    """
    Creates a blog in the specified directory.  Mostly this involves
    copying things over, but there are a few cases where we expand
    template variables.
    """
    parser = build_parser("%prog create [options] <dir>")
    (options, args) = parser.parse_args()

    if args:
        d = args[0]
    else:
        d = "."

    if d == ".":
        d = "." + os.sep + "blog"

    d = os.path.abspath(d)

    verbose = options.verbose

    if os.path.isfile(d) or os.path.isdir(d):
        pwrap_error("ERROR: Cannot create '%s'--something is in the way." % d)
        return 0

    def _mkdir(d):
        if verbose:
            print "Creating '%s'..." % d
        os.makedirs(d)

    _mkdir(d)
    _mkdir(os.path.join(d, "entries"))
    _mkdir(os.path.join(d, "plugins"))

    source = os.path.join(os.path.dirname(__file__), "flavours")

    for root, dirs, files in os.walk(source):
        if ".svn" in root:
            continue

        dest = os.path.join(d, "flavours", root[len(source)+1:])
        if not os.path.isdir(dest):
            if verbose:
                print "Creating '%s'..." % dest
            os.mkdir(dest)

        for mem in files:
            if verbose:
                print "Creating file '%s'..." % os.path.join(dest, mem)
            fpin = open(os.path.join(root, mem), "r")
            fpout = open(os.path.join(dest, mem), "w")

            fpout.write(fpin.read())

            fpout.close()
            fpin.close()

    def _copyfile(frompath, topath, fn, fix=False):
        if verbose:
            print "Creating file '%s'..." % os.path.join(topath, fn)
        fp = open(os.path.join(frompath, fn), "r")
        filedata = fp.readlines()
        fp.close()

        if fix:
            basedir = topath
            if not basedir.endswith(os.sep):
                basedir = basedir + os.sep
            if os.sep == "\\":
                basedir = basedir.replace(os.sep, os.sep + os.sep)
            datamap = { "basedir": basedir,
                        "codedir": os.path.dirname(os.path.dirname(__file__)) }
            filedata = [line % datamap for line in filedata]

        fp = open(os.path.join(topath, fn), "w")
        fp.write("".join(filedata))
        fp.close()

    source = os.path.join(os.path.dirname(__file__), "data")

    _copyfile(source, d, "config.py", fix=True)
    _copyfile(source, d, "blog.ini", fix=True)
    _copyfile(source, d, "pyblosxom.cgi", fix=True)

    datadir = os.path.join(d, "entries")
    firstpost = os.path.join(datadir, "firstpost.txt")
    if verbose:
        print "Creating file '%s'..." % firstpost
    fp = open(firstpost, "w")
    fp.write("""First post!
<p>
  This is your first post!  If you can see this with a web-browser,
  then it's likely that everything's working nicely!
</p>
""")
    fp.close()

    if verbose:
        print "Done!"
    return 0
Пример #24
0
def test_installation(command, argv):
    """
    This function gets called when someone starts up pyblosxom.cgi
    from the command line with no REQUEST_METHOD environment variable.
    It:

    1. verifies config.py file properties
    2. initializes all the plugins they have installed
    3. runs ``cb_verify_installation``--plugins can print out whether
       they are installed correctly (i.e. have valid config property
       settings and can read/write to data files)

    The goal is to be as useful and informative to the user as we can
    be without being overly verbose and confusing.

    This is designed to make it easier for a user to verify their
    Pyblosxom installation is working and also to install new plugins
    and verify that their configuration is correct.
    """
    parser = build_parser("%prog test [options]")
    parser.parse_args()

    p = build_pyblosxom()
    if not p:
        return 0

    request = p.get_request()
    config = request.config

    pwrap("System Information")
    pwrap("==================")
    pwrap("")

    pwrap("- pyblosxom:    %s" % __version__)
    pwrap("- sys.version:  %s" % sys.version.replace("\n", " "))
    pwrap("- os.name:      %s" % os.name)
    codebase = os.path.dirname(os.path.dirname(__file__))
    pwrap("- codebase:     %s" % config.get("codebase", codebase))
    pwrap("")

    pwrap("Checking config.py file")
    pwrap("=======================")
    pwrap("- properties set: %s" % len(config))

    config_keys = config.keys()

    if "datadir" not in config_keys:
        pwrap_error("- ERROR: 'datadir' must be set.  Refer to installation "
              "documentation.")

    elif not os.path.isdir(config["datadir"]):
        pwrap_error("- ERROR: datadir '%s' does not exist."
                    "  You need to create your datadir and give it "
                    " appropriate permissions." % config["datadir"])
    else:
        pwrap("- datadir '%s' exists." % config["datadir"])

    if "flavourdir" not in config_keys:
        pwrap("- WARNING: You should consider setting flavourdir and putting "
              "your flavour templates there.  See the documentation for "
              "more details.")
    elif not os.path.isdir(config["flavourdir"]):
        pwrap_error("- ERROR: flavourdir '%s' does not exist."
                    "  You need to create your flavourdir and give it "
                    " appropriate permissions." % config["flavourdir"])
    else:
        pwrap("- flavourdir '%s' exists." % config["flavourdir"])

    if (("blog_encoding" in config_keys
         and config["blog_encoding"].lower() != "utf-8")):
        pwrap_error("- WARNING: 'blog_encoding' is set to something other "
                    "than 'utf-8'.  As of Pyblosxom 1.5, "
                    "this isn't a good idea unless you're absolutely certain "
                    "it's going to work for your blog.")
    pwrap("")

    pwrap("Checking plugin configuration")
    pwrap("=============================")

    import traceback

    no_verification_support = []

    if len(plugin_utils.plugins) + len(plugin_utils.bad_plugins) == 0:
        pwrap(" - There are no plugins installed.")

    else:
        if len(plugin_utils.bad_plugins) > 0:
            pwrap("- Some plugins failed to load.")
            pwrap("")
            pwrap("----")
            for mem in plugin_utils.bad_plugins:
                pwrap("plugin:  %s" % mem[0])
                print "%s" % mem[1]
                pwrap("----")

        if len(plugin_utils.plugins) > 0:
            pwrap("- This goes through your plugins and asks each of them "
                  "to verify configuration and installation.")
            pwrap("")
            pwrap("----")
            for mem in plugin_utils.plugins:
                if hasattr(mem, "verify_installation"):
                    pwrap("plugin:  %s" % mem.__name__)
                    print "file:    %s" % mem.__file__
                    print "version: %s" % (str(getattr(mem, "__version__")))

                    try:
                        if mem.verify_installation(request) == 1:
                            pwrap("PASS")
                        else:
                            pwrap_error("FAIL")
                    except StandardError:
                        pwrap_error("FAIL: Exception thrown:")
                        traceback.print_exc(file=sys.stdout)

                    pwrap("----")
                else:
                    mn = mem.__name__
                    mf = mem.__file__
                    no_verification_support.append( "'%s' (%s)" % (mn, mf))

            if len(no_verification_support) > 0:
                pwrap("")
                pwrap("The following plugins do not support installation "
                      "verification:")
                no_verification_support.sort()
                for mem in no_verification_support:
                    print "- %s" % mem

    pwrap("")
    pwrap("Verification complete.  Correct any errors and warnings above.")
Пример #25
0
def cb_comment_reject(args):
    from akismet import Akismet, AkismetError

    request = args['request']
    comment = args['comment']
    config = request.get_configuration()

    http = request.get_http()

    fields = {
        'comment': 'description',
        'comment_author_email': 'email',
        'comment_author': 'author',
        'comment_author_url': 'link',
        'comment_type': 'type',
    }
    data = {}
    for field in fields:
        if fields[field] in comment:
            data[field] = ""
            for char in list(comment[fields[field]]):
                try:
                    char.encode('ascii')
                # FIXME - bare except--bad!
                except:
                    data[field] = data[field] + "&#" + str(ord(char)) + ";"
                else:
                    data[field] = data[field] + char

    if not data.get('comment'):
        pwrap_error("Comment info not enough.")
        return False
    body = data['comment']

    if 'ipaddress' in comment:
        data['user_ip'] = comment['ipaddress']
    data['user_agent'] = http.get('HTTP_USER_AGENT', '')
    data['referrer'] = http.get('HTTP_REFERER', '')

    api_key = config.get('akismet_api_key')
    base_url = config.get('base_url')

    # initialize the api
    api = Akismet(api_key, base_url, agent='Pyblosxom/1.5')

    if not api.verify_key():
        pwrap_error("Could not verify akismet API key. Comments accepted.")
        return False

    # false is ham, true is spam
    try:
        if api.comment_check(body, data):
            pwrap_error("Rejecting comment")
            return (True, 'I\'m sorry, but your comment was rejected by '
                    'the <a href="http://akismet.com/">Akismet</a> '
                    'spam filtering system.')
        else:
            return False
    except AkismetError:
        pwrap_error("Rejecting comment (AkismetError)")
        return (True, "Missing essential data (e.g., a UserAgent string).")
Пример #26
0
def verify_installation(request):
    config = request.get_configuration()
    # Check for preview path element def
    if not config.has_key('newslists-preview'):
        pwrap_error("py[\"newslists-preview\"] string is undefined in config.py")
        return False
    # Check for defined categories
    if not config.has_key('newslists'):
        pwrap_error("py[\"newslists\"] is undefined in config.py.")
        return False
    if not type(config["newslists"]) == type({}):
        pwrap_error("py[\"newslists\"] must be %s, found %s" % (type({}), type(config["newslists"])))
        return False
    # Check for at least one category, all with a correspnding directory and a full
    # set of keys
    status = False
    for key in config['newslists']:
        status = True
        if not os.path.exists(os.path.join(config["datadir"],key)):
            pwrap_error("Data directory %s must have category \"%s\" as an immediate subdirectory" % (config["datadir"], key))
            return False
        for subkey in ["itemCount","useLink","useDate"]:
            if not config["newslists"][key].has_key(subkey):
                pwrap_error("py[\"newslists\"] key \"%s\" is missing a value for \"%s\"" % (key,subkey))
                return False
    if status == False:
        pwrap_error("py[\"newslists\"] must define at least one category")
        return False
    return True
Пример #27
0
def generate_entries(command, argv):
    """
    This function is primarily for testing purposes.  It creates
    a bunch of blog entries with random text in them.
    """
    parser = build_parser("%prog entries [options] <num_entries>")
    (options, args) = parser.parse_args()

    if args:
        try:
            num_entries = int(args[0])
            assert num_entries > 0
        except ValueError:
            pwrap_error("ERROR: num_entries must be a positive integer.")
            return 0
    else:
        num_entries = 5

    verbose = options.verbose

    p = build_pyblosxom()
    if not p:
        return 0

    datadir = p.get_request().config["datadir"]

    sm_para = "<p>Lorem ipsum dolor sit amet.</p>"
    med_para = """<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus
  in mi lacus, sed interdum nisi. Vestibulum commodo urna et libero
  vestibulum gravida. Vivamus hendrerit justo quis lorem auctor
  consectetur. Aenean ornare, tortor in sollicitudin imperdiet, neque
  diam pellentesque risus, vitae.
</p>"""
    lg_para = """<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
  dictum tortor orci. Lorem ipsum dolor sit amet, consectetur
  adipiscing elit. Etiam quis lectus vel odio convallis tincidunt sed
  et magna. Suspendisse at dolor suscipit eros ullamcorper iaculis. In
  aliquet ornare libero eget rhoncus. Sed ac ipsum eget eros fringilla
  aliquet ut eget velit. Curabitur dui nibh, eleifend non suscipit at,
  laoreet ac purus. Morbi id sem diam. Cras sit amet ante lacus, nec
  euismod urna. Curabitur iaculis, lorem at fringilla malesuada, nunc
  ligula eleifend nisi, at bibendum libero est quis
  tellus. Pellentesque habitant morbi tristique senectus et netus et
  malesuada.
</p>"""
    paras = [sm_para, med_para, lg_para]

    if verbose:
        print "Creating %d entries" % num_entries

    now = time.time()

    for i in range(num_entries):
        title = "post number %d\n" % (i + 1)
        body = []
        for _ in range(random.randrange(1, 6)):
            body.append(random.choice(paras))

        fn = os.path.join(datadir, "post%d.txt" % (i + 1))
        f = open(fn, "w")
        f.write(title)
        f.write("\n".join(body))
        f.close()

        mtime = now - ((num_entries - i) * 3600)
        os.utime(fn, (mtime, mtime))

        if verbose:
            print "Creating '%s'..." % fn

    if verbose:
        print "Done!"
    return 0
Пример #28
0
def cb_comment_reject(args):
    from akismet import Akismet, AkismetError

    request = args['request']
    comment = args['comment']
    config = request.get_configuration()

    http = request.get_http()

    fields = {'comment': 'description',
              'comment_author_email': 'email',
              'comment_author': 'author',
              'comment_author_url': 'link',
              'comment_type': 'type',
              }
    data = {}
    for field in fields:
        if fields[field] in comment:
            data[field] = ""
            for char in list(comment[fields[field]]):
                try:
                    char.encode('ascii')
                # FIXME - bare except--bad!
                except:
                    data[field] = data[field] + "&#" + str(ord(char)) + ";"
                else:
                    data[field] = data[field] + char

    if not data.get('comment'):
        pwrap_error("Comment info not enough.")
        return False
    body = data['comment']

    if 'ipaddress' in comment:
        data['user_ip'] = comment['ipaddress']
    data['user_agent'] = http.get('HTTP_USER_AGENT', '')
    data['referrer'] = http.get('HTTP_REFERER', '')

    api_key = config.get('akismet_api_key')
    base_url = config.get('base_url')

    # initialize the api
    api = Akismet(api_key, base_url, agent='Pyblosxom/1.5')

    if not api.verify_key():
        pwrap_error("Could not verify akismet API key. Comments accepted.")
        return False

    # false is ham, true is spam
    try:
        if api.comment_check(body, data):
            pwrap_error("Rejecting comment")
            return (True,
                    'I\'m sorry, but your comment was rejected by '
                    'the <a href="http://akismet.com/">Akismet</a> '
                    'spam filtering system.')
        else:
            return False
    except AkismetError:
        pwrap_error("Rejecting comment (AkismetError)")
        return (True, "Missing essential data (e.g., a UserAgent string).")