"Fossies" - the Fresh Open Source Software Archive

Member "anticms-0.2.1/cgi-bin/index.py" (5 Nov 2005, 4558 Bytes) of package /linux/www/old/anticms-0.2.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "index.py" see the Fossies "Dox" file reference documentation.

    1 #!/usr/bin/env python
    2 # -*- coding: utf-8 -*-
    3 
    4 # $Id: index.py,v 1.2 2005/11/05 12:43:26 aurb Exp $
    5 
    6 # AntiCMS, a small and simple content management system for websites
    7 # Copyright (C) 2005  Aurelius Bruzas <aurelijus.b@gmail.com>
    8 
    9 # This program is free software; you can redistribute it and/or modify it
   10 # under the terms of the GNU General Public License as published by the
   11 # Free Software Foundation; either version 2 of the License, or (at your
   12 # option) any later version.
   13 
   14 # This program is distributed in the hope that it will be useful, but
   15 # WITHOUT ANY WARRANTY; without even the implied warranty of
   16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
   17 # Public License for more details.
   18 
   19 # You should have received a copy of the GNU General Public License along
   20 # with this program; if not, write to the Free Software Foundation, Inc.,
   21 # 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22 
   23 import os, sys, cgitb, time, xml.dom.minidom, re
   24 from datetime import datetime, timedelta
   25 
   26 start_time = time.time()
   27 version = '0.2.1'
   28 
   29 
   30 class Config:
   31     cfg = {}
   32 
   33     def __init__(self, file):
   34         doc = xml.dom.minidom.parse(file)
   35 
   36         if os.environ.has_key('SERVER_NAME'): host = os.environ['SERVER_NAME']
   37         else: host = 'localhost'    # :-/
   38 
   39         for j in doc.getElementsByTagName('config'):
   40             if re.match(j.getAttribute('host'), host):
   41                 for i in j.getElementsByTagName('item'):
   42                     if i.getAttribute('type') == 'bool':
   43                         self.cfg[i.getAttribute('name')] = bool(i.getAttribute('value') == 'true')
   44                     elif i.getAttribute('type') == 'int':
   45                         self.cfg[i.getAttribute('name')] = int(i.getAttribute('value'))
   46                     else:
   47                         self.cfg[i.getAttribute('name')] = unicode(i.getAttribute('value'))
   48                 break
   49 
   50         doc.unlink()
   51 
   52         if self.cfg == {}: raise
   53 
   54     def getOption(self, name):
   55         try:
   56             val = self.cfg[name]
   57         except:
   58             val = None
   59 
   60         return val
   61 
   62 
   63 def print_error(txt, header = "Error"):
   64     print "Content-type: text/html\n"
   65     print """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
   66 <html><head>
   67 <title>""" + header + """</title>
   68 </head><body>
   69 <h1>""" + header + """</h1>
   70 <p>""" + txt + """</p>
   71 </body></html>"""
   72 
   73 
   74 if __name__ == "__main__":
   75     try:
   76         config = Config('config.xml')
   77     except:
   78         print_error("No suitable config for this host. Check installation and|or configuration.")
   79         sys.exit(0)
   80 
   81     sys.path.insert(0, os.path.join(os.getcwd(), config.getOption('code_dir')))
   82 
   83     try:
   84         from template import Template
   85         from content import Content
   86         from request import Request
   87     except:
   88         print_error("Could not load program modules. Check installation.")
   89         sys.exit(0)
   90 
   91     cgitb.enable(display = config.getOption('debug'))
   92 
   93     try:
   94         template = Template(config.getOption('template_file'), config.getOption('input_encoding'))
   95         content = Content(config)
   96     except:
   97         print_error("Could not find some of the required files. Check installation.")
   98         sys.exit(0)
   99 
  100     info = content.getInfo()
  101     request = Request(info, config)
  102     content.setRequest(request)
  103 
  104     # If the requested page is not found...
  105     # TODO: custom error pages maybe?
  106     if not content.getPage():
  107         print "Status: 404 Not Found"
  108         print_error("The requested page " + request.page + " was not found.", "404 Not Found")
  109         sys.exit(0)
  110 
  111     # Set the useful template variables.
  112     template.set_var('LANGS', info['langs'])
  113     template.set_var('LANG', request.lang)
  114     template.set_var('PAGES', content.getPages())
  115     template.set_var('PAGE', content.getPage())
  116     template.set_var('PATH', content.getPath())
  117     template.set_var('ENCODING', config.getOption('output_encoding'))
  118 
  119     # Set the useless template variables.
  120     template.set_var('POWERED', '<a href="http://anticms.sourceforge.net" title="AntiCMS: CMS for nerds">AntiCMS v' + version + '</a>')
  121 
  122     # Populate template with the values from content.
  123     for k, v in content.getContent().iteritems():
  124         template.set_var(k, v)
  125 
  126     # Print HTTP headers.
  127     if info['expires']['enabled']:
  128         print "Expires: " + (datetime.utcnow() + timedelta(
  129             days=info['expires']['days'],
  130             hours=info['expires']['hours'],
  131             minutes=info['expires']['minutes'],
  132             seconds=info['expires']['seconds'])).strftime("%a, %d %b %Y %H:%M:%S GMT")
  133 
  134     # If something goes wrong with the encodings, take a look at this - I
  135     # specify the output encoding in the HTTP header also.
  136     print "Content-type: text/html; charset=" + config.getOption('output_encoding') + "\n"
  137 
  138     # Here goes the content.
  139     print template.process().strip().encode(config.getOption('output_encoding'))
  140 
  141     if config.getOption('print_gen_time'):
  142         print "\n<!-- generated in: " + str(time.time() - start_time) + "s -->"