euscanwww: initial structure

Signed-off-by: Corentin Chary <corentincj@iksaif.net>
This commit is contained in:
Corentin Chary 2011-04-12 16:09:17 +02:00
parent c313d4f146
commit 2bbd20279c
8 changed files with 123 additions and 985 deletions

0
euscanwww/__init__.py Normal file
View File

11
euscanwww/manage.py Normal file
View File

@ -0,0 +1,11 @@
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)

96
euscanwww/settings.py Normal file
View File

@ -0,0 +1,96 @@
# Django settings for euscanwww project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'h!@c5^bi%emv1malwhk(txwqo1(uxyzvp6@+^gn4zyyr2pu*1c'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'euscanwww.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)

16
euscanwww/urls.py Normal file
View File

@ -0,0 +1,16 @@
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^euscanwww/', include('euscanwww.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)

View File

@ -1,229 +0,0 @@
#!/usr/bin/env python
import subprocess
import portage
import sqlite3
import sys
import argparse
def package_id_by_name(c, catpkg):
cat, pkg = catpkg.split('/')
c.execute('SELECT id FROM packages WHERE category = ? AND package = ?', (cat, pkg))
row = c.fetchone()
if row:
package_id = row[0]
else:
c.execute('INSERT OR IGNORE INTO packages (category, package) VALUES (?,?)', (cat, pkg))
package_id = c.lastrowid
print '[e] %s/%s' % (cat, pkg)
return package_id
def store_package(c, cpv, slot):
catpkg, ver, rev = portage.pkgsplit(cpv)
cat, pkg = catpkg.split('/')
package_id = -1
package_id = package_id_by_name(c, catpkg)
sql = 'INSERT OR IGNORE INTO versions (package_id, slot, revision, version, packaged) VALUES (?, ?, ?, ?, 1)'
c.execute(sql, (package_id, slot, rev, ver))
if c.lastrowid:
print '[v] %s:%s' % (cpv, slot)
def portage_scan(db, package=None):
c = db.cursor()
cmd = ['eix', '--format', '<availableversions:NAMEVERSION>', '--pure-packages', '-x']
if package:
cmd.append(package)
output1 = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
cmd = ['eix', '--format', '<availableversions:NAMEASLOT>', '--pure-packages', '-x']
if package:
cmd.append(package)
output2 = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
output1 = output1.split('\n')
output2 = output2.split('\n')
for i in range(0, len(output1)):
if not output1[i]:
continue
cpv = output1[i]
slot = output2[i].split(':')[1]
store_package(c, cpv, slot)
db.commit()
def herd_id_by_name(cursor, herd):
cursor.execute('SELECT id FROM herds WHERE herd = ?', (herd,))
row = cursor.fetchone()
if row:
herd_id = row[0]
else:
cursor.execute('INSERT INTO herds (herd) VALUES (?)', (herd,))
herd_id = cursor.lastrowid
print '[h] %s' % (herd)
return herd_id
def maintainer_id_by_name(cursor, maintainer):
cursor.execute('SELECT id FROM maintainers WHERE maintainer = ?', (maintainer,))
row = cursor.fetchone()
if row:
maintainer_id = row[0]
else:
cursor.execute('INSERT INTO maintainers (maintainer) VALUES (?)', (maintainer,))
maintainer_id = cursor.lastrowid
print '[m] %s' % (maintainer)
return maintainer_id
def store_herd(cursor, catpkg, herd):
if herd == 'no-herd':
return
package_id = package_id_by_name(cursor, catpkg)
herd_id = herd_id_by_name(cursor, herd)
print catpkg, herd
cursor.execute('INSERT OR IGNORE INTO package_herds (herd_id, package_id) VALUES (?, ?)', (herd_id, package_id))
def store_maintainer(cursor, catpkg, maintainer):
if maintainer == 'None specified':
return
package_id = package_id_by_name(cursor, catpkg)
maintainer_id = maintainer_id_by_name(cursor, maintainer)
print catpkg, maintainer
cursor.execute('INSERT OR IGNORE INTO package_maintainers (maintainer_id, package_id) VALUES (?, ?)', (maintainer_id, package_id))
def metadata_scan_some(c, packages):
cmd = ['epkginfo']
cmd.extend(packages[:-1])
output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
output = output.split('\n\n')
for infos in output:
infos = infos.split('\n')
package = packages.pop(0)
for line in infos:
if line.startswith('Herd:'):
line = line.replace('Herd:', '').strip()
store_herd(c, package, line)
if line.startswith('Maintainer:'):
line = line.replace('Maintainer:', '').strip()
store_maintainer(c, package, line)
def metadata_scan(db, package=None):
c = db.cursor()
cmd = ['eix', '--only-names']
if package:
cmd.append(package)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
packages = output.split('\n')
tmp = []
for package in packages:
tmp.append(package)
if len(tmp) > 10:
metadata_scan_some(c, tmp)
tmp = []
metadata_scan_some(c, tmp)
db.commit()
def version_id_by_version(cursor, package_id, version):
cursor.execute('SELECT id, packaged FROM versions WHERE package_id = ? AND version = ?', (package_id, version))
row = cursor.fetchone()
if row:
version_id = row[0]
packaged = row[1]
else:
cursor.execute('INSERT INTO versions (package_id, slot, revision, version, packaged) VALUES (?, ?, ?, ?, 0)',
(package_id, '', 'r0', version))
version_id = cursor.lastrowid
packaged = 0
return version_id, packaged
def upstream_scan(db, package):
c = db.cursor()
cmd = ['eix', '--format', '<bestversion*:NAMEVERSION>', '--pure-packages']
if package:
cmd.append(package)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
packages = output.split('\n')
for package in packages:
if not package.strip():
continue
catpkg, ver, rev = portage.pkgsplit(package)
cmd = ['../euscan', package]
output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
output = output.split('\n')
for line in output:
if not line.startswith('New Upstream Version: '):
continue
line = line.replace('New Upstream Version: ', '').split(' ')
ver = line[0]
urls = line[1:]
package_id = package_id_by_name(c, catpkg)
version_id, packaged= version_id_by_version(c, package_id, ver)
if packaged:
continue
print '[u] %s %s' % (ver, ' '.join(urls))
for url in urls:
c.execute('INSERT OR REPLACE INTO upstream_urls (version_id, url) VALUES (?, ?)', (version_id, url))
db.commit()
def main():
parser = argparse.ArgumentParser(description='Update euscan database.')
parser.add_argument('--skip-portage', action='store_true', help='Skip portage scan.')
parser.add_argument('--skip-metadata', action='store_true', help='Skip metadata scan.')
parser.add_argument('package', nargs='*', help='Only check updates for these packages')
args = parser.parse_args()
db = sqlite3.connect('euscan.db')
if not args.package:
args.package = [None]
for package in args.package:
if not args.skip_portage:
portage_scan(db, package)
if not args.skip_metadata:
metadata_scan(db, package)
upstream_scan(db, package)
db.close()
if __name__ == '__main__':
main()

View File

@ -1,54 +0,0 @@
CREATE TABLE IF NOT EXISTS "packages" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"category" TEXT NOT NULL,
"package" TEXT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS "packages_catpkg" ON packages (category, package);
CREATE TABLE IF NOT EXISTS "herds" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"herd" TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS "herds_herd" ON herds (herd);
CREATE TABLE IF NOT EXISTS "maintainers" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"maintainer" TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS "maintainers_maintainer" ON maintainers (maintainer);
CREATE TABLE IF NOT EXISTS "package_herds" (
"herd_id" INTEGER NOT NULL,
"package_id" INTEGER NOT NULL,
PRIMARY KEY("herd_id", "package_id")
);
CREATE TABLE IF NOT EXISTS "package_maintainers" (
"maintainer_id" INTEGER NOT NULL,
"package_id" INTEGER NOT NULL,
PRIMARY KEY("maintainer_id", "package_id")
);
CREATE TABLE IF NOT EXISTS "versions" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"package_id" INTEGER NOT NULL,
"slot" TEXT NOT NULL,
"revision" TEXT NOT NULL,
"version" TEXT NOT NULL,
"packaged" INTEGER NOT NULL DEFAULT (0)
);
CREATE INDEX IF NOT EXISTS "versions_packaged" on versions (package_id, packaged);
CREATE UNIQUE INDEX IF NOT EXISTS "versions_version" on versions (package_id, version, slot, revision);
CREATE TABLE IF NOT EXISTS "upstream_urls" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"version_id" INTEGER NOT NULL,
"url" TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS "upstream_version" on upstream_urls (version_id);
CREATE UNIQUE INDEX IF NOT EXISTS "upstream_unique_urls" on upstream_urls (version_id, url);

View File

@ -1,209 +0,0 @@
<?php echo '<?xml version="1.0" encoding="iso-8859-1"?>' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
<head>
<title>euscan</title>
<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="/style.css" media="screen" title="Normal" />
<script src="sorttable.js"></script>
</head>
<body>
<div id="header">
<h1>euscan</h1>
</div>
<div id="content">
<?php
$db = new SQLite3('euscan.db');
$act = isset($_GET['act']) ? $_GET['act'] : "home";
$cat = isset($_GET['cat']) ? $_GET['cat'] : '';
$pkg = isset($_GET['pkg']) ? $_GET['pkg'] : '';
$herd = isset($_GET['herd']) ? $_GET['herd'] : '';
$mtnr = isset($_GET['maintainer']) ? $_GET['maintainer'] : '';
if ($act == "home") {
} else if ($act == "categories") {
$sql = "SELECT category, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM packages JOIN versions ON package_id = packages.id";
$sql.= " GROUP BY category";
$results = $db->query($sql);
echo "<table class=\"sortable\"><tr><th>Category</th><th>Ebuilds</th><th>New versions</th></tr>";
while ($row = $results->fetchArray()) {
$new = $row['versions'] - $row['ebuilds'];
$color = $new == 0 ? 'green' : 'red';
echo "<tr>";
echo "<td><a href=\"?act=packages&amp;cat={$row['category']}\">{$row['category']}</a></td>";
echo "<td>{$row['ebuilds']}</td>";
echo "<td style=\"color: $color\">$new</td>";
echo "</tr>";
}
echo "</table>";
} else if ($act == "herds") {
$sql = "SELECT herd, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM herds";
$sql.= " JOIN package_herds ON herds.id = herd_id";
$sql.= " JOIN packages ON package_herds.package_id = packages.id";
$sql.= " JOIN versions ON versions.package_id = packages.id";
$sql.= " GROUP BY herd";
$results = $db->query($sql);
echo "<table class=\"sortable\"><tr><th>Herd</th><th>Ebuilds</th><th>New versions</th></tr>";
while ($row = $results->fetchArray()) {
$new = $row['versions'] - $row['ebuilds'];
$color = $new == 0 ? 'green' : 'red';
echo "<tr>";
echo "<td><a href=\"?act=packages&amp;herd={$row['herd']}\">{$row['herd']}</a></td>";
echo "<td>{$row['ebuilds']}</td>";
echo "<td style=\"color: $color\">$new</td>";
echo "</tr>";
}
echo "</table>";
} else if ($act == "maintainers") {
$sql = "SELECT maintainer, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM maintainers";
$sql.= " JOIN package_maintainers ON maintainers.id = maintainer_id";
$sql.= " JOIN packages ON package_maintainers.package_id = packages.id";
$sql.= " JOIN versions ON versions.package_id = packages.id";
$sql.= " GROUP BY maintainer";
$results = $db->query($sql);
echo "<table class=\"sortable\"><tr><th>Maintainer</th><th>Ebuilds</th><th>New versions</th></tr>";
while ($row = $results->fetchArray()) {
$new = $row['versions'] - $row['ebuilds'];
$color = $new == 0 ? 'green' : 'red';
echo "<tr>";
echo "<td><a href=\"?act=packages&amp;maintainer={$row['maintainer']}\">{$row['maintainer']}</a></td>";
echo "<td>{$row['ebuilds']}</td>";
echo "<td style=\"color: $color\">$new</td>";
echo "</tr>";
}
echo "</table>";
} else if ($act == "categories") {
$sql = "SELECT category, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM packages JOIN versions ON package_id = packages.id";
$sql.= " GROUP BY category";
$results = $db->query($sql);
echo "<table class=\"sortable\"><tr><th>Category</th><th>Ebuilds</th><th>New versions</th></tr>";
while ($row = $results->fetchArray()) {
$new = $row['versions'] - $row['ebuilds'];
$color = $new == 0 ? 'green' : 'red';
echo "<tr>";
echo "<td><a href=\"?act=packages&amp;cat={$row['category']}\">{$row['category']}</a></td>";
echo "<td>{$row['ebuilds']}</td>";
echo "<td style=\"color: $color\">$new</td>";
echo "</tr>";
}
echo "</table>";
} else if ($act == 'packages') {
$db_cat = $db->escapeString($cat);
$db_herd = $db->escapeString($herd);
$db_mtnr = $db->escapeString($mtnr);
if ($db_cat) {
$sql = "SELECT category, package, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM packages JOIN versions ON package_id = packages.id";
$sql.= " WHERE category = '$db_cat'";
$sql.= " GROUP BY category, package";
} else if ($db_herd) {
$sql = "SELECT category, package, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM herds";
$sql.= " JOIN package_herds ON herds.id = herd_id";
$sql.= " JOIN packages ON package_herds.package_id = packages.id";
$sql.= " JOIN versions ON versions.package_id = packages.id";
$sql.= " WHERE herd LIKE '$db_herd'";
$sql.= " GROUP BY category, package";
} else if ($db_mtnr) {
$sql = "SELECT category, package, COUNT(version) as versions, SUM(packaged) as ebuilds";
$sql.= " FROM maintainers";
$sql.= " JOIN package_maintainers ON maintainers.id = maintainer_id";
$sql.= " JOIN packages ON package_maintainers.package_id = packages.id";
$sql.= " JOIN versions ON versions.package_id = packages.id";
$sql.= " WHERE maintainer LIKE '%$db_mtnr%'";
$sql.= " GROUP BY category, package";
}
if ($sql) {
$results = $db->query($sql);
echo "<table class=\"sortable\"><tr><th>Category</th><th>Ebuilds</th><th>New versions</th></tr>";
while ($row = $results->fetchArray()) {
$new = $row['versions'] - $row['ebuilds'];
$catpkg = "{$row['category']}/{$row['package']}";
$color = $new == 0 ? 'green' : 'red';
echo "<tr>";
echo "<td><a href=\"?act=package&amp;pkg=$catpkg\">$catpkg</td>";
echo "<td>{$row['ebuilds']}</td>";
echo "<td style=\"color: $color\">$new</td>";
echo "</tr>";
}
echo "</table>";
}
} else if ($act == 'package') {
$pkg = explode("/", $pkg);
if (count($pkg) == 2) {
$cat = $db->escapeString($pkg[0]);
$pkg = $db->escapeString($pkg[1]);
} else {
$cat = $pkg = "";
}
$sql = "SELECT * FROM packages WHERE category = '$cat' AND package = '$pkg'";
$infos = $db->query($sql);
$infos = $infos->fetchArray();
if ($infos) {
echo "<h3>{$infos['category']}/${infos['package']}</h3>";
$sql = "SELECT * FROM versions WHERE package_id = ${infos['id']} AND packaged = 1";
$results = $db->query($sql);
echo '<h3>Packaged versions:</h3><ul>';
while ($version = $results->fetchArray()) {
echo "<li>${version['version']}-${version['revision']}:${version['slot']}</li>";
}
$sql = "SELECT * FROM versions ";
$sql.= "JOIN upstream_urls ON versions.id = version_id ";
$sql.= "WHERE package_id = ${infos['id']} AND packaged = 0";
$results = $db->query($sql);
echo '</ul>';
echo '<h3>Upstream versions:</h3><ul>';
while ($version = $results->fetchArray()) {
echo "<li>${version['version']} - ${version['url']}</li>";
}
echo '</ul>';
} else {
echo '<div class="error">Invalid package</div>';
}
}
?>
</div>
<div id="menus">
<div id="menu">
<ul>
<li><a href="?act=categories">Categories</a></li>
<li><a href="?act=herds">Herds</a></li>
<li><a href="?act=maintainers">Maintainers</a></li>
</div>
</div>
</div>
<div id="footer">
Powered by:
<a href="http://kernel.org"><img src="/linux.png" alt="Linux" /></a>
<a href="http://gentoo.org"><img src="/gentoo.png" alt="Gentoo Linux" /></a>
-
Copyright (C) 2011 <strong>Corentin Chary</strong>
</div>
</body>
</html>

View File

@ -1,493 +0,0 @@
/*
SortTable
version 2
7th April 2007
Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
Instructions:
Download this file
Add <script src="sorttable.js"></script> to your HTML
Add class="sortable" to any table you'd like to make sortable
Click on the headers to sort
Thanks to many, many people for contributions and suggestions.
Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
This basically means: do what you want with it.
*/
var stIsIE = /*@cc_on!@*/false;
sorttable = {
init: function() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
if (!document.createElement || !document.getElementsByTagName) return;
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
forEach(document.getElementsByTagName('table'), function(table) {
if (table.className.search(/\bsortable\b/) != -1) {
sorttable.makeSortable(table);
}
});
},
makeSortable: function(table) {
if (table.getElementsByTagName('thead').length == 0) {
// table doesn't have a tHead. Since it should have, create one and
// put the first table row in it.
the = document.createElement('thead');
the.appendChild(table.rows[0]);
table.insertBefore(the,table.firstChild);
}
// Safari doesn't support table.tHead, sigh
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
if (table.tHead.rows.length != 1) return; // can't cope with two header rows
// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
// "total" rows, for example). This is B&R, since what you're supposed
// to do is put them in a tfoot. So, if there are sortbottom rows,
// for backwards compatibility, move them to tfoot (creating it if needed).
sortbottomrows = [];
for (var i=0; i<table.rows.length; i++) {
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
sortbottomrows[sortbottomrows.length] = table.rows[i];
}
}
if (sortbottomrows) {
if (table.tFoot == null) {
// table doesn't have a tfoot. Create one.
tfo = document.createElement('tfoot');
table.appendChild(tfo);
}
for (var i=0; i<sortbottomrows.length; i++) {
tfo.appendChild(sortbottomrows[i]);
}
delete sortbottomrows;
}
// work through each column and calculate its type
headrow = table.tHead.rows[0].cells;
for (var i=0; i<headrow.length; i++) {
// manually override the type with a sorttable_type attribute
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
if (mtch) { override = mtch[1]; }
if (mtch && typeof sorttable["sort_"+override] == 'function') {
headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
} else {
headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
}
// make it clickable to sort
headrow[i].sorttable_columnindex = i;
headrow[i].sorttable_tbody = table.tBodies[0];
dean_addEvent(headrow[i],"click", function(e) {
if (this.className.search(/\bsorttable_sorted\b/) != -1) {
// if we're already sorted by this column, just
// reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted',
'sorttable_sorted_reverse');
this.removeChild(document.getElementById('sorttable_sortfwdind'));
sortrevind = document.createElement('span');
sortrevind.id = "sorttable_sortrevind";
sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
this.appendChild(sortrevind);
return;
}
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
// if we're already sorted by this column in reverse, just
// re-reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted_reverse',
'sorttable_sorted');
this.removeChild(document.getElementById('sorttable_sortrevind'));
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
this.appendChild(sortfwdind);
return;
}
// remove sorttable_sorted classes
theadrow = this.parentNode;
forEach(theadrow.childNodes, function(cell) {
if (cell.nodeType == 1) { // an element
cell.className = cell.className.replace('sorttable_sorted_reverse','');
cell.className = cell.className.replace('sorttable_sorted','');
}
});
sortfwdind = document.getElementById('sorttable_sortfwdind');
if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
sortrevind = document.getElementById('sorttable_sortrevind');
if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
this.className += ' sorttable_sorted';
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
this.appendChild(sortfwdind);
// build an array to sort. This is a Schwartzian transform thing,
// i.e., we "decorate" each row with the actual sort key,
// sort based on the sort keys, and then put the rows back in order
// which is a lot faster because you only do getInnerText once per row
row_array = [];
col = this.sorttable_columnindex;
rows = this.sorttable_tbody.rows;
for (var j=0; j<rows.length; j++) {
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
}
/* If you want a stable sort, uncomment the following line */
//sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
/* and comment out this one */
row_array.sort(this.sorttable_sortfunction);
tb = this.sorttable_tbody;
for (var j=0; j<row_array.length; j++) {
tb.appendChild(row_array[j][1]);
}
delete row_array;
});
}
}
},
guessType: function(table, column) {
// guess the type of a column based on its first non-blank row
sortfn = sorttable.sort_alpha;
for (var i=0; i<table.tBodies[0].rows.length; i++) {
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
if (text != '') {
if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
return sorttable.sort_numeric;
}
// check for a date: dd/mm/yyyy or dd/mm/yy
// can have / or . or - as separator
// can be mm/dd as well
possdate = text.match(sorttable.DATE_RE)
if (possdate) {
// looks like a date
first = parseInt(possdate[1]);
second = parseInt(possdate[2]);
if (first > 12) {
// definitely dd/mm
return sorttable.sort_ddmm;
} else if (second > 12) {
return sorttable.sort_mmdd;
} else {
// looks like a date, but we can't tell which, so assume
// that it's dd/mm (English imperialism!) and keep looking
sortfn = sorttable.sort_ddmm;
}
}
}
}
return sortfn;
},
getInnerText: function(node) {
// gets the text we want to use for sorting for a cell.
// strips leading and trailing whitespace.
// this is *not* a generic getInnerText function; it's special to sorttable.
// for example, you can override the cell text with a customkey attribute.
// it also gets .value for <input> fields.
hasInputs = (typeof node.getElementsByTagName == 'function') &&
node.getElementsByTagName('input').length;
if (node.getAttribute("sorttable_customkey") != null) {
return node.getAttribute("sorttable_customkey");
}
else if (typeof node.textContent != 'undefined' && !hasInputs) {
return node.textContent.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.innerText != 'undefined' && !hasInputs) {
return node.innerText.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.text != 'undefined' && !hasInputs) {
return node.text.replace(/^\s+|\s+$/g, '');
}
else {
switch (node.nodeType) {
case 3:
if (node.nodeName.toLowerCase() == 'input') {
return node.value.replace(/^\s+|\s+$/g, '');
}
case 4:
return node.nodeValue.replace(/^\s+|\s+$/g, '');
break;
case 1:
case 11:
var innerText = '';
for (var i = 0; i < node.childNodes.length; i++) {
innerText += sorttable.getInnerText(node.childNodes[i]);
}
return innerText.replace(/^\s+|\s+$/g, '');
break;
default:
return '';
}
}
},
reverse: function(tbody) {
// reverse the rows in a tbody
newrows = [];
for (var i=0; i<tbody.rows.length; i++) {
newrows[newrows.length] = tbody.rows[i];
}
for (var i=newrows.length-1; i>=0; i--) {
tbody.appendChild(newrows[i]);
}
delete newrows;
},
/* sort functions
each sort function takes two parameters, a and b
you are comparing a[0] and b[0] */
sort_numeric: function(a,b) {
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
if (isNaN(bb)) bb = 0;
return aa-bb;
},
sort_alpha: function(a,b) {
if (a[0]==b[0]) return 0;
if (a[0]<b[0]) return -1;
return 1;
},
sort_ddmm: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
sort_mmdd: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
shaker_sort: function(list, comp_func) {
// A stable sort function to allow multi-level sorting of data
// see: http://en.wikipedia.org/wiki/Cocktail_sort
// thanks to Joseph Nahmias
var b = 0;
var t = list.length - 1;
var swap = true;
while(swap) {
swap = false;
for(var i = b; i < t; ++i) {
if ( comp_func(list[i], list[i+1]) > 0 ) {
var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
swap = true;
}
} // for
t--;
if (!swap) break;
for(var i = t; i > b; --i) {
if ( comp_func(list[i], list[i-1]) < 0 ) {
var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
swap = true;
}
} // for
b++;
} // while(swap)
}
}
/* ******************************************************************
Supporting functions: bundled here to avoid depending on a library
****************************************************************** */
// Dean Edwards/Matthias Miller/John Resig
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", sorttable.init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
sorttable.init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
sorttable.init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = sorttable.init;
// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
function dean_addEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
// assign each event handler a unique ID
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
// create a hash table of event types for the element
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
// store the existing event handler (if there is one)
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// store the event handler in the hash table
handlers[handler.$$guid] = handler;
// assign a global event handler to do all the work
element["on" + type] = handleEvent;
}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;
function removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else {
// delete the event handler from the hash table
if (element.events && element.events[type]) {
delete element.events[type][handler.$$guid];
}
}
};
function handleEvent(event) {
var returnValue = true;
// grab the event object (IE uses a global event object)
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
// get a reference to the hash table of event handlers
var handlers = this.events[event.type];
// execute each event handler
for (var i in handlers) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
};
function fixEvent(event) {
// add W3C standard event methods
event.preventDefault = fixEvent.preventDefault;
event.stopPropagation = fixEvent.stopPropagation;
return event;
};
fixEvent.preventDefault = function() {
this.returnValue = false;
};
fixEvent.stopPropagation = function() {
this.cancelBubble = true;
}
// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
forEach, version 1.0
Copyright 2006, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
Array.forEach = function(array, block, context) {
for (var i = 0; i < array.length; i++) {
block.call(context, array[i], i, array);
}
};
}
// generic enumeration
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype[key] == "undefined") {
block.call(context, object[key], key, object);
}
}
};
// character enumeration
String.forEach = function(string, block, context) {
Array.forEach(string.split(""), function(chr, index) {
block.call(context, chr, index, string);
});
};
// globally resolve forEach enumeration
var forEach = function(object, block, context) {
if (object) {
var resolve = Object; // default
if (object instanceof Function) {
// functions have a "length" property
resolve = Function;
} else if (object.forEach instanceof Function) {
// the object implements a custom forEach method so use that
object.forEach(block, context);
return;
} else if (typeof object == "string") {
// the object is a string
resolve = String;
} else if (typeof object.length == "number") {
// the object is array-like
resolve = Array;
}
resolve.forEach(object, block, context);
}
};