# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


__doc__ = """Glasnost Web Tools"""

__version__ = '$Revision$'[11:-2]


import os
import smtplib
import socket
import time

try:
    from mod_python import apache
except ImportError:
    class apache:
        OK = 200

import glasnost

import glasnost.common.context as context
import glasnost.common.tools_new as commonTools
import glasnost.common.xhtmlgenerator as X


def addContextualHeader(htmlLine):
    knownLines = {
        'calendar.css':
            '<link href="%s" rel="stylesheet" type="text/css" />' % \
                X.fileUrl('/css/calendar.css'),
        'noindex':
            '<meta name="robots" content="noindex" />',
        'jscalendar':
            """
<script type="text/javascript" src="/javascript/jscalendar/calendar.js"></script>
<script type="text/javascript" src="/javascript/jscalendar/calendar-setup.js"></script>
<script type="text/javascript" src="/javascript/jscalendar/lang/calendar-%s.js"></script>
<link rel="stylesheet" type="text/css" href="/javascript/jscalendar/calendar-win2k-cold-1.css" />""" % context.getVar('readLanguages')[0],
        'jsform':
            '<script type="text/javascript" src="/javascript/form.js"></script>',
    }
    if htmlLine in knownLines.keys():
        htmlLine = knownLines[htmlLine]
    contextualHeaders = context.getVar('htmlHeaders')
    if not htmlLine in contextualHeaders:
        contextualHeaders.append(htmlLine)


def debugInfos():
    req = context.getVar('req')
    req.content_type = 'text/html'
    req.send_http_header()
    req.write("""\
<html>
  <title>Test</title>
<body>
""")
    req.write('<h1>OS.ENVIRON</h1>\n')
    env = os.environ
    for key in env.keys():
        value = env[key]
        req.write('<p><b>%(key)s:</b> %(value)s</p>\n' % {
            'key': key,
            'value': value,
            })
    req.write('<h1>ENVIRON</h1>\n')
    env = req._req.subprocess_env
    for key in env.keys():
        value = env[key]
        req.write('<p><b>%(key)s:</b> %(value)s</p>\n' % {
            'key': key,
            'value': value,
            })
    req.write('<h1>REQUEST</h1>\n')
    for key, value in req.__dict__.items():
        req.write('<p><b>%(key)s:</b> %(value)s</p>\n' % {
            'key': key,
            'value': value,
            })
    req.write('<h2>REQUEST hidden fields</h2>\n')
    req.write('<p><b>the_request</b>: %s</p>\n' % req.the_request)
    req.write('<p><b>assbackwards</b>: %s</p>\n' % req.assbackwards)
    req.write('<p><b>header_only</b>: %s</p>\n' % req.header_only)
    req.write('<p><b>protocol</b>: %s</p>\n' % req.protocol)
    req.write('<p><b>proto_num</b>: %s</p>\n' % req.proto_num)
    req.write('<p><b>request_time</b>: %s</p>\n' % req.request_time)
    req.write('<p><b>status_line</b>: %s</p>\n' % req.status_line)
    req.write('<p><b>method</b>: %s</p>\n' % req.method)
    req.write('<p><b>method_number</b>: %s</p>\n' % req.method_number)
    req.write('<p><b>mtime</b>: %s</p>\n' % req.mtime)
    req.write('<p><b>unparsed_uri</b>: %s</p>\n' % req.unparsed_uri)
    req.write('<p><b>uri</b>: %s</p>\n' % req.uri)
    req.write('<p><b>filename</b>: %s</p>\n' % req.filename)
    req.write('<p><b>path_info</b>: %s</p>\n' % req.path_info)
    req.write('<p><b>args</b>: %s</p>\n' % req.args)
    req.write('<p><b>get_config()</b>: %s</p>\n' % req.get_config())
    req.write('<p><b>headers_in</b>: \n')
    req.write('  <ul>\n')
    for label in req.headers_in.keys():
        header = req.headers_in[label]
        req.write('    <li><b>%s</b>: %s</li>\n' % (label, header))
    req.write('  </ul>\n')
    req.write('</p>\n')
    req.write('<h1>Context Variables</h1>\n')
    varNames = context.getVarNames()[:]
    varNames.sort()
    for varName in varNames:
        var = context.getVar(varName)
        req.write('<p><b>%(key)s:</b> %(value)s</p>\n' % {
            'key': varName,
            'value': var,
            })
    req.write("""\
</body>
</html>
""")
    return apache.OK


def getConfig(value, default = None, vars = None, raw = 0):
    if not context.getVar('virtualHost'):
        return commonTools.getConfig('Misc', value, default, vars, raw)

    return commonTools.getConfig(
            context.getVar('virtualHost').hostName, value,
            default = commonTools.getConfig('Misc', value, default, vars, raw),
            vars = vars, raw = raw)

def sendTalkBack(req, message):
    if not commonTools.getConfig('Misc', 'SendTalkBackTo'):
        return

    userAgent = '(not set)'
    if req.headers_in.has_key('User-Agent'):
        userAgent = req.headers_in['User-Agent']
    if req.headers_in.has_key('Host'):
        host = req.headers_in['Host']
    else:
        host = '%s (from socket.getfqdn())' % socket.getfqdn()
    message = """From: %(from)s
To: %(to)s
Subject: [%(host)s] Glasnost Talkback

Version: %(version)s
Time: %(time)s
Host: %(host)s
Url: %(url)s
User-Agent: %(user-agent)s
Client: %(client-ip)s %(client-host)s


%(message)s
""" % {         'time': time.ctime(),
        'host': host,
        'to': commonTools.getConfig('Misc', 'SendTalkBackTo'),
        'from': commonTools.getConfig('Misc', 'AdminEmailAddress',
                                default = 'root@localhost'),
        'message': message,
        'version': glasnost.versionNumber,
        'url': req.unparsed_uri,
        'user-agent': userAgent,
        'client-ip': req.connection.remote_ip,
        'client-host': (req.connection.remote_host or '')}
    server = smtplib.SMTP('localhost')
    try:
        server.sendmail(
                commonTools.getConfig('Misc', 'AdminEmailAddress',
                        default = 'root@localhost'),
                commonTools.getConfig('Misc', 'SendTalkBackTo'),
                message)
    except:
        pass

