Commits

Anonymous committed 6a22292

- Removed and moved files
Tane Piper <digitalspaghetti@gmail.com>

  • Participants
  • Parent commits 510ac42

Comments (0)

Files changed (15)

core/RemoveSelfLinks.py

-import re
-
-class RemoveSelfLinks:
-    def process_response(self, request, response):
-        if response.status_code == 200:
-            link = request.META['PATH_INFO']
-            response.content = \
-                re.sub( \
-                    r'<a([^>]+)href="%s"([^>]*)>([^<]+)</a>' % link, \
-                    r'<span \1 \2>\3</span>', \
-                    response.content)
-        return response

core/RequireLogin.py

-###
-# Copyright (c) 2006-2007, Jared Kuolt
-# All rights reserved.
-# 
-# Redistribution and use in source and binary forms, with or without 
-# modification, are permitted provided that the following conditions are met:
-# 
-#     * Redistributions of source code must retain the above copyright notice, 
-#       this list of conditions and the following disclaimer.
-#     * Redistributions in binary form must reproduce the above copyright 
-#       notice, this list of conditions and the following disclaimer in the 
-#       documentation and/or other materials provided with the distribution.
-#     * Neither the name of the SuperJared.com nor the names of its 
-#       contributors may be used to endorse or promote products derived from 
-#       this software without specific prior written permission.
-# 
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
-# POSSIBILITY OF SUCH DAMAGE.
-###
-
-from django.conf import settings
-from django.contrib.auth.views import login
-from django.http import HttpResponseRedirect
-from django.core.urlresolvers import resolve
-
-class RequireLoginMiddleware(object):
-    """
-    Require Login middleware. If enabled, each Django-powered page will
-    require authentication.
-    
-    If an anonymous user requests a page, he/she is redirected to the login
-    page set by REQUIRE_LOGIN_PATH or /accounts/login/ by default.
-    """
-    def __init__(self):
-        self.require_login_path = resolve(login)
-    
-    def process_request(self, request):
-        if request.path != self.require_login_path and request.user.is_anonymous():
-            if request.POST:
-                return login(request)
-            else:
-                return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path))
-                

core/SQLLogMiddleware.py

-"""
-$Id: SQLLogMiddleware.py 306 2007-10-22 14:55:47Z tguettler $
-
-This middleware
-in settings.py you need to set
-
-DEBUG=True
-DEBUG_SQL=True
-
-# Since you can't see the output if the page results in a redirect,
-# you can log the result into a directory:
-# DEBUG_SQL='/mypath/...'
-
-MIDDLEWARE_CLASSES = (
-	'YOURPATH.SQLLogMiddleware.SQLLogMiddleware',
-	'django.middleware.transaction.TransactionMiddleware',
-	...)
-
-Slightly modified from original by Rob van der Linde <robvdl@gmail.com>
-
-	- Now supports XHTML content types
-	- Now generates a nice dropdown window/banner at the top of the page.
-	  Only works in Firefox (and other standards compliant browsers), but
-	  then, no serious developers use IE anyway...
-
-"""
-
-import re, os, time, datetime
-from django.conf import settings
-from django.db import connection
-from django.template import Template, Context
-
-_HEAD_SECTION_RE = re.compile(r'(</head.*>)', re.DOTALL)
-_BODY_SECTION_RE = re.compile(r'(<body.*?>)', re.DOTALL)
-
-class SQLLogMiddleware:
-	start = None
-
-	def process_request(self, request):
-		self.start = time.time()
-
-	def process_response (self, request, response):
-		# self.start is empty if an append slash redirect happened.
-		debug_sql = getattr(settings, "DEBUG_SQL", False)
-		if (not self.start) or not (settings.DEBUG and debug_sql):
-			return response
-		timesql = 0.0
-		for q in connection.queries:
-			timesql += float(q['time'])
-			seen = {}
-			duplicate = 0
-		for q in connection.queries:
-			sql = q["sql"]
-			c = seen.get(sql, 0)
-			if c:
-				duplicate += 1
-			q["seen"] = c
-			seen[sql] = c + 1
-		t = Template('''
-			<div id="sqllog">
-				<span><a href="javascript:activate_slider();"><strong>Django SQL log for this page: click to toggle</strong></a></span>
-				<div>
-					<p>
-						<strong>request.path:</strong> {{ request.path|escape }}<br />
-						<strong>Total query count:</strong> {{ queries|length }}<br />
-						<strong>Total duplicate query count:</strong> {{ duplicate }}<br />
-						<strong>Total SQL execution time:</strong> {{ timesql }}<br />
-						<strong>Total Request execution time:</strong> {{ timerequest }}<br />
-					</p>
-					<table border="0" cellspacing="0">
-						<tr>
-							<th>Time</th>
-							<th>Frequency</th>
-							<th>SQL</th>
-						</tr>
-						{% for sql in queries %}
-							<tr>
-								<td>{{ sql.time }}</td>
-								<td class="alright">{{ sql.seen }}</td>
-								<td>{{ sql.sql }}</td>
-							</tr>
-						{% endfor %}
-					</table>
-					{% if duplicate %}
-						<p>To avoid duplicates, read: <a href="http://www.djangoproject.com/documentation/db-api/#caching-and-querysets" target="_blank">Caching and Querysets</a>.</p>
-					{% endif %}
-					<p><button onclick="about_sql_debug()">About</button></p>
-				</div>
-			</div>
-		''')
-		c = Template(r'''
-			<style type="text/css">
-				/*<![CDATA[*/
-					/* I use the !important keyword on just about any element
-					   here, mainly as a precaution. Since we want this to work
-					   with any web page (if possible), We should make sure other
-					   CSS styles from the underlying page do not interfere with
-					   the infobar. This should work on _most_ webpages, but I do
-					   expect that in some cases, you may need to add some minor
-					   corrections in your site's CSS file. This is, only if some
-					   of your styles are interfering with the infobar's styles.
-					   Also, this thing is only expected to work in Firefox, and
-					   other CSS compliant browsers, Opera, Safari, Konqueror, etc.
-					   Most web developers don't use IE anyway, which is who this
-					   middleware is aimed at. It's not recommended to run on
-					   production sites for security.
-					*/
-
-					html {
-						padding-top: 24px !important;
-					}
-
-					#sqllog {
-						font: normal 11px "MS Sans Serif", sans !important;
-						color: black !important;
-						background: #ffffe1 !important;
-						position: fixed !important;
-						top: 0 !important;
-						left: 0 !important;
-						width: 100% !important;
-						height: 24px !important;
-						border-bottom: 2px outset !important;
-						z-index: 255 !important;
-						overflow: hidden !important;
-					}
-
-					#sqllog div {
-						overflow: auto !important;
-						height: 276px !important;
-					}
-
-					#sqllog.slideropen {
-						height: 300px !important;
-					}
-
-					html.slideropen {
-						padding-top: 300px !important;
-					}
-
-					#sqllog table, #sqllog tr, #sqllog td, #sqllog th {
-						border: none !important;
-					}
-
-					#sqllog table {
-						margin: 0 4px !important;
-					}
-
-					#sqllog th {
-						padding-right: 20px !important;
-						font: bold 8px "MS Sans Serif", sans !important;
-					}
-
-					#sqllog .alright {
-						padding-right: 20px !important;
-						text-align: right !important;
-					}
-
-					#sqllog span a {
-						color: black !important;
-						display: block !important;
-						padding: 5px 4px 0 26px !important;
-						height: 19px;
-						background-image: url('/media/images/infobar_icon.png') !important;
-						background-repeat: no-repeat !important;
-						background-position: 4px 3px !important;
-						cursor: default !important;
-						text-decoration: none !important;
-					}
-
-					#sqllog span a:hover {
-						text-decoration: none !imporant;
-						color: HighlightText !important;
-						background-color: Highlight !important;
-					}
-
-					#sqllog a {
-						color: #5b80b2 !important;
-						text-decoration: none !imporant;
-					}
-
-					#sqllog a:hover {
-						color: #003366 !important;
-						text-decoration: none !imporant;
-					}
-
-					#sqllog p {
-						margin: 12px 4px 12px 4px !important;
-					}
-
-					#sqllog p strong {
-						display: block !important;
-						float: left !important;
-						width: 220px !important;
-					}
-				/*]]>*/
-			</style>
-			<script type="text/javascript">
-				//<![CDATA[
-					function activate_slider()
-					{
-						var sqllogClass = document.getElementById('sqllog').className
-						var htmlClass = document.getElementsByTagName('html')[0].className;
-						if (sqllogClass.search(/slideropen/) == -1)
-						{
-							document.getElementById('sqllog').className += ' slideropen';
-							document.getElementsByTagName('html')[0].className += ' slideropen';
-						}
-						else
-						{
-							sqllogClass = sqllogClass.replace(/slideropen/, '');
-							htmlClass = htmlClass.replace(/slideropen/, '');
-							document.getElementById('sqllog').className = sqllogClass;
-							document.getElementsByTagName('html')[0].className = htmlClass;
-						}
-					}
-
-					function about_sql_debug()
-					{
-						alert('Django SQL Debugger 0.1\\n\\nA free middleware (filter), for use in any Django application. Shows the SQL queries generated by your web applications in realtime, using an \'IE style\' collapsable infobar at the top of every page. To get rid of this bar, the web developer should disable this middleware from the web application\\'s settings.py file.\\n\\nOriginal code "SQLLogMiddleware + duplicates", from Django Snippet #344, by "guettli".\\nModifications & Javascript + CSS implementation of the Infobar by Rob van der Linde.\\n\\nUnknown Licence, I would like to go with BSD, but that depends on the original author\'s Licence.');
-					}
-				//]]>
-			</script>
-		''')
-		timerequest = round(time.time() - self.start, 3)
-		queries = connection.queries
-		html = t.render(Context(locals()))
-		css = c.render(Context(locals()))
-		if debug_sql == True:
-			if response.get("content-type", "").startswith("text/html") or response.get("content-type", "").startswith("application/xhtml+xml"):
-				tag = _BODY_SECTION_RE.search(response.content)
-				if tag:
-					response.content = _BODY_SECTION_RE.sub(tag.group(0) + html, response.content)
-					tag = _HEAD_SECTION_RE.search(response.content)
-					if tag:
-						response.content = _HEAD_SECTION_RE.sub(css + tag.group(0), response.content)
-			return response
-		assert os.path.isdir(debug_sql), debug_sql
-		outfile = os.path.join(debug_sql, "%s.html" % datetime.datetime.now().isoformat())
-		fd = open(outfile, "wt")
-		fd.write('''<html><head><title>SQL Log %s</title></head><body>%s</body></html>''' % (request.path, html))
-		fd.close()
-		return response

core/UrlMiddleware.py

-from django.conf import settings
-from django import http
-from django.utils.http import urlquote
-from django.core import urlresolvers
-
-class UrlMiddleware(object):
-    """
-    Middleware for removing the WWW from a URL if the users sets settings.REMOVE_WWW.
-    Based on Django CommonMiddleware.
-    """
-    
-    def process_request(self, request):
-        host = request.get_host()
-        old_url = [host, request.path]
-        new_url = old_url[:]
-        
-        if (settings.REMOVE_WWW and old_url[0] and old_url[0].startswith('www.')):
-            new_url[0] = old_url[0][4:]
-        
-        if new_url != old_url:
-            try:
-                urlresolvers.resolve(new_url[1])
-            except urlresolvers.Resolver404:
-                pass
-            else:
-                if new_url[0]:
-                    newurl = "%s://%s%s" % (
-                        request.is_secure() and 'https' or 'http',
-                        new_url[0], urlquote(new_url[1]))
-                else:
-                    newurl = urlquote(new_url[1])
-                if request.GET:
-                    newurl += '?' + request.GET.urlencode()
-                return http.HttpResponsePermanentRedirect(newurl)
-        return None

core/htpasswdutils.py

-import crypt, random, os, os.path
-
-from repo.models import Repo
-from django.contrib.auth.models import User
-
-from django.conf import settings
-
-# I would be using mod_auth_dbm, but Dreamhost doesn't load it...
-class Htpasswd(object):
-    # FIXME this doesn't do any locking... so...
-    def __init__(self, filename, mode="r"):
-        self.mode = mode
-        self.records = {}
-        self.changed_keys = set()
-        self.filename = filename
-        if mode != 'c' or os.path.exists(filename):
-            file = open(filename, "r")
-            for line in file:
-                try:
-                    k, v = line.strip().split(':',1)
-                except ValueError:
-                    continue
-                self.records[k] = v
-            file.close()
-
-    def __getitem__(self, k):
-        return self.records[k]
-
-    def __setitem__(self, k, v):
-        if self.mode == "r":
-            raise ValueError("Htpasswd file opened for reading only.")
-        self.changed_keys.add(str(k))
-        self.records[str(k)] = str(v)
-
-    def close(self):
-        if not self.changed_keys: return
-        # This is just a race condition waiting to happen...
-        f = open(self.filename, 'w')
-        f.writelines("%s:%s\n" % i for i in self.records.iteritems())
-        f.close()
-
-def update_password(username, password):
-    alphabeta = "./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
-    salt = random.choice(alphabeta)+random.choice(alphabeta)
-    crypted = crypt.crypt(password, salt)
-
-    #db = Htpasswd(settings.HTPASSWD_FILE, "c")
-    db = Htpasswd(Repo.repo_options.htpasswd_file, "c")
-    db[str(username)] = crypted+":hguser"
-    db.close()
-
-def monkeypatch_user_model():
-    _old_set_password = User.set_password
-    def set_password(self, raw_password):
-        update_password(self.username, raw_password)
-        _old_set_password(self, raw_password)
-    User.set_password = set_password

core/json_encode.py

-from django.core.serializers.json import DateTimeAwareJSONEncoder
-from django.db import models
-from django.utils.functional import Promise
-from django.utils.encoding import force_unicode
-from django.utils import simplejson as json
-from decimal import Decimal
-
-
-def json_encode(data):
-    """
-    The main issues with django's default json serializer is that properties that
-    had been added to an object dynamically are being ignored (and it also has 
-    problems with some models).
-    """
-
-    def _any(data):
-        ret = None
-        # Opps, we used to check if it is of type list, but that fails 
-        # i.e. in the case of django.newforms.utils.ErrorList, which extends
-        # the type "list". Oh man, that was a dumb mistake!
-        if isinstance(data, list):
-            ret = _list(data)
-        # Same as for lists above.
-        elif isinstance(data, dict):
-            ret = _dict(data)
-        elif isinstance(data, Decimal):
-            # json.dumps() cant handle Decimal
-            ret = str(data)
-        elif isinstance(data, models.query.QuerySet):
-            # Actually its the same as a list ...
-            ret = _list(data)
-        elif isinstance(data, models.Model):
-            ret = _model(data)
-        # here we need to encode the string as unicode (otherwise we get utf-16 in the json-response)
-        elif isinstance(data, basestring):
-            ret = unicode(data)
-        # see http://code.djangoproject.com/ticket/5868
-        elif isinstance(data, Promise):
-            ret = force_unicode(data)
-        else:
-            ret = data
-        return ret
-    
-    def _model(data):
-        ret = {}
-        # If we only have a model, we only want to encode the fields.
-        for f in data._meta.fields:
-            ret[f.attname] = _any(getattr(data, f.attname))
-        # And additionally encode arbitrary properties that had been added.
-        fields = dir(data.__class__) + ret.keys()
-        add_ons = [k for k in dir(data) if k not in fields]
-        for k in add_ons:
-            ret[k] = _any(getattr(data, k))
-        return ret
-    
-    def _list(data):
-        ret = []
-        for v in data:
-            ret.append(_any(v))
-        return ret
-    
-    def _dict(data):
-        ret = {}
-        for k,v in data.items():
-            ret[k] = _any(v)
-        return ret
-    
-    ret = _any(data)
-    
-    return json.dumps(ret, cls=DateTimeAwareJSONEncoder)

core/json_response.py

-from django.core.serializers import serialize
-from django.db.models.query import QuerySet
-from django.http import HttpResponse
-from django.utils import simplejson
-
-class JsonResponse(HttpResponse):
-    def __init__(self, object):
-        if isinstance(object, QuerySet):
-            content = serialize('json', object)
-        else:
-            content = simplejson.dumps(object)
-        super(JsonResponse, self).__init__(content, mimetype='application/json')

core/libs/__init__.py

Empty file added.

core/libs/htpasswdutils.py

+import crypt, random, os, os.path
+
+from repo.models import Repo
+from django.contrib.auth.models import User
+
+from django.conf import settings
+
+# I would be using mod_auth_dbm, but Dreamhost doesn't load it...
+class Htpasswd(object):
+    # FIXME this doesn't do any locking... so...
+    def __init__(self, filename, mode="r"):
+        self.mode = mode
+        self.records = {}
+        self.changed_keys = set()
+        self.filename = filename
+        if mode != 'c' or os.path.exists(filename):
+            file = open(filename, "r")
+            for line in file:
+                try:
+                    k, v = line.strip().split(':',1)
+                except ValueError:
+                    continue
+                self.records[k] = v
+            file.close()
+
+    def __getitem__(self, k):
+        return self.records[k]
+
+    def __setitem__(self, k, v):
+        if self.mode == "r":
+            raise ValueError("Htpasswd file opened for reading only.")
+        self.changed_keys.add(str(k))
+        self.records[str(k)] = str(v)
+
+    def close(self):
+        if not self.changed_keys: return
+        # This is just a race condition waiting to happen...
+        f = open(self.filename, 'w')
+        f.writelines("%s:%s\n" % i for i in self.records.iteritems())
+        f.close()
+
+def update_password(username, password):
+    alphabeta = "./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+    salt = random.choice(alphabeta)+random.choice(alphabeta)
+    crypted = crypt.crypt(password, salt)
+
+    #db = Htpasswd(settings.HTPASSWD_FILE, "c")
+    db = Htpasswd(Repo.repo_options.htpasswd_file, "c")
+    db[str(username)] = crypted+":hguser"
+    db.close()
+
+def monkeypatch_user_model():
+    _old_set_password = User.set_password
+    def set_password(self, raw_password):
+        update_password(self.username, raw_password)
+        _old_set_password(self, raw_password)
+    User.set_password = set_password

core/libs/json_libs.py

+import datetime
+from decimal import Decimal
+
+from django.conf import settings
+from django.core.serializers import serialize
+from django.core.serializers.json import DateTimeAwareJSONEncoder
+from django.db import models
+from django.db.models import signals
+from django.db.models.query import QuerySet
+from django.dispatch import dispatcher
+from django.http import HttpResponse
+from django.utils import simplejson
+from django.utils.functional import Promise
+from django.utils.encoding import force_unicode
+
+
+def json_encode(data):
+    """
+    The main issues with django's default json serializer is that properties that
+    had been added to an object dynamically are being ignored (and it also has 
+    problems with some models).
+    """
+
+    def _any(data):
+        ret = None
+        # Opps, we used to check if it is of type list, but that fails 
+        # i.e. in the case of django.newforms.utils.ErrorList, which extends
+        # the type "list". Oh man, that was a dumb mistake!
+        if isinstance(data, list):
+            ret = _list(data)
+        # Same as for lists above.
+        elif isinstance(data, dict):
+            ret = _dict(data)
+        elif isinstance(data, Decimal):
+            # json.dumps() cant handle Decimal
+            ret = str(data)
+        elif isinstance(data, models.query.QuerySet):
+            # Actually its the same as a list ...
+            ret = _list(data)
+        elif isinstance(data, models.Model):
+            ret = _model(data)
+        # here we need to encode the string as unicode (otherwise we get utf-16 in the json-response)
+        elif isinstance(data, basestring):
+            ret = unicode(data)
+        # see http://code.djangoproject.com/ticket/5868
+        elif isinstance(data, Promise):
+            ret = force_unicode(data)
+        else:
+            ret = data
+        return ret
+    
+    def _model(data):
+        ret = {}
+        # If we only have a model, we only want to encode the fields.
+        for f in data._meta.fields:
+            ret[f.attname] = _any(getattr(data, f.attname))
+        # And additionally encode arbitrary properties that had been added.
+        fields = dir(data.__class__) + ret.keys()
+        add_ons = [k for k in dir(data) if k not in fields]
+        for k in add_ons:
+            ret[k] = _any(getattr(data, k))
+        return ret
+    
+    def _list(data):
+        ret = []
+        for v in data:
+            ret.append(_any(v))
+        return ret
+    
+    def _dict(data):
+        ret = {}
+        for k,v in data.items():
+            ret[k] = _any(v)
+        return ret
+    
+    ret = _any(data)
+    
+    return simplejson.dumps(ret, cls=DateTimeAwareJSONEncoder)
+
+class JsonResponse(HttpResponse):
+    def __init__(self, object):
+        if isinstance(object, QuerySet):
+            content = serialize('json', object)
+        else:
+            content = simplejson.dumps(object)
+        super(JsonResponse, self).__init__(content, mimetype='application/json')
+        
+class JSONEncoder(simplejson.JSONEncoder):
+    def default(self, obj):
+        if isinstance(obj, datetime.datetime):
+            return obj.strftime('%Y-%m-%d %H:%M:%S')
+        elif isinstance(obj, datetime.date):
+            return obj.strftime('%Y-%m-%d')
+        elif isinstance(obj, datetime.time):
+            return obj.strftime('%H:%M:%S')
+        return simplejson.JSONEncoder.default(self, obj)
+        
+def dumps(data):
+    return JSONEncoder().encode(data)
+    
+def loads(str):
+    return simplejson.loads(str, encoding=settings.DEFAULT_CHARSET)
+    
+class JSONField(models.TextField):
+    def db_type(self):
+        return 'text'
+        
+    def pre_save(self, model_instance, add):
+        value = getattr(model_instance, self.attname, None)
+        return dumps(value)
+    
+    def contribute_to_class(self, cls, name):
+        super(JSONField, self).contribute_to_class(cls, name)
+        dispatcher.connect(self.post_init, signal=signals.post_init, sender=cls)
+        
+        def get_json(model_instance):
+            return dumps(getattr(model_instance, self.attname, None))
+        setattr(cls, 'get_%s_json' % self.name, get_json)
+    
+        def set_json(model_instance, json):
+            return setattr(model_instance, self.attname, loads(json))
+        setattr(cls, 'set_%s_json' % self.name, set_json)
+    
+    def post_init(self, instance=None):
+        value = self.value_from_object(instance)
+        if (value):
+            setattr(instance, self.attname, loads(value))
+        else:
+            setattr(instance, self.attname, None)

core/middleware/RemoveSelfLinks.py

+import re
+
+class RemoveSelfLinks:
+    def process_response(self, request, response):
+        if response.status_code == 200:
+            link = request.META['PATH_INFO']
+            response.content = \
+                re.sub( \
+                    r'<a([^>]+)href="%s"([^>]*)>([^<]+)</a>' % link, \
+                    r'<span \1 \2>\3</span>', \
+                    response.content)
+        return response

core/middleware/RequireLogin.py

+###
+# Copyright (c) 2006-2007, Jared Kuolt
+# All rights reserved.
+# 
+# Redistribution and use in source and binary forms, with or without 
+# modification, are permitted provided that the following conditions are met:
+# 
+#     * Redistributions of source code must retain the above copyright notice, 
+#       this list of conditions and the following disclaimer.
+#     * Redistributions in binary form must reproduce the above copyright 
+#       notice, this list of conditions and the following disclaimer in the 
+#       documentation and/or other materials provided with the distribution.
+#     * Neither the name of the SuperJared.com nor the names of its 
+#       contributors may be used to endorse or promote products derived from 
+#       this software without specific prior written permission.
+# 
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+# POSSIBILITY OF SUCH DAMAGE.
+###
+
+from django.conf import settings
+from django.contrib.auth.views import login
+from django.http import HttpResponseRedirect
+from django.core.urlresolvers import resolve
+
+class RequireLoginMiddleware(object):
+    """
+    Require Login middleware. If enabled, each Django-powered page will
+    require authentication.
+    
+    If an anonymous user requests a page, he/she is redirected to the login
+    page set by REQUIRE_LOGIN_PATH or /accounts/login/ by default.
+    """
+    def __init__(self):
+        self.require_login_path = resolve(login)
+    
+    def process_request(self, request):
+        if request.path != self.require_login_path and request.user.is_anonymous():
+            if request.POST:
+                return login(request)
+            else:
+                return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path))
+                

core/middleware/SQLLogMiddleware.py

+"""
+$Id: SQLLogMiddleware.py 306 2007-10-22 14:55:47Z tguettler $
+
+This middleware
+in settings.py you need to set
+
+DEBUG=True
+DEBUG_SQL=True
+
+# Since you can't see the output if the page results in a redirect,
+# you can log the result into a directory:
+# DEBUG_SQL='/mypath/...'
+
+MIDDLEWARE_CLASSES = (
+	'YOURPATH.SQLLogMiddleware.SQLLogMiddleware',
+	'django.middleware.transaction.TransactionMiddleware',
+	...)
+
+Slightly modified from original by Rob van der Linde <robvdl@gmail.com>
+
+	- Now supports XHTML content types
+	- Now generates a nice dropdown window/banner at the top of the page.
+	  Only works in Firefox (and other standards compliant browsers), but
+	  then, no serious developers use IE anyway...
+
+"""
+
+import re, os, time, datetime
+from django.conf import settings
+from django.db import connection
+from django.template import Template, Context
+
+_HEAD_SECTION_RE = re.compile(r'(</head.*>)', re.DOTALL)
+_BODY_SECTION_RE = re.compile(r'(<body.*?>)', re.DOTALL)
+
+class SQLLogMiddleware:
+	start = None
+
+	def process_request(self, request):
+		self.start = time.time()
+
+	def process_response (self, request, response):
+		# self.start is empty if an append slash redirect happened.
+		debug_sql = getattr(settings, "DEBUG_SQL", False)
+		if (not self.start) or not (settings.DEBUG and debug_sql):
+			return response
+		timesql = 0.0
+		for q in connection.queries:
+			timesql += float(q['time'])
+			seen = {}
+			duplicate = 0
+		for q in connection.queries:
+			sql = q["sql"]
+			c = seen.get(sql, 0)
+			if c:
+				duplicate += 1
+			q["seen"] = c
+			seen[sql] = c + 1
+		t = Template('''
+			<div id="sqllog">
+				<span><a href="javascript:activate_slider();"><strong>Django SQL log for this page: click to toggle</strong></a></span>
+				<div>
+					<p>
+						<strong>request.path:</strong> {{ request.path|escape }}<br />
+						<strong>Total query count:</strong> {{ queries|length }}<br />
+						<strong>Total duplicate query count:</strong> {{ duplicate }}<br />
+						<strong>Total SQL execution time:</strong> {{ timesql }}<br />
+						<strong>Total Request execution time:</strong> {{ timerequest }}<br />
+					</p>
+					<table border="0" cellspacing="0">
+						<tr>
+							<th>Time</th>
+							<th>Frequency</th>
+							<th>SQL</th>
+						</tr>
+						{% for sql in queries %}
+							<tr>
+								<td>{{ sql.time }}</td>
+								<td class="alright">{{ sql.seen }}</td>
+								<td>{{ sql.sql }}</td>
+							</tr>
+						{% endfor %}
+					</table>
+					{% if duplicate %}
+						<p>To avoid duplicates, read: <a href="http://www.djangoproject.com/documentation/db-api/#caching-and-querysets" target="_blank">Caching and Querysets</a>.</p>
+					{% endif %}
+					<p><button onclick="about_sql_debug()">About</button></p>
+				</div>
+			</div>
+		''')
+		c = Template(r'''
+			<style type="text/css">
+				/*<![CDATA[*/
+					/* I use the !important keyword on just about any element
+					   here, mainly as a precaution. Since we want this to work
+					   with any web page (if possible), We should make sure other
+					   CSS styles from the underlying page do not interfere with
+					   the infobar. This should work on _most_ webpages, but I do
+					   expect that in some cases, you may need to add some minor
+					   corrections in your site's CSS file. This is, only if some
+					   of your styles are interfering with the infobar's styles.
+					   Also, this thing is only expected to work in Firefox, and
+					   other CSS compliant browsers, Opera, Safari, Konqueror, etc.
+					   Most web developers don't use IE anyway, which is who this
+					   middleware is aimed at. It's not recommended to run on
+					   production sites for security.
+					*/
+
+					html {
+						padding-top: 24px !important;
+					}
+
+					#sqllog {
+						font: normal 11px "MS Sans Serif", sans !important;
+						color: black !important;
+						background: #ffffe1 !important;
+						position: fixed !important;
+						top: 0 !important;
+						left: 0 !important;
+						width: 100% !important;
+						height: 24px !important;
+						border-bottom: 2px outset !important;
+						z-index: 255 !important;
+						overflow: hidden !important;
+					}
+
+					#sqllog div {
+						overflow: auto !important;
+						height: 276px !important;
+					}
+
+					#sqllog.slideropen {
+						height: 300px !important;
+					}
+
+					html.slideropen {
+						padding-top: 300px !important;
+					}
+
+					#sqllog table, #sqllog tr, #sqllog td, #sqllog th {
+						border: none !important;
+					}
+
+					#sqllog table {
+						margin: 0 4px !important;
+					}
+
+					#sqllog th {
+						padding-right: 20px !important;
+						font: bold 8px "MS Sans Serif", sans !important;
+					}
+
+					#sqllog .alright {
+						padding-right: 20px !important;
+						text-align: right !important;
+					}
+
+					#sqllog span a {
+						color: black !important;
+						display: block !important;
+						padding: 5px 4px 0 26px !important;
+						height: 19px;
+						background-image: url('/media/images/infobar_icon.png') !important;
+						background-repeat: no-repeat !important;
+						background-position: 4px 3px !important;
+						cursor: default !important;
+						text-decoration: none !important;
+					}
+
+					#sqllog span a:hover {
+						text-decoration: none !imporant;
+						color: HighlightText !important;
+						background-color: Highlight !important;
+					}
+
+					#sqllog a {
+						color: #5b80b2 !important;
+						text-decoration: none !imporant;
+					}
+
+					#sqllog a:hover {
+						color: #003366 !important;
+						text-decoration: none !imporant;
+					}
+
+					#sqllog p {
+						margin: 12px 4px 12px 4px !important;
+					}
+
+					#sqllog p strong {
+						display: block !important;
+						float: left !important;
+						width: 220px !important;
+					}
+				/*]]>*/
+			</style>
+			<script type="text/javascript">
+				//<![CDATA[
+					function activate_slider()
+					{
+						var sqllogClass = document.getElementById('sqllog').className
+						var htmlClass = document.getElementsByTagName('html')[0].className;
+						if (sqllogClass.search(/slideropen/) == -1)
+						{
+							document.getElementById('sqllog').className += ' slideropen';
+							document.getElementsByTagName('html')[0].className += ' slideropen';
+						}
+						else
+						{
+							sqllogClass = sqllogClass.replace(/slideropen/, '');
+							htmlClass = htmlClass.replace(/slideropen/, '');
+							document.getElementById('sqllog').className = sqllogClass;
+							document.getElementsByTagName('html')[0].className = htmlClass;
+						}
+					}
+
+					function about_sql_debug()
+					{
+						alert('Django SQL Debugger 0.1\\n\\nA free middleware (filter), for use in any Django application. Shows the SQL queries generated by your web applications in realtime, using an \'IE style\' collapsable infobar at the top of every page. To get rid of this bar, the web developer should disable this middleware from the web application\\'s settings.py file.\\n\\nOriginal code "SQLLogMiddleware + duplicates", from Django Snippet #344, by "guettli".\\nModifications & Javascript + CSS implementation of the Infobar by Rob van der Linde.\\n\\nUnknown Licence, I would like to go with BSD, but that depends on the original author\'s Licence.');
+					}
+				//]]>
+			</script>
+		''')
+		timerequest = round(time.time() - self.start, 3)
+		queries = connection.queries
+		html = t.render(Context(locals()))
+		css = c.render(Context(locals()))
+		if debug_sql == True:
+			if response.get("content-type", "").startswith("text/html") or response.get("content-type", "").startswith("application/xhtml+xml"):
+				tag = _BODY_SECTION_RE.search(response.content)
+				if tag:
+					response.content = _BODY_SECTION_RE.sub(tag.group(0) + html, response.content)
+					tag = _HEAD_SECTION_RE.search(response.content)
+					if tag:
+						response.content = _HEAD_SECTION_RE.sub(css + tag.group(0), response.content)
+			return response
+		assert os.path.isdir(debug_sql), debug_sql
+		outfile = os.path.join(debug_sql, "%s.html" % datetime.datetime.now().isoformat())
+		fd = open(outfile, "wt")
+		fd.write('''<html><head><title>SQL Log %s</title></head><body>%s</body></html>''' % (request.path, html))
+		fd.close()
+		return response

core/middleware/UrlMiddleware.py

+from django.conf import settings
+from django import http
+from django.utils.http import urlquote
+from django.core import urlresolvers
+
+class UrlMiddleware(object):
+    """
+    Middleware for removing the WWW from a URL if the users sets settings.REMOVE_WWW.
+    Based on Django CommonMiddleware.
+    """
+    
+    def process_request(self, request):
+        host = request.get_host()
+        old_url = [host, request.path]
+        new_url = old_url[:]
+        
+        if (settings.REMOVE_WWW and old_url[0] and old_url[0].startswith('www.')):
+            new_url[0] = old_url[0][4:]
+        
+        if new_url != old_url:
+            try:
+                urlresolvers.resolve(new_url[1])
+            except urlresolvers.Resolver404:
+                pass
+            else:
+                if new_url[0]:
+                    newurl = "%s://%s%s" % (
+                        request.is_secure() and 'https' or 'http',
+                        new_url[0], urlquote(new_url[1]))
+                else:
+                    newurl = urlquote(new_url[1])
+                if request.GET:
+                    newurl += '?' + request.GET.urlencode()
+                return http.HttpResponsePermanentRedirect(newurl)
+        return None

core/middleware/__init__.py

Empty file added.