remove all the DOS linefeeds

This commit is contained in:
Wookey 2011-07-11 02:10:22 +01:00
parent c8ff8e3ef6
commit dc1327674c
75 changed files with 6323 additions and 6323 deletions

View File

@ -1,39 +1,39 @@
Troggle is an application for caving expedition data management, originally created for use on Cambridge University Caving Club expeditions and licensed under the GNU Lesser General Public License. Troggle is an application for caving expedition data management, originally created for use on Cambridge University Caving Club expeditions and licensed under the GNU Lesser General Public License.
Troggle setup Troggle setup
========== ==========
Python, Django, and Database setup Python, Django, and Database setup
----------------------------------- -----------------------------------
Troggle requires Django 1.1 or greater, and any version of Python that works with it. As of writing this readme, there was no actual Django 1.1 release, so Troggle required the SVN version of Django. Check Django out to somewhere on your PYTHONPATH with the following command: Troggle requires Django 1.1 or greater, and any version of Python that works with it. As of writing this readme, there was no actual Django 1.1 release, so Troggle required the SVN version of Django. Check Django out to somewhere on your PYTHONPATH with the following command:
svn co http://code.djangoproject.com/svn/django/trunk/ svn co http://code.djangoproject.com/svn/django/trunk/
If you have an older installation of Django installed on your system, the easiest way to make sure troggle is using the newest version of Django is to simply checkout into your top troggle directory, into a folder called django. If you have an older installation of Django installed on your system, the easiest way to make sure troggle is using the newest version of Django is to simply checkout into your top troggle directory, into a folder called django.
If you want to use MySQL or Postgresql, download and install them. However, you can also use Django with Sqlite3, which is included in Python and thus requires no extra installation. If you want to use MySQL or Postgresql, download and install them. However, you can also use Django with Sqlite3, which is included in Python and thus requires no extra installation.
Troggle itself Troggle itself
------------- -------------
Choose a directory where you will keep troggle, and svn check out Troggle into it using the following command: Choose a directory where you will keep troggle, and svn check out Troggle into it using the following command:
svn co http://troggle.googlecode.com/svn/ svn co http://troggle.googlecode.com/svn/
If you want to work on the source code and be able to commit, you will need to use https instead of http, and your google account will need to be added to the troggle project members list. Contact aaron dot curtis at cantab dot net to get this set up. If you want to work on the source code and be able to commit, you will need to use https instead of http, and your google account will need to be added to the troggle project members list. Contact aaron dot curtis at cantab dot net to get this set up.
Next, you need to fill in your local settings. Copy either localsettingsubuntu.py or localsettingsserver.py to a new file called localsettings.py. Follow the instructions contained in the file to fill out your settings. Next, you need to fill in your local settings. Copy either localsettingsubuntu.py or localsettingsserver.py to a new file called localsettings.py. Follow the instructions contained in the file to fill out your settings.
Setting up tables and importing legacy data Setting up tables and importing legacy data
------------------------------------------ ------------------------------------------
Run "python databaseReset.py reset" from the troggle directory. Run "python databaseReset.py reset" from the troggle directory.
Once troggle is running, you can also log in and then go to "Import / export" data under "admin" on the menu. Once troggle is running, you can also log in and then go to "Import / export" data under "admin" on the menu.
Running a Troggle server Running a Troggle server
------------------------ ------------------------
For high volume use, Troggle should be run using a web server like apache. However, a quick way to get started is to use the development server built into Django. For high volume use, Troggle should be run using a web server like apache. However, a quick way to get started is to use the development server built into Django.
To do this, run "python manage.py runserver" from the troggle directory. To do this, run "python manage.py runserver" from the troggle directory.

View File

@ -1,141 +1,141 @@
from troggle.core.models import * from troggle.core.models import *
from django.contrib import admin from django.contrib import admin
from django.forms import ModelForm from django.forms import ModelForm
import django.forms as forms import django.forms as forms
from django.http import HttpResponse from django.http import HttpResponse
from django.core import serializers from django.core import serializers
from core.views_other import downloadLogbook from core.views_other import downloadLogbook
#from troggle.reversion.admin import VersionAdmin #django-reversion version control #from troggle.reversion.admin import VersionAdmin #django-reversion version control
class TroggleModelAdmin(admin.ModelAdmin): class TroggleModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change): def save_model(self, request, obj, form, change):
"""overriding admin save to fill the new_since parsing_field""" """overriding admin save to fill the new_since parsing_field"""
obj.new_since_parsing=True obj.new_since_parsing=True
obj.save() obj.save()
class Media: class Media:
js = ('js/jquery.js','js/QM_helper.js') js = ('js/jquery.js','js/QM_helper.js')
class RoleInline(admin.TabularInline): class RoleInline(admin.TabularInline):
model = SurvexPersonRole model = SurvexPersonRole
extra = 4 extra = 4
class SurvexBlockAdmin(TroggleModelAdmin): class SurvexBlockAdmin(TroggleModelAdmin):
inlines = (RoleInline,) inlines = (RoleInline,)
class ScannedImageInline(admin.TabularInline): class ScannedImageInline(admin.TabularInline):
model = ScannedImage model = ScannedImage
extra = 4 extra = 4
class OtherCaveInline(admin.TabularInline): class OtherCaveInline(admin.TabularInline):
model = OtherCaveName model = OtherCaveName
extra = 1 extra = 1
class SurveyAdmin(TroggleModelAdmin): class SurveyAdmin(TroggleModelAdmin):
inlines = (ScannedImageInline,) inlines = (ScannedImageInline,)
search_fields = ('expedition__year','wallet_number') search_fields = ('expedition__year','wallet_number')
class QMsFoundInline(admin.TabularInline): class QMsFoundInline(admin.TabularInline):
model=QM model=QM
fk_name='found_by' fk_name='found_by'
fields=('number','grade','location_description','comment')#need to add foreignkey to cave part fields=('number','grade','location_description','comment')#need to add foreignkey to cave part
extra=1 extra=1
class PhotoInline(admin.TabularInline): class PhotoInline(admin.TabularInline):
model = DPhoto model = DPhoto
exclude = ['is_mugshot' ] exclude = ['is_mugshot' ]
extra = 1 extra = 1
class PersonTripInline(admin.TabularInline): class PersonTripInline(admin.TabularInline):
model = PersonTrip model = PersonTrip
raw_id_fields = ('personexpedition',) raw_id_fields = ('personexpedition',)
extra = 1 extra = 1
#class LogbookEntryAdmin(VersionAdmin): #class LogbookEntryAdmin(VersionAdmin):
class LogbookEntryAdmin(TroggleModelAdmin): class LogbookEntryAdmin(TroggleModelAdmin):
prepopulated_fields = {'slug':("title",)} prepopulated_fields = {'slug':("title",)}
raw_id_fields = ('cave',) raw_id_fields = ('cave',)
search_fields = ('title','expedition__year') search_fields = ('title','expedition__year')
date_heirarchy = ('date') date_heirarchy = ('date')
inlines = (PersonTripInline, PhotoInline, QMsFoundInline) inlines = (PersonTripInline, PhotoInline, QMsFoundInline)
class Media: class Media:
css = { css = {
"all": ("css/troggleadmin.css",) "all": ("css/troggleadmin.css",)
} }
actions=('export_logbook_entries_as_html','export_logbook_entries_as_txt') actions=('export_logbook_entries_as_html','export_logbook_entries_as_txt')
def export_logbook_entries_as_html(modeladmin, request, queryset): def export_logbook_entries_as_html(modeladmin, request, queryset):
response=downloadLogbook(request=request, queryset=queryset, extension='html') response=downloadLogbook(request=request, queryset=queryset, extension='html')
return response return response
def export_logbook_entries_as_txt(modeladmin, request, queryset): def export_logbook_entries_as_txt(modeladmin, request, queryset):
response=downloadLogbook(request=request, queryset=queryset, extension='txt') response=downloadLogbook(request=request, queryset=queryset, extension='txt')
return response return response
class PersonExpeditionInline(admin.TabularInline): class PersonExpeditionInline(admin.TabularInline):
model = PersonExpedition model = PersonExpedition
extra = 1 extra = 1
class PersonAdmin(TroggleModelAdmin): class PersonAdmin(TroggleModelAdmin):
search_fields = ('first_name','last_name') search_fields = ('first_name','last_name')
inlines = (PersonExpeditionInline,) inlines = (PersonExpeditionInline,)
class QMAdmin(TroggleModelAdmin): class QMAdmin(TroggleModelAdmin):
search_fields = ('found_by__cave__kataster_number','number','found_by__date') search_fields = ('found_by__cave__kataster_number','number','found_by__date')
list_display = ('__unicode__','grade','found_by','ticked_off_by') list_display = ('__unicode__','grade','found_by','ticked_off_by')
list_display_links = ('__unicode__',) list_display_links = ('__unicode__',)
list_editable = ('found_by','ticked_off_by','grade') list_editable = ('found_by','ticked_off_by','grade')
list_per_page = 20 list_per_page = 20
raw_id_fields=('found_by','ticked_off_by') raw_id_fields=('found_by','ticked_off_by')
class PersonExpeditionAdmin(TroggleModelAdmin): class PersonExpeditionAdmin(TroggleModelAdmin):
search_fields = ('person__first_name','expedition__year') search_fields = ('person__first_name','expedition__year')
class CaveAdmin(TroggleModelAdmin): class CaveAdmin(TroggleModelAdmin):
search_fields = ('official_name','kataster_number','unofficial_number') search_fields = ('official_name','kataster_number','unofficial_number')
inlines = (OtherCaveInline,) inlines = (OtherCaveInline,)
extra = 4 extra = 4
class EntranceAdmin(TroggleModelAdmin): class EntranceAdmin(TroggleModelAdmin):
search_fields = ('caveandentrance__cave__kataster_number',) search_fields = ('caveandentrance__cave__kataster_number',)
admin.site.register(DPhoto) admin.site.register(DPhoto)
admin.site.register(Cave, CaveAdmin) admin.site.register(Cave, CaveAdmin)
admin.site.register(Area) admin.site.register(Area)
#admin.site.register(OtherCaveName) #admin.site.register(OtherCaveName)
admin.site.register(CaveAndEntrance) admin.site.register(CaveAndEntrance)
admin.site.register(NewSubCave) admin.site.register(NewSubCave)
admin.site.register(CaveDescription) admin.site.register(CaveDescription)
admin.site.register(Entrance, EntranceAdmin) admin.site.register(Entrance, EntranceAdmin)
admin.site.register(SurvexBlock, SurvexBlockAdmin) admin.site.register(SurvexBlock, SurvexBlockAdmin)
admin.site.register(Expedition) admin.site.register(Expedition)
admin.site.register(Person,PersonAdmin) admin.site.register(Person,PersonAdmin)
admin.site.register(SurvexPersonRole) admin.site.register(SurvexPersonRole)
admin.site.register(PersonExpedition,PersonExpeditionAdmin) admin.site.register(PersonExpedition,PersonExpeditionAdmin)
admin.site.register(LogbookEntry, LogbookEntryAdmin) admin.site.register(LogbookEntry, LogbookEntryAdmin)
#admin.site.register(PersonTrip) #admin.site.register(PersonTrip)
admin.site.register(QM, QMAdmin) admin.site.register(QM, QMAdmin)
admin.site.register(Survey, SurveyAdmin) admin.site.register(Survey, SurveyAdmin)
admin.site.register(ScannedImage) admin.site.register(ScannedImage)
admin.site.register(SurvexScansFolder) admin.site.register(SurvexScansFolder)
admin.site.register(SurvexScanSingle) admin.site.register(SurvexScanSingle)
def export_as_json(modeladmin, request, queryset): def export_as_json(modeladmin, request, queryset):
response = HttpResponse(mimetype="text/json") response = HttpResponse(mimetype="text/json")
response['Content-Disposition'] = 'attachment; filename=troggle_output.json' response['Content-Disposition'] = 'attachment; filename=troggle_output.json'
serializers.serialize("json", queryset, stream=response) serializers.serialize("json", queryset, stream=response)
return response return response
def export_as_xml(modeladmin, request, queryset): def export_as_xml(modeladmin, request, queryset):
response = HttpResponse(mimetype="text/xml") response = HttpResponse(mimetype="text/xml")
response['Content-Disposition'] = 'attachment; filename=troggle_output.xml' response['Content-Disposition'] = 'attachment; filename=troggle_output.xml'
serializers.serialize("xml", queryset, stream=response) serializers.serialize("xml", queryset, stream=response)
return response return response
#admin.site.add_action(export_as_xml) #admin.site.add_action(export_as_xml)
#admin.site.add_action(export_as_json) #admin.site.add_action(export_as_json)

View File

@ -1,121 +1,121 @@
from django.forms import ModelForm from django.forms import ModelForm
from models import Cave, Person, PersonExpedition, LogbookEntry, QM, Expedition from models import Cave, Person, PersonExpedition, LogbookEntry, QM, Expedition
import django.forms as forms import django.forms as forms
from django.forms.formsets import formset_factory from django.forms.formsets import formset_factory
from django.contrib.admin.widgets import AdminDateWidget from django.contrib.admin.widgets import AdminDateWidget
import string import string
from datetime import date from datetime import date
from tinymce.widgets import TinyMCE from tinymce.widgets import TinyMCE
#class CaveForm(ModelForm): #class CaveForm(ModelForm):
# class Meta: # class Meta:
# model = Cave # model = Cave
#class PersonForm(ModelForm): #class PersonForm(ModelForm):
# class Meta: # class Meta:
# model = Person # model = Person
#class LogbookEntryForm(ModelForm): #class LogbookEntryForm(ModelForm):
# class Meta: # class Meta:
# model = LogbookEntry# # model = LogbookEntry#
# def wikiLinkHints(LogbookEntry=None): # def wikiLinkHints(LogbookEntry=None):
# """ # """
# This function returns html-formatted paragraphs for each of the # This function returns html-formatted paragraphs for each of the
# wikilink types that are related to this logbookentry. Each paragraph # wikilink types that are related to this logbookentry. Each paragraph
# contains a list of all of the related wikilinks. # contains a list of all of the related wikilinks.
# #
# Perhaps an admin javascript solution would be better. # Perhaps an admin javascript solution would be better.
# """ # """
# res = ["Please use the following wikilinks, which are related to this logbook entry:"] # res = ["Please use the following wikilinks, which are related to this logbook entry:"]
# #
# res.append(r'</p><p style="float: left;"><b>QMs found:</b>') # res.append(r'</p><p style="float: left;"><b>QMs found:</b>')
# for QM in LogbookEntry.instance.QMs_found.all(): # for QM in LogbookEntry.instance.QMs_found.all():
# res.append(QM.wiki_link()) # res.append(QM.wiki_link())
# res.append(r'</p><p style="float: left;"><b>QMs ticked off:</b>') # res.append(r'</p><p style="float: left;"><b>QMs ticked off:</b>')
# for QM in LogbookEntry.instance.QMs_ticked_off.all(): # for QM in LogbookEntry.instance.QMs_ticked_off.all():
# res.append(QM.wiki_link()) # res.append(QM.wiki_link())
# res.append(r'</p><p style="float: left; "><b>People</b>') # res.append(r'</p><p style="float: left; "><b>People</b>')
# for persontrip in LogbookEntry.instance.persontrip_set.all(): # for persontrip in LogbookEntry.instance.persontrip_set.all():
# res.append(persontrip.wiki_link()) # res.append(persontrip.wiki_link())
# res.append(r'</p>') # res.append(r'</p>')
# return string.join(res, r'<br />') # return string.join(res, r'<br />')
# def __init__(self, *args, **kwargs): # def __init__(self, *args, **kwargs):
# super(LogbookEntryForm, self).__init__(*args, **kwargs) # super(LogbookEntryForm, self).__init__(*args, **kwargs)
# self.fields['text'].help_text=self.wikiLinkHints()# # self.fields['text'].help_text=self.wikiLinkHints()#
class CaveForm(forms.Form): class CaveForm(forms.Form):
html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
def getTripForm(expedition): def getTripForm(expedition):
class TripForm(forms.Form): class TripForm(forms.Form):
date = forms.DateField() date = forms.DateField()
title = forms.CharField(max_length=200) title = forms.CharField(max_length=200)
caves = [cave.reference() for cave in Cave.objects.all()] caves = [cave.reference() for cave in Cave.objects.all()]
caves.sort() caves.sort()
caves = ["-----"] + caves caves = ["-----"] + caves
cave = forms.ChoiceField([(c, c) for c in caves], required=False) cave = forms.ChoiceField([(c, c) for c in caves], required=False)
location = forms.CharField(max_length=200, required=False) location = forms.CharField(max_length=200, required=False)
caveOrLocation = forms.ChoiceField([("cave", "Cave"), ("location", "Location")], widget = forms.widgets.RadioSelect()) caveOrLocation = forms.ChoiceField([("cave", "Cave"), ("location", "Location")], widget = forms.widgets.RadioSelect())
html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
def clean(self): def clean(self):
print dir(self) print dir(self)
if self.cleaned_data.get("caveOrLocation") == "cave" and not self.cleaned_data.get("cave"): if self.cleaned_data.get("caveOrLocation") == "cave" and not self.cleaned_data.get("cave"):
self._errors["cave"] = self.error_class(["This field is required"]) self._errors["cave"] = self.error_class(["This field is required"])
if self.cleaned_data.get("caveOrLocation") == "location" and not self.cleaned_data.get("location"): if self.cleaned_data.get("caveOrLocation") == "location" and not self.cleaned_data.get("location"):
self._errors["location"] = self.error_class(["This field is required"]) self._errors["location"] = self.error_class(["This field is required"])
return self.cleaned_data return self.cleaned_data
class PersonTripForm(forms.Form): class PersonTripForm(forms.Form):
names = [get_name(pe) for pe in PersonExpedition.objects.filter(expedition = expedition)] names = [get_name(pe) for pe in PersonExpedition.objects.filter(expedition = expedition)]
names.sort() names.sort()
names = ["-----"] + names names = ["-----"] + names
name = forms.ChoiceField([(n, n) for n in names]) name = forms.ChoiceField([(n, n) for n in names])
TU = forms.FloatField(required=False) TU = forms.FloatField(required=False)
author = forms.BooleanField(required=False) author = forms.BooleanField(required=False)
PersonTripFormSet = formset_factory(PersonTripForm, extra=1) PersonTripFormSet = formset_factory(PersonTripForm, extra=1)
return PersonTripFormSet, TripForm return PersonTripFormSet, TripForm
def get_name(pe): def get_name(pe):
if pe.nickname: if pe.nickname:
return pe.nickname return pe.nickname
else: else:
return pe.person.first_name return pe.person.first_name
class UploadFileForm(forms.Form): class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50) title = forms.CharField(max_length=50)
file = forms.FileField() file = forms.FileField()
html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) html = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
lon_utm = forms.FloatField(required=False) lon_utm = forms.FloatField(required=False)
lat_utm = forms.FloatField(required=False) lat_utm = forms.FloatField(required=False)
slug = forms.CharField(max_length=50) slug = forms.CharField(max_length=50)
date = forms.DateField(required=False) date = forms.DateField(required=False)
caves = [cave.slug for cave in Cave.objects.all()] caves = [cave.slug for cave in Cave.objects.all()]
caves.sort() caves.sort()
caves = ["-----"] + caves caves = ["-----"] + caves
cave = forms.ChoiceField([(c, c) for c in caves], required=False) cave = forms.ChoiceField([(c, c) for c in caves], required=False)
entrance = forms.ChoiceField([("-----", "Please select a cave"), ], required=False) entrance = forms.ChoiceField([("-----", "Please select a cave"), ], required=False)
qm = forms.ChoiceField([("-----", "Please select a cave"), ], required=False) qm = forms.ChoiceField([("-----", "Please select a cave"), ], required=False)
expeditions = [e.year for e in Expedition.objects.all()] expeditions = [e.year for e in Expedition.objects.all()]
expeditions.sort() expeditions.sort()
expeditions = ["-----"] + expeditions expeditions = ["-----"] + expeditions
expedition = forms.ChoiceField([(e, e) for e in expeditions], required=False) expedition = forms.ChoiceField([(e, e) for e in expeditions], required=False)
logbookentry = forms.ChoiceField([("-----", "Please select an expedition"), ], required=False) logbookentry = forms.ChoiceField([("-----", "Please select an expedition"), ], required=False)
person = forms.ChoiceField([("-----", "Please select an expedition"), ], required=False) person = forms.ChoiceField([("-----", "Please select an expedition"), ], required=False)
survey_point = forms.CharField() survey_point = forms.CharField()

File diff suppressed because it is too large Load Diff

View File

@ -1,213 +1,213 @@
from django.db import models from django.db import models
from django.conf import settings from django.conf import settings
import os import os
import urlparse import urlparse
import re import re
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
########################################################### ###########################################################
# These will allow browsing and editing of the survex data # These will allow browsing and editing of the survex data
########################################################### ###########################################################
# Needs to add: # Needs to add:
# Equates # Equates
# reloading # reloading
class SurvexDirectory(models.Model): class SurvexDirectory(models.Model):
path = models.CharField(max_length=200) path = models.CharField(max_length=200)
cave = models.ForeignKey('Cave', blank=True, null=True) cave = models.ForeignKey('Cave', blank=True, null=True)
primarysurvexfile = models.ForeignKey('SurvexFile', related_name='primarysurvexfile', blank=True, null=True) primarysurvexfile = models.ForeignKey('SurvexFile', related_name='primarysurvexfile', blank=True, null=True)
# could also include files in directory but not referenced # could also include files in directory but not referenced
class Meta: class Meta:
ordering = ('id',) ordering = ('id',)
class SurvexFile(models.Model): class SurvexFile(models.Model):
path = models.CharField(max_length=200) path = models.CharField(max_length=200)
survexdirectory = models.ForeignKey("SurvexDirectory", blank=True, null=True) survexdirectory = models.ForeignKey("SurvexDirectory", blank=True, null=True)
cave = models.ForeignKey('Cave', blank=True, null=True) cave = models.ForeignKey('Cave', blank=True, null=True)
class Meta: class Meta:
ordering = ('id',) ordering = ('id',)
def exists(self): def exists(self):
fname = os.path.join(settings.SURVEX_DATA, self.path + ".svx") fname = os.path.join(settings.SURVEX_DATA, self.path + ".svx")
return os.path.isfile(fname) return os.path.isfile(fname)
def OpenFile(self): def OpenFile(self):
fname = os.path.join(settings.SURVEX_DATA, self.path + ".svx") fname = os.path.join(settings.SURVEX_DATA, self.path + ".svx")
return open(fname) return open(fname)
def SetDirectory(self): def SetDirectory(self):
dirpath = os.path.split(self.path)[0] dirpath = os.path.split(self.path)[0]
survexdirectorylist = SurvexDirectory.objects.filter(cave=self.cave, path=dirpath) survexdirectorylist = SurvexDirectory.objects.filter(cave=self.cave, path=dirpath)
if survexdirectorylist: if survexdirectorylist:
self.survexdirectory = survexdirectorylist[0] self.survexdirectory = survexdirectorylist[0]
else: else:
survexdirectory = SurvexDirectory(path=dirpath, cave=self.cave, primarysurvexfile=self) survexdirectory = SurvexDirectory(path=dirpath, cave=self.cave, primarysurvexfile=self)
survexdirectory.save() survexdirectory.save()
self.survexdirectory = survexdirectory self.survexdirectory = survexdirectory
self.save() self.save()
class SurvexEquate(models.Model): class SurvexEquate(models.Model):
cave = models.ForeignKey('Cave', blank=True, null=True) cave = models.ForeignKey('Cave', blank=True, null=True)
class SurvexStationLookUpManager(models.Manager): class SurvexStationLookUpManager(models.Manager):
def lookup(self, name): def lookup(self, name):
blocknames, sep, stationname = name.rpartition(".") blocknames, sep, stationname = name.rpartition(".")
return self.get(block = SurvexBlock.objects.lookup(blocknames), return self.get(block = SurvexBlock.objects.lookup(blocknames),
name = stationname) name = stationname)
class SurvexStation(models.Model): class SurvexStation(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
block = models.ForeignKey('SurvexBlock') block = models.ForeignKey('SurvexBlock')
equate = models.ForeignKey('SurvexEquate', blank=True, null=True) equate = models.ForeignKey('SurvexEquate', blank=True, null=True)
objects = SurvexStationLookUpManager() objects = SurvexStationLookUpManager()
x = models.FloatField(blank=True, null=True) x = models.FloatField(blank=True, null=True)
y = models.FloatField(blank=True, null=True) y = models.FloatField(blank=True, null=True)
z = models.FloatField(blank=True, null=True) z = models.FloatField(blank=True, null=True)
class SurvexLeg(models.Model): class SurvexLeg(models.Model):
block = models.ForeignKey('SurvexBlock') block = models.ForeignKey('SurvexBlock')
#title = models.ForeignKey('SurvexTitle') #title = models.ForeignKey('SurvexTitle')
stationfrom = models.ForeignKey('SurvexStation', related_name='stationfrom') stationfrom = models.ForeignKey('SurvexStation', related_name='stationfrom')
stationto = models.ForeignKey('SurvexStation', related_name='stationto') stationto = models.ForeignKey('SurvexStation', related_name='stationto')
tape = models.FloatField() tape = models.FloatField()
compass = models.FloatField() compass = models.FloatField()
clino = models.FloatField() clino = models.FloatField()
# #
# Single SurvexBlock # Single SurvexBlock
# #
class SurvexBlockLookUpManager(models.Manager): class SurvexBlockLookUpManager(models.Manager):
def lookup(self, name): def lookup(self, name):
blocknames = name.split(".") blocknames = name.split(".")
block = SurvexBlock.objects.get(parent=None, survexfile__path="all") block = SurvexBlock.objects.get(parent=None, survexfile__path="all")
for blockname in blocknames: for blockname in blocknames:
block = SurvexBlock.objects.get(parent=block, name=blockname) block = SurvexBlock.objects.get(parent=block, name=blockname)
return block return block
class SurvexBlock(models.Model): class SurvexBlock(models.Model):
objects = SurvexBlockLookUpManager() objects = SurvexBlockLookUpManager()
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
parent = models.ForeignKey('SurvexBlock', blank=True, null=True) parent = models.ForeignKey('SurvexBlock', blank=True, null=True)
text = models.TextField() text = models.TextField()
cave = models.ForeignKey('Cave', blank=True, null=True) cave = models.ForeignKey('Cave', blank=True, null=True)
date = models.DateField(blank=True, null=True) date = models.DateField(blank=True, null=True)
expeditionday = models.ForeignKey("ExpeditionDay", null=True) expeditionday = models.ForeignKey("ExpeditionDay", null=True)
expedition = models.ForeignKey('Expedition', blank=True, null=True) expedition = models.ForeignKey('Expedition', blank=True, null=True)
survexfile = models.ForeignKey("SurvexFile", blank=True, null=True) survexfile = models.ForeignKey("SurvexFile", blank=True, null=True)
begin_char = models.IntegerField() # code for where in the survex data files this block sits begin_char = models.IntegerField() # code for where in the survex data files this block sits
survexpath = models.CharField(max_length=200) # the path for the survex stations survexpath = models.CharField(max_length=200) # the path for the survex stations
survexscansfolder = models.ForeignKey("SurvexScansFolder", null=True) survexscansfolder = models.ForeignKey("SurvexScansFolder", null=True)
#refscandir = models.CharField(max_length=100) #refscandir = models.CharField(max_length=100)
totalleglength = models.FloatField() totalleglength = models.FloatField()
class Meta: class Meta:
ordering = ('id',) ordering = ('id',)
def isSurvexBlock(self): # Function used in templates def isSurvexBlock(self): # Function used in templates
return True return True
def __unicode__(self): def __unicode__(self):
return self.name and unicode(self.name) or 'no name' return self.name and unicode(self.name) or 'no name'
def GetPersonroles(self): def GetPersonroles(self):
res = [ ] res = [ ]
for personrole in self.personrole_set.order_by('personexpedition'): for personrole in self.personrole_set.order_by('personexpedition'):
if res and res[-1]['person'] == personrole.personexpedition.person: if res and res[-1]['person'] == personrole.personexpedition.person:
res[-1]['roles'] += ", " + str(personrole.role) res[-1]['roles'] += ", " + str(personrole.role)
else: else:
res.append({'person':personrole.personexpedition.person, 'expeditionyear':personrole.personexpedition.expedition.year, 'roles':str(personrole.role)}) res.append({'person':personrole.personexpedition.person, 'expeditionyear':personrole.personexpedition.expedition.year, 'roles':str(personrole.role)})
return res return res
def MakeSurvexStation(self, name): def MakeSurvexStation(self, name):
ssl = self.survexstation_set.filter(name=name) ssl = self.survexstation_set.filter(name=name)
if ssl: if ssl:
assert len(ssl) == 1 assert len(ssl) == 1
return ssl[0] return ssl[0]
ss = SurvexStation(name=name, block=self) ss = SurvexStation(name=name, block=self)
ss.save() ss.save()
return ss return ss
def DayIndex(self): def DayIndex(self):
return list(self.expeditionday.survexblock_set.all()).index(self) return list(self.expeditionday.survexblock_set.all()).index(self)
class SurvexTitle(models.Model): class SurvexTitle(models.Model):
survexblock = models.ForeignKey('SurvexBlock') survexblock = models.ForeignKey('SurvexBlock')
title = models.CharField(max_length=200) title = models.CharField(max_length=200)
cave = models.ForeignKey('Cave', blank=True, null=True) cave = models.ForeignKey('Cave', blank=True, null=True)
# #
# member of a SurvexBlock # member of a SurvexBlock
# #
ROLE_CHOICES = ( ROLE_CHOICES = (
('insts','Instruments'), ('insts','Instruments'),
('dog','Other'), ('dog','Other'),
('notes','Notes'), ('notes','Notes'),
('pics','Pictures'), ('pics','Pictures'),
('tape','Tape measure'), ('tape','Tape measure'),
('useless','Useless'), ('useless','Useless'),
('helper','Helper'), ('helper','Helper'),
('disto','Disto'), ('disto','Disto'),
('consultant','Consultant'), ('consultant','Consultant'),
) )
class SurvexPersonRole(models.Model): class SurvexPersonRole(models.Model):
survexblock = models.ForeignKey('SurvexBlock') survexblock = models.ForeignKey('SurvexBlock')
nrole = models.CharField(choices=ROLE_CHOICES, max_length=200, blank=True, null=True) nrole = models.CharField(choices=ROLE_CHOICES, max_length=200, blank=True, null=True)
# increasing levels of precision # increasing levels of precision
personname = models.CharField(max_length=100) personname = models.CharField(max_length=100)
person = models.ForeignKey('Person', blank=True, null=True) person = models.ForeignKey('Person', blank=True, null=True)
personexpedition = models.ForeignKey('PersonExpedition', blank=True, null=True) personexpedition = models.ForeignKey('PersonExpedition', blank=True, null=True)
persontrip = models.ForeignKey('PersonTrip', blank=True, null=True) persontrip = models.ForeignKey('PersonTrip', blank=True, null=True)
expeditionday = models.ForeignKey("ExpeditionDay", null=True) expeditionday = models.ForeignKey("ExpeditionDay", null=True)
def __unicode__(self): def __unicode__(self):
return unicode(self.person) + " - " + unicode(self.survexblock) + " - " + unicode(self.nrole) return unicode(self.person) + " - " + unicode(self.survexblock) + " - " + unicode(self.nrole)
class SurvexScansFolder(models.Model): class SurvexScansFolder(models.Model):
fpath = models.CharField(max_length=200) fpath = models.CharField(max_length=200)
walletname = models.CharField(max_length=200) walletname = models.CharField(max_length=200)
class Meta: class Meta:
ordering = ('walletname',) ordering = ('walletname',)
def get_absolute_url(self): def get_absolute_url(self):
return urlparse.urljoin(settings.URL_ROOT, reverse('surveyscansfolder', kwargs={"path":re.sub("#", "%23", self.walletname)})) return urlparse.urljoin(settings.URL_ROOT, reverse('surveyscansfolder', kwargs={"path":re.sub("#", "%23", self.walletname)}))
class SurvexScanSingle(models.Model): class SurvexScanSingle(models.Model):
ffile = models.CharField(max_length=200) ffile = models.CharField(max_length=200)
name = models.CharField(max_length=200) name = models.CharField(max_length=200)
survexscansfolder = models.ForeignKey("SurvexScansFolder", null=True) survexscansfolder = models.ForeignKey("SurvexScansFolder", null=True)
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
def get_absolute_url(self): def get_absolute_url(self):
return urlparse.urljoin(settings.URL_ROOT, reverse('surveyscansingle', kwargs={"path":re.sub("#", "%23", self.survexscansfolder.walletname), "file":self.name})) return urlparse.urljoin(settings.URL_ROOT, reverse('surveyscansingle', kwargs={"path":re.sub("#", "%23", self.survexscansfolder.walletname), "file":self.name}))
class TunnelFile(models.Model): class TunnelFile(models.Model):
tunnelpath = models.CharField(max_length=200) tunnelpath = models.CharField(max_length=200)
tunnelname = models.CharField(max_length=200) tunnelname = models.CharField(max_length=200)
bfontcolours = models.BooleanField() bfontcolours = models.BooleanField()
survexscansfolders = models.ManyToManyField("SurvexScansFolder") survexscansfolders = models.ManyToManyField("SurvexScansFolder")
survexscans = models.ManyToManyField("SurvexScanSingle") survexscans = models.ManyToManyField("SurvexScanSingle")
survexblocks = models.ManyToManyField("SurvexBlock") survexblocks = models.ManyToManyField("SurvexBlock")
tunnelcontains = models.ManyToManyField("TunnelFile") # case when its a frame type tunnelcontains = models.ManyToManyField("TunnelFile") # case when its a frame type
filesize = models.IntegerField(default=0) filesize = models.IntegerField(default=0)
npaths = models.IntegerField(default=0) npaths = models.IntegerField(default=0)
survextitles = models.ManyToManyField("SurvexTitle") survextitles = models.ManyToManyField("SurvexTitle")
class Meta: class Meta:
ordering = ('tunnelpath',) ordering = ('tunnelpath',)

View File

@ -1,9 +1,9 @@
from django import template from django import template
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
register = template.Library() register = template.Library()
@register.filter() @register.filter()
def link(value): def link(value):
return mark_safe("<a href=\'%s\'>"%value.get_absolute_url()+unicode(value)+"</a>") return mark_safe("<a href=\'%s\'>"%value.get_absolute_url()+unicode(value)+"</a>")

View File

@ -1,52 +1,52 @@
from django import template from django import template
from django.utils.html import conditional_escape from django.utils.html import conditional_escape
from django.template.defaultfilters import stringfilter from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
import re import re
register = template.Library() register = template.Library()
# seems to add extra lines between the commented lines, which isn't so great. # seems to add extra lines between the commented lines, which isn't so great.
regexes = [] regexes = []
regexes.append((re.compile(r"(;.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"(;.*)$", re.IGNORECASE|re.MULTILINE),
r'<span class = "comment">\1</span>\n')) r'<span class = "comment">\1</span>\n'))
regexes.append((re.compile(r"^(\s*)(\*include)(\s+)([^\s]*)(.svx)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*include)(\s+)([^\s]*)(.svx)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3<a href="\4.index">\4\5</a>')) r'\1<span class = "command">\2</span>\3<a href="\4.index">\4\5</a>'))
regexes.append((re.compile(r"^(\s*)(\*include)(\s+)([^\s]*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*include)(\s+)([^\s]*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3<a href="\4.index">\4</a>')) r'\1<span class = "command">\2</span>\3<a href="\4.index">\4</a>'))
regexes.append((re.compile(r"^(\s*)(\*team\s+(?:notes|tape|insts|pics))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*team\s+(?:notes|tape|insts|pics))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*(?:begin|end|copyright|date|entrance|equate|export|fix|prefix|require|SOLVE|title|truncate))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*(?:begin|end|copyright|date|entrance|equate|export|fix|prefix|require|SOLVE|title|truncate))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*calibrate\s+(?:TAPE|COMPASS|CLINO|COUNTER|DEPTH|DECLINATION|X|Y|Z)+)(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*calibrate\s+(?:TAPE|COMPASS|CLINO|COUNTER|DEPTH|DECLINATION|X|Y|Z)+)(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*data\s+(?:DEFAULT|NORMAL|DIVING|CARTESIAN|TOPOFIL|CYLPOLAR|NOSURVEY|passage)(?:\s+station|\s+from|\s+to|\s+FROMDEPTH|\s+TODEPTH|\s+DEPTHCHANGE|\s+newline|\s+direction|\s+tape|\s+compass|\s+clino|\s+northing|\s+easting|\s+altitude|\s+length|\s+bearing|\s+gradient|\s+ignoreall|\sleft|\sright|\sup|\sdown)*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*data\s+(?:DEFAULT|NORMAL|DIVING|CARTESIAN|TOPOFIL|CYLPOLAR|NOSURVEY|passage)(?:\s+station|\s+from|\s+to|\s+FROMDEPTH|\s+TODEPTH|\s+DEPTHCHANGE|\s+newline|\s+direction|\s+tape|\s+compass|\s+clino|\s+northing|\s+easting|\s+altitude|\s+length|\s+bearing|\s+gradient|\s+ignoreall|\sleft|\sright|\sup|\sdown)*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>')) r'\1<span class = "command">\2</span>'))
regexes.append((re.compile(r"^(\s*)(\*default\s+(?:CALIBRATE|DATA|UNITS)+)(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*default\s+(?:CALIBRATE|DATA|UNITS)+)(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*flags\s+(?:DUPLICATE|SPLAY|SURFACE|not DUPLICATE|not SPLAY|not SURFACE))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*flags\s+(?:DUPLICATE|SPLAY|SURFACE|not DUPLICATE|not SPLAY|not SURFACE))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*infer\s+(?:plumbs|equates|exports))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*infer\s+(?:plumbs|equates|exports))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*instrument\s+(?:compass|clino|tape))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*instrument\s+(?:compass|clino|tape))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*instrument\s+(?:compass|clino|tape))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*instrument\s+(?:compass|clino|tape))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*sd\s+(?:TAPE|COMPASS|CLINO|COUNTER|DEPTH|DECLINATION|DX|DY|DZ))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*sd\s+(?:TAPE|COMPASS|CLINO|COUNTER|DEPTH|DECLINATION|DX|DY|DZ))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*set\s+(?:BLANK|COMMENT|DECIMAL|EOL|KEYWORD|MINUS|NAMES|OMIT|PLUS|ROOT|SEPARATOR))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*set\s+(?:BLANK|COMMENT|DECIMAL|EOL|KEYWORD|MINUS|NAMES|OMIT|PLUS|ROOT|SEPARATOR))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(\s*)(\*units\s+(?:TAPE|LENGTH|COMPASS|BEARING|CLINO|GRADIENT|COUNTER|DEPTH|DECLINATION|X|Y|Z))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(\s*)(\*units\s+(?:TAPE|LENGTH|COMPASS|BEARING|CLINO|GRADIENT|COUNTER|DEPTH|DECLINATION|X|Y|Z))(\s+)(.*)$", re.IGNORECASE|re.MULTILINE),
r'\1<span class = "command">\2</span>\3\4')) r'\1<span class = "command">\2</span>\3\4'))
regexes.append((re.compile(r"^(.*)$", re.IGNORECASE|re.MULTILINE), regexes.append((re.compile(r"^(.*)$", re.IGNORECASE|re.MULTILINE),
r'<div>\1&nbsp;</div>\n')) r'<div>\1&nbsp;</div>\n'))
@register.filter() @register.filter()
@stringfilter @stringfilter
def survex_to_html(value, autoescape=None): def survex_to_html(value, autoescape=None):
if autoescape: if autoescape:
value = conditional_escape(value) value = conditional_escape(value)
for regex, sub in regexes: for regex, sub in regexes:
print sub print sub
value = regex.sub(sub, value) value = regex.sub(sub, value)
return mark_safe(value) return mark_safe(value)

View File

@ -1,169 +1,169 @@
from django import template from django import template
from django.utils.html import conditional_escape from django.utils.html import conditional_escape
from django.template.defaultfilters import stringfilter from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.conf import settings from django.conf import settings
from core.models import QM, DPhoto, LogbookEntry, Cave from core.models import QM, DPhoto, LogbookEntry, Cave
import re, urlparse import re, urlparse
register = template.Library() register = template.Library()
@register.filter() @register.filter()
def plusone(n): def plusone(n):
return n + 1 return n + 1
def wiki_list(line, listdepth): def wiki_list(line, listdepth):
l = "" l = ""
for d in listdepth: for d in listdepth:
l += d l += d
mstar = re.match(l + "\*(.*)", line) mstar = re.match(l + "\*(.*)", line)
if mstar: if mstar:
listdepth.append("\*") listdepth.append("\*")
return ("<ul>\n" + " " * len(listdepth) + "<li>%s</li>\n" % mstar.groups()[0], listdepth) return ("<ul>\n" + " " * len(listdepth) + "<li>%s</li>\n" % mstar.groups()[0], listdepth)
mhash = re.match(l + "#(.*)", line) mhash = re.match(l + "#(.*)", line)
if mhash: if mhash:
listdepth.append("#") listdepth.append("#")
return ("<ol>\n" + " " * len(listdepth) + "<li>%s</li>\n" % mhash.groups()[0], listdepth) return ("<ol>\n" + " " * len(listdepth) + "<li>%s</li>\n" % mhash.groups()[0], listdepth)
mflat = re.match(l + "(.*)", line) mflat = re.match(l + "(.*)", line)
if mflat and listdepth: if mflat and listdepth:
return (" " * len(listdepth) + "<li>%s</li>\n" % mflat.groups()[0], listdepth) return (" " * len(listdepth) + "<li>%s</li>\n" % mflat.groups()[0], listdepth)
if listdepth: if listdepth:
prev = listdepth.pop() prev = listdepth.pop()
if prev == "\*": if prev == "\*":
t, l = wiki_list(line, listdepth) t, l = wiki_list(line, listdepth)
return ("</ul>\n" + t, l) return ("</ul>\n" + t, l)
if prev == "#": if prev == "#":
t, l = wiki_list(line, listdepth) t, l = wiki_list(line, listdepth)
return ("</ol>\n" + t, l) return ("</ol>\n" + t, l)
return (line, listdepth) return (line, listdepth)
@register.filter() @register.filter()
@stringfilter @stringfilter
def wiki_to_html(value, autoescape=None): def wiki_to_html(value, autoescape=None):
""" """
This is the tag which turns wiki syntax into html. It is intended for long pieces of wiki. This is the tag which turns wiki syntax into html. It is intended for long pieces of wiki.
Hence it splits the wiki into HTML paragraphs based on double line feeds. Hence it splits the wiki into HTML paragraphs based on double line feeds.
""" """
#find paragraphs #find paragraphs
outValue = "" outValue = ""
for paragraph in re.split("\n\s*?\n", value, re.DOTALL): for paragraph in re.split("\n\s*?\n", value, re.DOTALL):
outValue += "<p>" outValue += "<p>"
outValue += wiki_to_html_short(paragraph, autoescape) outValue += wiki_to_html_short(paragraph, autoescape)
outValue += "</p>\n" outValue += "</p>\n"
return mark_safe(outValue) return mark_safe(outValue)
@register.filter() @register.filter()
@stringfilter @stringfilter
def wiki_to_html_short(value, autoescape=None): def wiki_to_html_short(value, autoescape=None):
""" """
This is the tag which turns wiki syntax into html. It is intended for short pieces of wiki. This is the tag which turns wiki syntax into html. It is intended for short pieces of wiki.
Hence it is not split the wiki into paragraphs using where it finds double line feeds. Hence it is not split the wiki into paragraphs using where it finds double line feeds.
""" """
if autoescape: if autoescape:
value = conditional_escape(value) value = conditional_escape(value)
#deescape doubly escaped characters #deescape doubly escaped characters
value = re.sub("&amp;(.*?);", r"&\1;", value, re.DOTALL) value = re.sub("&amp;(.*?);", r"&\1;", value, re.DOTALL)
#italics and bold #italics and bold
value = re.sub("&#39;&#39;&#39;&#39;([^']+)&#39;&#39;&#39;&#39;", r"<b><i>\1</i></b>", value, re.DOTALL) value = re.sub("&#39;&#39;&#39;&#39;([^']+)&#39;&#39;&#39;&#39;", r"<b><i>\1</i></b>", value, re.DOTALL)
value = re.sub("&#39;b&#39;&#39;([^']+)&#39;&#39;&#39;", r"<b>\1</b>", value, re.DOTALL) value = re.sub("&#39;b&#39;&#39;([^']+)&#39;&#39;&#39;", r"<b>\1</b>", value, re.DOTALL)
value = re.sub("&#39;&#39;([^']+)&#39;&#39;", r"<i>\1</i>", value, re.DOTALL) value = re.sub("&#39;&#39;([^']+)&#39;&#39;", r"<i>\1</i>", value, re.DOTALL)
#make headers #make headers
def headerrepl(matchobj): def headerrepl(matchobj):
number=len(matchobj.groups()[0]) number=len(matchobj.groups()[0])
num=str(number) num=str(number)
if number>1: if number>1:
return '<h'+num+'>'+matchobj.groups()[1]+'</h'+num+'>' return '<h'+num+'>'+matchobj.groups()[1]+'</h'+num+'>'
else: else:
print 'morethanone' print 'morethanone'
return matchobj.group() return matchobj.group()
value = re.sub(r"(?m)^(=+)([^=]+)(=+)$",headerrepl,value) value = re.sub(r"(?m)^(=+)([^=]+)(=+)$",headerrepl,value)
#make qm links. this takes a little doing #make qm links. this takes a little doing
qmMatchPattern=settings.QM_PATTERN qmMatchPattern=settings.QM_PATTERN
def qmrepl(matchobj): def qmrepl(matchobj):
""" """
A function for replacing wikicode qm links with html qm links. A function for replacing wikicode qm links with html qm links.
Given a matchobj matching a wikilink in the format Given a matchobj matching a wikilink in the format
[[QM:C204-1999-24]] [[QM:C204-1999-24]]
If the QM does not exist, the function will return a link for creating it. If the QM does not exist, the function will return a link for creating it.
""" """
qmdict={'urlroot':settings.URL_ROOT,'cave':matchobj.groups()[2],'year':matchobj.groups()[1],'number':matchobj.groups()[3]} qmdict={'urlroot':settings.URL_ROOT,'cave':matchobj.groups()[2],'year':matchobj.groups()[1],'number':matchobj.groups()[3]}
try: try:
qm=QM.objects.get(found_by__cave__kataster_number = qmdict['cave'], qm=QM.objects.get(found_by__cave__kataster_number = qmdict['cave'],
found_by__date__year = qmdict['year'], found_by__date__year = qmdict['year'],
number = qmdict['number']) number = qmdict['number'])
return r'<a href="%s" id="q%s">%s</a>' % (qm.get_absolute_url(), qm.code, unicode(qm)) return r'<a href="%s" id="q%s">%s</a>' % (qm.get_absolute_url(), qm.code, unicode(qm))
except QM.DoesNotExist: #bother aaron to make him clean up the below code - AC except QM.DoesNotExist: #bother aaron to make him clean up the below code - AC
try: try:
placeholder=LogbookEntry.objects.get(date__year=qmdict['year'],cave__kataster_number=qmdict['cave'], title__icontains='placeholder') placeholder=LogbookEntry.objects.get(date__year=qmdict['year'],cave__kataster_number=qmdict['cave'], title__icontains='placeholder')
except LogbookEntry.DoesNotExist: except LogbookEntry.DoesNotExist:
placeholder=LogbookEntry( placeholder=LogbookEntry(
date='01-01'+qmdict['year'], date='01-01'+qmdict['year'],
cave=Cave.objects.get(kataster_number=qmdict['cave']), cave=Cave.objects.get(kataster_number=qmdict['cave']),
title='placeholder' title='placeholder'
) )
qm=QM(found_by = placeholder, number = qmdict['number']) qm=QM(found_by = placeholder, number = qmdict['number'])
return r'<a class="redtext" href="%s" id="q%s">%s</a>' % (qm.get_absolute_url(), qm.code, unicode(qm)) return r'<a class="redtext" href="%s" id="q%s">%s</a>' % (qm.get_absolute_url(), qm.code, unicode(qm))
value = re.sub(qmMatchPattern,qmrepl, value, re.DOTALL) value = re.sub(qmMatchPattern,qmrepl, value, re.DOTALL)
#make photo links for [[photo:filename]] or [[photo:filename linktext]], and #make photo links for [[photo:filename]] or [[photo:filename linktext]], and
#insert photos for [[display:left photo:filename]] #insert photos for [[display:left photo:filename]]
photoLinkPattern="\[\[\s*photo:(?P<photoName>[^\s]+)\s*(?P<linkText>.*)\]\]" photoLinkPattern="\[\[\s*photo:(?P<photoName>[^\s]+)\s*(?P<linkText>.*)\]\]"
photoSrcPattern="\[\[\s*display:(?P<style>[^\s]+) photo:(?P<photoName>[^\s]+)\s*\]\]" photoSrcPattern="\[\[\s*display:(?P<style>[^\s]+) photo:(?P<photoName>[^\s]+)\s*\]\]"
def photoLinkRepl(matchobj): def photoLinkRepl(matchobj):
matchdict=matchobj.groupdict() matchdict=matchobj.groupdict()
try: try:
linkText=matchdict['linkText'] linkText=matchdict['linkText']
except KeyError: except KeyError:
linkText=None linkText=None
try: try:
photo=DPhoto.objects.get(file=matchdict['photoName']) photo=DPhoto.objects.get(file=matchdict['photoName'])
if not linkText: if not linkText:
linkText=str(photo) linkText=str(photo)
res=r'<a href=' + photo.get_admin_url() +'>' + linkText + '</a>' res=r'<a href=' + photo.get_admin_url() +'>' + linkText + '</a>'
except Photo.DoesNotExist: except Photo.DoesNotExist:
res = r'<a class="redtext" href="">make new photo</a>' res = r'<a class="redtext" href="">make new photo</a>'
return res return res
def photoSrcRepl(matchobj): def photoSrcRepl(matchobj):
matchdict=matchobj.groupdict() matchdict=matchobj.groupdict()
style=matchdict['style'] style=matchdict['style']
try: try:
photo=Photo.objects.get(file=matchdict['photoName']) photo=Photo.objects.get(file=matchdict['photoName'])
res=r'<a href='+photo.file.url+'><img src=' + photo.thumbnail_image.url +' class='+style+' /></a>' res=r'<a href='+photo.file.url+'><img src=' + photo.thumbnail_image.url +' class='+style+' /></a>'
except Photo.DoesNotExist: except Photo.DoesNotExist:
res = r'<a class="redtext" href="">make new photo</a>' res = r'<a class="redtext" href="">make new photo</a>'
return res return res
value = re.sub(photoLinkPattern,photoLinkRepl, value, re.DOTALL) value = re.sub(photoLinkPattern,photoLinkRepl, value, re.DOTALL)
value = re.sub(photoSrcPattern,photoSrcRepl, value, re.DOTALL) value = re.sub(photoSrcPattern,photoSrcRepl, value, re.DOTALL)
#make cave links #make cave links
value = re.sub("\[\[\s*cave:([^\s]+)\s*\s*\]\]", r'<a href="%scave/\1/">\1</a>' % settings.URL_ROOT, value, re.DOTALL) value = re.sub("\[\[\s*cave:([^\s]+)\s*\s*\]\]", r'<a href="%scave/\1/">\1</a>' % settings.URL_ROOT, value, re.DOTALL)
#make people links #make people links
value = re.sub("\[\[\s*person:(.+)\|(.+)\]\]",r'<a href="%sperson/\1/">\2</a>' % settings.URL_ROOT, value, re.DOTALL) value = re.sub("\[\[\s*person:(.+)\|(.+)\]\]",r'<a href="%sperson/\1/">\2</a>' % settings.URL_ROOT, value, re.DOTALL)
#make subcave links #make subcave links
value = re.sub("\[\[\s*subcave:(.+)\|(.+)\]\]",r'<a href="%ssubcave/\1/">\2</a>' % settings.URL_ROOT, value, re.DOTALL) value = re.sub("\[\[\s*subcave:(.+)\|(.+)\]\]",r'<a href="%ssubcave/\1/">\2</a>' % settings.URL_ROOT, value, re.DOTALL)
#make cavedescription links #make cavedescription links
value = re.sub("\[\[\s*cavedescription:(.+)\|(.+)\]\]",r'<a href="%scavedescription/\1/">\2</a>' % settings.URL_ROOT, value, re.DOTALL) value = re.sub("\[\[\s*cavedescription:(.+)\|(.+)\]\]",r'<a href="%scavedescription/\1/">\2</a>' % settings.URL_ROOT, value, re.DOTALL)
#Make lists from lines starting with lists of [stars and hashes] #Make lists from lines starting with lists of [stars and hashes]
outValue = "" outValue = ""
listdepth = [] listdepth = []
for line in value.split("\n"): for line in value.split("\n"):
t, listdepth = wiki_list(line, listdepth) t, listdepth = wiki_list(line, listdepth)
outValue += t outValue += t
for item in listdepth: for item in listdepth:
if item == "\*": if item == "\*":
outValue += "</ul>\n" outValue += "</ul>\n"
elif item == "#": elif item == "#":
outValue += "</ol>\n" outValue += "</ol>\n"
return mark_safe(outValue) return mark_safe(outValue)
wiki_to_html.needs_autoescape = True wiki_to_html.needs_autoescape = True

View File

@ -1,233 +1,233 @@
from django.conf import settings from django.conf import settings
import fileAbstraction import fileAbstraction
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
import os, stat import os, stat
import re import re
from troggle.core.models import SurvexScansFolder, SurvexScanSingle, SurvexBlock, TunnelFile from troggle.core.models import SurvexScansFolder, SurvexScanSingle, SurvexBlock, TunnelFile
import parsers.surveys import parsers.surveys
# inline fileabstraction into here if it's not going to be useful anywhere else # inline fileabstraction into here if it's not going to be useful anywhere else
# keep things simple and ignore exceptions everywhere for now # keep things simple and ignore exceptions everywhere for now
def getMimeType(extension): def getMimeType(extension):
try: try:
return {"txt": "text/plain", return {"txt": "text/plain",
"html": "text/html", "html": "text/html",
}[extension] }[extension]
except: except:
print "unknown file type" print "unknown file type"
return "text/plain" return "text/plain"
def listdir(request, path): def listdir(request, path):
#try: #try:
return HttpResponse(fileAbstraction.listdir(path), mimetype = "text/plain") return HttpResponse(fileAbstraction.listdir(path), mimetype = "text/plain")
#except: #except:
# raise Http404 # raise Http404
def upload(request, path): def upload(request, path):
pass pass
def download(request, path): def download(request, path):
#try: #try:
return HttpResponse(fileAbstraction.readFile(path), mimetype=getMimeType(path.split(".")[-1])) return HttpResponse(fileAbstraction.readFile(path), mimetype=getMimeType(path.split(".")[-1]))
#except: #except:
# raise Http404 # raise Http404
# #
# julian's quick hack for something that works # julian's quick hack for something that works
# could signal directories by ending with /, and forward cases where it's missing # could signal directories by ending with /, and forward cases where it's missing
# #
extmimetypes = {".txt": "text/plain", extmimetypes = {".txt": "text/plain",
".html": "text/html", ".html": "text/html",
".png": "image/png", ".png": "image/png",
".jpg": "image/jpeg", ".jpg": "image/jpeg",
} }
# dead # dead
def jgtfile(request, f): def jgtfile(request, f):
fp = os.path.join(settings.SURVEYS, f) fp = os.path.join(settings.SURVEYS, f)
# could also surf through SURVEX_DATA # could also surf through SURVEX_DATA
# directory listing # directory listing
if os.path.isdir(fp): if os.path.isdir(fp):
listdirfiles = [ ] listdirfiles = [ ]
listdirdirs = [ ] listdirdirs = [ ]
for lf in sorted(os.listdir(fp)): for lf in sorted(os.listdir(fp)):
hpath = os.path.join(f, lf) # not absolute path hpath = os.path.join(f, lf) # not absolute path
if lf[0] == "." or lf[-1] == "~": if lf[0] == "." or lf[-1] == "~":
continue continue
hpath = hpath.replace("\\", "/") # for windows users hpath = hpath.replace("\\", "/") # for windows users
href = hpath.replace("#", "%23") # '#' in file name annoyance href = hpath.replace("#", "%23") # '#' in file name annoyance
flf = os.path.join(fp, lf) flf = os.path.join(fp, lf)
if os.path.isdir(flf): if os.path.isdir(flf):
nfiles = len([sf for sf in os.listdir(flf) if sf[0] != "."]) nfiles = len([sf for sf in os.listdir(flf) if sf[0] != "."])
listdirdirs.append((href, hpath + "/", nfiles)) listdirdirs.append((href, hpath + "/", nfiles))
else: else:
listdirfiles.append((href, hpath, os.path.getsize(flf))) listdirfiles.append((href, hpath, os.path.getsize(flf)))
upperdirs = [ ] upperdirs = [ ]
lf = f lf = f
while lf: while lf:
hpath = lf.replace("\\", "/") # for windows users hpath = lf.replace("\\", "/") # for windows users
if hpath[-1] != "/": if hpath[-1] != "/":
hpath += "/" hpath += "/"
href = hpath.replace("#", "%23") href = hpath.replace("#", "%23")
lf = os.path.split(lf)[0] lf = os.path.split(lf)[0]
upperdirs.append((href, hpath)) upperdirs.append((href, hpath))
upperdirs.append(("", "/")) upperdirs.append(("", "/"))
return render_to_response('listdir.html', {'file':f, 'listdirfiles':listdirfiles, 'listdirdirs':listdirdirs, 'upperdirs':upperdirs, 'settings': settings}) return render_to_response('listdir.html', {'file':f, 'listdirfiles':listdirfiles, 'listdirdirs':listdirdirs, 'upperdirs':upperdirs, 'settings': settings})
# flat output of file when loaded # flat output of file when loaded
if os.path.isfile(fp): if os.path.isfile(fp):
ext = os.path.splitext(fp)[1].lower() ext = os.path.splitext(fp)[1].lower()
mimetype = extmimetypes.get(ext, "text/plain") mimetype = extmimetypes.get(ext, "text/plain")
fin = open(fp) fin = open(fp)
ftext = fin.read() ftext = fin.read()
fin.close() fin.close()
return HttpResponse(ftext, mimetype=mimetype) return HttpResponse(ftext, mimetype=mimetype)
return HttpResponse("unknown file::%s::" % f, mimetype = "text/plain") return HttpResponse("unknown file::%s::" % f, mimetype = "text/plain")
def UniqueFile(fname): def UniqueFile(fname):
while True: while True:
if not os.path.exists(fname): if not os.path.exists(fname):
break break
mname = re.match("(.*?)(?:-(\d+))?\.(png|jpg|jpeg)$(?i)", fname) mname = re.match("(.*?)(?:-(\d+))?\.(png|jpg|jpeg)$(?i)", fname)
if mname: if mname:
fname = "%s-%d.%s" % (mname.group(1), int(mname.group(2) or "0") + 1, mname.group(3)) fname = "%s-%d.%s" % (mname.group(1), int(mname.group(2) or "0") + 1, mname.group(3))
return fname return fname
# join it all up and then split them off for the directories that don't exist # join it all up and then split them off for the directories that don't exist
# anyway, this mkdir doesn't work # anyway, this mkdir doesn't work
def SaveImageInDir(name, imgdir, project, fdata, bbinary): def SaveImageInDir(name, imgdir, project, fdata, bbinary):
print ("hihihihi", fdata, settings.SURVEYS) print ("hihihihi", fdata, settings.SURVEYS)
fimgdir = os.path.join(settings.SURVEYS, imgdir) fimgdir = os.path.join(settings.SURVEYS, imgdir)
if not os.path.isdir(fimgdir): if not os.path.isdir(fimgdir):
print "*** Making directory", fimgdir print "*** Making directory", fimgdir
os.path.mkdir(fimgdir) os.path.mkdir(fimgdir)
fprojdir = os.path.join(fimgdir, project) fprojdir = os.path.join(fimgdir, project)
if not os.path.isdir(fprojdir): if not os.path.isdir(fprojdir):
print "*** Making directory", fprojdir print "*** Making directory", fprojdir
os.path.mkdir(fprojdir) os.path.mkdir(fprojdir)
print "hhh" print "hhh"
fname = os.path.join(fprojdir, name) fname = os.path.join(fprojdir, name)
print fname, "fff" print fname, "fff"
fname = UniqueFile(fname) fname = UniqueFile(fname)
p2, p1 = os.path.split(fname) p2, p1 = os.path.split(fname)
p3, p2 = os.path.split(p2) p3, p2 = os.path.split(p2)
p4, p3 = os.path.split(p3) p4, p3 = os.path.split(p3)
res = os.path.join(p3, p2, p1) res = os.path.join(p3, p2, p1)
print "saving file", fname print "saving file", fname
fout = open(fname, (bbinary and "wb" or "w")) fout = open(fname, (bbinary and "wb" or "w"))
fout.write(fdata.read()) fout.write(fdata.read())
fout.close() fout.close()
res = os.path.join(imgdir, name) res = os.path.join(imgdir, name)
return res.replace("\\", "/") return res.replace("\\", "/")
# do we want to consider saving project/field rather than field/project # do we want to consider saving project/field rather than field/project
def jgtuploadfile(request): def jgtuploadfile(request):
filesuploaded = [ ] filesuploaded = [ ]
project, user, password, tunnelversion = request.POST["tunnelproject"], request.POST["tunneluser"], request.POST["tunnelpassword"], request.POST["tunnelversion"] project, user, password, tunnelversion = request.POST["tunnelproject"], request.POST["tunneluser"], request.POST["tunnelpassword"], request.POST["tunnelversion"]
print (project, user, tunnelversion) print (project, user, tunnelversion)
for uploadedfile in request.FILES.values(): for uploadedfile in request.FILES.values():
if uploadedfile.field_name in ["tileimage", "backgroundimage"] and \ if uploadedfile.field_name in ["tileimage", "backgroundimage"] and \
uploadedfile.content_type in ["image/png", "image/jpeg"]: uploadedfile.content_type in ["image/png", "image/jpeg"]:
fname = user + "_" + re.sub("[\\\\/]", "-", uploadedfile.name) # very escaped \ fname = user + "_" + re.sub("[\\\\/]", "-", uploadedfile.name) # very escaped \
print fname print fname
fileuploaded = SaveImageInDir(fname, uploadedfile.field_name, project, uploadedfile, True) fileuploaded = SaveImageInDir(fname, uploadedfile.field_name, project, uploadedfile, True)
filesuploaded.append(settings.URL_ROOT + "/jgtfile/" + fileuploaded) filesuploaded.append(settings.URL_ROOT + "/jgtfile/" + fileuploaded)
if uploadedfile.field_name in ["sketch"] and \ if uploadedfile.field_name in ["sketch"] and \
uploadedfile.content_type in ["text/plain"]: uploadedfile.content_type in ["text/plain"]:
fname = user + "_" + re.sub("[\\\\/]", "-", uploadedfile.name) # very escaped \ fname = user + "_" + re.sub("[\\\\/]", "-", uploadedfile.name) # very escaped \
print fname print fname
fileuploaded = SaveImageInDir(fname, uploadedfile.field_name, project, uploadedfile, False) fileuploaded = SaveImageInDir(fname, uploadedfile.field_name, project, uploadedfile, False)
filesuploaded.append(settings.URL_ROOT + "/jgtfile/" + fileuploaded) filesuploaded.append(settings.URL_ROOT + "/jgtfile/" + fileuploaded)
#print "FF", request.FILES #print "FF", request.FILES
#print ("FFF", request.FILES.values()) #print ("FFF", request.FILES.values())
message = "" message = ""
print "gothere" print "gothere"
return render_to_response('fileupload.html', {'message':message, 'filesuploaded':filesuploaded, 'settings': settings}) return render_to_response('fileupload.html', {'message':message, 'filesuploaded':filesuploaded, 'settings': settings})
def surveyscansfolder(request, path): def surveyscansfolder(request, path):
#print [ s.walletname for s in SurvexScansFolder.objects.all() ] #print [ s.walletname for s in SurvexScansFolder.objects.all() ]
survexscansfolder = SurvexScansFolder.objects.get(walletname=path) survexscansfolder = SurvexScansFolder.objects.get(walletname=path)
return render_to_response('survexscansfolder.html', { 'survexscansfolder':survexscansfolder, 'settings': settings }) return render_to_response('survexscansfolder.html', { 'survexscansfolder':survexscansfolder, 'settings': settings })
def surveyscansingle(request, path, file): def surveyscansingle(request, path, file):
survexscansfolder = SurvexScansFolder.objects.get(walletname=path) survexscansfolder = SurvexScansFolder.objects.get(walletname=path)
survexscansingle = SurvexScanSingle.objects.get(survexscansfolder=survexscansfolder, name=file) survexscansingle = SurvexScanSingle.objects.get(survexscansfolder=survexscansfolder, name=file)
return HttpResponse(content=open(survexscansingle.ffile), mimetype="image/png") return HttpResponse(content=open(survexscansingle.ffile), mimetype="image/png")
#return render_to_response('survexscansfolder.html', { 'survexscansfolder':survexscansfolder, 'settings': settings }) #return render_to_response('survexscansfolder.html', { 'survexscansfolder':survexscansfolder, 'settings': settings })
def surveyscansfolders(request): def surveyscansfolders(request):
survexscansfolders = SurvexScansFolder.objects.all() survexscansfolders = SurvexScansFolder.objects.all()
return render_to_response('survexscansfolders.html', { 'survexscansfolders':survexscansfolders, 'settings': settings }) return render_to_response('survexscansfolders.html', { 'survexscansfolders':survexscansfolders, 'settings': settings })
def tunneldata(request): def tunneldata(request):
tunnelfiles = TunnelFile.objects.all() tunnelfiles = TunnelFile.objects.all()
return render_to_response('tunnelfiles.html', { 'tunnelfiles':tunnelfiles, 'settings': settings }) return render_to_response('tunnelfiles.html', { 'tunnelfiles':tunnelfiles, 'settings': settings })
def tunnelfile(request, path): def tunnelfile(request, path):
tunnelfile = TunnelFile.objects.get(tunnelpath=path) tunnelfile = TunnelFile.objects.get(tunnelpath=path)
tfile = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath) tfile = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath)
return HttpResponse(content=open(tfile), mimetype="text/plain") return HttpResponse(content=open(tfile), mimetype="text/plain")
def tunnelfileupload(request, path): def tunnelfileupload(request, path):
tunnelfile = TunnelFile.objects.get(tunnelpath=path) tunnelfile = TunnelFile.objects.get(tunnelpath=path)
tfile = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath) tfile = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath)
project, user, password, tunnelversion = request.POST["tunnelproject"], request.POST["tunneluser"], request.POST["tunnelpassword"], request.POST["tunnelversion"] project, user, password, tunnelversion = request.POST["tunnelproject"], request.POST["tunneluser"], request.POST["tunnelpassword"], request.POST["tunnelversion"]
print (project, user, tunnelversion) print (project, user, tunnelversion)
assert len(request.FILES.values()) == 1, "only one file to upload" assert len(request.FILES.values()) == 1, "only one file to upload"
uploadedfile = request.FILES.values()[0] uploadedfile = request.FILES.values()[0]
if uploadedfile.field_name != "sketch": if uploadedfile.field_name != "sketch":
return HttpResponse(content="Error: non-sketch file uploaded", mimetype="text/plain") return HttpResponse(content="Error: non-sketch file uploaded", mimetype="text/plain")
if uploadedfile.content_type != "text/plain": if uploadedfile.content_type != "text/plain":
return HttpResponse(content="Error: non-plain content type", mimetype="text/plain") return HttpResponse(content="Error: non-plain content type", mimetype="text/plain")
# could use this to add new files # could use this to add new files
if os.path.split(path)[1] != uploadedfile.name: if os.path.split(path)[1] != uploadedfile.name:
return HttpResponse(content="Error: name disagrees", mimetype="text/plain") return HttpResponse(content="Error: name disagrees", mimetype="text/plain")
orgsize = tunnelfile.filesize # = os.stat(tfile)[stat.ST_SIZE] orgsize = tunnelfile.filesize # = os.stat(tfile)[stat.ST_SIZE]
ttext = uploadedfile.read() ttext = uploadedfile.read()
# could check that the user and projects agree here # could check that the user and projects agree here
fout = open(tfile, "w") fout = open(tfile, "w")
fout.write(ttext) fout.write(ttext)
fout.close() fout.close()
# redo its settings of # redo its settings of
parsers.surveys.SetTunnelfileInfo(tunnelfile) parsers.surveys.SetTunnelfileInfo(tunnelfile)
tunnelfile.save() tunnelfile.save()
uploadedfile.close() uploadedfile.close()
message = "File size %d overwritten with size %d" % (orgsize, tunnelfile.filesize) message = "File size %d overwritten with size %d" % (orgsize, tunnelfile.filesize)
return HttpResponse(content=message, mimetype="text/plain") return HttpResponse(content=message, mimetype="text/plain")

View File

@ -1,8 +1,8 @@
# primary namespace # primary namespace
import view_surveys import view_surveys
import views_caves import views_caves
import views_survex import views_survex
import views_logbooks import views_logbooks
import views_other import views_other

View File

@ -1,141 +1,141 @@
from troggle.core.models import Cave, CaveAndEntrance, Survey, Expedition, QM, CaveDescription from troggle.core.models import Cave, CaveAndEntrance, Survey, Expedition, QM, CaveDescription
from troggle.core.forms import CaveForm from troggle.core.forms import CaveForm
import troggle.core.models as models import troggle.core.models as models
import troggle.settings as settings import troggle.settings as settings
from troggle.helper import login_required_if_public from troggle.helper import login_required_if_public
from django.forms.models import formset_factory from django.forms.models import formset_factory
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from utils import render_with_context # see views_logbooks for explanation on this. from utils import render_with_context # see views_logbooks for explanation on this.
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.conf import settings from django.conf import settings
import re, urlparse import re, urlparse
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
def getCave(cave_id): def getCave(cave_id):
"""Returns a cave object when given a cave name or number. It is used by views including cavehref, ent, and qm.""" """Returns a cave object when given a cave name or number. It is used by views including cavehref, ent, and qm."""
try: try:
cave = Cave.objects.get(kataster_number=cave_id) cave = Cave.objects.get(kataster_number=cave_id)
except Cave.DoesNotExist: except Cave.DoesNotExist:
cave = Cave.objects.get(unofficial_number=cave_id) cave = Cave.objects.get(unofficial_number=cave_id)
return cave return cave
def caveindex(request): def caveindex(request):
caves = Cave.objects.all() caves = Cave.objects.all()
notablecavehrefs = [ "161", "204", "258", "76" ] # could detect notability by trips and notability of people who have been down them notablecavehrefs = [ "161", "204", "258", "76" ] # could detect notability by trips and notability of people who have been down them
notablecaves = [Cave.objects.get(kataster_number=kataster_number) for kataster_number in notablecavehrefs ] notablecaves = [Cave.objects.get(kataster_number=kataster_number) for kataster_number in notablecavehrefs ]
caves1623 = Cave.objects.filter(area__short_name = "1623") caves1623 = Cave.objects.filter(area__short_name = "1623")
caves1626 = Cave.objects.filter(area__short_name = "1626") caves1626 = Cave.objects.filter(area__short_name = "1626")
return render_with_context(request,'caveindex.html', {'caves1623': caves1623, 'caves1626': caves1626, 'notablecaves':notablecaves, 'cavepage': True}) return render_with_context(request,'caveindex.html', {'caves1623': caves1623, 'caves1626': caves1626, 'notablecaves':notablecaves, 'cavepage': True})
def cave(request, cave_id='', offical_name=''): def cave(request, cave_id='', offical_name=''):
cave=getCave(cave_id) cave=getCave(cave_id)
if cave.non_public and not request.user.is_authenticated(): if cave.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': cave, 'cavepage': True}) return render_with_context(request,'nonpublic.html', {'instance': cave, 'cavepage': True})
else: else:
return render_with_context(request,'cave.html', {'cave': cave, 'cavepage': True}) return render_with_context(request,'cave.html', {'cave': cave, 'cavepage': True})
def caveEntrance(request, slug): def caveEntrance(request, slug):
cave = Cave.objects.get(slug = slug) cave = Cave.objects.get(slug = slug)
if cave.non_public and not request.user.is_authenticated(): if cave.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': cave}) return render_with_context(request,'nonpublic.html', {'instance': cave})
else: else:
return render_with_context(request,'cave_entrances.html', {'cave': cave}) return render_with_context(request,'cave_entrances.html', {'cave': cave})
def caveDescription(request, slug): def caveDescription(request, slug):
cave = Cave.objects.get(slug = slug) cave = Cave.objects.get(slug = slug)
if cave.non_public and not request.user.is_authenticated(): if cave.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': cave}) return render_with_context(request,'nonpublic.html', {'instance': cave})
else: else:
return render_with_context(request,'cave_uground_description.html', {'cave': cave}) return render_with_context(request,'cave_uground_description.html', {'cave': cave})
def caveQMs(request, slug): def caveQMs(request, slug):
cave = Cave.objects.get(slug = slug) cave = Cave.objects.get(slug = slug)
if cave.non_public and not request.user.is_authenticated(): if cave.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': cave}) return render_with_context(request,'nonpublic.html', {'instance': cave})
else: else:
return render_with_context(request,'cave_qms.html', {'cave': cave}) return render_with_context(request,'cave_qms.html', {'cave': cave})
def caveLogbook(request, slug): def caveLogbook(request, slug):
cave = Cave.objects.get(slug = slug) cave = Cave.objects.get(slug = slug)
if cave.non_public and not request.user.is_authenticated(): if cave.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': cave}) return render_with_context(request,'nonpublic.html', {'instance': cave})
else: else:
return render_with_context(request,'cave_logbook.html', {'cave': cave}) return render_with_context(request,'cave_logbook.html', {'cave': cave})
def caveSlug(request, slug): def caveSlug(request, slug):
cave = Cave.objects.get(slug = slug) cave = Cave.objects.get(slug = slug)
if cave.non_public and not request.user.is_authenticated(): if cave.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': cave}) return render_with_context(request,'nonpublic.html', {'instance': cave})
else: else:
return render_with_context(request,'cave.html', {'cave': cave}) return render_with_context(request,'cave.html', {'cave': cave})
@login_required_if_public @login_required_if_public
def editCave(request, slug=None): def editCave(request, slug=None):
form = CaveForm() form = CaveForm()
return render_with_context(request, return render_with_context(request,
'editcave.html', 'editcave.html',
{'form': form}) {'form': form})
def qm(request,cave_id,qm_id,year,grade=None): def qm(request,cave_id,qm_id,year,grade=None):
year=int(year) year=int(year)
try: try:
qm=getCave(cave_id).get_QMs().get(number=qm_id,found_by__date__year=year) qm=getCave(cave_id).get_QMs().get(number=qm_id,found_by__date__year=year)
return render_with_context(request,'qm.html',locals()) return render_with_context(request,'qm.html',locals())
except QM.DoesNotExist: except QM.DoesNotExist:
url=urlparse.urljoin(settings.URL_ROOT, r'/admin/core/qm/add/'+'?'+ r'number=' + qm_id) url=urlparse.urljoin(settings.URL_ROOT, r'/admin/core/qm/add/'+'?'+ r'number=' + qm_id)
if grade: if grade:
url += r'&grade=' + grade url += r'&grade=' + grade
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
def ent(request, cave_id, ent_letter): def ent(request, cave_id, ent_letter):
cave = Cave.objects.filter(kataster_number = cave_id)[0] cave = Cave.objects.filter(kataster_number = cave_id)[0]
cave_and_ent = CaveAndEntrance.objects.filter(cave = cave).filter(entrance_letter = ent_letter)[0] cave_and_ent = CaveAndEntrance.objects.filter(cave = cave).filter(entrance_letter = ent_letter)[0]
return render_with_context(request,'entrance.html', {'cave': cave, return render_with_context(request,'entrance.html', {'cave': cave,
'entrance': cave_and_ent.entrance, 'entrance': cave_and_ent.entrance,
'letter': cave_and_ent.entrance_letter,}) 'letter': cave_and_ent.entrance_letter,})
def entranceSlug(request, slug): def entranceSlug(request, slug):
entrance = Entrance.objects.get(slug = slug) entrance = Entrance.objects.get(slug = slug)
if entrance.non_public and not request.user.is_authenticated(): if entrance.non_public and not request.user.is_authenticated():
return render_with_context(request,'nonpublic.html', {'instance': entrance}) return render_with_context(request,'nonpublic.html', {'instance': entrance})
else: else:
return render_with_context(request,'entranceslug.html', {'entrance': entrance}) return render_with_context(request,'entranceslug.html', {'entrance': entrance})
def survexblock(request, survexpath): def survexblock(request, survexpath):
survexpath = re.sub("/", ".", survexpath) survexpath = re.sub("/", ".", survexpath)
print "jjjjjj", survexpath print "jjjjjj", survexpath
survexblock = models.SurvexBlock.objects.get(survexpath=survexpath) survexblock = models.SurvexBlock.objects.get(survexpath=survexpath)
#ftext = survexblock.filecontents() #ftext = survexblock.filecontents()
ftext = survexblock.text ftext = survexblock.text
return render_with_context(request,'survexblock.html', {'survexblock':survexblock, 'ftext':ftext, }) return render_with_context(request,'survexblock.html', {'survexblock':survexblock, 'ftext':ftext, })
def surveyindex(request): def surveyindex(request):
surveys=Survey.objects.all() surveys=Survey.objects.all()
expeditions=Expedition.objects.order_by("-year") expeditions=Expedition.objects.order_by("-year")
return render_with_context(request,'survey.html',locals()) return render_with_context(request,'survey.html',locals())
def survey(request,year,wallet_number): def survey(request,year,wallet_number):
surveys=Survey.objects.all() surveys=Survey.objects.all()
expeditions=Expedition.objects.order_by("-year") expeditions=Expedition.objects.order_by("-year")
current_expedition=Expedition.objects.filter(year=year)[0] current_expedition=Expedition.objects.filter(year=year)[0]
if wallet_number!='': if wallet_number!='':
current_survey=Survey.objects.filter(expedition=current_expedition,wallet_number=wallet_number)[0] current_survey=Survey.objects.filter(expedition=current_expedition,wallet_number=wallet_number)[0]
notes=current_survey.scannedimage_set.filter(contents='notes') notes=current_survey.scannedimage_set.filter(contents='notes')
planSketches=current_survey.scannedimage_set.filter(contents='plan') planSketches=current_survey.scannedimage_set.filter(contents='plan')
elevationSketches=current_survey.scannedimage_set.filter(contents='elevation') elevationSketches=current_survey.scannedimage_set.filter(contents='elevation')
return render_with_context(request,'survey.html', locals()) return render_with_context(request,'survey.html', locals())
def cave_description(request, cavedescription_name): def cave_description(request, cavedescription_name):
cave_description = get_object_or_404(CaveDescription, short_name = cavedescription_name) cave_description = get_object_or_404(CaveDescription, short_name = cavedescription_name)
return render_with_context(request,'cave_description.html', locals()) return render_with_context(request,'cave_description.html', locals())
def get_entrances(request, caveslug): def get_entrances(request, caveslug):
cave = Cave.objects.get(slug = caveslug) cave = Cave.objects.get(slug = caveslug)
return render_with_context(request,'options.html', {"items": [(e.entrance.slug, e.entrance.slug) for e in cave.entrances()]}) return render_with_context(request,'options.html', {"items": [(e.entrance.slug, e.entrance.slug) for e in cave.entrances()]})
def get_qms(request, caveslug): def get_qms(request, caveslug):
cave = Cave.objects.get(slug = caveslug) cave = Cave.objects.get(slug = caveslug)
return render_with_context(request,'options.html', {"items": [(e.entrance.slug, e.entrance.slug) for e in cave.entrances()]}) return render_with_context(request,'options.html', {"items": [(e.entrance.slug, e.entrance.slug) for e in cave.entrances()]})

View File

@ -1,252 +1,252 @@
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from troggle.core.models import Expedition, Person, PersonExpedition, PersonTrip, LogbookEntry, SurvexBlock from troggle.core.models import Expedition, Person, PersonExpedition, PersonTrip, LogbookEntry, SurvexBlock
import troggle.core.models as models import troggle.core.models as models
import troggle.settings as settings import troggle.settings as settings
import django.db.models import django.db.models
from troggle.parsers.logbooks import LoadLogbookForExpedition from troggle.parsers.logbooks import LoadLogbookForExpedition
from troggle.parsers.people import GetPersonExpeditionNameLookup from troggle.parsers.people import GetPersonExpeditionNameLookup
#from troggle.core.forms import PersonForm, getTripForm, get_name #from troggle.core.forms import PersonForm, getTripForm, get_name
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse from django.http import HttpResponseRedirect, HttpResponse
from django.template import Context, loader from django.template import Context, loader
from utils import render_with_context from utils import render_with_context
import os.path import os.path
import troggle.parsers.logbooks as logbookparsers import troggle.parsers.logbooks as logbookparsers
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
from troggle.helper import login_required_if_public from troggle.helper import login_required_if_public
import datetime import datetime
# Django uses Context, not RequestContext when you call render_to_response. We always want to use RequestContext, so that django adds the context from settings.TEMPLATE_CONTEXT_PROCESSORS. This way we automatically get necessary settings variables passed to each template. So we use a custom method, render_response instead of render_to_response. Hopefully future Django releases will make this unnecessary. # Django uses Context, not RequestContext when you call render_to_response. We always want to use RequestContext, so that django adds the context from settings.TEMPLATE_CONTEXT_PROCESSORS. This way we automatically get necessary settings variables passed to each template. So we use a custom method, render_response instead of render_to_response. Hopefully future Django releases will make this unnecessary.
#from troggle.alwaysUseRequestContext import render_response #from troggle.alwaysUseRequestContext import render_response
import re import re
@django.db.models.permalink #this allows the nice get_absolute_url syntax we are using @django.db.models.permalink #this allows the nice get_absolute_url syntax we are using
def getNotablePersons(): def getNotablePersons():
notablepersons = [] notablepersons = []
for person in Person.objects.all(): for person in Person.objects.all():
if person.bisnotable(): if person.bisnotable():
notablepersons.append(person) notablepersons.append(person)
return notablepersons return notablepersons
def personindex(request): def personindex(request):
persons = Person.objects.all() persons = Person.objects.all()
# From what I can tell, "persons" seems to be the table rows, while "personss" is the table columns. - AC 16 Feb 09 # From what I can tell, "persons" seems to be the table rows, while "personss" is the table columns. - AC 16 Feb 09
personss = [ ] personss = [ ]
ncols = 4 ncols = 4
nc = (len(persons) + ncols - 1) / ncols nc = (len(persons) + ncols - 1) / ncols
for i in range(ncols): for i in range(ncols):
personss.append(persons[i * nc: (i + 1) * nc]) personss.append(persons[i * nc: (i + 1) * nc])
notablepersons = [] notablepersons = []
for person in Person.objects.all(): for person in Person.objects.all():
if person.bisnotable(): if person.bisnotable():
notablepersons.append(person) notablepersons.append(person)
return render_with_context(request,'personindex.html', {'persons': persons, 'personss':personss, 'notablepersons':notablepersons, }) return render_with_context(request,'personindex.html', {'persons': persons, 'personss':personss, 'notablepersons':notablepersons, })
def expedition(request, expeditionname): def expedition(request, expeditionname):
expedition = Expedition.objects.get(year=int(expeditionname)) expedition = Expedition.objects.get(year=int(expeditionname))
expeditions = Expedition.objects.all() expeditions = Expedition.objects.all()
personexpeditiondays = [ ] personexpeditiondays = [ ]
dateditems = list(expedition.logbookentry_set.all()) + list(expedition.survexblock_set.all()) dateditems = list(expedition.logbookentry_set.all()) + list(expedition.survexblock_set.all())
dates = list(set([item.date for item in dateditems])) dates = list(set([item.date for item in dateditems]))
dates.sort() dates.sort()
for personexpedition in expedition.personexpedition_set.all(): for personexpedition in expedition.personexpedition_set.all():
prow = [ ] prow = [ ]
for date in dates: for date in dates:
pcell = { "persontrips": PersonTrip.objects.filter(personexpedition=personexpedition, pcell = { "persontrips": PersonTrip.objects.filter(personexpedition=personexpedition,
logbook_entry__date=date) } logbook_entry__date=date) }
pcell["survexblocks"] = set(SurvexBlock.objects.filter(survexpersonrole__personexpedition=personexpedition, pcell["survexblocks"] = set(SurvexBlock.objects.filter(survexpersonrole__personexpedition=personexpedition,
date = date)) date = date))
prow.append(pcell) prow.append(pcell)
personexpeditiondays.append({"personexpedition":personexpedition, "personrow":prow}) personexpeditiondays.append({"personexpedition":personexpedition, "personrow":prow})
message = "" message = ""
if "reload" in request.GET: if "reload" in request.GET:
message = LoadLogbookForExpedition(expedition) message = LoadLogbookForExpedition(expedition)
return render_with_context(request,'expedition.html', {'expedition': expedition, 'expeditions':expeditions, 'personexpeditiondays':personexpeditiondays, 'message':message, 'settings':settings, 'dateditems': dateditems }) return render_with_context(request,'expedition.html', {'expedition': expedition, 'expeditions':expeditions, 'personexpeditiondays':personexpeditiondays, 'message':message, 'settings':settings, 'dateditems': dateditems })
def get_absolute_url(self): def get_absolute_url(self):
return ('expedition', (expedition.year)) return ('expedition', (expedition.year))
def person(request, first_name='', last_name='', ): def person(request, first_name='', last_name='', ):
person = Person.objects.get(first_name = first_name, last_name = last_name) person = Person.objects.get(first_name = first_name, last_name = last_name)
#This is for removing the reference to the user's profile, in case they set it to the wrong person #This is for removing the reference to the user's profile, in case they set it to the wrong person
if request.method == 'GET': if request.method == 'GET':
if request.GET.get('clear_profile')=='True': if request.GET.get('clear_profile')=='True':
person.user=None person.user=None
person.save() person.save()
return HttpResponseRedirect(reverse('profiles_select_profile')) return HttpResponseRedirect(reverse('profiles_select_profile'))
return render_with_context(request,'person.html', {'person': person, }) return render_with_context(request,'person.html', {'person': person, })
def GetPersonChronology(personexpedition): def GetPersonChronology(personexpedition):
res = { } res = { }
for persontrip in personexpedition.persontrip_set.all(): for persontrip in personexpedition.persontrip_set.all():
a = res.setdefault(persontrip.date, { }) a = res.setdefault(persontrip.date, { })
a.setdefault("persontrips", [ ]).append(persontrip) a.setdefault("persontrips", [ ]).append(persontrip)
for personrole in personexpedition.survexpersonrole_set.all(): for personrole in personexpedition.survexpersonrole_set.all():
a = res.setdefault(personrole.survexblock.date, { }) a = res.setdefault(personrole.survexblock.date, { })
a.setdefault("personroles", [ ]).append(personrole.survexblock) a.setdefault("personroles", [ ]).append(personrole.survexblock)
# build up the tables # build up the tables
rdates = res.keys() rdates = res.keys()
rdates.sort() rdates.sort()
res2 = [ ] res2 = [ ]
for rdate in rdates: for rdate in rdates:
persontrips = res[rdate].get("persontrips", []) persontrips = res[rdate].get("persontrips", [])
personroles = res[rdate].get("personroles", []) personroles = res[rdate].get("personroles", [])
for n in range(max(len(persontrips), len(personroles))): for n in range(max(len(persontrips), len(personroles))):
res2.append(((n == 0 and rdate or "--"), (n < len(persontrips) and persontrips[n]), (n < len(personroles) and personroles[n]))) res2.append(((n == 0 and rdate or "--"), (n < len(persontrips) and persontrips[n]), (n < len(personroles) and personroles[n])))
return res2 return res2
def personexpedition(request, first_name='', last_name='', year=''): def personexpedition(request, first_name='', last_name='', year=''):
person = Person.objects.get(first_name = first_name, last_name = last_name) person = Person.objects.get(first_name = first_name, last_name = last_name)
expedition = Expedition.objects.get(year=year) expedition = Expedition.objects.get(year=year)
personexpedition = person.personexpedition_set.get(expedition=expedition) personexpedition = person.personexpedition_set.get(expedition=expedition)
personchronology = GetPersonChronology(personexpedition) personchronology = GetPersonChronology(personexpedition)
return render_with_context(request,'personexpedition.html', {'personexpedition': personexpedition, 'personchronology':personchronology}) return render_with_context(request,'personexpedition.html', {'personexpedition': personexpedition, 'personchronology':personchronology})
def logbookentry(request, date, slug): def logbookentry(request, date, slug):
logbookentry = LogbookEntry.objects.filter(date=date, slug=slug) logbookentry = LogbookEntry.objects.filter(date=date, slug=slug)
if len(logbookentry)>1: if len(logbookentry)>1:
return render_with_context(request, 'object_list.html',{'object_list':logbookentry}) return render_with_context(request, 'object_list.html',{'object_list':logbookentry})
else: else:
logbookentry=logbookentry[0] logbookentry=logbookentry[0]
return render_with_context(request, 'logbookentry.html', {'logbookentry': logbookentry}) return render_with_context(request, 'logbookentry.html', {'logbookentry': logbookentry})
def logbookSearch(request, extra): def logbookSearch(request, extra):
query_string = '' query_string = ''
found_entries = None found_entries = None
if ('q' in request.GET) and request.GET['q'].strip(): if ('q' in request.GET) and request.GET['q'].strip():
query_string = request.GET['q'] query_string = request.GET['q']
entry_query = search.get_query(query_string, ['text','title',]) entry_query = search.get_query(query_string, ['text','title',])
found_entries = LogbookEntry.objects.filter(entry_query) found_entries = LogbookEntry.objects.filter(entry_query)
return render_with_context(request,'logbooksearch.html', return render_with_context(request,'logbooksearch.html',
{ 'query_string': query_string, 'found_entries': found_entries, }) { 'query_string': query_string, 'found_entries': found_entries, })
#context_instance=RequestContext(request)) #context_instance=RequestContext(request))
def personForm(request,pk): def personForm(request,pk):
person=Person.objects.get(pk=pk) person=Person.objects.get(pk=pk)
form=PersonForm(instance=person) form=PersonForm(instance=person)
return render_with_context(request,'personform.html', {'form':form,}) return render_with_context(request,'personform.html', {'form':form,})
def experimental(request): def experimental(request):
legsbyexpo = [ ] legsbyexpo = [ ]
for expedition in Expedition.objects.all(): for expedition in Expedition.objects.all():
survexblocks = expedition.survexblock_set.all() survexblocks = expedition.survexblock_set.all()
survexlegs = [ ] survexlegs = [ ]
survexleglength = 0.0 survexleglength = 0.0
for survexblock in survexblocks: for survexblock in survexblocks:
survexlegs.extend(survexblock.survexleg_set.all()) survexlegs.extend(survexblock.survexleg_set.all())
survexleglength += survexblock.totalleglength survexleglength += survexblock.totalleglength
legsbyexpo.append((expedition, {"nsurvexlegs":len(survexlegs), "survexleglength":survexleglength})) legsbyexpo.append((expedition, {"nsurvexlegs":len(survexlegs), "survexleglength":survexleglength}))
legsbyexpo.reverse() legsbyexpo.reverse()
survexlegs = models.SurvexLeg.objects.all() survexlegs = models.SurvexLeg.objects.all()
totalsurvexlength = sum([survexleg.tape for survexleg in survexlegs]) totalsurvexlength = sum([survexleg.tape for survexleg in survexlegs])
return render_with_context(request, 'experimental.html', { "nsurvexlegs":len(survexlegs), "totalsurvexlength":totalsurvexlength, "legsbyexpo":legsbyexpo }) return render_with_context(request, 'experimental.html', { "nsurvexlegs":len(survexlegs), "totalsurvexlength":totalsurvexlength, "legsbyexpo":legsbyexpo })
@login_required_if_public @login_required_if_public
def newLogbookEntry(request, expeditionyear, pdate = None, pslug = None): def newLogbookEntry(request, expeditionyear, pdate = None, pslug = None):
expedition = Expedition.objects.get(year=expeditionyear) expedition = Expedition.objects.get(year=expeditionyear)
PersonTripFormSet, TripForm = getTripForm(expedition) PersonTripFormSet, TripForm = getTripForm(expedition)
if pslug and pdate: if pslug and pdate:
previousdate = datetime.date(*[int(x) for x in pdate.split("-")]) previousdate = datetime.date(*[int(x) for x in pdate.split("-")])
previouslbe = LogbookEntry.objects.get(slug = pslug, date = previousdate, expedition = expedition) previouslbe = LogbookEntry.objects.get(slug = pslug, date = previousdate, expedition = expedition)
assert previouslbe.filename assert previouslbe.filename
if request.method == 'POST': # If the form has been submitted... if request.method == 'POST': # If the form has been submitted...
tripForm = TripForm(request.POST) # A form bound to the POST data tripForm = TripForm(request.POST) # A form bound to the POST data
personTripFormSet = PersonTripFormSet(request.POST) personTripFormSet = PersonTripFormSet(request.POST)
if tripForm.is_valid() and personTripFormSet.is_valid(): # All validation rules pass if tripForm.is_valid() and personTripFormSet.is_valid(): # All validation rules pass
dateStr = tripForm.cleaned_data["date"].strftime("%Y-%m-%d") dateStr = tripForm.cleaned_data["date"].strftime("%Y-%m-%d")
directory = os.path.join(settings.EXPOWEB, directory = os.path.join(settings.EXPOWEB,
"years", "years",
expedition.year, expedition.year,
"autologbook") "autologbook")
filename = os.path.join(directory, filename = os.path.join(directory,
dateStr + "." + slugify(tripForm.cleaned_data["title"])[:50] + ".html") dateStr + "." + slugify(tripForm.cleaned_data["title"])[:50] + ".html")
if not os.path.isdir(directory): if not os.path.isdir(directory):
os.mkdir(directory) os.mkdir(directory)
if pslug and pdate: if pslug and pdate:
delLogbookEntry(previouslbe) delLogbookEntry(previouslbe)
f = open(filename, "w") f = open(filename, "w")
template = loader.get_template('dataformat/logbookentry.html') template = loader.get_template('dataformat/logbookentry.html')
context = Context({'trip': tripForm.cleaned_data, context = Context({'trip': tripForm.cleaned_data,
'persons': personTripFormSet.cleaned_data, 'persons': personTripFormSet.cleaned_data,
'date': dateStr, 'date': dateStr,
'expeditionyear': expeditionyear}) 'expeditionyear': expeditionyear})
f.write(template.render(context)) f.write(template.render(context))
f.close() f.close()
print logbookparsers.parseAutoLogBookEntry(filename) print logbookparsers.parseAutoLogBookEntry(filename)
return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST
else: else:
if pslug and pdate: if pslug and pdate:
if previouslbe.cave: if previouslbe.cave:
tripForm = TripForm(initial={"date": previousdate, tripForm = TripForm(initial={"date": previousdate,
"title": previouslbe.title, "title": previouslbe.title,
"cave": previouslbe.cave.reference(), "cave": previouslbe.cave.reference(),
"location": None, "location": None,
"caveOrLocation": "cave", "caveOrLocation": "cave",
"html": previouslbe.text}) "html": previouslbe.text})
else: else:
tripForm = TripForm(initial={"date": previousdate, tripForm = TripForm(initial={"date": previousdate,
"title": previouslbe.title, "title": previouslbe.title,
"cave": None, "cave": None,
"location": previouslbe.place, "location": previouslbe.place,
"caveOrLocation": "location", "caveOrLocation": "location",
"html": previouslbe.text}) "html": previouslbe.text})
personTripFormSet = PersonTripFormSet(initial=[{"name": get_name(py.personexpedition), personTripFormSet = PersonTripFormSet(initial=[{"name": get_name(py.personexpedition),
"TU": py.time_underground, "TU": py.time_underground,
"author": py.is_logbook_entry_author} "author": py.is_logbook_entry_author}
for py in previouslbe.persontrip_set.all()]) for py in previouslbe.persontrip_set.all()])
else: else:
tripForm = TripForm() # An unbound form tripForm = TripForm() # An unbound form
personTripFormSet = PersonTripFormSet() personTripFormSet = PersonTripFormSet()
return render_with_context(request, 'newlogbookentry.html', { return render_with_context(request, 'newlogbookentry.html', {
'tripForm': tripForm, 'tripForm': tripForm,
'personTripFormSet': personTripFormSet, 'personTripFormSet': personTripFormSet,
}) })
@login_required_if_public @login_required_if_public
def deleteLogbookEntry(request, expeditionyear, date = None, slug = None): def deleteLogbookEntry(request, expeditionyear, date = None, slug = None):
expedition = Expedition.objects.get(year=expeditionyear) expedition = Expedition.objects.get(year=expeditionyear)
previousdate = datetime.date(*[int(x) for x in date.split("-")]) previousdate = datetime.date(*[int(x) for x in date.split("-")])
previouslbe = LogbookEntry.objects.get(slug = slug, date = previousdate, expedition = expedition) previouslbe = LogbookEntry.objects.get(slug = slug, date = previousdate, expedition = expedition)
delLogbookEntry(previouslbe) delLogbookEntry(previouslbe)
return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST
def delLogbookEntry(lbe): def delLogbookEntry(lbe):
for pt in lbe.persontrip_set.all(): for pt in lbe.persontrip_set.all():
pt.delete() pt.delete()
lbe.delete() lbe.delete()
os.remove(lbe.filename) os.remove(lbe.filename)
def get_people(request, expeditionslug): def get_people(request, expeditionslug):
exp = Expedition.objects.get(year = expeditionslug) exp = Expedition.objects.get(year = expeditionslug)
return render_with_context(request,'options.html', {"items": [(pe.slug, pe.name) for pe in exp.personexpedition_set.all()]}) return render_with_context(request,'options.html', {"items": [(pe.slug, pe.name) for pe in exp.personexpedition_set.all()]})
def get_logbook_entries(request, expeditionslug): def get_logbook_entries(request, expeditionslug):
exp = Expedition.objects.get(year = expeditionslug) exp = Expedition.objects.get(year = expeditionslug)
return render_with_context(request,'options.html', {"items": [(le.slug, "%s - %s" % (le.date, le.title)) for le in exp.logbookentry_set.all()]}) return render_with_context(request,'options.html', {"items": [(le.slug, "%s - %s" % (le.date, le.title)) for le in exp.logbookentry_set.all()]})

View File

@ -1,282 +1,282 @@
from troggle.core.models import Cave, Expedition, Person, LogbookEntry, PersonExpedition, PersonTrip, DPhoto, QM from troggle.core.models import Cave, Expedition, Person, LogbookEntry, PersonExpedition, PersonTrip, DPhoto, QM
from troggle.core.forms import UploadFileForm from troggle.core.forms import UploadFileForm
from django.conf import settings from django.conf import settings
from django import forms from django import forms
from django.template import loader, Context from django.template import loader, Context
from django.db.models import Q from django.db.models import Q
import databaseReset import databaseReset
import re import re
from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from utils import render_with_context from utils import render_with_context
from core.models import * from core.models import *
from troggle.helper import login_required_if_public from troggle.helper import login_required_if_public
def showrequest(request): def showrequest(request):
return HttpResponse(request.GET) return HttpResponse(request.GET)
def stats(request): def stats(request):
statsDict={} statsDict={}
statsDict['expoCount'] = int(Expedition.objects.count()) statsDict['expoCount'] = int(Expedition.objects.count())
statsDict['caveCount'] = int(Cave.objects.count()) statsDict['caveCount'] = int(Cave.objects.count())
statsDict['personCount'] = int(Person.objects.count()) statsDict['personCount'] = int(Person.objects.count())
statsDict['logbookEntryCount'] = int(LogbookEntry.objects.count()) statsDict['logbookEntryCount'] = int(LogbookEntry.objects.count())
return render_with_context(request,'statistics.html', statsDict) return render_with_context(request,'statistics.html', statsDict)
def frontpage(request): def frontpage(request):
if request.user.is_authenticated(): if request.user.is_authenticated():
return render_with_context(request,'tasks.html') return render_with_context(request,'tasks.html')
expeditions = Expedition.objects.order_by("-year") expeditions = Expedition.objects.order_by("-year")
logbookentry = LogbookEntry logbookentry = LogbookEntry
cave = Cave cave = Cave
photo = DPhoto photo = DPhoto
from django.contrib.admin.templatetags import log from django.contrib.admin.templatetags import log
return render_with_context(request,'frontpage.html', locals()) return render_with_context(request,'frontpage.html', locals())
def todo(request): def todo(request):
message = "no test message" #reverse('personn', kwargs={"name":"hkjhjh"}) message = "no test message" #reverse('personn', kwargs={"name":"hkjhjh"})
if "reloadexpos" in request.GET: if "reloadexpos" in request.GET:
message = LoadPersonsExpos() message = LoadPersonsExpos()
message = "Reloaded personexpos" message = "Reloaded personexpos"
if "reloadsurvex" in request.POST: if "reloadsurvex" in request.POST:
message = LoadAllSurvexBlocks() message = LoadAllSurvexBlocks()
message = "Reloaded survexblocks" message = "Reloaded survexblocks"
expeditions = Expedition.objects.order_by("-year") expeditions = Expedition.objects.order_by("-year")
totallogbookentries = LogbookEntry.objects.count() totallogbookentries = LogbookEntry.objects.count()
return render_with_context(request,'index.html', {'expeditions':expeditions, 'all':'all', 'totallogbookentries':totallogbookentries, "message":message}) return render_with_context(request,'index.html', {'expeditions':expeditions, 'all':'all', 'totallogbookentries':totallogbookentries, "message":message})
def controlPanel(request): def controlPanel(request):
jobs_completed=[] jobs_completed=[]
if request.method=='POST': if request.method=='POST':
if request.user.is_superuser: if request.user.is_superuser:
#importlist is mostly here so that things happen in the correct order. #importlist is mostly here so that things happen in the correct order.
#http post data seems to come in an unpredictable order, so we do it this way. #http post data seems to come in an unpredictable order, so we do it this way.
importlist=['reload_db', 'import_people', 'import_cavetab', 'import_logbooks', 'import_surveys', 'import_QMs'] importlist=['reload_db', 'import_people', 'import_cavetab', 'import_logbooks', 'import_surveys', 'import_QMs']
databaseReset.make_dirs() databaseReset.make_dirs()
for item in importlist: for item in importlist:
if item in request.POST: if item in request.POST:
print "running"+ " databaseReset."+item+"()" print "running"+ " databaseReset."+item+"()"
exec "databaseReset."+item+"()" exec "databaseReset."+item+"()"
jobs_completed.append(item) jobs_completed.append(item)
else: else:
if request.user.is_authenticated(): #The user is logged in, but is not a superuser. if request.user.is_authenticated(): #The user is logged in, but is not a superuser.
return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'error':'You must be a superuser to use that feature.'}) return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'error':'You must be a superuser to use that feature.'})
else: else:
return HttpResponseRedirect(reverse('auth_login')) return HttpResponseRedirect(reverse('auth_login'))
return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed}) return render_with_context(request,'controlPanel.html', {'caves':Cave.objects.all(),'expeditions':Expedition.objects.all(),'jobs_completed':jobs_completed})
def downloadCavetab(request): def downloadCavetab(request):
from export import tocavetab from export import tocavetab
response = HttpResponse(mimetype='text/csv') response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=CAVETAB2.CSV' response['Content-Disposition'] = 'attachment; filename=CAVETAB2.CSV'
tocavetab.writeCaveTab(response) tocavetab.writeCaveTab(response)
return response return response
def downloadSurveys(request): def downloadSurveys(request):
from export import tosurveys from export import tosurveys
response = HttpResponse(mimetype='text/csv') response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=Surveys.csv' response['Content-Disposition'] = 'attachment; filename=Surveys.csv'
tosurveys.writeCaveTab(response) tosurveys.writeCaveTab(response)
return response return response
def downloadLogbook(request,year=None,extension=None,queryset=None): def downloadLogbook(request,year=None,extension=None,queryset=None):
if year: if year:
expedition=Expedition.objects.get(year=year) expedition=Expedition.objects.get(year=year)
logbook_entries=LogbookEntry.objects.filter(expedition=expedition) logbook_entries=LogbookEntry.objects.filter(expedition=expedition)
filename='logbook'+year filename='logbook'+year
elif queryset: elif queryset:
logbook_entries=queryset logbook_entries=queryset
filename='logbook' filename='logbook'
else: else:
return response(r"Error: Logbook downloader doesn't know what year you want") return response(r"Error: Logbook downloader doesn't know what year you want")
if 'year' in request.GET: if 'year' in request.GET:
year=request.GET['year'] year=request.GET['year']
if 'extension' in request.GET: if 'extension' in request.GET:
extension=request.GET['extension'] extension=request.GET['extension']
if extension =='txt': if extension =='txt':
response = HttpResponse(mimetype='text/plain') response = HttpResponse(mimetype='text/plain')
style='2008' style='2008'
elif extension == 'html': elif extension == 'html':
response = HttpResponse(mimetype='text/html') response = HttpResponse(mimetype='text/html')
style='2005' style='2005'
template='logbook'+style+'style.'+extension template='logbook'+style+'style.'+extension
response['Content-Disposition'] = 'attachment; filename='+filename+'.'+extension response['Content-Disposition'] = 'attachment; filename='+filename+'.'+extension
t=loader.get_template(template) t=loader.get_template(template)
c=Context({'logbook_entries':logbook_entries}) c=Context({'logbook_entries':logbook_entries})
response.write(t.render(c)) response.write(t.render(c))
return response return response
def downloadQMs(request): def downloadQMs(request):
# Note to self: use get_cave method for the below # Note to self: use get_cave method for the below
if request.method=='GET': if request.method=='GET':
try: try:
cave=Cave.objects.get(kataster_number=request.GET['cave_id']) cave=Cave.objects.get(kataster_number=request.GET['cave_id'])
except Cave.DoesNotExist: except Cave.DoesNotExist:
cave=Cave.objects.get(name=cave_id) cave=Cave.objects.get(name=cave_id)
from export import toqms from export import toqms
response = HttpResponse(mimetype='text/csv') response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=qm.csv' response['Content-Disposition'] = 'attachment; filename=qm.csv'
toqms.writeQmTable(response,cave) toqms.writeQmTable(response,cave)
return response return response
def ajax_test(request): def ajax_test(request):
post_text = request.POST['post_data'] post_text = request.POST['post_data']
return HttpResponse("{'response_text': '"+post_text+" recieved.'}", return HttpResponse("{'response_text': '"+post_text+" recieved.'}",
mimetype="application/json") mimetype="application/json")
def eyecandy(request): def eyecandy(request):
return return
def ajax_QM_number(request): def ajax_QM_number(request):
if request.method=='POST': if request.method=='POST':
cave=Cave.objects.get(id=request.POST['cave']) cave=Cave.objects.get(id=request.POST['cave'])
print cave print cave
exp=Expedition.objects.get(pk=request.POST['year']) exp=Expedition.objects.get(pk=request.POST['year'])
print exp print exp
res=cave.new_QM_number(exp.year) res=cave.new_QM_number(exp.year)
return HttpResponse(res) return HttpResponse(res)
def logbook_entry_suggestions(request): def logbook_entry_suggestions(request):
""" """
Generates a html box with suggestions about what to do with QMs Generates a html box with suggestions about what to do with QMs
in logbook entry text. in logbook entry text.
""" """
unwiki_QM_pattern=r"(?P<whole>(?P<explorer_code>[ABC]?)(?P<cave>\d*)-?(?P<year>\d\d\d?\d?)-(?P<number>\d\d)(?P<grade>[ABCDXV]?))" unwiki_QM_pattern=r"(?P<whole>(?P<explorer_code>[ABC]?)(?P<cave>\d*)-?(?P<year>\d\d\d?\d?)-(?P<number>\d\d)(?P<grade>[ABCDXV]?))"
unwiki_QM_pattern=re.compile(unwiki_QM_pattern) unwiki_QM_pattern=re.compile(unwiki_QM_pattern)
#wikilink_QM_pattern=settings.QM_PATTERN #wikilink_QM_pattern=settings.QM_PATTERN
slug=request.POST['slug'] slug=request.POST['slug']
date=request.POST['date'] date=request.POST['date']
lbo=LogbookEntry.objects.get(slug=slug, date=date) lbo=LogbookEntry.objects.get(slug=slug, date=date)
#unwiki_QMs=re.findall(unwiki_QM_pattern,lbo.text) #unwiki_QMs=re.findall(unwiki_QM_pattern,lbo.text)
unwiki_QMs=[m.groupdict() for m in unwiki_QM_pattern.finditer(lbo.text)] unwiki_QMs=[m.groupdict() for m in unwiki_QM_pattern.finditer(lbo.text)]
print unwiki_QMs print unwiki_QMs
for qm in unwiki_QMs: for qm in unwiki_QMs:
#try: #try:
if len(qm['year'])==2: if len(qm['year'])==2:
if int(qm['year'])<50: if int(qm['year'])<50:
qm['year']='20'+qm['year'] qm['year']='20'+qm['year']
else: else:
qm['year']='19'+qm['year'] qm['year']='19'+qm['year']
if lbo.date.year!=int(qm['year']): if lbo.date.year!=int(qm['year']):
try: try:
lbo=LogbookEntry.objects.get(date__year=qm['year'],title__icontains="placeholder for QMs in") lbo=LogbookEntry.objects.get(date__year=qm['year'],title__icontains="placeholder for QMs in")
except: except:
print "failed to get placeholder for year "+str(qm['year']) print "failed to get placeholder for year "+str(qm['year'])
temp_QM=QM(found_by=lbo,number=qm['number'],grade=qm['grade']) temp_QM=QM(found_by=lbo,number=qm['number'],grade=qm['grade'])
temp_QM.grade=qm['grade'] temp_QM.grade=qm['grade']
qm['wikilink']=temp_QM.wiki_link() qm['wikilink']=temp_QM.wiki_link()
#except: #except:
#print 'failed' #print 'failed'
print unwiki_QMs print unwiki_QMs
#wikilink_QMs=re.findall(wikilink_QM_pattern,lbo.text) #wikilink_QMs=re.findall(wikilink_QM_pattern,lbo.text)
attached_QMs=lbo.QMs_found.all() attached_QMs=lbo.QMs_found.all()
unmentioned_attached_QMs=''#not implemented, fill this in by subtracting wiklink_QMs from attached_QMs unmentioned_attached_QMs=''#not implemented, fill this in by subtracting wiklink_QMs from attached_QMs
#Find unattached_QMs. We only look at the QMs with a proper wiki link. #Find unattached_QMs. We only look at the QMs with a proper wiki link.
#for qm in wikilink_QMs: #for qm in wikilink_QMs:
#Try to look up the QM. #Try to look up the QM.
print 'got 208' print 'got 208'
any_suggestions=True any_suggestions=True
print 'got 210' print 'got 210'
return render_with_context(request,'suggestions.html', return render_with_context(request,'suggestions.html',
{ {
'unwiki_QMs':unwiki_QMs, 'unwiki_QMs':unwiki_QMs,
'any_suggestions':any_suggestions 'any_suggestions':any_suggestions
}) })
@login_required_if_public @login_required_if_public
def newFile(request, pslug = None): def newFile(request, pslug = None):
# if pslug: # if pslug:
# previousfile = LogbookEntry.objects.get(slug = pslug, date = previousdate, expedition = expedition) # previousfile = LogbookEntry.objects.get(slug = pslug, date = previousdate, expedition = expedition)
# assert previousfile.filename # assert previousfile.filename
if request.method == 'POST': # If the form has been submitted... if request.method == 'POST': # If the form has been submitted...
tripForm = TripForm(request.POST) # A form bound to the POST data tripForm = TripForm(request.POST) # A form bound to the POST data
# personTripFormSet = PersonTripFormSet(request.POST) # personTripFormSet = PersonTripFormSet(request.POST)
# if tripForm.is_valid() and personTripFormSet.is_valid(): # All validation rules pass # if tripForm.is_valid() and personTripFormSet.is_valid(): # All validation rules pass
# dateStr = tripForm.cleaned_data["date"].strftime("%Y-%m-%d") # dateStr = tripForm.cleaned_data["date"].strftime("%Y-%m-%d")
# directory = os.path.join(settings.EXPOWEB, # directory = os.path.join(settings.EXPOWEB,
# "years", # "years",
# expedition.year, # expedition.year,
# "autologbook") # "autologbook")
# filename = os.path.join(directory, # filename = os.path.join(directory,
# dateStr + "." + slugify(tripForm.cleaned_data["title"])[:50] + ".html") # dateStr + "." + slugify(tripForm.cleaned_data["title"])[:50] + ".html")
# if not os.path.isdir(directory): # if not os.path.isdir(directory):
# os.mkdir(directory) # os.mkdir(directory)
# if pslug and pdate: # if pslug and pdate:
# delLogbookEntry(previouslbe) # delLogbookEntry(previouslbe)
# f = open(filename, "w") # f = open(filename, "w")
# template = loader.get_template('dataformat/logbookentry.html') # template = loader.get_template('dataformat/logbookentry.html')
# context = Context({'trip': tripForm.cleaned_data, # context = Context({'trip': tripForm.cleaned_data,
# 'persons': personTripFormSet.cleaned_data, # 'persons': personTripFormSet.cleaned_data,
# 'date': dateStr, # 'date': dateStr,
# 'expeditionyear': expeditionyear}) # 'expeditionyear': expeditionyear})
# f.write(template.render(context)) # f.write(template.render(context))
# f.close() # f.close()
# print logbookparsers.parseAutoLogBookEntry(filename) # print logbookparsers.parseAutoLogBookEntry(filename)
# return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST # return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST
else: else:
if pslug: if pslug:
pass pass
# if previouslbe.cave: # if previouslbe.cave:
# tripForm = TripForm(initial={"date": previousdate, # tripForm = TripForm(initial={"date": previousdate,
# "title": previouslbe.title, # "title": previouslbe.title,
# "cave": previouslbe.cave.reference(), # "cave": previouslbe.cave.reference(),
# "location": None, # "location": None,
# "caveOrLocation": "cave", # "caveOrLocation": "cave",
# "html": previouslbe.text}) # "html": previouslbe.text})
# else: # else:
# tripForm = TripForm(initial={"date": previousdate, # tripForm = TripForm(initial={"date": previousdate,
# "title": previouslbe.title, # "title": previouslbe.title,
# "cave": None, # "cave": None,
# "location": previouslbe.place, # "location": previouslbe.place,
# "caveOrLocation": "location", # "caveOrLocation": "location",
# "html": previouslbe.text}) # "html": previouslbe.text})
# personTripFormSet = PersonTripFormSet(initial=[{"name": get_name(py.personexpedition), # personTripFormSet = PersonTripFormSet(initial=[{"name": get_name(py.personexpedition),
# "TU": py.time_underground, # "TU": py.time_underground,
# "author": py.is_logbook_entry_author} # "author": py.is_logbook_entry_author}
# for py in previouslbe.persontrip_set.all()]) # for py in previouslbe.persontrip_set.all()])
else: else:
fileform = UploadFileForm() # An unbound form fileform = UploadFileForm() # An unbound form
return render_with_context(request, 'editfile.html', { return render_with_context(request, 'editfile.html', {
'fileForm': fileform, 'fileForm': fileform,
}) })
@login_required_if_public @login_required_if_public
def deleteFile(request, expeditionyear, date = None, slug = None): def deleteFile(request, expeditionyear, date = None, slug = None):
expedition = Expedition.objects.get(year=expeditionyear) expedition = Expedition.objects.get(year=expeditionyear)
previousdate = datetime.date(*[int(x) for x in date.split("-")]) previousdate = datetime.date(*[int(x) for x in date.split("-")])
previouslbe = LogbookEntry.objects.get(slug = slug, date = previousdate, expedition = expedition) previouslbe = LogbookEntry.objects.get(slug = slug, date = previousdate, expedition = expedition)
delLogbookEntry(previouslbe) delLogbookEntry(previouslbe)
return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST return HttpResponseRedirect(reverse('expedition', args=[expedition.year])) # Redirect after POST
def delFile(f): def delFile(f):
for pt in lbe.persontrip_set.all(): for pt in lbe.persontrip_set.all():
pt.delete() pt.delete()
lbe.delete() lbe.delete()
os.remove(lbe.filename) os.remove(lbe.filename)

View File

@ -1,318 +1,318 @@
from django import forms from django import forms
from django.http import HttpResponseRedirect, HttpResponse from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
import re import re
import os import os
import datetime import datetime
import difflib import difflib
from troggle.core.models import Expedition, Person, PersonExpedition, PersonTrip, LogbookEntry, Cave from troggle.core.models import Expedition, Person, PersonExpedition, PersonTrip, LogbookEntry, Cave
from troggle.core.models import SurvexBlock, SurvexPersonRole, SurvexFile, SurvexDirectory, SurvexTitle from troggle.core.models import SurvexBlock, SurvexPersonRole, SurvexFile, SurvexDirectory, SurvexTitle
from parsers.people import GetPersonExpeditionNameLookup from parsers.people import GetPersonExpeditionNameLookup
import troggle.settings as settings import troggle.settings as settings
import parsers.survex import parsers.survex
survextemplatefile = """; Locn: Totes Gebirge, Austria - Loser/Augst-Eck Plateau (kataster group 1623) survextemplatefile = """; Locn: Totes Gebirge, Austria - Loser/Augst-Eck Plateau (kataster group 1623)
; Cave: ; Cave:
*begin [surveyname] *begin [surveyname]
*export [connecting stations] *export [connecting stations]
*title "area title" *title "area title"
*date 2999.99.99 *date 2999.99.99
*team Insts [Caver] *team Insts [Caver]
*team Insts [Caver] *team Insts [Caver]
*team Notes [Caver] *team Notes [Caver]
*instrument [set number] *instrument [set number]
;ref.: 2009#NN ;ref.: 2009#NN
*calibrate tape +0.0 ; +ve if tape was too short, -ve if too long *calibrate tape +0.0 ; +ve if tape was too short, -ve if too long
*data normal from to tape compass clino *data normal from to tape compass clino
1 2 3.90 298 -20 1 2 3.90 298 -20
*data passage station left right up down ignoreall *data passage station left right up down ignoreall
1 [L] [R] [U] [D] comment 1 [L] [R] [U] [D] comment
*end [surveyname]""" *end [surveyname]"""
def ReplaceTabs(stext): def ReplaceTabs(stext):
res = [ ] res = [ ]
nsl = 0 nsl = 0
for s in re.split("(\t|\n)", stext): for s in re.split("(\t|\n)", stext):
if s == "\t": if s == "\t":
res.append(" " * (4 - (nsl % 4))) res.append(" " * (4 - (nsl % 4)))
nsl = 0 nsl = 0
continue continue
if s == "\n": if s == "\n":
nsl = 0 nsl = 0
else: else:
nsl += len(s) nsl += len(s)
res.append(s) res.append(s)
return "".join(res) return "".join(res)
class SvxForm(forms.Form): class SvxForm(forms.Form):
dirname = forms.CharField(widget=forms.TextInput(attrs={"readonly":True})) dirname = forms.CharField(widget=forms.TextInput(attrs={"readonly":True}))
filename = forms.CharField(widget=forms.TextInput(attrs={"readonly":True})) filename = forms.CharField(widget=forms.TextInput(attrs={"readonly":True}))
datetime = forms.DateTimeField(widget=forms.TextInput(attrs={"readonly":True})) datetime = forms.DateTimeField(widget=forms.TextInput(attrs={"readonly":True}))
outputtype = forms.CharField(widget=forms.TextInput(attrs={"readonly":True})) outputtype = forms.CharField(widget=forms.TextInput(attrs={"readonly":True}))
code = forms.CharField(widget=forms.Textarea(attrs={"cols":150, "rows":18})) code = forms.CharField(widget=forms.Textarea(attrs={"cols":150, "rows":18}))
def GetDiscCode(self): def GetDiscCode(self):
fname = settings.SURVEX_DATA + self.data['filename'] + ".svx" fname = settings.SURVEX_DATA + self.data['filename'] + ".svx"
if not os.path.isfile(fname): if not os.path.isfile(fname):
return survextemplatefile return survextemplatefile
fin = open(fname, "rb") fin = open(fname, "rb")
svxtext = fin.read().decode("latin1") # unicode(a, "latin1") svxtext = fin.read().decode("latin1") # unicode(a, "latin1")
svxtext = ReplaceTabs(svxtext).strip() svxtext = ReplaceTabs(svxtext).strip()
fin.close() fin.close()
return svxtext return svxtext
def DiffCode(self, rcode): def DiffCode(self, rcode):
code = self.GetDiscCode() code = self.GetDiscCode()
difftext = difflib.unified_diff(code.splitlines(), rcode.splitlines()) difftext = difflib.unified_diff(code.splitlines(), rcode.splitlines())
difflist = [ diffline.strip() for diffline in difftext if not re.match("\s*$", diffline) ] difflist = [ diffline.strip() for diffline in difftext if not re.match("\s*$", diffline) ]
return difflist return difflist
def SaveCode(self, rcode): def SaveCode(self, rcode):
fname = settings.SURVEX_DATA + self.data['filename'] + ".svx" fname = settings.SURVEX_DATA + self.data['filename'] + ".svx"
if not os.path.isfile(fname): if not os.path.isfile(fname):
# only save if appears valid # only save if appears valid
if re.search("\[|\]", rcode): if re.search("\[|\]", rcode):
return "Error: clean up all []s from the text" return "Error: clean up all []s from the text"
mbeginend = re.search("(?s)\*begin\s+(\w+).*?\*end\s+(\w+)", rcode) mbeginend = re.search("(?s)\*begin\s+(\w+).*?\*end\s+(\w+)", rcode)
if not mbeginend: if not mbeginend:
return "Error: no begin/end block here" return "Error: no begin/end block here"
if mbeginend.group(1) != mbeginend.group(2): if mbeginend.group(1) != mbeginend.group(2):
return "Error: mismatching beginend" return "Error: mismatching beginend"
fout = open(fname, "w") fout = open(fname, "w")
res = fout.write(rcode.encode("latin1")) res = fout.write(rcode.encode("latin1"))
fout.close() fout.close()
return "SAVED" return "SAVED"
def Process(self): def Process(self):
print "....\n\n\n....Processing\n\n\n" print "....\n\n\n....Processing\n\n\n"
cwd = os.getcwd() cwd = os.getcwd()
os.chdir(os.path.split(settings.SURVEX_DATA + self.data['filename'])[0]) os.chdir(os.path.split(settings.SURVEX_DATA + self.data['filename'])[0])
os.system(settings.CAVERN + " --log " + settings.SURVEX_DATA + self.data['filename'] + ".svx") os.system(settings.CAVERN + " --log " + settings.SURVEX_DATA + self.data['filename'] + ".svx")
os.chdir(cwd) os.chdir(cwd)
fin = open(settings.SURVEX_DATA + self.data['filename'] + ".log", "rb") fin = open(settings.SURVEX_DATA + self.data['filename'] + ".log", "rb")
log = fin.read() log = fin.read()
fin.close() fin.close()
log = re.sub("(?s).*?(Survey contains)", "\\1", log) log = re.sub("(?s).*?(Survey contains)", "\\1", log)
return log return log
def svx(request, survex_file): def svx(request, survex_file):
# get the basic data from the file given in the URL # get the basic data from the file given in the URL
dirname = os.path.split(survex_file)[0] dirname = os.path.split(survex_file)[0]
dirname += "/" dirname += "/"
nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
outputtype = "normal" outputtype = "normal"
form = SvxForm({'filename':survex_file, 'dirname':dirname, 'datetime':nowtime, 'outputtype':outputtype}) form = SvxForm({'filename':survex_file, 'dirname':dirname, 'datetime':nowtime, 'outputtype':outputtype})
# if the form has been returned # if the form has been returned
difflist = [ ] difflist = [ ]
logmessage = "" logmessage = ""
message = "" message = ""
if request.method == 'POST': # If the form has been submitted... if request.method == 'POST': # If the form has been submitted...
rform = SvxForm(request.POST) # rform = SvxForm(request.POST) #
if rform.is_valid(): # All validation rules pass (how do we check it against the filename and users?) if rform.is_valid(): # All validation rules pass (how do we check it against the filename and users?)
rcode = rform.cleaned_data['code'] rcode = rform.cleaned_data['code']
outputtype = rform.cleaned_data['outputtype'] outputtype = rform.cleaned_data['outputtype']
difflist = form.DiffCode(rcode) difflist = form.DiffCode(rcode)
#print "ssss", rform.data #print "ssss", rform.data
if "revert" in rform.data: if "revert" in rform.data:
pass pass
if "process" in rform.data: if "process" in rform.data:
if not difflist: if not difflist:
message = "OUTPUT FROM PROCESSING" message = "OUTPUT FROM PROCESSING"
logmessage = form.Process() logmessage = form.Process()
print logmessage print logmessage
else: else:
message = "SAVE FILE FIRST" message = "SAVE FILE FIRST"
form.data['code'] = rcode form.data['code'] = rcode
if "save" in rform.data: if "save" in rform.data:
if request.user.is_authenticated(): if request.user.is_authenticated():
#print "sssavvving" #print "sssavvving"
message = form.SaveCode(rcode) message = form.SaveCode(rcode)
else: else:
message = "You do not have authority to save this file" message = "You do not have authority to save this file"
if message != "SAVED": if message != "SAVED":
form.data['code'] = rcode form.data['code'] = rcode
if "diff" in rform.data: if "diff" in rform.data:
form.data['code'] = rcode form.data['code'] = rcode
#process(survex_file) #process(survex_file)
if 'code' not in form.data: if 'code' not in form.data:
form.data['code'] = form.GetDiscCode() form.data['code'] = form.GetDiscCode()
if not difflist: if not difflist:
difflist.append("none") difflist.append("none")
if message: if message:
difflist.insert(0, message) difflist.insert(0, message)
#print [ form.data['code'] ] #print [ form.data['code'] ]
svxincludes = re.findall('\*include\s+(\S+)(?i)', form.data['code'] or "") svxincludes = re.findall('\*include\s+(\S+)(?i)', form.data['code'] or "")
vmap = {'settings': settings, vmap = {'settings': settings,
'has_3d': os.path.isfile(settings.SURVEX_DATA + survex_file + ".3d"), 'has_3d': os.path.isfile(settings.SURVEX_DATA + survex_file + ".3d"),
'title': survex_file, 'title': survex_file,
'svxincludes': svxincludes, 'svxincludes': svxincludes,
'difflist': difflist, 'difflist': difflist,
'logmessage':logmessage, 'logmessage':logmessage,
'form':form} 'form':form}
if outputtype == "ajax": if outputtype == "ajax":
return render_to_response('svxfiledifflistonly.html', vmap) return render_to_response('svxfiledifflistonly.html', vmap)
return render_to_response('svxfile.html', vmap) return render_to_response('svxfile.html', vmap)
def svxraw(request, survex_file): def svxraw(request, survex_file):
svx = open(os.path.join(settings.SURVEX_DATA, survex_file+".svx"), "rb") svx = open(os.path.join(settings.SURVEX_DATA, survex_file+".svx"), "rb")
return HttpResponse(svx, mimetype="text") return HttpResponse(svx, mimetype="text")
# The cavern running function # The cavern running function
def process(survex_file): def process(survex_file):
cwd = os.getcwd() cwd = os.getcwd()
os.chdir(os.path.split(settings.SURVEX_DATA + survex_file)[0]) os.chdir(os.path.split(settings.SURVEX_DATA + survex_file)[0])
os.system(settings.CAVERN + " --log " + settings.SURVEX_DATA + survex_file + ".svx") os.system(settings.CAVERN + " --log " + settings.SURVEX_DATA + survex_file + ".svx")
os.chdir(cwd) os.chdir(cwd)
def threed(request, survex_file): def threed(request, survex_file):
process(survex_file) process(survex_file)
try: try:
threed = open(settings.SURVEX_DATA + survex_file + ".3d", "rb") threed = open(settings.SURVEX_DATA + survex_file + ".3d", "rb")
return HttpResponse(threed, mimetype="model/3d") return HttpResponse(threed, mimetype="model/3d")
except: except:
log = open(settings.SURVEX_DATA + survex_file + ".log", "rb") log = open(settings.SURVEX_DATA + survex_file + ".log", "rb")
return HttpResponse(log, mimetype="text") return HttpResponse(log, mimetype="text")
def log(request, survex_file): def log(request, survex_file):
process(survex_file) process(survex_file)
log = open(settings.SURVEX_DATA + survex_file + ".log", "rb") log = open(settings.SURVEX_DATA + survex_file + ".log", "rb")
return HttpResponse(log, mimetype="text") return HttpResponse(log, mimetype="text")
def err(request, survex_file): def err(request, survex_file):
process(survex_file) process(survex_file)
err = open(settings.SURVEX_DATA + survex_file + ".err", "rb") err = open(settings.SURVEX_DATA + survex_file + ".err", "rb")
return HttpResponse(err, mimetype="text") return HttpResponse(err, mimetype="text")
def identifycavedircontents(gcavedir): def identifycavedircontents(gcavedir):
name = os.path.split(gcavedir)[1] name = os.path.split(gcavedir)[1]
subdirs = [ ] subdirs = [ ]
subsvx = [ ] subsvx = [ ]
primesvx = None primesvx = None
for f in os.listdir(gcavedir): for f in os.listdir(gcavedir):
if name == "204" and (f in ["skel.svx", "template.svx", "204withents.svx"]): if name == "204" and (f in ["skel.svx", "template.svx", "204withents.svx"]):
pass pass
elif name == "136" and (f in ["136-noents.svx"]): elif name == "136" and (f in ["136-noents.svx"]):
pass pass
elif name == "115" and (f in ["115cufix.svx", "115fix.svx"]): elif name == "115" and (f in ["115cufix.svx", "115fix.svx"]):
pass pass
elif os.path.isdir(os.path.join(gcavedir, f)): elif os.path.isdir(os.path.join(gcavedir, f)):
if f[0] != ".": if f[0] != ".":
subdirs.append(f) subdirs.append(f)
elif f[-4:] == ".svx": elif f[-4:] == ".svx":
nf = f[:-4] nf = f[:-4]
if nf.lower() == name.lower() or nf[:3] == "all" or (name, nf) in [("144arge", "144"), ("resurvey2005", "145-2005"), ("cucc", "cu115")]: if nf.lower() == name.lower() or nf[:3] == "all" or (name, nf) in [("144arge", "144"), ("resurvey2005", "145-2005"), ("cucc", "cu115")]:
if primesvx: if primesvx:
if nf[:3] == "all": if nf[:3] == "all":
assert primesvx[:3] != "all", (name, nf, primesvx, gcavedir, subsvx) assert primesvx[:3] != "all", (name, nf, primesvx, gcavedir, subsvx)
primesvx = nf primesvx = nf
else: else:
assert primesvx[:3] == "all", (name, nf, primesvx, gcavedir, subsvx) assert primesvx[:3] == "all", (name, nf, primesvx, gcavedir, subsvx)
else: else:
primesvx = nf primesvx = nf
else: else:
subsvx.append(nf) subsvx.append(nf)
else: else:
assert re.match(".*?(?:.3d|.log|.err|.txt|.tmp|.diff|.e?spec|~)$", f), (gcavedir, f) assert re.match(".*?(?:.3d|.log|.err|.txt|.tmp|.diff|.e?spec|~)$", f), (gcavedir, f)
subsvx.sort() subsvx.sort()
assert primesvx, (gcavedir, subsvx) assert primesvx, (gcavedir, subsvx)
if primesvx: if primesvx:
subsvx.insert(0, primesvx) subsvx.insert(0, primesvx)
return subdirs, subsvx return subdirs, subsvx
# direct local non-database browsing through the svx file repositories # direct local non-database browsing through the svx file repositories
# perhaps should use the database and have a reload button for it # perhaps should use the database and have a reload button for it
def survexcaveslist(request): def survexcaveslist(request):
cavesdir = os.path.join(settings.SURVEX_DATA, "caves") cavesdir = os.path.join(settings.SURVEX_DATA, "caves")
cavesdircontents = { } cavesdircontents = { }
onefilecaves = [ ] onefilecaves = [ ]
multifilecaves = [ ] multifilecaves = [ ]
subdircaves = [ ] subdircaves = [ ]
# first sort the file list # first sort the file list
fnumlist = [ (-int(re.match("\d*", f).group(0) or "0"), f) for f in os.listdir(cavesdir) ] fnumlist = [ (-int(re.match("\d*", f).group(0) or "0"), f) for f in os.listdir(cavesdir) ]
fnumlist.sort() fnumlist.sort()
# go through the list and identify the contents of each cave directory # go through the list and identify the contents of each cave directory
for num, cavedir in fnumlist: for num, cavedir in fnumlist:
if cavedir in ["144", "40"]: if cavedir in ["144", "40"]:
continue continue
gcavedir = os.path.join(cavesdir, cavedir) gcavedir = os.path.join(cavesdir, cavedir)
if os.path.isdir(gcavedir) and cavedir[0] != ".": if os.path.isdir(gcavedir) and cavedir[0] != ".":
subdirs, subsvx = identifycavedircontents(gcavedir) subdirs, subsvx = identifycavedircontents(gcavedir)
survdirobj = [ ] survdirobj = [ ]
for lsubsvx in subsvx: for lsubsvx in subsvx:
survdirobj.append(("caves/"+cavedir+"/"+lsubsvx, lsubsvx)) survdirobj.append(("caves/"+cavedir+"/"+lsubsvx, lsubsvx))
# caves with subdirectories # caves with subdirectories
if subdirs: if subdirs:
subsurvdirs = [ ] subsurvdirs = [ ]
for subdir in subdirs: for subdir in subdirs:
dsubdirs, dsubsvx = identifycavedircontents(os.path.join(gcavedir, subdir)) dsubdirs, dsubsvx = identifycavedircontents(os.path.join(gcavedir, subdir))
assert not dsubdirs assert not dsubdirs
lsurvdirobj = [ ] lsurvdirobj = [ ]
for lsubsvx in dsubsvx: for lsubsvx in dsubsvx:
lsurvdirobj.append(("caves/"+cavedir+"/"+subdir+"/"+lsubsvx, lsubsvx)) lsurvdirobj.append(("caves/"+cavedir+"/"+subdir+"/"+lsubsvx, lsubsvx))
subsurvdirs.append((lsurvdirobj[0], lsurvdirobj[1:])) subsurvdirs.append((lsurvdirobj[0], lsurvdirobj[1:]))
subdircaves.append((cavedir, (survdirobj[0], survdirobj[1:]), subsurvdirs)) subdircaves.append((cavedir, (survdirobj[0], survdirobj[1:]), subsurvdirs))
# multifile caves # multifile caves
elif len(survdirobj) > 1: elif len(survdirobj) > 1:
multifilecaves.append((survdirobj[0], survdirobj[1:])) multifilecaves.append((survdirobj[0], survdirobj[1:]))
# single file caves # single file caves
else: else:
onefilecaves.append(survdirobj[0]) onefilecaves.append(survdirobj[0])
return render_to_response('svxfilecavelist.html', {'settings': settings, "onefilecaves":onefilecaves, "multifilecaves":multifilecaves, "subdircaves":subdircaves }) return render_to_response('svxfilecavelist.html', {'settings': settings, "onefilecaves":onefilecaves, "multifilecaves":multifilecaves, "subdircaves":subdircaves })
# parsing all the survex files of a single cave and showing that it's consistent and can find all the files and people # parsing all the survex files of a single cave and showing that it's consistent and can find all the files and people
# doesn't use recursion. just writes it twice # doesn't use recursion. just writes it twice
def survexcavesingle(request, survex_cave): def survexcavesingle(request, survex_cave):
breload = False breload = False
cave = Cave.objects.get(kataster_number=survex_cave) cave = Cave.objects.get(kataster_number=survex_cave)
if breload: if breload:
parsers.survex.ReloadSurvexCave(survex_cave) parsers.survex.ReloadSurvexCave(survex_cave)
return render_to_response('svxcavesingle.html', {'settings': settings, "cave":cave }) return render_to_response('svxcavesingle.html', {'settings': settings, "cave":cave })

View File

@ -1,217 +1,217 @@
import os import os
import time import time
import settings import settings
os.environ['PYTHONPATH'] = settings.PYTHON_PATH os.environ['PYTHONPATH'] = settings.PYTHON_PATH
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.core import management from django.core import management
from django.db import connection from django.db import connection
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.http import HttpResponse from django.http import HttpResponse
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
import flatpages.models import flatpages.models
def reload_db(): def reload_db():
if settings.DATABASE_ENGINE == 'sqlite3': if settings.DATABASE_ENGINE == 'sqlite3':
try: try:
os.remove(settings.DATABASE_NAME) os.remove(settings.DATABASE_NAME)
except OSError: except OSError:
pass pass
else: else:
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("DROP DATABASE %s" % settings.DATABASE_NAME) cursor.execute("DROP DATABASE %s" % settings.DATABASE_NAME)
cursor.execute("CREATE DATABASE %s" % settings.DATABASE_NAME) cursor.execute("CREATE DATABASE %s" % settings.DATABASE_NAME)
cursor.execute("ALTER DATABASE %s CHARACTER SET=utf8" % settings.DATABASE_NAME) cursor.execute("ALTER DATABASE %s CHARACTER SET=utf8" % settings.DATABASE_NAME)
cursor.execute("USE %s" % settings.DATABASE_NAME) cursor.execute("USE %s" % settings.DATABASE_NAME)
management.call_command('syncdb', interactive=False) management.call_command('syncdb', interactive=False)
user = User.objects.create_user('expo', 'goatchurch@gmail.com', 'gosser') user = User.objects.create_user('expo', 'goatchurch@gmail.com', 'gosser')
user.is_staff = True user.is_staff = True
user.is_superuser = True user.is_superuser = True
user.save() user.save()
def make_dirs(): def make_dirs():
"""Make directories that troggle requires""" """Make directories that troggle requires"""
#should also deal with permissions here. #should also deal with permissions here.
if not os.path.isdir(settings.PHOTOS_ROOT): if not os.path.isdir(settings.PHOTOS_ROOT):
os.mkdir(settings.PHOTOS_ROOT) os.mkdir(settings.PHOTOS_ROOT)
def import_cavetab(): def import_cavetab():
import parsers.cavetab import parsers.cavetab
print "importing cavetab" print "importing cavetab"
parsers.cavetab.LoadCaveTab() parsers.cavetab.LoadCaveTab()
def import_people(): def import_people():
import parsers.people import parsers.people
parsers.people.LoadPersonsExpos() parsers.people.LoadPersonsExpos()
def import_logbooks(): def import_logbooks():
# The below line was causing errors I didn't understand (it said LOGFILE was a string), and I couldn't be bothered to figure # The below line was causing errors I didn't understand (it said LOGFILE was a string), and I couldn't be bothered to figure
# what was going on so I just catch the error with a try. - AC 21 May # what was going on so I just catch the error with a try. - AC 21 May
try: try:
settings.LOGFILE.write('\nBegun importing logbooks at ' + time.asctime() +'\n'+'-'*60) settings.LOGFILE.write('\nBegun importing logbooks at ' + time.asctime() +'\n'+'-'*60)
except: except:
pass pass
import parsers.logbooks import parsers.logbooks
parsers.logbooks.LoadLogbooks() parsers.logbooks.LoadLogbooks()
def import_survex(): def import_survex():
import parsers.survex import parsers.survex
parsers.survex.LoadAllSurvexBlocks() parsers.survex.LoadAllSurvexBlocks()
parsers.survex.LoadPos() parsers.survex.LoadPos()
def import_QMs(): def import_QMs():
import parsers.QMs import parsers.QMs
def import_surveys(): def import_surveys():
import parsers.surveys import parsers.surveys
parsers.surveys.parseSurveys(logfile=settings.LOGFILE) parsers.surveys.parseSurveys(logfile=settings.LOGFILE)
def import_surveyscans(): def import_surveyscans():
import parsers.surveys import parsers.surveys
parsers.surveys.LoadListScans() parsers.surveys.LoadListScans()
def import_descriptions(): def import_descriptions():
import parsers.descriptions import parsers.descriptions
parsers.descriptions.getDescriptions() parsers.descriptions.getDescriptions()
def parse_descriptions(): def parse_descriptions():
import parsers.descriptions import parsers.descriptions
parsers.descriptions.parseDescriptions() parsers.descriptions.parseDescriptions()
parsers.descriptions.parseDescriptionsOnCaveObjects() parsers.descriptions.parseDescriptionsOnCaveObjects()
def import_tunnelfiles(): def import_tunnelfiles():
import parsers.surveys import parsers.surveys
parsers.surveys.LoadTunnelFiles() parsers.surveys.LoadTunnelFiles()
def reset(): def reset():
""" Wipe the troggle database and import everything from legacy data """ Wipe the troggle database and import everything from legacy data
""" """
reload_db() reload_db()
make_dirs() make_dirs()
pageredirects() pageredirects()
import_cavetab() import_cavetab()
import_people() import_people()
import_surveyscans() import_surveyscans()
import_survex() import_survex()
import_logbooks() import_logbooks()
import_QMs() import_QMs()
import_tunnelfiles() import_tunnelfiles()
import_surveys() import_surveys()
import_descriptions() import_descriptions()
parse_descriptions() parse_descriptions()
def resetdesc(): def resetdesc():
""" Wipe the troggle database and import descriptions """ Wipe the troggle database and import descriptions
""" """
import core.models import core.models
for desc in core.models.CaveDescription.objects.all(): for desc in core.models.CaveDescription.objects.all():
desc.delete() desc.delete()
import_descriptions() import_descriptions()
parse_descriptions() parse_descriptions()
def export_cavetab(): def export_cavetab():
from export import tocavetab from export import tocavetab
outfile=file(os.path.join(settings.EXPOWEB, "noinfo", "CAVETAB2.CSV"),'w') outfile=file(os.path.join(settings.EXPOWEB, "noinfo", "CAVETAB2.CSV"),'w')
tocavetab.writeCaveTab(outfile) tocavetab.writeCaveTab(outfile)
outfile.close() outfile.close()
def import_auto_logbooks(): def import_auto_logbooks():
import parsers.logbooks import parsers.logbooks
import os import os
for pt in core.models.PersonTrip.objects.all(): for pt in core.models.PersonTrip.objects.all():
pt.delete() pt.delete()
for lbe in core.models.LogbookEntry.objects.all(): for lbe in core.models.LogbookEntry.objects.all():
lbe.delete() lbe.delete()
for expedition in core.models.Expedition.objects.all(): for expedition in core.models.Expedition.objects.all():
directory = os.path.join(settings.EXPOWEB, directory = os.path.join(settings.EXPOWEB,
"years", "years",
expedition.year, expedition.year,
"autologbook") "autologbook")
for root, dirs, filenames in os.walk(directory): for root, dirs, filenames in os.walk(directory):
for filename in filenames: for filename in filenames:
print os.path.join(root, filename) print os.path.join(root, filename)
parsers.logbooks.parseAutoLogBookEntry(os.path.join(root, filename)) parsers.logbooks.parseAutoLogBookEntry(os.path.join(root, filename))
#Temporary function until definative source of data transfered. #Temporary function until definative source of data transfered.
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
from django.template import Context, loader from django.template import Context, loader
def dumplogbooks(): def dumplogbooks():
def get_name(pe): def get_name(pe):
if pe.nickname: if pe.nickname:
return pe.nickname return pe.nickname
else: else:
return pe.person.first_name return pe.person.first_name
for lbe in core.models.LogbookEntry.objects.all(): for lbe in core.models.LogbookEntry.objects.all():
dateStr = lbe.date.strftime("%Y-%m-%d") dateStr = lbe.date.strftime("%Y-%m-%d")
directory = os.path.join(settings.EXPOWEB, directory = os.path.join(settings.EXPOWEB,
"years", "years",
lbe.expedition.year, lbe.expedition.year,
"autologbook") "autologbook")
if not os.path.isdir(directory): if not os.path.isdir(directory):
os.mkdir(directory) os.mkdir(directory)
filename = os.path.join(directory, filename = os.path.join(directory,
dateStr + "." + slugify(lbe.title)[:50] + ".html") dateStr + "." + slugify(lbe.title)[:50] + ".html")
if lbe.cave: if lbe.cave:
print lbe.cave.reference() print lbe.cave.reference()
trip = {"title": lbe.title, "html":lbe.text, "cave": lbe.cave.reference(), "caveOrLocation": "cave"} trip = {"title": lbe.title, "html":lbe.text, "cave": lbe.cave.reference(), "caveOrLocation": "cave"}
else: else:
trip = {"title": lbe.title, "html":lbe.text, "location":lbe.place, "caveOrLocation": "location"} trip = {"title": lbe.title, "html":lbe.text, "location":lbe.place, "caveOrLocation": "location"}
pts = [pt for pt in lbe.persontrip_set.all() if pt.personexpedition] pts = [pt for pt in lbe.persontrip_set.all() if pt.personexpedition]
persons = [{"name": get_name(pt.personexpedition), "TU": pt.time_underground, "author": pt.is_logbook_entry_author} for pt in pts] persons = [{"name": get_name(pt.personexpedition), "TU": pt.time_underground, "author": pt.is_logbook_entry_author} for pt in pts]
f = open(filename, "wb") f = open(filename, "wb")
template = loader.get_template('dataformat/logbookentry.html') template = loader.get_template('dataformat/logbookentry.html')
context = Context({'trip': trip, context = Context({'trip': trip,
'persons': persons, 'persons': persons,
'date': dateStr, 'date': dateStr,
'expeditionyear': lbe.expedition.year}) 'expeditionyear': lbe.expedition.year})
output = template.render(context) output = template.render(context)
f.write(unicode(output).encode( "utf-8" )) f.write(unicode(output).encode( "utf-8" ))
f.close() f.close()
def pageredirects(): def pageredirects():
for oldURL, newURL in [("indxal.htm", reverse("caveindex"))]: for oldURL, newURL in [("indxal.htm", reverse("caveindex"))]:
f = flatpages.models.Redirect(originalURL = oldURL, newURL = newURL) f = flatpages.models.Redirect(originalURL = oldURL, newURL = newURL)
f.save() f.save()
if __name__ == "__main__": if __name__ == "__main__":
import core.models import core.models
import sys import sys
if "desc" in sys.argv: if "desc" in sys.argv:
resetdesc() resetdesc()
elif "scans" in sys.argv: elif "scans" in sys.argv:
import_surveyscans() import_surveyscans()
elif "caves" in sys.argv: elif "caves" in sys.argv:
reload_db() reload_db()
make_dirs() make_dirs()
pageredirects() pageredirects()
import_cavetab() import_cavetab()
elif "QMs" in sys.argv: elif "QMs" in sys.argv:
import_QMs() import_QMs()
elif "tunnel" in sys.argv: elif "tunnel" in sys.argv:
import_tunnelfiles() import_tunnelfiles()
elif "reset" in sys.argv: elif "reset" in sys.argv:
reset() reset()
elif "survex" in sys.argv: elif "survex" in sys.argv:
management.call_command('syncdb', interactive=False) # this sets the path so that import settings works in import_survex management.call_command('syncdb', interactive=False) # this sets the path so that import settings works in import_survex
import_survex() import_survex()
elif "logbooks" in sys.argv: elif "logbooks" in sys.argv:
management.call_command('syncdb', interactive=False) # this sets the path so that import settings works in import_survex management.call_command('syncdb', interactive=False) # this sets the path so that import settings works in import_survex
import_logbooks() import_logbooks()
elif "autologbooks" in sys.argv: elif "autologbooks" in sys.argv:
import_auto_logbooks() import_auto_logbooks()
elif "dumplogbooks" in sys.argv: elif "dumplogbooks" in sys.argv:
dumplogbooks() dumplogbooks()
else: else:
print "Do 'python databaseReset.py reset'" print "Do 'python databaseReset.py reset'"

View File

@ -1,49 +1,49 @@
import troggle.core.models as models import troggle.core.models as models
from django.conf import settings from django.conf import settings
import csv, re, os import csv, re, os
#format of CAVETAB2.CSV is #format of CAVETAB2.CSV is
headers=['KatasterNumber','KatStatusCode','Entrances','UnofficialNumber','MultipleEntrances','AutogenFile','LinkFile','LinkEntrance','Name','UnofficialName', headers=['KatasterNumber','KatStatusCode','Entrances','UnofficialNumber','MultipleEntrances','AutogenFile','LinkFile','LinkEntrance','Name','UnofficialName',
'Comment','Area','Explorers','UndergroundDescription','Equipment','QMList','KatasterStatus','References','UndergroundCentreLine','UndergroundDrawnSurvey', 'Comment','Area','Explorers','UndergroundDescription','Equipment','QMList','KatasterStatus','References','UndergroundCentreLine','UndergroundDrawnSurvey',
'SurvexFile','Length','Depth','Extent','Notes','EntranceName','TagPoint','OtherPoint','DescriptionOfOtherPoint','ExactEntrance','TypeOfFix','GPSpreSA', 'SurvexFile','Length','Depth','Extent','Notes','EntranceName','TagPoint','OtherPoint','DescriptionOfOtherPoint','ExactEntrance','TypeOfFix','GPSpreSA',
'GPSpostSA','Northing','Easting','Altitude','Bearings','Map','Location','Approach','EntranceDescription','PhotoOfLocation','Marking','MarkingComment', 'GPSpostSA','Northing','Easting','Altitude','Bearings','Map','Location','Approach','EntranceDescription','PhotoOfLocation','Marking','MarkingComment',
'Findability','FindabilityComment'] 'Findability','FindabilityComment']
def cavetabRow(cave): def cavetabRow(cave):
#mapping of troggle models to table columns is: (guess this could just be a tuple of tuples rather than a dictionary actually) #mapping of troggle models to table columns is: (guess this could just be a tuple of tuples rather than a dictionary actually)
columnsToModelFields={ columnsToModelFields={
'Name':cave.official_name, 'Name':cave.official_name,
'Area':cave.kat_area(), 'Area':cave.kat_area(),
'KatStatusCode':cave.kataster_code, 'KatStatusCode':cave.kataster_code,
'KatasterNumber':cave.kataster_number, 'KatasterNumber':cave.kataster_number,
'UnofficialNumber':cave.unofficial_number, 'UnofficialNumber':cave.unofficial_number,
#'' : cave.entrances This is a multiple foreignkey now, may be tricky to dump back into csv. Work on this. #'' : cave.entrances This is a multiple foreignkey now, may be tricky to dump back into csv. Work on this.
'Explorers':cave.explorers, 'Explorers':cave.explorers,
'UndergroundDescription':cave.underground_description, 'UndergroundDescription':cave.underground_description,
'Equipment':cave.equipment, 'Equipment':cave.equipment,
'References':cave.references, 'References':cave.references,
'UndergroundDrawnSurvey':cave.survey, 'UndergroundDrawnSurvey':cave.survey,
'KatasterStatus':cave.kataster_status, 'KatasterStatus':cave.kataster_status,
'UndergroundCentreLine':cave.underground_centre_line, 'UndergroundCentreLine':cave.underground_centre_line,
'Notes':cave.notes, 'Notes':cave.notes,
'Length':cave.length, 'Length':cave.length,
'Depth':cave.depth, 'Depth':cave.depth,
'Extent':cave.extent, 'Extent':cave.extent,
'SurvexFile':cave.survex_file, 'SurvexFile':cave.survex_file,
} }
caveRow=['' for x in range(len(headers))] caveRow=['' for x in range(len(headers))]
for column, modelField in columnsToModelFields.items(): for column, modelField in columnsToModelFields.items():
if modelField: if modelField:
# Very sorry about the atrocious replace below. I will fix this soon if noone beats me to it. - AC # Very sorry about the atrocious replace below. I will fix this soon if noone beats me to it. - AC
caveRow[headers.index(column)]=modelField.replace(u'\xd7','x').replace(u'\u201c','').replace(u'\u2013','').replace(u'\xbd','') caveRow[headers.index(column)]=modelField.replace(u'\xd7','x').replace(u'\u201c','').replace(u'\u2013','').replace(u'\xbd','')
return caveRow return caveRow
def writeCaveTab(outfile): def writeCaveTab(outfile):
cavewriter=csv.writer(outfile,lineterminator='\r') cavewriter=csv.writer(outfile,lineterminator='\r')
cavewriter.writerow(headers) cavewriter.writerow(headers)
for cave in models.Cave.objects.all(): for cave in models.Cave.objects.all():
cavewriter.writerow(cavetabRow(cave)) cavewriter.writerow(cavetabRow(cave))

View File

@ -1,16 +1,16 @@
import troggle.core.models as models import troggle.core.models as models
from django.conf import settings from django.conf import settings
import csv import csv
import re import re
import os import os
#format of QM tables #format of QM tables
headers=['Number','Grade','Area','Description','Page reference','Nearest station','Completion description','Comment'] headers=['Number','Grade','Area','Description','Page reference','Nearest station','Completion description','Comment']
def qmRow(qm): def qmRow(qm):
#mapping of troggle models to table columns is: (guess this could just be a tuple of tuples rather than a dictionary actually) #mapping of troggle models to table columns is: (guess this could just be a tuple of tuples rather than a dictionary actually)
columnsToModelFields={ columnsToModelFields={
'Number':str(qm.number), 'Number':str(qm.number),
'Grade':qm.grade, 'Grade':qm.grade,
'Area':qm.area, 'Area':qm.area,
@ -18,19 +18,19 @@ def qmRow(qm):
#'Page reference': #not implemented #'Page reference': #not implemented
'Nearest station':qm.nearest_station_description, 'Nearest station':qm.nearest_station_description,
'Completion description':qm.completion_description, 'Completion description':qm.completion_description,
'Comment':qm.comment 'Comment':qm.comment
} }
qmRow=['' for x in range(len(headers))] qmRow=['' for x in range(len(headers))]
for column, modelField in columnsToModelFields.items(): for column, modelField in columnsToModelFields.items():
if modelField: if modelField:
# Very sorry about the atrocious replace below. I will fix this soon if noone beats me to it. - AC # Very sorry about the atrocious replace below. I will fix this soon if noone beats me to it. - AC
qmRow[headers.index(column)]=modelField.replace(u'\xd7','x').replace(u'\u201c','').replace(u'\u2013','').replace(u'\xbd','') qmRow[headers.index(column)]=modelField.replace(u'\xd7','x').replace(u'\u201c','').replace(u'\u2013','').replace(u'\xbd','')
return qmRow return qmRow
def writeQmTable(outfile,cave): def writeQmTable(outfile,cave):
cavewriter=csv.writer(outfile,lineterminator='\r') cavewriter=csv.writer(outfile,lineterminator='\r')
cavewriter.writerow(headers) cavewriter.writerow(headers)
for qm in cave.get_QMs(): for qm in cave.get_QMs():
cavewriter.writerow(qmRow(qm)) cavewriter.writerow(qmRow(qm))

View File

@ -1,58 +1,58 @@
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3. DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
SURVEX_DATA = 'c:\\Expo\\loser\\' SURVEX_DATA = 'c:\\Expo\\loser\\'
CAVERN = 'cavern' CAVERN = 'cavern'
THREEDTOPOS = '3dtopos' THREEDTOPOS = '3dtopos'
EXPOWEB = 'C:\\Expo\\expoweb\\' EXPOWEB = 'C:\\Expo\\expoweb\\'
SURVEYS = 'E:\\surveys\\' SURVEYS = 'E:\\surveys\\'
SURVEY_SCANS = 'E:\\surveys\\surveyscans' SURVEY_SCANS = 'E:\\surveys\\surveyscans'
EXPOWEB_URL = 'http://expo.survex.com/' EXPOWEB_URL = 'http://expo.survex.com/'
LOGFILE = EXPOWEB+'troggle\\parsing_log.txt' LOGFILE = EXPOWEB+'troggle\\parsing_log.txt'
PHOTOS = 'C:\\Expo\\expoweb\\photos' PHOTOS = 'C:\\Expo\\expoweb\\photos'
URL_ROOT = 'http://127.0.0.1:8000' URL_ROOT = 'http://127.0.0.1:8000'
DIR_ROOT = ''#this should end in / if a value is given DIR_ROOT = ''#this should end in / if a value is given
PUBLIC_SITE = False PUBLIC_SITE = False
TINY_MCE_MEDIA_ROOT = '/usr/share/tinymce/www/' TINY_MCE_MEDIA_ROOT = '/usr/share/tinymce/www/'
TINY_MCE_MEDIA_URL = URL_ROOT + DIR_ROOT + 'tinymce_media/' TINY_MCE_MEDIA_URL = URL_ROOT + DIR_ROOT + 'tinymce_media/'
PYTHON_PATH = 'C:\\expoweb\\troggle\\' PYTHON_PATH = 'C:\\expoweb\\troggle\\'
MEDIA_ROOT = 'C:/Expo/expoweb/troggle/media/' MEDIA_ROOT = 'C:/Expo/expoweb/troggle/media/'
MEDIA_URL = URL_ROOT + DIR_ROOT + 'site_media/' MEDIA_URL = URL_ROOT + DIR_ROOT + 'site_media/'
#FILES = "http://framos.lawoftheland.co.uk/troggle/survey_files/" #FILES = "http://framos.lawoftheland.co.uk/troggle/survey_files/"
EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "cuccexpo@gmail.com" EMAIL_HOST_USER = "cuccexpo@gmail.com"
EMAIL_HOST_PASSWORD = "" EMAIL_HOST_PASSWORD = ""
EMAIL_PORT=587 EMAIL_PORT=587
EMAIL_USE_TLS = True EMAIL_USE_TLS = True
# URL that handles the media served from MEDIA_ROOT. Make sure to use a # 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). # trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/" # Examples: "http://media.lawrence.com", "http://example.com/media/"
TEMPLATE_DIRS = ( TEMPLATE_DIRS = (
"C:/Expo/expoweb/troggle/templates", "C:/Expo/expoweb/troggle/templates",
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows. # Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths. # Don't forget to use absolute paths, not relative paths.
) )

View File

@ -1,11 +1,11 @@
#!/usr/bin/env python #!/usr/bin/env python
from django.core.management import execute_manager from django.core.management import execute_manager
try: try:
import settings # Assumed to be in the same directory. import settings # Assumed to be in the same directory.
except ImportError: except ImportError:
import sys 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.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) sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":
execute_manager(settings) execute_manager(settings)

View File

@ -1,49 +1,49 @@
from django.conf import settings from django.conf import settings
from django import http from django import http
from django.core.urlresolvers import resolve from django.core.urlresolvers import resolve
class SmartAppendSlashMiddleware(object): class SmartAppendSlashMiddleware(object):
""" """
"SmartAppendSlash" middleware for taking care of URL rewriting. "SmartAppendSlash" middleware for taking care of URL rewriting.
This middleware appends a missing slash, if: This middleware appends a missing slash, if:
* the SMART_APPEND_SLASH setting is True * the SMART_APPEND_SLASH setting is True
* the URL without the slash does not exist * the URL without the slash does not exist
* the URL with an appended slash does exist. * the URL with an appended slash does exist.
Otherwise it won't touch the URL. Otherwise it won't touch the URL.
""" """
def process_request(self, request): def process_request(self, request):
""" """
Rewrite the URL based on settings.SMART_APPEND_SLASH Rewrite the URL based on settings.SMART_APPEND_SLASH
""" """
# Check for a redirect based on settings.SMART_APPEND_SLASH # Check for a redirect based on settings.SMART_APPEND_SLASH
host = http.get_host(request) host = http.get_host(request)
old_url = [host, request.path] old_url = [host, request.path]
new_url = old_url[:] new_url = old_url[:]
# Append a slash if SMART_APPEND_SLASH is set and the resulting URL # Append a slash if SMART_APPEND_SLASH is set and the resulting URL
# resolves. # resolves.
if settings.SMART_APPEND_SLASH and (not old_url[1].endswith('/')) and not _resolves(old_url[1]) and _resolves(old_url[1] + '/'): if settings.SMART_APPEND_SLASH and (not old_url[1].endswith('/')) and not _resolves(old_url[1]) and _resolves(old_url[1] + '/'):
new_url[1] = new_url[1] + '/' new_url[1] = new_url[1] + '/'
if settings.DEBUG and request.method == 'POST': if settings.DEBUG and request.method == 'POST':
raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have SMART_APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set SMART_APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1]) raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have SMART_APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set SMART_APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1])
if new_url != old_url: if new_url != old_url:
# Redirect # Redirect
if new_url[0]: if new_url[0]:
newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], new_url[1]) newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], new_url[1])
else: else:
newurl = new_url[1] newurl = new_url[1]
if request.GET: if request.GET:
newurl += '?' + request.GET.urlencode() newurl += '?' + request.GET.urlencode()
return http.HttpResponsePermanentRedirect(newurl) return http.HttpResponsePermanentRedirect(newurl)
return None return None
def _resolves(url): def _resolves(url):
try: try:
resolve(url) resolve(url)
return True return True
except http.Http404: except http.Http404:
return False return False

View File

@ -1,253 +1,253 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import troggle.core.models as models import troggle.core.models as models
from django.conf import settings from django.conf import settings
import csv, time, re, os, logging import csv, time, re, os, logging
from utils import save_carefully from utils import save_carefully
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
import flatpages.models import flatpages.models
##format of CAVETAB2.CSV is ##format of CAVETAB2.CSV is
KatasterNumber = 0 KatasterNumber = 0
KatStatusCode = 1 KatStatusCode = 1
Entrances = 2 Entrances = 2
UnofficialNumber = 3 UnofficialNumber = 3
MultipleEntrances = 4 MultipleEntrances = 4
AutogenFile = 5 AutogenFile = 5
LinkFile = 6 LinkFile = 6
LinkEntrance = 7 LinkEntrance = 7
Name = 8 Name = 8
UnofficialName = 9 UnofficialName = 9
Comment = 10 Comment = 10
Area = 11 Area = 11
Explorers = 12 Explorers = 12
UndergroundDescription = 13 UndergroundDescription = 13
Equipment = 14 Equipment = 14
QMList = 15 QMList = 15
KatasterStatus = 16 KatasterStatus = 16
References = 17 References = 17
UndergroundCentreLine = 18 UndergroundCentreLine = 18
UndergroundDrawnSurvey = 19 UndergroundDrawnSurvey = 19
SurvexFile = 20 SurvexFile = 20
Length = 21 Length = 21
Depth = 22 Depth = 22
Extent = 23 Extent = 23
Notes = 24 Notes = 24
EntranceName = 25 EntranceName = 25
TagPoint = 26 TagPoint = 26
OtherPoint = 27 OtherPoint = 27
DescriptionOfOtherPoint = 28 DescriptionOfOtherPoint = 28
ExactEntrance = 29 ExactEntrance = 29
TypeOfFix = 30 TypeOfFix = 30
GPSpreSA = 31 GPSpreSA = 31
GPSpostSA = 32 GPSpostSA = 32
Northing = 33 Northing = 33
Easting = 34 Easting = 34
Altitude = 35 Altitude = 35
Bearings = 36 Bearings = 36
Map = 37 Map = 37
Location = 38 Location = 38
Approach = 39 Approach = 39
EntranceDescription = 40 EntranceDescription = 40
PhotoOfLocation = 41 PhotoOfLocation = 41
Marking = 42 Marking = 42
MarkingComment = 43 MarkingComment = 43
Findability = 44 Findability = 44
FindabilityComment = 45 FindabilityComment = 45
def LoadCaveTab(): def LoadCaveTab():
cavetab = open(os.path.join(settings.EXPOWEB, "noinfo", "CAVETAB2.CSV"),'rU') cavetab = open(os.path.join(settings.EXPOWEB, "noinfo", "CAVETAB2.CSV"),'rU')
caveReader = csv.reader(cavetab) caveReader = csv.reader(cavetab)
caveReader.next() # Strip out column headers caveReader.next() # Strip out column headers
logging.info("Beginning to import caves from "+str(cavetab)+"\n"+"-"*60+"\n") logging.info("Beginning to import caves from "+str(cavetab)+"\n"+"-"*60+"\n")
for katArea in ['1623', '1626']: for katArea in ['1623', '1626']:
if not models.Area.objects.filter(short_name = katArea): if not models.Area.objects.filter(short_name = katArea):
newArea = models.Area(short_name = katArea) newArea = models.Area(short_name = katArea)
newArea.save() newArea.save()
logging.info("Added area "+str(newArea.short_name)+"\n") logging.info("Added area "+str(newArea.short_name)+"\n")
area1626 = models.Area.objects.filter(short_name = '1626')[0] area1626 = models.Area.objects.filter(short_name = '1626')[0]
area1623 = models.Area.objects.filter(short_name = '1623')[0] area1623 = models.Area.objects.filter(short_name = '1623')[0]
counter=0 counter=0
for line in caveReader : for line in caveReader :
if line[Area] == 'nonexistent': if line[Area] == 'nonexistent':
continue continue
entranceLetters=[] #Used in caves that have mulitlple entrances, which are not described on seperate lines entranceLetters=[] #Used in caves that have mulitlple entrances, which are not described on seperate lines
if line[MultipleEntrances] == 'yes' or line[MultipleEntrances]=='': #When true, this line contains an actual cave, otherwise it is an extra entrance. if line[MultipleEntrances] == 'yes' or line[MultipleEntrances]=='': #When true, this line contains an actual cave, otherwise it is an extra entrance.
args = {} args = {}
defaultArgs = {} defaultArgs = {}
def addToArgs(CSVname, modelName): def addToArgs(CSVname, modelName):
if line[CSVname]: if line[CSVname]:
args[modelName] = line[CSVname] args[modelName] = line[CSVname]
def addToDefaultArgs(CSVname, modelName): #This has to do with the non-destructive import. These arguments will be passed as the "default" dictionary in a get_or_create def addToDefaultArgs(CSVname, modelName): #This has to do with the non-destructive import. These arguments will be passed as the "default" dictionary in a get_or_create
if line[CSVname]: if line[CSVname]:
defaultArgs[modelName] = line[CSVname] defaultArgs[modelName] = line[CSVname]
# The attributes added using "addToArgs" will be used to look up an existing cave. Those added using "addToDefaultArgs" will not. # The attributes added using "addToArgs" will be used to look up an existing cave. Those added using "addToDefaultArgs" will not.
addToArgs(KatasterNumber, "kataster_number") addToArgs(KatasterNumber, "kataster_number")
addToDefaultArgs(KatStatusCode, "kataster_code") addToDefaultArgs(KatStatusCode, "kataster_code")
addToArgs(UnofficialNumber, "unofficial_number") addToArgs(UnofficialNumber, "unofficial_number")
addToArgs(Name, "official_name") addToArgs(Name, "official_name")
addToDefaultArgs(Comment, "notes") addToDefaultArgs(Comment, "notes")
addToDefaultArgs(Explorers, "explorers") addToDefaultArgs(Explorers, "explorers")
addToDefaultArgs(UndergroundDescription, "underground_description") addToDefaultArgs(UndergroundDescription, "underground_description")
addToDefaultArgs(Equipment, "equipment") addToDefaultArgs(Equipment, "equipment")
addToDefaultArgs(KatasterStatus, "kataster_status") addToDefaultArgs(KatasterStatus, "kataster_status")
addToDefaultArgs(References, "references") addToDefaultArgs(References, "references")
addToDefaultArgs(UndergroundCentreLine, "underground_centre_line") addToDefaultArgs(UndergroundCentreLine, "underground_centre_line")
addToDefaultArgs(UndergroundDrawnSurvey, "survey") addToDefaultArgs(UndergroundDrawnSurvey, "survey")
addToDefaultArgs(Length, "length") addToDefaultArgs(Length, "length")
addToDefaultArgs(Depth, "depth") addToDefaultArgs(Depth, "depth")
addToDefaultArgs(Extent, "extent") addToDefaultArgs(Extent, "extent")
addToDefaultArgs(SurvexFile, "survex_file") addToDefaultArgs(SurvexFile, "survex_file")
addToDefaultArgs(Notes, "notes") addToDefaultArgs(Notes, "notes")
addToDefaultArgs(AutogenFile, "url") addToDefaultArgs(AutogenFile, "url")
if line[Area] == "1626": if line[Area] == "1626":
if line[KatasterNumber] != "": if line[KatasterNumber] != "":
args["slug"] = line[Area] + "-" + line[KatasterNumber] args["slug"] = line[Area] + "-" + line[KatasterNumber]
else: else:
args["slug"] = line[Area] + "-" + line[UnofficialNumber] args["slug"] = line[Area] + "-" + line[UnofficialNumber]
else: else:
if line[KatasterNumber] != "": if line[KatasterNumber] != "":
args["slug"] = "1623" + "-" + line[KatasterNumber] args["slug"] = "1623" + "-" + line[KatasterNumber]
else: else:
args["slug"] = "1623" + "-" + line[UnofficialNumber] args["slug"] = "1623" + "-" + line[UnofficialNumber]
#The following adds the legacy_file_path. This is always in either Autogen file or Link file #The following adds the legacy_file_path. This is always in either Autogen file or Link file
for header in (AutogenFile,LinkFile): for header in (AutogenFile,LinkFile):
if line[header]: if line[header]:
addToDefaultArgs(header,"description_file") addToDefaultArgs(header,"description_file")
break break
#The following checks if this cave is non-public i.e. we don't have rights to display it online. #The following checks if this cave is non-public i.e. we don't have rights to display it online.
#Noinfo was the name of the old password protected directory, so if it has that then we will #Noinfo was the name of the old password protected directory, so if it has that then we will
#set the non_public field of the model instance to true. #set the non_public field of the model instance to true.
defaultArgs["non_public"]=line[AutogenFile].startswith('noinfo') or line[LinkFile].startswith('noinfo') defaultArgs["non_public"]=line[AutogenFile].startswith('noinfo') or line[LinkFile].startswith('noinfo')
newCave, created=save_carefully(models.Cave, lookupAttribs=args, nonLookupAttribs=defaultArgs) newCave, created=save_carefully(models.Cave, lookupAttribs=args, nonLookupAttribs=defaultArgs)
logging.info("Added cave "+str(newCave)+"\n") logging.info("Added cave "+str(newCave)+"\n")
#If we created a new cave, add the area to it. This does mean that if a cave's identifying features have not changed, areas will not be updated from csv. #If we created a new cave, add the area to it. This does mean that if a cave's identifying features have not changed, areas will not be updated from csv.
if created and line[Area]: if created and line[Area]:
if line[Area] == "1626": if line[Area] == "1626":
newCave.area.add(area1626) newCave.area.add(area1626)
else: else:
area = models.Area.objects.filter(short_name = line[Area]) area = models.Area.objects.filter(short_name = line[Area])
if area: if area:
newArea = area[0] newArea = area[0]
else: else:
newArea = models.Area(short_name = line[Area], parent = area1623) newArea = models.Area(short_name = line[Area], parent = area1623)
newArea.save() newArea.save()
newCave.area.add(newArea) newCave.area.add(newArea)
newCave.area.add(area1623) newCave.area.add(area1623)
elif created: elif created:
newCave.area.add(area1623) newCave.area.add(area1623)
newCave.save() newCave.save()
logging.info("Added area "+line[Area]+" to cave "+str(newCave)+"\n") logging.info("Added area "+line[Area]+" to cave "+str(newCave)+"\n")
if created and line[UnofficialName]: if created and line[UnofficialName]:
newUnofficialName = models.OtherCaveName(cave = newCave, name = line[UnofficialName]) newUnofficialName = models.OtherCaveName(cave = newCave, name = line[UnofficialName])
newUnofficialName.save() newUnofficialName.save()
logging.info("Added unofficial name "+str(newUnofficialName)+" to cave "+str(newCave)+"\n") logging.info("Added unofficial name "+str(newUnofficialName)+" to cave "+str(newCave)+"\n")
if created and line[MultipleEntrances] == '' or \ if created and line[MultipleEntrances] == '' or \
line[MultipleEntrances] == 'entrance' or \ line[MultipleEntrances] == 'entrance' or \
line[MultipleEntrances] == 'last entrance': line[MultipleEntrances] == 'last entrance':
args = {} args = {}
if line[Entrances]: if line[Entrances]:
entrance_letter = line[Entrances] entrance_letter = line[Entrances]
else: else:
entrance_letter = '' entrance_letter = ''
def addToArgs(CSVname, modelName): def addToArgs(CSVname, modelName):
if line[CSVname]: if line[CSVname]:
args[modelName] = line[CSVname] args[modelName] = line[CSVname]
def addToArgsViaDict(CSVname, modelName, dictionary): def addToArgsViaDict(CSVname, modelName, dictionary):
if line[CSVname]: if line[CSVname]:
args[modelName] = dictionary[line[CSVname]] args[modelName] = dictionary[line[CSVname]]
addToArgs(EntranceName, 'name') addToArgs(EntranceName, 'name')
addToArgs(Explorers, 'explorers') addToArgs(Explorers, 'explorers')
addToArgs(Map, 'map_description') addToArgs(Map, 'map_description')
addToArgs(Location, 'location_description') addToArgs(Location, 'location_description')
addToArgs(Approach, 'approach') addToArgs(Approach, 'approach')
addToArgs(EntranceDescription, 'entrance_description') addToArgs(EntranceDescription, 'entrance_description')
addToArgs(UndergroundDescription, 'underground_description') addToArgs(UndergroundDescription, 'underground_description')
addToArgs(PhotoOfLocation, 'photo') addToArgs(PhotoOfLocation, 'photo')
addToArgsViaDict(Marking, 'marking', {"Paint": "P", addToArgsViaDict(Marking, 'marking', {"Paint": "P",
"Paint (?)": "P?", "Paint (?)": "P?",
"Tag": "T", "Tag": "T",
"Tag (?)": "T?", "Tag (?)": "T?",
"Retagged": "R", "Retagged": "R",
"Retag": "R", "Retag": "R",
"Spit": "S", "Spit": "S",
"Spit (?)": "S?", "Spit (?)": "S?",
"Unmarked": "U", "Unmarked": "U",
"": "?", "": "?",
}) })
addToArgs(MarkingComment, 'marking_comment') addToArgs(MarkingComment, 'marking_comment')
addToArgsViaDict(Findability, 'findability', {"Surveyed": "S", addToArgsViaDict(Findability, 'findability', {"Surveyed": "S",
"Lost": "L", "Lost": "L",
"Refindable": "R", "Refindable": "R",
"": "?", "": "?",
"?": "?", "?": "?",
}) })
addToArgs(FindabilityComment, 'findability_description') addToArgs(FindabilityComment, 'findability_description')
addToArgs(Easting, 'easting') addToArgs(Easting, 'easting')
addToArgs(Northing, 'northing') addToArgs(Northing, 'northing')
addToArgs(Altitude, 'alt') addToArgs(Altitude, 'alt')
addToArgs(DescriptionOfOtherPoint, 'other_description') addToArgs(DescriptionOfOtherPoint, 'other_description')
addToArgs(TagPoint, 'tag_station') addToArgs(TagPoint, 'tag_station')
addToArgs(ExactEntrance, 'exact_station') addToArgs(ExactEntrance, 'exact_station')
addToArgs(OtherPoint, 'other_station') addToArgs(OtherPoint, 'other_station')
addToArgs(OtherPoint, 'other_description') addToArgs(OtherPoint, 'other_description')
if line[GPSpreSA]: if line[GPSpreSA]:
addToArgs(GPSpreSA, 'other_station') addToArgs(GPSpreSA, 'other_station')
args['other_description'] = 'pre selective availability GPS' args['other_description'] = 'pre selective availability GPS'
if line[GPSpostSA]: if line[GPSpostSA]:
addToArgs(GPSpostSA, 'other_station') addToArgs(GPSpostSA, 'other_station')
args['other_description'] = 'post selective availability GPS' args['other_description'] = 'post selective availability GPS'
addToArgs(Bearings, 'bearings') addToArgs(Bearings, 'bearings')
args['slug'] = newCave.slug + entrance_letter args['slug'] = newCave.slug + entrance_letter
newEntrance = models.Entrance(**args) newEntrance = models.Entrance(**args)
newEntrance.save() newEntrance.save()
logging.info("Added entrance "+str(newEntrance)+"\n") logging.info("Added entrance "+str(newEntrance)+"\n")
newCaveAndEntrance = models.CaveAndEntrance(cave = newCave, entrance = newEntrance, entrance_letter = entrance_letter) newCaveAndEntrance = models.CaveAndEntrance(cave = newCave, entrance = newEntrance, entrance_letter = entrance_letter)
newCaveAndEntrance.save() newCaveAndEntrance.save()
logging.info("Added CaveAndEntrance "+str(newCaveAndEntrance)+"\n") logging.info("Added CaveAndEntrance "+str(newCaveAndEntrance)+"\n")
f = flatpages.models.EntranceRedirect(originalURL = line[AutogenFile], entrance = newEntrance) f = flatpages.models.EntranceRedirect(originalURL = line[AutogenFile], entrance = newEntrance)
f.save() f.save()
# lookup function modelled on GetPersonExpeditionNameLookup # lookup function modelled on GetPersonExpeditionNameLookup
Gcavelookup = None Gcavelookup = None
def GetCaveLookup(): def GetCaveLookup():
global Gcavelookup global Gcavelookup
if Gcavelookup: if Gcavelookup:
return Gcavelookup return Gcavelookup
Gcavelookup = {"NONEPLACEHOLDER":None} Gcavelookup = {"NONEPLACEHOLDER":None}
for cave in models.Cave.objects.all(): for cave in models.Cave.objects.all():
Gcavelookup[cave.official_name.lower()] = cave Gcavelookup[cave.official_name.lower()] = cave
if cave.kataster_number: if cave.kataster_number:
Gcavelookup[cave.kataster_number] = cave Gcavelookup[cave.kataster_number] = cave
if cave.unofficial_number: if cave.unofficial_number:
Gcavelookup[cave.unofficial_number] = cave Gcavelookup[cave.unofficial_number] = cave
Gcavelookup["tunnocks"] = Gcavelookup["258"] Gcavelookup["tunnocks"] = Gcavelookup["258"]
Gcavelookup["hauchhole"] = Gcavelookup["234"] Gcavelookup["hauchhole"] = Gcavelookup["234"]
return Gcavelookup return Gcavelookup

View File

@ -1,45 +1,45 @@
from django.conf import settings from django.conf import settings
import core.models as models import core.models as models
import os import os
from utils import html_to_wiki, get_html_body, get_html_title from utils import html_to_wiki, get_html_body, get_html_title
pages = [(["smkridge", "204", "ariston-rigging.html"], "ariston-rigging"), pages = [(["smkridge", "204", "ariston-rigging.html"], "ariston-rigging"),
(["smkridge", "204", "ariston.html"], "ariston"), (["smkridge", "204", "ariston.html"], "ariston"),
(["smkridge", "204", "bivvy.html"], "bivvy"), (["smkridge", "204", "bivvy.html"], "bivvy"),
(["smkridge", "204", "bridge.html"], "bridge"), (["smkridge", "204", "bridge.html"], "bridge"),
(["smkridge", "204", "entrance-rigging.html"], "entrance-rigging"), (["smkridge", "204", "entrance-rigging.html"], "entrance-rigging"),
(["smkridge", "204", "entrance.html"], "entrance"), (["smkridge", "204", "entrance.html"], "entrance"),
(["smkridge", "204", "midlevel.html"], "midlevel"), (["smkridge", "204", "midlevel.html"], "midlevel"),
(["smkridge", "204", "millennium.html"], "millennium"), (["smkridge", "204", "millennium.html"], "millennium"),
(["smkridge", "204", "nopain.html"], "nopain"), (["smkridge", "204", "nopain.html"], "nopain"),
(["smkridge", "204", "razordance.html"], "razordance"), (["smkridge", "204", "razordance.html"], "razordance"),
(["smkridge", "204", "rhino.html"], "rhino"), (["smkridge", "204", "rhino.html"], "rhino"),
(["smkridge", "204", "sbview.html"], "sbview"), (["smkridge", "204", "sbview.html"], "sbview"),
(["smkridge", "204", "subway.html"], "subway"), (["smkridge", "204", "subway.html"], "subway"),
(["smkridge", "204", "swings.html"], "swings"), (["smkridge", "204", "swings.html"], "swings"),
(["smkridge", "204", "treeumphant.html"], "treeumphant"), (["smkridge", "204", "treeumphant.html"], "treeumphant"),
(["smkridge", "204", "uworld.html"], "uworld"), ] (["smkridge", "204", "uworld.html"], "uworld"), ]
def getDescriptions(): def getDescriptions():
"""Creates objects in the database for each item in the list 'pages' . """ """Creates objects in the database for each item in the list 'pages' . """
for filelocation, name in pages: for filelocation, name in pages:
f = open(os.path.join(settings.EXPOWEB, *filelocation), "r") f = open(os.path.join(settings.EXPOWEB, *filelocation), "r")
html = f.read() html = f.read()
cd = models.CaveDescription(short_name = name, cd = models.CaveDescription(short_name = name,
long_name = unicode(get_html_title(html), "latin1"), long_name = unicode(get_html_title(html), "latin1"),
description = unicode(get_html_body(html), "latin1")) description = unicode(get_html_body(html), "latin1"))
cd.save() cd.save()
def parseDescriptions(): def parseDescriptions():
"""Turns the HTML in each cave description into wikicode""" """Turns the HTML in each cave description into wikicode"""
for cd in models.CaveDescription.objects.all(): for cd in models.CaveDescription.objects.all():
cd.description = html_to_wiki(cd.description) cd.description = html_to_wiki(cd.description)
cd.save() cd.save()
def parseDescriptionsOnCaveObjects(): def parseDescriptionsOnCaveObjects():
for cave in models.Cave.objects.all(): for cave in models.Cave.objects.all():
cave.underground_description=html_to_wiki(unicode(cave.underground_description)) cave.underground_description=html_to_wiki(unicode(cave.underground_description))
cave.save() cave.save()

View File

@ -1,432 +1,432 @@
#.-*- coding: utf-8 -*- #.-*- coding: utf-8 -*-
from django.conf import settings from django.conf import settings
import core.models as models import core.models as models
from parsers.people import GetPersonExpeditionNameLookup from parsers.people import GetPersonExpeditionNameLookup
from parsers.cavetab import GetCaveLookup from parsers.cavetab import GetCaveLookup
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
import csv import csv
import re import re
import datetime import datetime
import os import os
from utils import save_carefully from utils import save_carefully
# #
# When we edit logbook entries, allow a "?" after any piece of data to say we've frigged it and # When we edit logbook entries, allow a "?" after any piece of data to say we've frigged it and
# it can be checked up later from the hard-copy if necessary; or it's not possible to determin (name, trip place, etc) # it can be checked up later from the hard-copy if necessary; or it's not possible to determin (name, trip place, etc)
# #
# #
# the logbook loading section # the logbook loading section
# #
def GetTripPersons(trippeople, expedition, logtime_underground): def GetTripPersons(trippeople, expedition, logtime_underground):
res = [ ] res = [ ]
author = None author = None
for tripperson in re.split(",|\+|&amp;|&(?!\w+;)| and ", trippeople): for tripperson in re.split(",|\+|&amp;|&(?!\w+;)| and ", trippeople):
tripperson = tripperson.strip() tripperson = tripperson.strip()
mul = re.match("<u>(.*?)</u>$(?i)", tripperson) mul = re.match("<u>(.*?)</u>$(?i)", tripperson)
if mul: if mul:
tripperson = mul.group(1).strip() tripperson = mul.group(1).strip()
if tripperson and tripperson[0] != '*': if tripperson and tripperson[0] != '*':
#assert tripperson in personyearmap, "'%s' << %s\n\n %s" % (tripperson, trippeople, personyearmap) #assert tripperson in personyearmap, "'%s' << %s\n\n %s" % (tripperson, trippeople, personyearmap)
personyear = GetPersonExpeditionNameLookup(expedition).get(tripperson.lower()) personyear = GetPersonExpeditionNameLookup(expedition).get(tripperson.lower())
if not personyear: if not personyear:
print "NoMatchFor: '%s'" % tripperson print "NoMatchFor: '%s'" % tripperson
res.append((personyear, logtime_underground)) res.append((personyear, logtime_underground))
if mul: if mul:
author = personyear author = personyear
if not author: if not author:
if not res: if not res:
return None, None return None, None
author = res[-1][0] author = res[-1][0]
return res, author return res, author
def GetTripCave(place): #need to be fuzzier about matching here. Already a very slow function... def GetTripCave(place): #need to be fuzzier about matching here. Already a very slow function...
# print "Getting cave for " , place # print "Getting cave for " , place
try: try:
katastNumRes=[] katastNumRes=[]
katastNumRes=list(models.Cave.objects.filter(kataster_number=int(place))) katastNumRes=list(models.Cave.objects.filter(kataster_number=int(place)))
except ValueError: except ValueError:
pass pass
officialNameRes=list(models.Cave.objects.filter(official_name=place)) officialNameRes=list(models.Cave.objects.filter(official_name=place))
tripCaveRes=officialNameRes+katastNumRes tripCaveRes=officialNameRes+katastNumRes
if len(tripCaveRes)==1: if len(tripCaveRes)==1:
# print "Place " , place , "entered as" , tripCaveRes[0] # print "Place " , place , "entered as" , tripCaveRes[0]
return tripCaveRes[0] return tripCaveRes[0]
elif models.OtherCaveName.objects.filter(name=place): elif models.OtherCaveName.objects.filter(name=place):
tripCaveRes=models.OtherCaveName.objects.filter(name__icontains=place)[0].cave tripCaveRes=models.OtherCaveName.objects.filter(name__icontains=place)[0].cave
# print "Place " , place , "entered as" , tripCaveRes # print "Place " , place , "entered as" , tripCaveRes
return tripCaveRes return tripCaveRes
elif len(tripCaveRes)>1: elif len(tripCaveRes)>1:
print "Ambiguous place " + str(place) + " entered. Choose from " + str(tripCaveRes) print "Ambiguous place " + str(place) + " entered. Choose from " + str(tripCaveRes)
correctIndex=input("type list index of correct cave") correctIndex=input("type list index of correct cave")
return tripCaveRes[correctIndex] return tripCaveRes[correctIndex]
else: else:
print "No cave found for place " , place print "No cave found for place " , place
return return
noncaveplaces = [ "Journey", "Loser Plateau" ] noncaveplaces = [ "Journey", "Loser Plateau" ]
def EnterLogIntoDbase(date, place, title, text, trippeople, expedition, logtime_underground): def EnterLogIntoDbase(date, place, title, text, trippeople, expedition, logtime_underground):
""" saves a logbook entry and related persontrips """ """ saves a logbook entry and related persontrips """
trippersons, author = GetTripPersons(trippeople, expedition, logtime_underground) trippersons, author = GetTripPersons(trippeople, expedition, logtime_underground)
if not author: if not author:
print "skipping logentry", title print "skipping logentry", title
return return
# tripCave = GetTripCave(place) # tripCave = GetTripCave(place)
# #
lplace = place.lower() lplace = place.lower()
if lplace not in noncaveplaces: if lplace not in noncaveplaces:
cave=GetCaveLookup().get(lplace) cave=GetCaveLookup().get(lplace)
#Check for an existing copy of the current entry, and save #Check for an existing copy of the current entry, and save
expeditionday = expedition.get_expedition_day(date) expeditionday = expedition.get_expedition_day(date)
lookupAttribs={'date':date, 'title':title} lookupAttribs={'date':date, 'title':title}
nonLookupAttribs={'place':place, 'text':text, 'expedition':expedition, 'cave':cave, 'slug':slugify(title)[:50]} nonLookupAttribs={'place':place, 'text':text, 'expedition':expedition, 'cave':cave, 'slug':slugify(title)[:50]}
lbo, created=save_carefully(models.LogbookEntry, lookupAttribs, nonLookupAttribs) lbo, created=save_carefully(models.LogbookEntry, lookupAttribs, nonLookupAttribs)
for tripperson, time_underground in trippersons: for tripperson, time_underground in trippersons:
lookupAttribs={'personexpedition':tripperson, 'logbook_entry':lbo} lookupAttribs={'personexpedition':tripperson, 'logbook_entry':lbo}
nonLookupAttribs={'time_underground':time_underground, 'is_logbook_entry_author':(tripperson == author)} nonLookupAttribs={'time_underground':time_underground, 'is_logbook_entry_author':(tripperson == author)}
#print nonLookupAttribs #print nonLookupAttribs
save_carefully(models.PersonTrip, lookupAttribs, nonLookupAttribs) save_carefully(models.PersonTrip, lookupAttribs, nonLookupAttribs)
def ParseDate(tripdate, year): def ParseDate(tripdate, year):
""" Interprets dates in the expo logbooks and returns a correct datetime.date object """ """ Interprets dates in the expo logbooks and returns a correct datetime.date object """
mdatestandard = re.match("(\d\d\d\d)-(\d\d)-(\d\d)", tripdate) mdatestandard = re.match("(\d\d\d\d)-(\d\d)-(\d\d)", tripdate)
mdategoof = re.match("(\d\d?)/0?(\d)/(20|19)?(\d\d)", tripdate) mdategoof = re.match("(\d\d?)/0?(\d)/(20|19)?(\d\d)", tripdate)
if mdatestandard: if mdatestandard:
assert mdatestandard.group(1) == year, (tripdate, year) assert mdatestandard.group(1) == year, (tripdate, year)
year, month, day = int(mdatestandard.group(1)), int(mdatestandard.group(2)), int(mdatestandard.group(3)) year, month, day = int(mdatestandard.group(1)), int(mdatestandard.group(2)), int(mdatestandard.group(3))
elif mdategoof: elif mdategoof:
assert not mdategoof.group(3) or mdategoof.group(3) == year[:2], mdategoof.groups() assert not mdategoof.group(3) or mdategoof.group(3) == year[:2], mdategoof.groups()
yadd = int(year[:2]) * 100 yadd = int(year[:2]) * 100
day, month, year = int(mdategoof.group(1)), int(mdategoof.group(2)), int(mdategoof.group(4)) + yadd day, month, year = int(mdategoof.group(1)), int(mdategoof.group(2)), int(mdategoof.group(4)) + yadd
else: else:
assert False, tripdate assert False, tripdate
return datetime.date(year, month, day) return datetime.date(year, month, day)
# 2007, 2008, 2006 # 2007, 2008, 2006
def Parselogwikitxt(year, expedition, txt): def Parselogwikitxt(year, expedition, txt):
trippara = re.findall("===(.*?)===([\s\S]*?)(?====)", txt) trippara = re.findall("===(.*?)===([\s\S]*?)(?====)", txt)
for triphead, triptext in trippara: for triphead, triptext in trippara:
tripheadp = triphead.split("|") tripheadp = triphead.split("|")
#print "ttt", tripheadp #print "ttt", tripheadp
assert len(tripheadp) == 3, (tripheadp, triptext) assert len(tripheadp) == 3, (tripheadp, triptext)
tripdate, tripplace, trippeople = tripheadp tripdate, tripplace, trippeople = tripheadp
tripsplace = tripplace.split(" - ") tripsplace = tripplace.split(" - ")
tripcave = tripsplace[0].strip() tripcave = tripsplace[0].strip()
tul = re.findall("T/?U:?\s*(\d+(?:\.\d*)?|unknown)\s*(hrs|hours)?", triptext) tul = re.findall("T/?U:?\s*(\d+(?:\.\d*)?|unknown)\s*(hrs|hours)?", triptext)
if tul: if tul:
#assert len(tul) <= 1, (triphead, triptext) #assert len(tul) <= 1, (triphead, triptext)
#assert tul[0][1] in ["hrs", "hours"], (triphead, triptext) #assert tul[0][1] in ["hrs", "hours"], (triphead, triptext)
tu = tul[0][0] tu = tul[0][0]
else: else:
tu = "" tu = ""
#assert tripcave == "Journey", (triphead, triptext) #assert tripcave == "Journey", (triphead, triptext)
#print tripdate #print tripdate
ldate = ParseDate(tripdate.strip(), year) ldate = ParseDate(tripdate.strip(), year)
#print "\n", tripcave, "--- ppp", trippeople, len(triptext) #print "\n", tripcave, "--- ppp", trippeople, len(triptext)
EnterLogIntoDbase(date = ldate, place = tripcave, title = tripplace, text = triptext, trippeople=trippeople, expedition=expedition, logtime_underground=0) EnterLogIntoDbase(date = ldate, place = tripcave, title = tripplace, text = triptext, trippeople=trippeople, expedition=expedition, logtime_underground=0)
# 2002, 2004, 2005 # 2002, 2004, 2005
def Parseloghtmltxt(year, expedition, txt): def Parseloghtmltxt(year, expedition, txt):
tripparas = re.findall("<hr\s*/>([\s\S]*?)(?=<hr)", txt) tripparas = re.findall("<hr\s*/>([\s\S]*?)(?=<hr)", txt)
for trippara in tripparas: for trippara in tripparas:
s = re.match('''(?x)(?:\s*<div\sclass="tripdate"\sid=".*?">.*?</div>\s*<p>)? # second date s = re.match('''(?x)(?:\s*<div\sclass="tripdate"\sid=".*?">.*?</div>\s*<p>)? # second date
\s*(?:<a\s+id="(.*?)"\s*/>\s*</a>)? \s*(?:<a\s+id="(.*?)"\s*/>\s*</a>)?
\s*<div\s+class="tripdate"\s*(?:id="(.*?)")?>(.*?)</div>(?:<p>)? \s*<div\s+class="tripdate"\s*(?:id="(.*?)")?>(.*?)</div>(?:<p>)?
\s*<div\s+class="trippeople">\s*(.*?)</div> \s*<div\s+class="trippeople">\s*(.*?)</div>
\s*<div\s+class="triptitle">\s*(.*?)</div> \s*<div\s+class="triptitle">\s*(.*?)</div>
([\s\S]*?) ([\s\S]*?)
\s*(?:<div\s+class="timeug">\s*(.*?)</div>)? \s*(?:<div\s+class="timeug">\s*(.*?)</div>)?
\s*$ \s*$
''', trippara) ''', trippara)
if not s: if not s:
if not re.search("Rigging Guide", trippara): if not re.search("Rigging Guide", trippara):
print "can't parse: ", trippara # this is 2007 which needs editing print "can't parse: ", trippara # this is 2007 which needs editing
#assert s, trippara #assert s, trippara
continue continue
tripid, tripid1, tripdate, trippeople, triptitle, triptext, tu = s.groups() tripid, tripid1, tripdate, trippeople, triptitle, triptext, tu = s.groups()
ldate = ParseDate(tripdate.strip(), year) ldate = ParseDate(tripdate.strip(), year)
#assert tripid[:-1] == "t" + tripdate, (tripid, tripdate) #assert tripid[:-1] == "t" + tripdate, (tripid, tripdate)
trippeople = re.sub("Ol(?!l)", "Olly", trippeople) trippeople = re.sub("Ol(?!l)", "Olly", trippeople)
trippeople = re.sub("Wook(?!e)", "Wookey", trippeople) trippeople = re.sub("Wook(?!e)", "Wookey", trippeople)
triptitles = triptitle.split(" - ") triptitles = triptitle.split(" - ")
if len(triptitles) >= 2: if len(triptitles) >= 2:
tripcave = triptitles[0] tripcave = triptitles[0]
else: else:
tripcave = "UNKNOWN" tripcave = "UNKNOWN"
#print "\n", tripcave, "--- ppp", trippeople, len(triptext) #print "\n", tripcave, "--- ppp", trippeople, len(triptext)
ltriptext = re.sub("</p>", "", triptext) ltriptext = re.sub("</p>", "", triptext)
ltriptext = re.sub("\s*?\n\s*", " ", ltriptext) ltriptext = re.sub("\s*?\n\s*", " ", ltriptext)
ltriptext = re.sub("<p>", "\n\n", ltriptext).strip() ltriptext = re.sub("<p>", "\n\n", ltriptext).strip()
EnterLogIntoDbase(date = ldate, place = tripcave, title = triptitle, text = ltriptext, trippeople=trippeople, expedition=expedition, logtime_underground=0) EnterLogIntoDbase(date = ldate, place = tripcave, title = triptitle, text = ltriptext, trippeople=trippeople, expedition=expedition, logtime_underground=0)
# main parser for pre-2001. simpler because the data has been hacked so much to fit it # main parser for pre-2001. simpler because the data has been hacked so much to fit it
def Parseloghtml01(year, expedition, txt): def Parseloghtml01(year, expedition, txt):
tripparas = re.findall("<hr[\s/]*>([\s\S]*?)(?=<hr)", txt) tripparas = re.findall("<hr[\s/]*>([\s\S]*?)(?=<hr)", txt)
for trippara in tripparas: for trippara in tripparas:
s = re.match(u"(?s)\s*(?:<p>)?(.*?)</?p>(.*)$(?i)", trippara) s = re.match(u"(?s)\s*(?:<p>)?(.*?)</?p>(.*)$(?i)", trippara)
assert s, trippara[:300] assert s, trippara[:300]
tripheader, triptext = s.group(1), s.group(2) tripheader, triptext = s.group(1), s.group(2)
mtripid = re.search('<a id="(.*?)"', tripheader) mtripid = re.search('<a id="(.*?)"', tripheader)
tripid = mtripid and mtripid.group(1) or "" tripid = mtripid and mtripid.group(1) or ""
tripheader = re.sub("</?(?:[ab]|span)[^>]*>", "", tripheader) tripheader = re.sub("</?(?:[ab]|span)[^>]*>", "", tripheader)
#print " ", [tripheader] #print " ", [tripheader]
#continue #continue
tripdate, triptitle, trippeople = tripheader.split("|") tripdate, triptitle, trippeople = tripheader.split("|")
ldate = ParseDate(tripdate.strip(), year) ldate = ParseDate(tripdate.strip(), year)
mtu = re.search('<p[^>]*>(T/?U.*)', triptext) mtu = re.search('<p[^>]*>(T/?U.*)', triptext)
if mtu: if mtu:
tu = mtu.group(1) tu = mtu.group(1)
triptext = triptext[:mtu.start(0)] + triptext[mtu.end():] triptext = triptext[:mtu.start(0)] + triptext[mtu.end():]
else: else:
tu = "" tu = ""
triptitles = triptitle.split(" - ") triptitles = triptitle.split(" - ")
tripcave = triptitles[0].strip() tripcave = triptitles[0].strip()
ltriptext = triptext ltriptext = triptext
mtail = re.search('(?:<a href="[^"]*">[^<]*</a>|\s|/|-|&amp;|</?p>|\((?:same day|\d+)\))*$', ltriptext) mtail = re.search('(?:<a href="[^"]*">[^<]*</a>|\s|/|-|&amp;|</?p>|\((?:same day|\d+)\))*$', ltriptext)
if mtail: if mtail:
#print mtail.group(0) #print mtail.group(0)
ltriptext = ltriptext[:mtail.start(0)] ltriptext = ltriptext[:mtail.start(0)]
ltriptext = re.sub("</p>", "", ltriptext) ltriptext = re.sub("</p>", "", ltriptext)
ltriptext = re.sub("\s*?\n\s*", " ", ltriptext) ltriptext = re.sub("\s*?\n\s*", " ", ltriptext)
ltriptext = re.sub("<p>|<br>", "\n\n", ltriptext).strip() ltriptext = re.sub("<p>|<br>", "\n\n", ltriptext).strip()
#ltriptext = re.sub("[^\s0-9a-zA-Z\-.,:;'!]", "NONASCII", ltriptext) #ltriptext = re.sub("[^\s0-9a-zA-Z\-.,:;'!]", "NONASCII", ltriptext)
ltriptext = re.sub("</?u>", "_", ltriptext) ltriptext = re.sub("</?u>", "_", ltriptext)
ltriptext = re.sub("</?i>", "''", ltriptext) ltriptext = re.sub("</?i>", "''", ltriptext)
ltriptext = re.sub("</?b>", "'''", ltriptext) ltriptext = re.sub("</?b>", "'''", ltriptext)
#print ldate, trippeople.strip() #print ldate, trippeople.strip()
# could includ the tripid (url link for cross referencing) # could includ the tripid (url link for cross referencing)
EnterLogIntoDbase(date=ldate, place=tripcave, title=triptitle, text=ltriptext, trippeople=trippeople, expedition=expedition, logtime_underground=0) EnterLogIntoDbase(date=ldate, place=tripcave, title=triptitle, text=ltriptext, trippeople=trippeople, expedition=expedition, logtime_underground=0)
def Parseloghtml03(year, expedition, txt): def Parseloghtml03(year, expedition, txt):
tripparas = re.findall("<hr\s*/>([\s\S]*?)(?=<hr)", txt) tripparas = re.findall("<hr\s*/>([\s\S]*?)(?=<hr)", txt)
for trippara in tripparas: for trippara in tripparas:
s = re.match(u"(?s)\s*<p>(.*?)</p>(.*)$", trippara) s = re.match(u"(?s)\s*<p>(.*?)</p>(.*)$", trippara)
assert s, trippara assert s, trippara
tripheader, triptext = s.group(1), s.group(2) tripheader, triptext = s.group(1), s.group(2)
tripheader = re.sub("&nbsp;", " ", tripheader) tripheader = re.sub("&nbsp;", " ", tripheader)
tripheader = re.sub("\s+", " ", tripheader).strip() tripheader = re.sub("\s+", " ", tripheader).strip()
sheader = tripheader.split(" -- ") sheader = tripheader.split(" -- ")
tu = "" tu = ""
if re.match("T/U|Time underwater", sheader[-1]): if re.match("T/U|Time underwater", sheader[-1]):
tu = sheader.pop() tu = sheader.pop()
if len(sheader) != 3: if len(sheader) != 3:
print "header not three pieces", sheader print "header not three pieces", sheader
tripdate, triptitle, trippeople = sheader tripdate, triptitle, trippeople = sheader
ldate = ParseDate(tripdate.strip(), year) ldate = ParseDate(tripdate.strip(), year)
triptitles = triptitle.split(" , ") triptitles = triptitle.split(" , ")
if len(triptitles) >= 2: if len(triptitles) >= 2:
tripcave = triptitles[0] tripcave = triptitles[0]
else: else:
tripcave = "UNKNOWN" tripcave = "UNKNOWN"
#print tripcave, "--- ppp", triptitle, trippeople, len(triptext) #print tripcave, "--- ppp", triptitle, trippeople, len(triptext)
ltriptext = re.sub("</p>", "", triptext) ltriptext = re.sub("</p>", "", triptext)
ltriptext = re.sub("\s*?\n\s*", " ", ltriptext) ltriptext = re.sub("\s*?\n\s*", " ", ltriptext)
ltriptext = re.sub("<p>", "\n\n", ltriptext).strip() ltriptext = re.sub("<p>", "\n\n", ltriptext).strip()
ltriptext = re.sub("[^\s0-9a-zA-Z\-.,:;'!&()\[\]<>?=+*%]", "_NONASCII_", ltriptext) ltriptext = re.sub("[^\s0-9a-zA-Z\-.,:;'!&()\[\]<>?=+*%]", "_NONASCII_", ltriptext)
EnterLogIntoDbase(date = ldate, place = tripcave, title = triptitle, text = ltriptext, trippeople=trippeople, expedition=expedition, logtime_underground=0) EnterLogIntoDbase(date = ldate, place = tripcave, title = triptitle, text = ltriptext, trippeople=trippeople, expedition=expedition, logtime_underground=0)
yearlinks = [ yearlinks = [
("2009", "2009/2009logbook.txt", Parselogwikitxt), ("2009", "2009/2009logbook.txt", Parselogwikitxt),
("2008", "2008/2008logbook.txt", Parselogwikitxt), ("2008", "2008/2008logbook.txt", Parselogwikitxt),
("2007", "2007/logbook.html", Parseloghtmltxt), ("2007", "2007/logbook.html", Parseloghtmltxt),
("2006", "2006/logbook/logbook_06.txt", Parselogwikitxt), ("2006", "2006/logbook/logbook_06.txt", Parselogwikitxt),
("2005", "2005/logbook.html", Parseloghtmltxt), ("2005", "2005/logbook.html", Parseloghtmltxt),
("2004", "2004/logbook.html", Parseloghtmltxt), ("2004", "2004/logbook.html", Parseloghtmltxt),
("2003", "2003/logbook.html", Parseloghtml03), ("2003", "2003/logbook.html", Parseloghtml03),
("2002", "2002/logbook.html", Parseloghtmltxt), ("2002", "2002/logbook.html", Parseloghtmltxt),
("2001", "2001/log.htm", Parseloghtml01), ("2001", "2001/log.htm", Parseloghtml01),
("2000", "2000/log.htm", Parseloghtml01), ("2000", "2000/log.htm", Parseloghtml01),
("1999", "1999/log.htm", Parseloghtml01), ("1999", "1999/log.htm", Parseloghtml01),
("1998", "1998/log.htm", Parseloghtml01), ("1998", "1998/log.htm", Parseloghtml01),
("1997", "1997/log.htm", Parseloghtml01), ("1997", "1997/log.htm", Parseloghtml01),
("1996", "1996/log.htm", Parseloghtml01), ("1996", "1996/log.htm", Parseloghtml01),
("1995", "1995/log.htm", Parseloghtml01), ("1995", "1995/log.htm", Parseloghtml01),
("1994", "1994/log.htm", Parseloghtml01), ("1994", "1994/log.htm", Parseloghtml01),
("1993", "1993/log.htm", Parseloghtml01), ("1993", "1993/log.htm", Parseloghtml01),
("1992", "1992/log.htm", Parseloghtml01), ("1992", "1992/log.htm", Parseloghtml01),
("1991", "1991/log.htm", Parseloghtml01), ("1991", "1991/log.htm", Parseloghtml01),
] ]
def SetDatesFromLogbookEntries(expedition): def SetDatesFromLogbookEntries(expedition):
""" """
Sets the date_from and date_to field for an expedition based on persontrips. Sets the date_from and date_to field for an expedition based on persontrips.
Then sets the expedition date_from and date_to based on the personexpeditions. Then sets the expedition date_from and date_to based on the personexpeditions.
""" """
for personexpedition in expedition.personexpedition_set.all(): for personexpedition in expedition.personexpedition_set.all():
persontrips = personexpedition.persontrip_set.order_by('logbook_entry__date') persontrips = personexpedition.persontrip_set.order_by('logbook_entry__date')
# sequencing is difficult to do # sequencing is difficult to do
lprevpersontrip = None lprevpersontrip = None
for persontrip in persontrips: for persontrip in persontrips:
persontrip.persontrip_prev = lprevpersontrip persontrip.persontrip_prev = lprevpersontrip
if lprevpersontrip: if lprevpersontrip:
lprevpersontrip.persontrip_next = persontrip lprevpersontrip.persontrip_next = persontrip
lprevpersontrip.save() lprevpersontrip.save()
persontrip.persontrip_next = None persontrip.persontrip_next = None
lprevpersontrip = persontrip lprevpersontrip = persontrip
persontrip.save() persontrip.save()
def LoadLogbookForExpedition(expedition): def LoadLogbookForExpedition(expedition):
""" Parses all logbook entries for one expedition """ """ Parses all logbook entries for one expedition """
expowebbase = os.path.join(settings.EXPOWEB, "years") expowebbase = os.path.join(settings.EXPOWEB, "years")
year = str(expedition.year) year = str(expedition.year)
for lyear, lloc, parsefunc in yearlinks: for lyear, lloc, parsefunc in yearlinks:
if lyear == year: if lyear == year:
break break
fin = open(os.path.join(expowebbase, lloc)) fin = open(os.path.join(expowebbase, lloc))
print "opennning", lloc print "opennning", lloc
txt = fin.read().decode("latin1") txt = fin.read().decode("latin1")
fin.close() fin.close()
parsefunc(year, expedition, txt) parsefunc(year, expedition, txt)
SetDatesFromLogbookEntries(expedition) SetDatesFromLogbookEntries(expedition)
return "TOLOAD: " + year + " " + str(expedition.personexpedition_set.all()[1].logbookentry_set.count()) + " " + str(models.PersonTrip.objects.filter(personexpedition__expedition=expedition).count()) return "TOLOAD: " + year + " " + str(expedition.personexpedition_set.all()[1].logbookentry_set.count()) + " " + str(models.PersonTrip.objects.filter(personexpedition__expedition=expedition).count())
def LoadLogbooks(): def LoadLogbooks():
""" This is the master function for parsing all logbooks into the Troggle database. Requires yearlinks, which is a list of tuples for each expedition with expedition year, logbook path, and parsing function. """ """ This is the master function for parsing all logbooks into the Troggle database. Requires yearlinks, which is a list of tuples for each expedition with expedition year, logbook path, and parsing function. """
#Deletion has been moved to a seperate function to enable the non-destructive importing #Deletion has been moved to a seperate function to enable the non-destructive importing
#models.LogbookEntry.objects.all().delete() #models.LogbookEntry.objects.all().delete()
expowebbase = os.path.join(settings.EXPOWEB, "years") expowebbase = os.path.join(settings.EXPOWEB, "years")
#yearlinks = [ ("2001", "2001/log.htm", Parseloghtml01), ] #overwrite #yearlinks = [ ("2001", "2001/log.htm", Parseloghtml01), ] #overwrite
#yearlinks = [ ("1996", "1996/log.htm", Parseloghtml01),] # overwrite #yearlinks = [ ("1996", "1996/log.htm", Parseloghtml01),] # overwrite
for year, lloc, parsefunc in yearlinks: for year, lloc, parsefunc in yearlinks:
expedition = models.Expedition.objects.filter(year = year)[0] expedition = models.Expedition.objects.filter(year = year)[0]
fin = open(os.path.join(expowebbase, lloc)) fin = open(os.path.join(expowebbase, lloc))
txt = fin.read().decode("latin1") txt = fin.read().decode("latin1")
fin.close() fin.close()
parsefunc(year, expedition, txt) parsefunc(year, expedition, txt)
SetDatesFromLogbookEntries(expedition) SetDatesFromLogbookEntries(expedition)
dateRegex = re.compile('<span\s+class="date">(\d\d\d\d)-(\d\d)-(\d\d)</span>', re.S) dateRegex = re.compile('<span\s+class="date">(\d\d\d\d)-(\d\d)-(\d\d)</span>', re.S)
expeditionYearRegex = re.compile('<span\s+class="expeditionyear">(.*?)</span>', re.S) expeditionYearRegex = re.compile('<span\s+class="expeditionyear">(.*?)</span>', re.S)
titleRegex = re.compile('<H1>(.*?)</H1>', re.S) titleRegex = re.compile('<H1>(.*?)</H1>', re.S)
reportRegex = re.compile('<div\s+class="report">(.*)</div>\s*</body>', re.S) reportRegex = re.compile('<div\s+class="report">(.*)</div>\s*</body>', re.S)
personRegex = re.compile('<div\s+class="person">(.*?)</div>', re.S) personRegex = re.compile('<div\s+class="person">(.*?)</div>', re.S)
nameAuthorRegex = re.compile('<span\s+class="name(,author|)">(.*?)</span>', re.S) nameAuthorRegex = re.compile('<span\s+class="name(,author|)">(.*?)</span>', re.S)
TURegex = re.compile('<span\s+class="TU">([0-9]*\.?[0-9]+)</span>', re.S) TURegex = re.compile('<span\s+class="TU">([0-9]*\.?[0-9]+)</span>', re.S)
locationRegex = re.compile('<span\s+class="location">(.*?)</span>', re.S) locationRegex = re.compile('<span\s+class="location">(.*?)</span>', re.S)
caveRegex = re.compile('<span\s+class="cave">(.*?)</span>', re.S) caveRegex = re.compile('<span\s+class="cave">(.*?)</span>', re.S)
def parseAutoLogBookEntry(filename): def parseAutoLogBookEntry(filename):
errors = [] errors = []
f = open(filename, "r") f = open(filename, "r")
contents = f.read() contents = f.read()
f.close() f.close()
dateMatch = dateRegex.search(contents) dateMatch = dateRegex.search(contents)
if dateMatch: if dateMatch:
year, month, day = [int(x) for x in dateMatch.groups()] year, month, day = [int(x) for x in dateMatch.groups()]
date = datetime.date(year, month, day) date = datetime.date(year, month, day)
else: else:
errors.append("Date could not be found") errors.append("Date could not be found")
expeditionYearMatch = expeditionYearRegex.search(contents) expeditionYearMatch = expeditionYearRegex.search(contents)
if expeditionYearMatch: if expeditionYearMatch:
try: try:
expedition = models.Expedition.objects.get(year = expeditionYearMatch.groups()[0]) expedition = models.Expedition.objects.get(year = expeditionYearMatch.groups()[0])
personExpeditionNameLookup = GetPersonExpeditionNameLookup(expedition) personExpeditionNameLookup = GetPersonExpeditionNameLookup(expedition)
except models.Expedition.DoesNotExist: except models.Expedition.DoesNotExist:
errors.append("Expedition not in database") errors.append("Expedition not in database")
else: else:
errors.append("Expediton Year could not be parsed") errors.append("Expediton Year could not be parsed")
titleMatch = titleRegex.search(contents) titleMatch = titleRegex.search(contents)
if titleMatch: if titleMatch:
title, = titleMatch.groups() title, = titleMatch.groups()
if len(title) > settings.MAX_LOGBOOK_ENTRY_TITLE_LENGTH: if len(title) > settings.MAX_LOGBOOK_ENTRY_TITLE_LENGTH:
errors.append("Title too long") errors.append("Title too long")
else: else:
errors.append("Title could not be found") errors.append("Title could not be found")
caveMatch = caveRegex.search(contents) caveMatch = caveRegex.search(contents)
if caveMatch: if caveMatch:
caveRef, = caveMatch.groups() caveRef, = caveMatch.groups()
try: try:
cave = models.getCaveByReference(caveRef) cave = models.getCaveByReference(caveRef)
except AssertionError: except AssertionError:
cave = None cave = None
errors.append("Cave not found in database") errors.append("Cave not found in database")
else: else:
cave = None cave = None
locationMatch = locationRegex.search(contents) locationMatch = locationRegex.search(contents)
if locationMatch: if locationMatch:
location, = locationMatch.groups() location, = locationMatch.groups()
else: else:
location = None location = None
if cave is None and location is None: if cave is None and location is None:
errors.append("Location nor cave could not be found") errors.append("Location nor cave could not be found")
reportMatch = reportRegex.search(contents) reportMatch = reportRegex.search(contents)
if reportMatch: if reportMatch:
report, = reportMatch.groups() report, = reportMatch.groups()
else: else:
errors.append("Contents could not be found") errors.append("Contents could not be found")
if errors: if errors:
return errors # Easiest to bail out at this point as we need to make sure that we know which expedition to look for people from. return errors # Easiest to bail out at this point as we need to make sure that we know which expedition to look for people from.
people = [] people = []
for personMatch in personRegex.findall(contents): for personMatch in personRegex.findall(contents):
nameAuthorMatch = nameAuthorRegex.search(contents) nameAuthorMatch = nameAuthorRegex.search(contents)
if nameAuthorMatch: if nameAuthorMatch:
author, name = nameAuthorMatch.groups() author, name = nameAuthorMatch.groups()
if name.lower() in personExpeditionNameLookup: if name.lower() in personExpeditionNameLookup:
personExpo = personExpeditionNameLookup[name.lower()] personExpo = personExpeditionNameLookup[name.lower()]
else: else:
errors.append("Person could not be found in database") errors.append("Person could not be found in database")
author = bool(author) author = bool(author)
else: else:
errors.append("Persons name could not be found") errors.append("Persons name could not be found")
TUMatch = TURegex.search(contents) TUMatch = TURegex.search(contents)
if TUMatch: if TUMatch:
TU, = TUMatch.groups() TU, = TUMatch.groups()
else: else:
errors.append("TU could not be found") errors.append("TU could not be found")
if not errors: if not errors:
people.append((name, author, TU)) people.append((name, author, TU))
if errors: if errors:
return errors # Bail out before commiting to the database return errors # Bail out before commiting to the database
logbookEntry = models.LogbookEntry(date = date, logbookEntry = models.LogbookEntry(date = date,
expedition = expedition, expedition = expedition,
title = title, cave = cave, place = location, title = title, cave = cave, place = location,
text = report, slug = slugify(title)[:50], text = report, slug = slugify(title)[:50],
filename = filename) filename = filename)
logbookEntry.save() logbookEntry.save()
for name, author, TU in people: for name, author, TU in people:
models.PersonTrip(personexpedition = personExpo, models.PersonTrip(personexpedition = personExpo,
time_underground = TU, time_underground = TU,
logbook_entry = logbookEntry, logbook_entry = logbookEntry,
is_logbook_entry_author = author).save() is_logbook_entry_author = author).save()
print logbookEntry print logbookEntry

View File

@ -1,56 +1,56 @@
''' '''
This module is the part of troggle that parses descriptions of cave parts (subcaves) from the legacy html files and saves them in the troggle database as instances of the model Subcave. Unfortunately, this parser can not be very flexible because the legacy format is poorly structured. This module is the part of troggle that parses descriptions of cave parts (subcaves) from the legacy html files and saves them in the troggle database as instances of the model Subcave. Unfortunately, this parser can not be very flexible because the legacy format is poorly structured.
''' '''
import sys, os import sys, os
import os, re, logging import os, re, logging
from django.conf import settings from django.conf import settings
from core.models import Subcave, Cave from core.models import Subcave, Cave
from utils import save_carefully from utils import save_carefully
def getLinksInCaveDescription(cave): def getLinksInCaveDescription(cave):
''' '''
Returns all HTML <a href> tags from a given cave as a list of tuples Returns all HTML <a href> tags from a given cave as a list of tuples
in the format ('filename.html','Description') in the format ('filename.html','Description')
''' '''
pattern='<a href=\"(.*?)\">(.*?)</a>' pattern='<a href=\"(.*?)\">(.*?)</a>'
if cave.underground_description: if cave.underground_description:
return re.findall(pattern,cave.underground_description) return re.findall(pattern,cave.underground_description)
else: else:
return [] return []
def importSubcaves(cave): def importSubcaves(cave):
for link in getLinksInCaveDescription(cave): for link in getLinksInCaveDescription(cave):
try: try:
subcaveFilePath=os.path.join( subcaveFilePath=os.path.join(
settings.EXPOWEB, settings.EXPOWEB,
os.path.dirname(cave.description_file), os.path.dirname(cave.description_file),
link[0]) link[0])
subcaveFile=open(subcaveFilePath,'r') subcaveFile=open(subcaveFilePath,'r')
description=subcaveFile.read().decode('iso-8859-1').encode('utf-8') description=subcaveFile.read().decode('iso-8859-1').encode('utf-8')
lookupAttribs={'title':link[1], 'cave':cave} lookupAttribs={'title':link[1], 'cave':cave}
nonLookupAttribs={'description':description} nonLookupAttribs={'description':description}
newSubcave=save_carefully(Subcave,lookupAttribs=lookupAttribs,nonLookupAttribs=nonLookupAttribs) newSubcave=save_carefully(Subcave,lookupAttribs=lookupAttribs,nonLookupAttribs=nonLookupAttribs)
logging.info("Added " + unicode(newSubcave) + " to " + unicode(cave)) logging.info("Added " + unicode(newSubcave) + " to " + unicode(cave))
except IOError: except IOError:
logging.info("Subcave import couldn't open "+subcaveFilePath) logging.info("Subcave import couldn't open "+subcaveFilePath)
def getLinksInSubcaveDescription(subcave): def getLinksInSubcaveDescription(subcave):
pattern='<a href=\"(.*?)\">(.*?)</a>' pattern='<a href=\"(.*?)\">(.*?)</a>'
if subcave.description: if subcave.description:
return re.findall(pattern,subcave.description) return re.findall(pattern,subcave.description)
else: else:
return [] return []
def getLinksInAllSubcaves(): def getLinksInAllSubcaves():
bigList=[] bigList=[]
for subcave in Subcave.objects.all(): for subcave in Subcave.objects.all():
bigList+=getLinksInSubcaveDescription(subcave) bigList+=getLinksInSubcaveDescription(subcave)
return bigList return bigList
def importAllSubcaves(): def importAllSubcaves():
for cave in Cave.objects.all(): for cave in Cave.objects.all():
importSubcaves(cave) importSubcaves(cave)

View File

@ -1,301 +1,301 @@
import sys, os, types, logging, stat import sys, os, types, logging, stat
#sys.path.append('C:\\Expo\\expoweb') #sys.path.append('C:\\Expo\\expoweb')
#from troggle import * #from troggle import *
#os.environ['DJANGO_SETTINGS_MODULE']='troggle.settings' #os.environ['DJANGO_SETTINGS_MODULE']='troggle.settings'
import settings import settings
from core.models import * from core.models import *
from PIL import Image from PIL import Image
#import settings #import settings
#import core.models as models #import core.models as models
import csv import csv
import re import re
import datetime import datetime
from utils import save_carefully from utils import save_carefully
def get_or_create_placeholder(year): def get_or_create_placeholder(year):
""" All surveys must be related to a logbookentry. We don't have a way to """ All surveys must be related to a logbookentry. We don't have a way to
automatically figure out which survey went with which logbookentry, automatically figure out which survey went with which logbookentry,
so we create a survey placeholder logbook entry for each year. This so we create a survey placeholder logbook entry for each year. This
function always returns such a placeholder, and creates it if it doesn't function always returns such a placeholder, and creates it if it doesn't
exist yet. exist yet.
""" """
lookupAttribs={'date__year':int(year), 'title':"placeholder for surveys",} lookupAttribs={'date__year':int(year), 'title':"placeholder for surveys",}
nonLookupAttribs={'text':"surveys temporarily attached to this should be re-attached to their actual trips", 'date':datetime.date(int(year),1,1)} nonLookupAttribs={'text':"surveys temporarily attached to this should be re-attached to their actual trips", 'date':datetime.date(int(year),1,1)}
placeholder_logbook_entry, newly_created = save_carefully(LogbookEntry, lookupAttribs, nonLookupAttribs) placeholder_logbook_entry, newly_created = save_carefully(LogbookEntry, lookupAttribs, nonLookupAttribs)
return placeholder_logbook_entry return placeholder_logbook_entry
# dead # dead
def readSurveysFromCSV(): def readSurveysFromCSV():
try: # could probably combine these two try: # could probably combine these two
surveytab = open(os.path.join(settings.SURVEY_SCANS, "Surveys.csv")) surveytab = open(os.path.join(settings.SURVEY_SCANS, "Surveys.csv"))
except IOError: except IOError:
import cStringIO, urllib import cStringIO, urllib
surveytab = cStringIO.StringIO(urllib.urlopen(settings.SURVEY_SCANS + "/Surveys.csv").read()) surveytab = cStringIO.StringIO(urllib.urlopen(settings.SURVEY_SCANS + "/Surveys.csv").read())
dialect=csv.Sniffer().sniff(surveytab.read()) dialect=csv.Sniffer().sniff(surveytab.read())
surveytab.seek(0,0) surveytab.seek(0,0)
surveyreader = csv.reader(surveytab,dialect=dialect) surveyreader = csv.reader(surveytab,dialect=dialect)
headers = surveyreader.next() headers = surveyreader.next()
header = dict(zip(headers, range(len(headers)))) #set up a dictionary where the indexes are header names and the values are column numbers header = dict(zip(headers, range(len(headers)))) #set up a dictionary where the indexes are header names and the values are column numbers
# test if the expeditions have been added yet # test if the expeditions have been added yet
if Expedition.objects.count()==0: if Expedition.objects.count()==0:
print "There are no expeditions in the database. Please run the logbook parser." print "There are no expeditions in the database. Please run the logbook parser."
sys.exit() sys.exit()
logging.info("Deleting all scanned images") logging.info("Deleting all scanned images")
ScannedImage.objects.all().delete() ScannedImage.objects.all().delete()
logging.info("Deleting all survey objects") logging.info("Deleting all survey objects")
Survey.objects.all().delete() Survey.objects.all().delete()
logging.info("Beginning to import surveys from "+str(os.path.join(settings.SURVEYS, "Surveys.csv"))+"\n"+"-"*60+"\n") logging.info("Beginning to import surveys from "+str(os.path.join(settings.SURVEYS, "Surveys.csv"))+"\n"+"-"*60+"\n")
for survey in surveyreader: for survey in surveyreader:
#I hate this, but some surveys have a letter eg 2000#34a. The next line deals with that. #I hate this, but some surveys have a letter eg 2000#34a. The next line deals with that.
walletNumberLetter = re.match(r'(?P<number>\d*)(?P<letter>[a-zA-Z]*)',survey[header['Survey Number']]) walletNumberLetter = re.match(r'(?P<number>\d*)(?P<letter>[a-zA-Z]*)',survey[header['Survey Number']])
# print walletNumberLetter.groups() # print walletNumberLetter.groups()
year=survey[header['Year']] year=survey[header['Year']]
surveyobj = Survey( surveyobj = Survey(
expedition = Expedition.objects.filter(year=year)[0], expedition = Expedition.objects.filter(year=year)[0],
wallet_number = walletNumberLetter.group('number'), wallet_number = walletNumberLetter.group('number'),
logbook_entry = get_or_create_placeholder(year), logbook_entry = get_or_create_placeholder(year),
comments = survey[header['Comments']], comments = survey[header['Comments']],
location = survey[header['Location']] location = survey[header['Location']]
) )
surveyobj.wallet_letter = walletNumberLetter.group('letter') surveyobj.wallet_letter = walletNumberLetter.group('letter')
if survey[header['Finished']]=='Yes': if survey[header['Finished']]=='Yes':
#try and find the sketch_scan #try and find the sketch_scan
pass pass
surveyobj.save() surveyobj.save()
logging.info("added survey " + survey[header['Year']] + "#" + surveyobj.wallet_number + "\r") logging.info("added survey " + survey[header['Year']] + "#" + surveyobj.wallet_number + "\r")
# dead # dead
def listdir(*directories): def listdir(*directories):
try: try:
return os.listdir(os.path.join(settings.SURVEYS, *directories)) return os.listdir(os.path.join(settings.SURVEYS, *directories))
except: except:
import urllib import urllib
url = settings.SURVEYS + reduce(lambda x, y: x + "/" + y, ["listdir"] + list(directories)) url = settings.SURVEYS + reduce(lambda x, y: x + "/" + y, ["listdir"] + list(directories))
folders = urllib.urlopen(url.replace("#", "%23")).readlines() folders = urllib.urlopen(url.replace("#", "%23")).readlines()
return [folder.rstrip(r"/") for folder in folders] return [folder.rstrip(r"/") for folder in folders]
# add survey scans # add survey scans
def parseSurveyScans(year, logfile=None): def parseSurveyScans(year, logfile=None):
# yearFileList = listdir(year.year) # yearFileList = listdir(year.year)
yearPath=os.path.join(settings.SURVEY_SCANS, "years", year.year) yearPath=os.path.join(settings.SURVEY_SCANS, "years", year.year)
yearFileList=os.listdir(yearPath) yearFileList=os.listdir(yearPath)
print yearFileList print yearFileList
for surveyFolder in yearFileList: for surveyFolder in yearFileList:
try: try:
surveyNumber=re.match(r'\d\d\d\d#0*(\d+)',surveyFolder).groups() surveyNumber=re.match(r'\d\d\d\d#0*(\d+)',surveyFolder).groups()
# scanList = listdir(year.year, surveyFolder) # scanList = listdir(year.year, surveyFolder)
scanList=os.listdir(os.path.join(yearPath,surveyFolder)) scanList=os.listdir(os.path.join(yearPath,surveyFolder))
except AttributeError: except AttributeError:
print surveyFolder + " ignored", print surveyFolder + " ignored",
continue continue
for scan in scanList: for scan in scanList:
try: try:
scanChopped=re.match(r'(?i).*(notes|elev|plan|elevation|extend)(\d*)\.(png|jpg|jpeg)',scan).groups() scanChopped=re.match(r'(?i).*(notes|elev|plan|elevation|extend)(\d*)\.(png|jpg|jpeg)',scan).groups()
scanType,scanNumber,scanFormat=scanChopped scanType,scanNumber,scanFormat=scanChopped
except AttributeError: except AttributeError:
print scan + " ignored \r", print scan + " ignored \r",
continue continue
if scanType == 'elev' or scanType == 'extend': if scanType == 'elev' or scanType == 'extend':
scanType = 'elevation' scanType = 'elevation'
if scanNumber=='': if scanNumber=='':
scanNumber=1 scanNumber=1
if type(surveyNumber)==types.TupleType: if type(surveyNumber)==types.TupleType:
surveyNumber=surveyNumber[0] surveyNumber=surveyNumber[0]
try: try:
placeholder=get_or_create_placeholder(year=int(year.year)) placeholder=get_or_create_placeholder(year=int(year.year))
survey=Survey.objects.get_or_create(wallet_number=surveyNumber, expedition=year, defaults={'logbook_entry':placeholder})[0] survey=Survey.objects.get_or_create(wallet_number=surveyNumber, expedition=year, defaults={'logbook_entry':placeholder})[0]
except Survey.MultipleObjectsReturned: except Survey.MultipleObjectsReturned:
survey=Survey.objects.filter(wallet_number=surveyNumber, expedition=year)[0] survey=Survey.objects.filter(wallet_number=surveyNumber, expedition=year)[0]
file=os.path.join(year.year, surveyFolder, scan) file=os.path.join(year.year, surveyFolder, scan)
scanObj = ScannedImage( scanObj = ScannedImage(
file=file, file=file,
contents=scanType, contents=scanType,
number_in_wallet=scanNumber, number_in_wallet=scanNumber,
survey=survey, survey=survey,
new_since_parsing=False, new_since_parsing=False,
) )
#print "Added scanned image at " + str(scanObj) #print "Added scanned image at " + str(scanObj)
if scanFormat=="png": if scanFormat=="png":
if isInterlacedPNG(os.path.join(settings.SURVEY_SCANS,file)): if isInterlacedPNG(os.path.join(settings.SURVEY_SCANS,file)):
print file + " is an interlaced PNG. No can do." print file + " is an interlaced PNG. No can do."
continue continue
scanObj.save() scanObj.save()
# dead # dead
def parseSurveys(logfile=None): def parseSurveys(logfile=None):
readSurveysFromCSV() readSurveysFromCSV()
for year in Expedition.objects.filter(year__gte=2000): #expos since 2000, because paths and filenames were nonstandard before then for year in Expedition.objects.filter(year__gte=2000): #expos since 2000, because paths and filenames were nonstandard before then
parseSurveyScans(year) parseSurveyScans(year)
# dead # dead
def isInterlacedPNG(filePath): #We need to check for interlaced PNGs because the thumbnail engine can't handle them (uses PIL) def isInterlacedPNG(filePath): #We need to check for interlaced PNGs because the thumbnail engine can't handle them (uses PIL)
file=Image.open(filePath) file=Image.open(filePath)
print filePath print filePath
if 'interlace' in file.info: if 'interlace' in file.info:
return file.info['interlace'] return file.info['interlace']
else: else:
return False return False
# handles url or file, so we can refer to a set of scans on another server # handles url or file, so we can refer to a set of scans on another server
def GetListDir(sdir): def GetListDir(sdir):
res = [ ] res = [ ]
if sdir[:7] == "http://": if sdir[:7] == "http://":
assert False, "Not written" assert False, "Not written"
s = urllib.urlopen(sdir) s = urllib.urlopen(sdir)
else: else:
for f in os.listdir(sdir): for f in os.listdir(sdir):
if f[0] != ".": if f[0] != ".":
ff = os.path.join(sdir, f) ff = os.path.join(sdir, f)
res.append((f, ff, os.path.isdir(ff))) res.append((f, ff, os.path.isdir(ff)))
return res return res
def LoadListScansFile(survexscansfolder): def LoadListScansFile(survexscansfolder):
gld = [ ] gld = [ ]
# flatten out any directories in these book files # flatten out any directories in these book files
for (fyf, ffyf, fisdiryf) in GetListDir(survexscansfolder.fpath): for (fyf, ffyf, fisdiryf) in GetListDir(survexscansfolder.fpath):
if fisdiryf: if fisdiryf:
gld.extend(GetListDir(ffyf)) gld.extend(GetListDir(ffyf))
else: else:
gld.append((fyf, ffyf, fisdiryf)) gld.append((fyf, ffyf, fisdiryf))
for (fyf, ffyf, fisdiryf) in gld: for (fyf, ffyf, fisdiryf) in gld:
assert not fisdiryf, ffyf assert not fisdiryf, ffyf
if re.search("\.(?:png|jpg|jpeg)(?i)$", fyf): if re.search("\.(?:png|jpg|jpeg)(?i)$", fyf):
survexscansingle = SurvexScanSingle(ffile=ffyf, name=fyf, survexscansfolder=survexscansfolder) survexscansingle = SurvexScanSingle(ffile=ffyf, name=fyf, survexscansfolder=survexscansfolder)
survexscansingle.save() survexscansingle.save()
# this iterates through the scans directories (either here or on the remote server) # this iterates through the scans directories (either here or on the remote server)
# and builds up the models we can access later # and builds up the models we can access later
def LoadListScans(): def LoadListScans():
SurvexScanSingle.objects.all().delete() SurvexScanSingle.objects.all().delete()
SurvexScansFolder.objects.all().delete() SurvexScansFolder.objects.all().delete()
# first do the smkhs (large kh survey scans) directory # first do the smkhs (large kh survey scans) directory
survexscansfoldersmkhs = SurvexScansFolder(fpath=os.path.join(settings.SURVEY_SCANS, "smkhs"), walletname="smkhs") survexscansfoldersmkhs = SurvexScansFolder(fpath=os.path.join(settings.SURVEY_SCANS, "smkhs"), walletname="smkhs")
if os.path.isdir(survexscansfoldersmkhs.fpath): if os.path.isdir(survexscansfoldersmkhs.fpath):
survexscansfoldersmkhs.save() survexscansfoldersmkhs.save()
LoadListScansFile(survexscansfoldersmkhs) LoadListScansFile(survexscansfoldersmkhs)
# iterate into the surveyscans directory # iterate into the surveyscans directory
for f, ff, fisdir in GetListDir(os.path.join(settings.SURVEY_SCANS, "surveyscans")): for f, ff, fisdir in GetListDir(os.path.join(settings.SURVEY_SCANS, "surveyscans")):
if not fisdir: if not fisdir:
continue continue
# do the year folders # do the year folders
if re.match("\d\d\d\d$", f): if re.match("\d\d\d\d$", f):
for fy, ffy, fisdiry in GetListDir(ff): for fy, ffy, fisdiry in GetListDir(ff):
if fisdiry: if fisdiry:
assert fisdiry, ffy assert fisdiry, ffy
survexscansfolder = SurvexScansFolder(fpath=ffy, walletname=fy) survexscansfolder = SurvexScansFolder(fpath=ffy, walletname=fy)
survexscansfolder.save() survexscansfolder.save()
LoadListScansFile(survexscansfolder) LoadListScansFile(survexscansfolder)
# do the # do the
elif f != "thumbs": elif f != "thumbs":
survexscansfolder = SurvexScansFolder(fpath=ff, walletname=f) survexscansfolder = SurvexScansFolder(fpath=ff, walletname=f)
survexscansfolder.save() survexscansfolder.save()
LoadListScansFile(survexscansfolder) LoadListScansFile(survexscansfolder)
def FindTunnelScan(tunnelfile, path): def FindTunnelScan(tunnelfile, path):
scansfolder, scansfile = None, None scansfolder, scansfile = None, None
mscansdir = re.search("(\d\d\d\d#\d+\w?|1995-96kh|92-94Surveybookkh|1991surveybook|smkhs)/(.*?(?:png|jpg))$", path) mscansdir = re.search("(\d\d\d\d#\d+\w?|1995-96kh|92-94Surveybookkh|1991surveybook|smkhs)/(.*?(?:png|jpg))$", path)
if mscansdir: if mscansdir:
scansfolderl = SurvexScansFolder.objects.filter(walletname=mscansdir.group(1)) scansfolderl = SurvexScansFolder.objects.filter(walletname=mscansdir.group(1))
if len(scansfolderl): if len(scansfolderl):
assert len(scansfolderl) == 1 assert len(scansfolderl) == 1
scansfolder = scansfolderl[0] scansfolder = scansfolderl[0]
if scansfolder: if scansfolder:
scansfilel = scansfolder.survexscansingle_set.filter(name=mscansdir.group(2)) scansfilel = scansfolder.survexscansingle_set.filter(name=mscansdir.group(2))
if len(scansfilel): if len(scansfilel):
assert len(scansfilel) == 1 assert len(scansfilel) == 1
scansfile = scansfilel[0] scansfile = scansfilel[0]
if scansfolder: if scansfolder:
tunnelfile.survexscansfolders.add(scansfolder) tunnelfile.survexscansfolders.add(scansfolder)
if scansfile: if scansfile:
tunnelfile.survexscans.add(scansfile) tunnelfile.survexscans.add(scansfile)
elif path and not re.search("\.(?:png|jpg)$(?i)", path): elif path and not re.search("\.(?:png|jpg)$(?i)", path):
name = os.path.split(path)[1] name = os.path.split(path)[1]
print "ttt", tunnelfile.tunnelpath, path, name print "ttt", tunnelfile.tunnelpath, path, name
rtunnelfilel = TunnelFile.objects.filter(tunnelname=name) rtunnelfilel = TunnelFile.objects.filter(tunnelname=name)
if len(rtunnelfilel): if len(rtunnelfilel):
assert len(rtunnelfilel) == 1, ("two paths with name of", path, "need more discrimination coded") assert len(rtunnelfilel) == 1, ("two paths with name of", path, "need more discrimination coded")
rtunnelfile = rtunnelfilel[0] rtunnelfile = rtunnelfilel[0]
#print "ttt", tunnelfile.tunnelpath, path, name, rtunnelfile.tunnelpath #print "ttt", tunnelfile.tunnelpath, path, name, rtunnelfile.tunnelpath
tunnelfile.tunnelcontains.add(rtunnelfile) tunnelfile.tunnelcontains.add(rtunnelfile)
tunnelfile.save() tunnelfile.save()
def SetTunnelfileInfo(tunnelfile): def SetTunnelfileInfo(tunnelfile):
ff = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath) ff = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath)
tunnelfile.filesize = os.stat(ff)[stat.ST_SIZE] tunnelfile.filesize = os.stat(ff)[stat.ST_SIZE]
fin = open(ff) fin = open(ff)
ttext = fin.read() ttext = fin.read()
fin.close() fin.close()
mtype = re.search("<(fontcolours|sketch)", ttext) mtype = re.search("<(fontcolours|sketch)", ttext)
assert mtype, ff assert mtype, ff
tunnelfile.bfontcolours = (mtype.group(1)=="fontcolours") tunnelfile.bfontcolours = (mtype.group(1)=="fontcolours")
tunnelfile.npaths = len(re.findall("<skpath", ttext)) tunnelfile.npaths = len(re.findall("<skpath", ttext))
tunnelfile.save() tunnelfile.save()
# <tunnelxml tunnelversion="version2009-06-21 Matienzo" tunnelproject="ireby" tunneluser="goatchurch" tunneldate="2009-06-29 23:22:17"> # <tunnelxml tunnelversion="version2009-06-21 Matienzo" tunnelproject="ireby" tunneluser="goatchurch" tunneldate="2009-06-29 23:22:17">
# <pcarea area_signal="frame" sfscaledown="12.282584" sfrotatedeg="-90.76982" sfxtrans="11.676667377221136" sfytrans="-15.677173422877454" sfsketch="204description/scans/plan(38).png" sfstyle="" nodeconnzsetrelative="0.0"> # <pcarea area_signal="frame" sfscaledown="12.282584" sfrotatedeg="-90.76982" sfxtrans="11.676667377221136" sfytrans="-15.677173422877454" sfsketch="204description/scans/plan(38).png" sfstyle="" nodeconnzsetrelative="0.0">
for path, style in re.findall('<pcarea area_signal="frame".*?sfsketch="([^"]*)" sfstyle="([^"]*)"', ttext): for path, style in re.findall('<pcarea area_signal="frame".*?sfsketch="([^"]*)" sfstyle="([^"]*)"', ttext):
FindTunnelScan(tunnelfile, path) FindTunnelScan(tunnelfile, path)
# should also scan and look for survex blocks that might have been included # should also scan and look for survex blocks that might have been included
# and also survex titles as well. # and also survex titles as well.
tunnelfile.save() tunnelfile.save()
def LoadTunnelFiles(): def LoadTunnelFiles():
tunneldatadir = settings.TUNNEL_DATA tunneldatadir = settings.TUNNEL_DATA
TunnelFile.objects.all().delete() TunnelFile.objects.all().delete()
tunneldirs = [ "" ] tunneldirs = [ "" ]
while tunneldirs: while tunneldirs:
tunneldir = tunneldirs.pop() tunneldir = tunneldirs.pop()
for f in os.listdir(os.path.join(tunneldatadir, tunneldir)): for f in os.listdir(os.path.join(tunneldatadir, tunneldir)):
if f[0] == "." or f[-1] == "~": if f[0] == "." or f[-1] == "~":
continue continue
lf = os.path.join(tunneldir, f) lf = os.path.join(tunneldir, f)
ff = os.path.join(tunneldatadir, lf) ff = os.path.join(tunneldatadir, lf)
if os.path.isdir(ff): if os.path.isdir(ff):
tunneldirs.append(lf) tunneldirs.append(lf)
elif f[-4:] == ".xml": elif f[-4:] == ".xml":
tunnelfile = TunnelFile(tunnelpath=lf, tunnelname=os.path.split(f[:-4])[1]) tunnelfile = TunnelFile(tunnelpath=lf, tunnelname=os.path.split(f[:-4])[1])
tunnelfile.save() tunnelfile.save()
for tunnelfile in TunnelFile.objects.all(): for tunnelfile in TunnelFile.objects.all():
SetTunnelfileInfo(tunnelfile) SetTunnelfileInfo(tunnelfile)

View File

@ -1,10 +1,10 @@
{% extends "admin/base.html" %} {% extends "admin/base.html" %}
{% load i18n %} {% load i18n %}
{% block title %}{{ title }} | {% trans 'Troggle site admin' %}{% endblock %} {% block title %}{{ title }} | {% trans 'Troggle site admin' %}{% endblock %}
{% block branding %} {% block branding %}
<h1 id="site-name">{% trans 'Troggle administration' %}</h1> <h1 id="site-name">{% trans 'Troggle administration' %}</h1>
{% endblock %} {% endblock %}
{% block nav-global %}{% endblock %} {% block nav-global %}{% endblock %}

View File

@ -1,111 +1,111 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/main3.css" title="eyeCandy"/> <link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/main3.css" title="eyeCandy"/>
<link rel="alternate stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/mainplain.css" title="plain"/> <link rel="alternate stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/mainplain.css" title="plain"/>
<link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/dropdownNavStyle.css" /> <link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/dropdownNavStyle.css" />
<title>{% block title %}Troggle{% endblock %}</title> <title>{% block title %}Troggle{% endblock %}</title>
<script src="{{ settings.MEDIA_URL }}js/jquery.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/jquery.quicksearch.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery.quicksearch.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/base.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/base.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/jquery.dropdownPlain.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery.dropdownPlain.js" type="text/javascript"></script>
{% block head %}{% endblock %} {% block head %}{% endblock %}
</head> </head>
<body onLoad="contentHeight();"> <body onLoad="contentHeight();">
<div id="header"> <div id="header">
<h1>CUCC Expeditions to Austria: 1976 - 2009</h1> <h1>CUCC Expeditions to Austria: 1976 - 2009</h1>
<div id="editLinks"> {% block loginInfo %} <div id="editLinks"> {% block loginInfo %}
<a href="{{ settings.EXPOWEB_URL }}/index.htm">ExpoWeb</a> | <a href="{{ settings.EXPOWEB_URL }}/index.htm">ExpoWeb</a> |
<a href="{{ settings.URL_ROOT }}">Home</a> | <a href="{{ settings.URL_ROOT }}">Home</a> |
{% if user.username %} {% if user.username %}
You are logged in as {{ user.username }} You are logged in as {{ user.username }}
{% if user.person %}(<a href="{{ user.person.get_absolute_url }}">{{ user.person }}</a>) {% if user.person %}(<a href="{{ user.person.get_absolute_url }}">{{ user.person }}</a>)
{% else %}<a href={% url profiles_select_profile %}>sort your profile</a> {% else %}<a href={% url profiles_select_profile %}>sort your profile</a>
{% endif %}. {% endif %}.
| <a href="{% url auth_logout %}">Log out</a> {% else %} <a href="{% url registration_register %}">Sign up</a> | <a href="{% url auth_login %}">Log in</a> {% endif %} | <a href="{% url auth_logout %}">Log out</a> {% else %} <a href="{% url registration_register %}">Sign up</a> | <a href="{% url auth_login %}">Log in</a> {% endif %}
{% endblock%} {% endblock%}
{% block editLink %} {% block editLink %}
{% endblock %} {% endblock %}
</div> </div>
</div> </div>
<div class="toolbarlinks"> <div class="toolbarlinks">
<a href="{% url survexcaveslist %}">All Survex</a> | <a href="{% url survexcaveslist %}">All Survex</a> |
<a href="{% url surveyscansfolders %}">Scans</a> | <a href="{% url surveyscansfolders %}">Scans</a> |
<a href="{% url tunneldata %}">Tunneldata</a> | <a href="{% url tunneldata %}">Tunneldata</a> |
<a href="{% url survexcavessingle 161 %}">161</a> | <a href="{% url survexcavessingle 161 %}">161</a> |
<a href="{% url survexcavessingle 204 %}">204</a> | <a href="{% url survexcavessingle 204 %}">204</a> |
<a href="{% url survexcavessingle 258 %}">258</a> | <a href="{% url survexcavessingle 258 %}">258</a> |
<a href="{% url expedition 2009 %}">Expo2009</a> | <a href="{% url expedition 2009 %}">Expo2009</a> |
<a href="{% url expedition 2010 %}">Expo2010</a> | <a href="{% url expedition 2010 %}">Expo2010</a> |
<a href="{% url expedition 2011 %}">Expo2011</a> | <a href="{% url expedition 2011 %}">Expo2011</a> |
<a href="/admin">Django admin</a> <a href="/admin">Django admin</a>
</div> </div>
<div id="nav"> <div id="nav">
{% block nav %} {% block nav %}
<!-- Use id="nav" for the left side menu --> <!-- Use id="nav" for the left side menu -->
{% endblock %} {% endblock %}
</div> </div>
<div id="content" > <div id="content" >
{% block contentheader %} {% block contentheader %}
{% endblock %} {% endblock %}
<div id="related"> <div id="related">
{% block related %} {% block related %}
<script language="javascript"> <script language="javascript">
$('#related').remove() $('#related').remove()
/*This is a hack to stop a line appearing because of the empty div border*/ /*This is a hack to stop a line appearing because of the empty div border*/
</script> </script>
{% endblock %} {% endblock %}
</div> </div>
{% block content %} {% block content %}
REPLACE : The content REPLACE : The content
{% endblock %} {% endblock %}
</div> </div>
<div class="footer"> <div class="footer">
<ul class="dropdown" id="footerLinks"> <ul class="dropdown" id="footerLinks">
<li><a href="#">External links</a> <li><a href="#">External links</a>
<ul class="sub_menu"> <ul class="sub_menu">
<li><a id="cuccLink" href="http://www.srcf.ucam.org/caving/wiki/Main_Page">CUCC website</a></li> <li><a id="cuccLink" href="http://www.srcf.ucam.org/caving/wiki/Main_Page">CUCC website</a></li>
<li><a id="expoWebsiteLink" href="http://cucc.survex.com/expo">Expedition website</a></li> <li><a id="expoWebsiteLink" href="http://cucc.survex.com/expo">Expedition website</a></li>
</ul> </ul>
</li> </li>
<li><a href="{% url frontpage %}">Troggle front page</a></li> <li><a href="{% url frontpage %}">Troggle front page</a></li>
<li><a id="cavesLink" href="{% url caveindex %}">caves</a></li> <li><a id="cavesLink" href="{% url caveindex %}">caves</a></li>
<li><a id="caversLink" href="{% url personindex %}">cavers</a></li> <li><a id="caversLink" href="{% url personindex %}">cavers</a></li>
<li><a href="#">expeditions</a> <li><a href="#">expeditions</a>
<ul class="sub_menu"> <ul class="sub_menu">
<li><a id="expeditionsLink" href="{{ Expedition.objects.latest.get_absolute_url }}">newest</a></li> <li><a id="expeditionsLink" href="{{ Expedition.objects.latest.get_absolute_url }}">newest</a></li>
<li><a id="expeditionsLink" href="{% url expeditions %}">list all</a></li> <li><a id="expeditionsLink" href="{% url expeditions %}">list all</a></li>
</ul> </ul>
</li> </li>
<li><a id="surveyBinderLink" href="{% url survey %}">survey binder</a></li> <li><a id="surveyBinderLink" href="{% url survey %}">survey binder</a></li>
<li><a href="#">diversions</a> <li><a href="#">diversions</a>
<ul class="sub_menu"> <ul class="sub_menu">
<li><a href="{% url stats %}">statistics</a></li> <li><a href="{% url stats %}">statistics</a></li>
</ul> </ul>
</li> </li>
<li><a href="#">admin</a> <li><a href="#">admin</a>
<ul class="sub_menu"> <ul class="sub_menu">
<li><a id="cuccLink" href="{% url controlpanel %}">Import / export data</a></li> <li><a id="cuccLink" href="{% url controlpanel %}">Import / export data</a></li>
<li><a id="expoWebsiteLink" href="{{ settings.URL_ROOT }}admin">Troggle administration pages</a></li> <li><a id="expoWebsiteLink" href="{{ settings.URL_ROOT }}admin">Troggle administration pages</a></li>
</ul> </ul>
<li class="toggleMenu"><a href="#">hide menu</a></li> <li class="toggleMenu"><a href="#">hide menu</a></li>
</ul> </ul>
</div> </div>
</body> </body>
</html> </html>

View File

@ -1,43 +1,43 @@
{% extends "cavebase.html" %} {% extends "cavebase.html" %}
{% block content %} {% block content %}
{% block contentheader %} {% block contentheader %}
<table id="cavepage"> <table id="cavepage">
<tr> <tr>
<th id="kat_no"> <th id="kat_no">
{% if cave.kataster_number %} {% if cave.kataster_number %}
{{ cave.kataster_number|safe }} {{ cave.kataster_number|safe }}
{% if cave.entrancelist %} {% if cave.entrancelist %}
- {{ cave.entrancelist|safe }} - {{ cave.entrancelist|safe }}
{% endif %} {% endif %}
{% if cave.unofficial_number %} {% if cave.unofficial_number %}
<br />({{ cave.unofficial_number|safe }}) <br />({{ cave.unofficial_number|safe }})
{% endif %} {% endif %}
{% endif %} {% endif %}
</th> </th>
<th id="name"> <th id="name">
{{ cave.official_name|safe }} {{ cave.official_name|safe }}
</th> </th>
<th id="status"> <th id="status">
{{ cave.kataster_code|safe }} {{ cave.kataster_code|safe }}
</th> </th>
</tr> </tr>
</table> </table>
{% block related %} {% block related %}
{% endblock %}{% endblock %} {% endblock %}{% endblock %}
<div id="tabs"> <div id="tabs">
<ul> <ul>
<li><a href="/cave/description/{{cave.slug}}">Description</a></li> <li><a href="/cave/description/{{cave.slug}}">Description</a></li>
<li><a href="/cave/entrance/{{cave.slug}}">Entrances</a></li> <li><a href="/cave/entrance/{{cave.slug}}">Entrances</a></li>
<li><a href="/cave/logbook/{{cave.slug}}">Logbook</a></li> <li><a href="/cave/logbook/{{cave.slug}}">Logbook</a></li>
<li><a href="/cave/qms/{{cave.slug}}">QMs</a></li> <li><a href="/cave/qms/{{cave.slug}}">QMs</a></li>
</ul> </ul>
<div id="qms"> <div id="qms">
</div> </div>
</div> </div>
{% endblock %} {% endblock %}

View File

@ -1,19 +1,19 @@
{% extends "cavebase.html" %} {% extends "cavebase.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %} {{cave_description}} {% endblock title %} {% block title %} {{cave_description}} {% endblock title %}
{% block editLink %}<a href={{cave_description.get_admin_url}}>Edit description {{cave_description}}</a>{% endblock %} {% block editLink %}<a href={{cave_description.get_admin_url}}>Edit description {{cave_description}}</a>{% endblock %}
{% block contentheader %} {% block contentheader %}
{{cave_description.long_name}} {{cave_description.long_name}}
{% endblock contentheader %} {% endblock contentheader %}
{% block content %} {% block content %}
<h1>{{cave_description.long_name}}</h1> <h1>{{cave_description.long_name}}</h1>
<p> <p>
{{cave_description.description|wiki_to_html}} {{cave_description.description|wiki_to_html}}
</p> </p>
{% endblock content %} {% endblock content %}

View File

@ -1,26 +1,26 @@
<html> <html>
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>{% block title %}{{ cave.official_name|safe }}{% endblock %} <title>{% block title %}{{ cave.official_name|safe }}{% endblock %}
</title> </title>
<link rel="stylesheet" type="text/css" href="/css/main2.css" /> <link rel="stylesheet" type="text/css" href="/css/main2.css" />
<link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/redmond/jquery-ui-1.8.14.custom.css" /> <link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/redmond/jquery-ui-1.8.14.custom.css" />
<script src="{{ settings.MEDIA_URL }}js/jquery.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>
<script type="text/javascript"> <script type="text/javascript">
$(function() { $(function() {
$( "#tabs" ).tabs(); $( "#tabs" ).tabs();
}); });
</script> </script>
</head> </head>
<body> <body>
{% block content %}{% endblock %} {% block content %}{% endblock %}
{% block menu %} {% block menu %}
<ul id="links"> <ul id="links">
<li>Back to <a href="/index.htm">Expedition home page</a></li> <li>Back to <a href="/index.htm">Expedition home page</a></li>
<li>Back to <a href="http://cucc.survex.com/">CUCC home page</a></li> <li>Back to <a href="http://cucc.survex.com/">CUCC home page</a></li>
</ul> </ul>
{% endblock %} {% endblock %}
</body> </body>
</html> </html>

View File

@ -1,37 +1,37 @@
{% extends "cavebase.html" %} {% extends "cavebase.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Cave Index{% endblock %} {% block title %}Cave Index{% endblock %}
{% block content %} {% block content %}
<h1>Cave Index</h1> <h1>Cave Index</h1>
<h3>Notable caves</h3> <h3>Notable caves</h3>
<ul> <ul>
{% for cave in notablecaves %} {% for cave in notablecaves %}
<li> <a href="{{ cave.get_absolute_url }}">{% if cave.kataster_number %}{{ cave.kataster_number }}{% else %}{{cave.unofficial_number }}{%endif %} {{cave.official_name|safe}}</a> </li> <li> <a href="{{ cave.get_absolute_url }}">{% if cave.kataster_number %}{{ cave.kataster_number }}{% else %}{{cave.unofficial_number }}{%endif %} {{cave.official_name|safe}}</a> </li>
{% endfor %} {% endfor %}
</ul> </ul>
<h3>1623</h3> <h3>1623</h3>
<ul class="searchable"> <ul class="searchable">
{% for cave in caves1623 %} {% for cave in caves1623 %}
<li> <a href="{{ cave.get_absolute_url }}">{% if cave.kataster_number %}{{ cave.kataster_number }}{% else %}{{cave.unofficial_number }}{%endif %} {{cave.official_name|safe}}</a> </li> <li> <a href="{{ cave.get_absolute_url }}">{% if cave.kataster_number %}{{ cave.kataster_number }}{% else %}{{cave.unofficial_number }}{%endif %} {{cave.official_name|safe}}</a> </li>
{% endfor %} {% endfor %}
</ul> </ul>
<h3>1626</h3> <h3>1626</h3>
<ul class="searchable"> <ul class="searchable">
{% for cave in caves1626 %} {% for cave in caves1626 %}
<li> <a href="{{ cave.get_absolute_url }}">{% if cave.kataster_number %}{{ cave.kataster_number }}{% else %}{{cave.unofficial_number }}{%endif %} {{cave.official_name|safe}}</a> </li> <li> <a href="{{ cave.get_absolute_url }}">{% if cave.kataster_number %}{{ cave.kataster_number }}{% else %}{{cave.unofficial_number }}{%endif %} {{cave.official_name|safe}}</a> </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endblock %} {% endblock %}

View File

@ -1,157 +1,157 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
{% if jobs_completed %} {% if jobs_completed %}
<div class="noticeBox"> <div class="noticeBox">
Just finished running: Just finished running:
<ul> <ul>
{% for job in jobs_completed %} {% for job in jobs_completed %}
<li>{{ job }}</li> <li>{{ job }}</li>
{% endfor %} {% endfor %}
</ul> </ul>
{% if settings.LOGFILE %}See the logfile at {{settings.LOGFILE}} for more information.{% endif %} {% if settings.LOGFILE %}See the logfile at {{settings.LOGFILE}} for more information.{% endif %}
<a href="#" class="closeDiv">dismiss this message</a> <a href="#" class="closeDiv">dismiss this message</a>
</div> </div>
{% endif %} {% endif %}
{% if error %} {% if error %}
<div class="noticeBox"> <div class="noticeBox">
{{ error }} {{ error }}
<a href="#" class="closeDiv">dismiss this message</a> <a href="#" class="closeDiv">dismiss this message</a>
</div> </div>
{% endif %} {% endif %}
<form name="reset" method="post" action=""> <form name="reset" method="post" action="">
<h3>Wipe:</h3> <h3>Wipe:</h3>
<table> <table>
<tr><td>Wipe entire database and recreate tables: </td><td><input type="checkbox" name="reload_db" /></td><td> <input type="submit" id="Import" value="I really want to delete all information in troggle, and accept all responsibility."></td></tr> <tr><td>Wipe entire database and recreate tables: </td><td><input type="checkbox" name="reload_db" /></td><td> <input type="submit" id="Import" value="I really want to delete all information in troggle, and accept all responsibility."></td></tr>
</table> </table>
</form> </form>
<h3>Import (non-destructive):</h3> <h3>Import (non-destructive):</h3>
<form name="import" method="post" action=""> <form name="import" method="post" action="">
<table> <table>
<tr><td>people from folk.csv using parsers\people.py</td><td><input type="checkbox" name="import_people"/></td></tr> <tr><td>people from folk.csv using parsers\people.py</td><td><input type="checkbox" name="import_people"/></td></tr>
<tr><td>caves from cavetab2.csv using parsers\cavetab.py</td><td> <input type="checkbox" class="parser" name="import_cavetab"/></td></tr> <tr><td>caves from cavetab2.csv using parsers\cavetab.py</td><td> <input type="checkbox" class="parser" name="import_cavetab"/></td></tr>
<tr><td>logbook entries using parsers\logbooks.py</td><td><input type="checkbox" name="import_logbooks"/></td></tr> <tr><td>logbook entries using parsers\logbooks.py</td><td><input type="checkbox" name="import_logbooks"/></td></tr>
<tr><td>QMs using parsers\QMs.py</td><td><input type="checkbox" name="import_QMs" /></td></tr> <tr><td>QMs using parsers\QMs.py</td><td><input type="checkbox" name="import_QMs" /></td></tr>
<tr><td>survey scans using parsers\surveys.py</td><td><input type="checkbox" name="import_surveys" /></td></tr> <tr><td>survey scans using parsers\surveys.py</td><td><input type="checkbox" name="import_surveys" /></td></tr>
<tr><td>survex data using parsers\survex.py</td><td><input type="checkbox" name="import_survex" /></td></tr> <tr><td>survex data using parsers\survex.py</td><td><input type="checkbox" name="import_survex" /></td></tr>
</table> </table>
<p> <p>
<input type="submit" id="Import" value="Import"> <input type="submit" id="Import" value="Import">
<input type="submit" name="check_all_import" id="check_all_import" value="Check all" disabled > <input type="submit" name="check_all_import" id="check_all_import" value="Check all" disabled >
</p> </p>
</form> </form>
<h3>Export to legacy formats:</h3> <h3>Export to legacy formats:</h3>
<table> <table>
<th> <th>
<td>Export onto server</td> <td>Export onto server</td>
<td>Export and Download</td> <td>Export and Download</td>
</th> </th>
<tr> <tr>
<td> <td>
caves to cavetab2.csv caves to cavetab2.csv
</td> </td>
<td> <td>
<form name="export" method="post" action=""> <form name="export" method="post" action="">
<p>Overwrite the existing CAVETAB2.CSV file with one generated by Troggle.</p> <p>Overwrite the existing CAVETAB2.CSV file with one generated by Troggle.</p>
<input name="export_cavetab" type="submit" value="Update {{settings.EXPOWEB}}noinfo/CAVETAB2.CSV" /> <input name="export_cavetab" type="submit" value="Update {{settings.EXPOWEB}}noinfo/CAVETAB2.CSV" />
</form> </form>
</td> </td>
<td> <td>
<form name="export" method="get" action="{% url downloadcavetab %}"> <form name="export" method="get" action="{% url downloadcavetab %}">
<p>Download a CAVETAB2.CSV file which is dynamically generated by Troggle.</p> <p>Download a CAVETAB2.CSV file which is dynamically generated by Troggle.</p>
<input name="download_cavetab" type="submit" value="Download CAVETAB2.CSV" /> <input name="download_cavetab" type="submit" value="Download CAVETAB2.CSV" />
</form> </form>
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td>
surveys to Surveys.csv surveys to Surveys.csv
</td> </td>
<td> <td>
</td> </td>
<td> <td>
<form name="export" method="get" action={% url downloadlogbook %}> <form name="export" method="get" action={% url downloadlogbook %}>
<p>Download a logbook file which is dynamically generated by Troggle.</p> <p>Download a logbook file which is dynamically generated by Troggle.</p>
<p> <p>
Expedition year: Expedition year:
<select name="year"> <select name="year">
{% for expedition in expeditions %} {% for expedition in expeditions %}
<option value="{{expedition}}"> {{expedition}} </option> <option value="{{expedition}}"> {{expedition}} </option>
{% endfor %} {% endfor %}
</select> </select>
</p> </p>
<p> <p>
Output style: Output style:
<select name="extension"> <select name="extension">
<option value="txt">.txt file with MediaWiki markup - 2008 style</option> <option value="txt">.txt file with MediaWiki markup - 2008 style</option>
<option value="html">.html file - 2005 style</option> <option value="html">.html file - 2005 style</option>
</select> </select>
</p> </p>
<p> <p>
<input name="download_logbook" type="submit" value="Download logbook" /> <input name="download_logbook" type="submit" value="Download logbook" />
</p> </p>
</form> </form>
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td>
surveys to Surveys.csv surveys to Surveys.csv
</td> </td>
<td> <td>
<form name="export" method="post" action=""> <form name="export" method="post" action="">
<p>Overwrite the existing Surveys.csv file with one generated by Troggle.</p> <p>Overwrite the existing Surveys.csv file with one generated by Troggle.</p>
<input disabled name="export_surveys" type="submit" value="Update {{settings.SURVEYS}}noinfo/Surveys.csv" /> <input disabled name="export_surveys" type="submit" value="Update {{settings.SURVEYS}}noinfo/Surveys.csv" />
</form> </form>
</td> </td>
<td> <td>
<form name="export" method="get" action={% url downloadsurveys %}> <form name="export" method="get" action={% url downloadsurveys %}>
<p>Download a Surveys.csv file which is dynamically generated by Troggle.</p> <p>Download a Surveys.csv file which is dynamically generated by Troggle.</p>
<input disabled name="download_surveys" type="submit" value="Download Surveys.csv" /> <input disabled name="download_surveys" type="submit" value="Download Surveys.csv" />
</form> </form>
</td> </td>
</tr> </tr>
<tr> <tr>
<td>qms to qms.csv</td><td> <td>qms to qms.csv</td><td>
<form name="export_qms" method="get" action="downloadqms"> <form name="export_qms" method="get" action="downloadqms">
<!--This is for choosing caves by area (drilldown). <!--This is for choosing caves by area (drilldown).
<select id="qmcaveareachooser" class="searchable" > <select id="qmcaveareachooser" class="searchable" >
</select> </select>
--> -->
Choose a cave. Choose a cave.
<select name="cave_id" id="qmcavechooser"> <select name="cave_id" id="qmcavechooser">
{% for cave in caves %} {% for cave in caves %}
<option value="{{cave.kataster_number}}">{{cave}} <option value="{{cave.kataster_number}}">{{cave}}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
<input type="submit" value="Download"/> <input type="submit" value="Download"/>
</form> </form>
</td></tr> </td></tr>
</table> </table>
</form> </form>
{% endblock %} {% endblock %}

View File

@ -1,96 +1,96 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load csrffaker %} {% load csrffaker %}
{% block title %}File{% endblock %} {% block title %}File{% endblock %}
{% block head %} {% block head %}
<script> <script>
$(function() { $(function() {
$("#id_date").datepicker({dateFormat: "yy-mm-dd"}); $("#id_date").datepicker({dateFormat: "yy-mm-dd"});
$("#id_cave").change(function() { $("#id_cave").change(function() {
$('#id_entrance').load('{% url get_entrances caveslug="" %}' + this.value); $('#id_entrance').load('{% url get_entrances caveslug="" %}' + this.value);
}); });
$("#id_cave").change(function() { $("#id_cave").change(function() {
$('#id_qm').load('{% url get_qms caveslug="" %}' + this.value); $('#id_qm').load('{% url get_qms caveslug="" %}' + this.value);
}); });
$("#id_expedition").change(function() { $("#id_expedition").change(function() {
$('#id_logbookentry').load('{% url get_logbook_entries expeditionslug="" %}' + this.value); $('#id_logbookentry').load('{% url get_logbook_entries expeditionslug="" %}' + this.value);
}); });
$("#id_expedition").change(function() { $("#id_expedition").change(function() {
$('#id_person').load('{% url get_people expeditionslug="" %}' + this.value); $('#id_person').load('{% url get_people expeditionslug="" %}' + this.value);
}); });
}); });
</script> </script>
<link rel="stylesheet" href="{{ settings.MEDIA_URL }}css/ui-lightness/jquery-ui-1.8.12.custom.css" type="text/css" media="all" /> <link rel="stylesheet" href="{{ settings.MEDIA_URL }}css/ui-lightness/jquery-ui-1.8.12.custom.css" type="text/css" media="all" />
<script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/jquery.formset.min.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery.formset.min.js" type="text/javascript"></script>
<script src="{{ settings.TINY_MCE_MEDIA_URL }}tiny_mce.js" type="text/javascript"></script> <script src="{{ settings.TINY_MCE_MEDIA_URL }}tiny_mce.js" type="text/javascript"></script>
{{ fileForm.media }} {{ fileForm.media }}
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<form action="" method="post">{% csrf_token %} <form action="" method="post">{% csrf_token %}
{{ fileForm.non_field_errors }} {{ fileForm.non_field_errors }}
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ fileForm.title.errors }} {{ fileForm.title.errors }}
<label for="id_title">Title:</label> <label for="id_title">Title:</label>
{{ fileForm.title }} {{ fileForm.title }}
</div> </div>
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ fileForm.slug.errors }} {{ fileForm.slug.errors }}
<label for="id_slug">Slug:</label> <label for="id_slug">Slug:</label>
{{ fileForm.slug }} {{ fileForm.slug }}
</div> </div>
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ fileForm.date.errors }} {{ fileForm.date.errors }}
<label for="id_date">Date:</label> <label for="id_date">Date:</label>
{{ fileForm.date }} {{ fileForm.date }}
</div> </div>
<div class="fieldWrapper" id="lon_utm"> <div class="fieldWrapper" id="lon_utm">
{{ fileForm.lon_utm.errors }} {{ fileForm.lon_utm.errors }}
<label for="id_lon_utm">Longitude:</label> <label for="id_lon_utm">Longitude:</label>
{{ fileForm.lon_utm }} {{ fileForm.lon_utm }}
</div> </div>
<div class="fieldWrapper" id="lat_utm"> <div class="fieldWrapper" id="lat_utm">
{{ fileForm.lat_utm.errors }} {{ fileForm.lat_utm.errors }}
<label for="id_lat_utm">Latitude:</label> <label for="id_lat_utm">Latitude:</label>
{{ fileForm.lat_utm }} {{ fileForm.lat_utm }}
</div> </div>
<div class="fieldWrapper" id="cave"> <div class="fieldWrapper" id="cave">
{{ fileForm.cave.errors }} {{ fileForm.cave.errors }}
<label for="id_cave">Cave:</label> <label for="id_cave">Cave:</label>
{{ fileForm.cave }} {{ fileForm.cave }}
</div> </div>
<div class="fieldWrapper" id="entrance"> <div class="fieldWrapper" id="entrance">
{{ fileForm.entrance.errors }} {{ fileForm.entrance.errors }}
<label for="id_entrance">Entrance:</label> <label for="id_entrance">Entrance:</label>
{{ fileForm.entrance }} {{ fileForm.entrance }}
</div> </div>
<div class="fieldWrapper" id="qm"> <div class="fieldWrapper" id="qm">
{{ fileForm.qm.errors }} {{ fileForm.qm.errors }}
<label for="id_cavem">QM:</label> <label for="id_cavem">QM:</label>
{{ fileForm.qm }} {{ fileForm.qm }}
</div> </div>
<div class="fieldWrapper" id="expedition"> <div class="fieldWrapper" id="expedition">
{{ fileForm.expedition.errors }} {{ fileForm.expedition.errors }}
<label for="id_expediton">Expedition:</label> <label for="id_expediton">Expedition:</label>
{{ fileForm.expedition }} {{ fileForm.expedition }}
</div> </div>
<div class="fieldWrapper" id="logbookentry"> <div class="fieldWrapper" id="logbookentry">
{{ fileForm.logbookentry.errors }} {{ fileForm.logbookentry.errors }}
<label for="id_logbookentry">Logbook Entry:</label> <label for="id_logbookentry">Logbook Entry:</label>
{{ fileForm.logbookentry }} {{ fileForm.logbookentry }}
</div> </div>
<div class="fieldWrapper" id="person"> <div class="fieldWrapper" id="person">
{{ fileForm.person.errors }} {{ fileForm.person.errors }}
<label for="id_expediton">Person:</label> <label for="id_expediton">Person:</label>
{{ fileForm.person }} {{ fileForm.person }}
</div> </div>
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ fileForm.html.errors }} {{ fileForm.html.errors }}
<label for="id_date">Content:</label> <label for="id_date">Content:</label>
{{ fileForm.html }} {{ fileForm.html }}
</div> </div>
<p><input type="submit" value="Sumbit Trip Report" /></p> <p><input type="submit" value="Sumbit Trip Report" /></p>
</form> </form>
{% endblock %} {% endblock %}

View File

@ -1,80 +1,80 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}{{ cave.official_name|wiki_to_html }} - {{ entrance_letter|wiki_to_html }}{% endblock %} {% block title %}{{ cave.official_name|wiki_to_html }} - {{ entrance_letter|wiki_to_html }}{% endblock %}
{% block content %} {% block content %}
<table id="cavepage"> <table id="cavepage">
<tr> <tr>
<th id="kat_no"> <th id="kat_no">
{% if cave.kataster_number %} {% if cave.kataster_number %}
{{ cave.kataster_number|wiki_to_html }}{{ letter|wiki_to_html }} {{ cave.kataster_number|wiki_to_html }}{{ letter|wiki_to_html }}
{% if cave.unofficial_number %} {% if cave.unofficial_number %}
<br />({{ cave.unofficial_number|wiki_to_html }}) <br />({{ cave.unofficial_number|wiki_to_html }})
{% endif %} {% endif %}
{% endif %} {% endif %}
</th> </th>
<th id="name"> <th id="name">
{% if entrance.name %} {% if entrance.name %}
{{ entrance.name|wiki_to_html }} {{ entrance.name|wiki_to_html }}
{% else %} {% else %}
Unnamed Unnamed
{% endif %} - {{ cave.official_name|wiki_to_html }} {% endif %} - {{ cave.official_name|wiki_to_html }}
</th> </th>
<th id="status"> <th id="status">
{{ cave.kataster_code|wiki_to_html }} {{ cave.kataster_code|wiki_to_html }}
</th> </th>
</tr> </tr>
</table> </table>
{% if entrance.entrance_description %} {% if entrance.entrance_description %}
<h2>Entrance Description</h2> <h2>Entrance Description</h2>
{{ entrance.entrance_description|wiki_to_html }} {{ entrance.entrance_description|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.explorers %} {% if entrance.explorers %}
<h2>Explorers</h2> <h2>Explorers</h2>
{{ entrance.explorers|wiki_to_html }} {{ entrance.explorers|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.map_description %} {% if entrance.map_description %}
<h2>Map</h2> <h2>Map</h2>
{{ entrance.map_description|wiki_to_html }} {{ entrance.map_description|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.explorers %} {% if entrance.explorers %}
<h2>Entrance Description</h2> <h2>Entrance Description</h2>
{{ entrance.entrance_description|wiki_to_html }} {{ entrance.entrance_description|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.location_description %} {% if entrance.location_description %}
<h2>Location Description</h2> <h2>Location Description</h2>
{{ entrance.location_description|wiki_to_html }} {{ entrance.location_description|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.approach %} {% if entrance.approach %}
<h2>Approach</h2> <h2>Approach</h2>
{{ entrance.approach|wiki_to_html }} {{ entrance.approach|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.underground_description %} {% if entrance.underground_description %}
<h2>Underground Description</h2> <h2>Underground Description</h2>
{{ entrance.underground_description|wiki_to_html }} {{ entrance.underground_description|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.photo %} {% if entrance.photo %}
<h2>Photo</h2> <h2>Photo</h2>
{{ entrance.photo|wiki_to_html }} {{ entrance.photo|wiki_to_html }}
{% endif %} {% endif %}
{% if entrance.marking %} {% if entrance.marking %}
<h2>Marking - {{ entrance.marking_val|wiki_to_html }}</h2> <h2>Marking - {{ entrance.marking_val|wiki_to_html }}</h2>
{% if entrance.marking_comment %} {% if entrance.marking_comment %}
{{ entrance.marking_comment|wiki_to_html }} {{ entrance.marking_comment|wiki_to_html }}
{% endif %} {% endif %}
{% endif %} {% endif %}
{% if entrance.findability %} {% if entrance.findability %}
<h2>Findability - {{ entrance.findability_val|wiki_to_html }}</h2> <h2>Findability - {{ entrance.findability_val|wiki_to_html }}</h2>
{% if entrance.findability_description %} {% if entrance.findability_description %}
{{ entrance.findability_description|wiki_to_html }} {{ entrance.findability_description|wiki_to_html }}
{% endif %} {% endif %}
{% endif %} {% endif %}
{% if entrance.bearings %} {% if entrance.bearings %}
<h2>Bearings</h2> <h2>Bearings</h2>
{{ entrance.bearings|wiki_to_html }} {{ entrance.bearings|wiki_to_html }}
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -1,87 +1,87 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load link %} {% load link %}
{% block title %}Expedition {{expedition.name}}{% endblock %} {% block title %}Expedition {{expedition.name}}{% endblock %}
{% block editLink %}<a href={{expedition.get_admin_url}}>Edit expedition {{expedition|wiki_to_html_short}}</a>{% endblock %} {% block editLink %}<a href={{expedition.get_admin_url}}>Edit expedition {{expedition|wiki_to_html_short}}</a>{% endblock %}
{% block related %} {% block related %}
{% endblock %} {% endblock %}
{% block content %} {% block content %}
{% if message %} {% if message %}
<p>debug message: {{message}}</p> <p>debug message: {{message}}</p>
{% endif %} {% endif %}
<h2>{{expedition.name}}</h2> <h2>{{expedition.name}}</h2>
<p><b>Other years:</b> <p><b>Other years:</b>
{% for otherexpedition in expeditions %} {% for otherexpedition in expeditions %}
{% ifequal otherexpedition expedition %} {% ifequal otherexpedition expedition %}
| <b>{{otherexpedition.year}}</b> | <b>{{otherexpedition.year}}</b>
{% else %} {% else %}
| <a href="{{otherexpedition.get_absolute_url}}">{{ otherexpedition.year }}</a> | <a href="{{otherexpedition.get_absolute_url}}">{{ otherexpedition.year }}</a>
{% endifequal %} {% endifequal %}
{% endfor %} {% endfor %}
</p> </p>
<p><b>At a single glance:</b> The table shows all expo cavers and their recorded trips. <p><b>At a single glance:</b> The table shows all expo cavers and their recorded trips.
The columns are the date in the month (July or August), with a "T" for a logbook entry, and The columns are the date in the month (July or August), with a "T" for a logbook entry, and
an "S" for a survey trip. The colours are the same for people on the same trip.</p> an "S" for a survey trip. The colours are the same for people on the same trip.</p>
<table class="expeditionpersonlist"> <table class="expeditionpersonlist">
<tr> <tr>
<th>Caver</th> <th>Caver</th>
{% for expeditionday in expedition.expeditionday_set.all %} {% for expeditionday in expedition.expeditionday_set.all %}
<th> <th>
{{expeditionday.date.day}} {{expeditionday.date.day}}
</th> </th>
{% endfor %} {% endfor %}
</tr> </tr>
{% for personexpeditionday in personexpeditiondays %} {% for personexpeditionday in personexpeditiondays %}
<tr> <tr>
<td><a href="{{ personexpeditionday.personexpedition.get_absolute_url }}">{{personexpeditionday.personexpedition.person}}</a></td> <td><a href="{{ personexpeditionday.personexpedition.get_absolute_url }}">{{personexpeditionday.personexpedition.person}}</a></td>
{% for persondayactivities in personexpeditionday.personrow %} {% for persondayactivities in personexpeditionday.personrow %}
{% if persondayactivities.persontrips or persondayactivities.survexblocks %} {% if persondayactivities.persontrips or persondayactivities.survexblocks %}
<td class="persondayactivity"> <td class="persondayactivity">
{% for persontrip in persondayactivities.persontrips %} {% for persontrip in persondayactivities.persontrips %}
<a href="{{persontrip.logbook_entry.get_absolute_url}}" class="dayindexlog-{{persontrip.logbook_entry.DayIndex}}">T</a> <a href="{{persontrip.logbook_entry.get_absolute_url}}" class="dayindexlog-{{persontrip.logbook_entry.DayIndex}}">T</a>
{% endfor %} {% endfor %}
<br/> <br/>
{% for survexblock in persondayactivities.survexblocks %} {% for survexblock in persondayactivities.survexblocks %}
<a href="{% url svx survexblock.survexfile.path %}" class="dayindexsurvex-{{survexblock.DayIndex}}">S</a> <a href="{% url svx survexblock.survexfile.path %}" class="dayindexsurvex-{{survexblock.DayIndex}}">S</a>
{% endfor %} {% endfor %}
</td> </td>
{% else %} {% else %}
<td class="persondayactivity-nothing"> <td class="persondayactivity-nothing">
</td> </td>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
<form action="" method="GET"><input type="submit" name="reload" value="Reload"></form> <form action="" method="GET"><input type="submit" name="reload" value="Reload"></form>
<h3>Logbooks and survey trips per day</h3> <h3>Logbooks and survey trips per day</h3>
<a href="{% url newLogBookEntry expeditionyear=expedition.year %}">New logbook entry</a> <a href="{% url newLogBookEntry expeditionyear=expedition.year %}">New logbook entry</a>
<table class="expeditionlogbooks"> <table class="expeditionlogbooks">
<tr><th>Date</th><th>Logged trips</th><th>Surveys</th></tr> <tr><th>Date</th><th>Logged trips</th><th>Surveys</th></tr>
{% regroup dateditems|dictsort:"date" by date as dates %} {% regroup dateditems|dictsort:"date" by date as dates %}
{% for date in dates %} {% for date in dates %}
<tr> <tr>
<td>{{date.grouper}}</td> <td>{{date.grouper}}</td>
<td>{% for item in date.list %} <td>{% for item in date.list %}
{% if item.isLogbookEntry %}<a href="{{ item.get_absolute_url }}">{{item.title|safe}}</a><br/>{% endif %} {% if item.isLogbookEntry %}<a href="{{ item.get_absolute_url }}">{{item.title|safe}}</a><br/>{% endif %}
{% endfor %}</td> {% endfor %}</td>
<td>{% for item in date.list %} <td>{% for item in date.list %}
{% if item.isSurvexBlock %}<a href="{% url svx item.survexfile.path %}">{{item.name}}</a><br/>{% endif %} {% if item.isSurvexBlock %}<a href="{% url svx item.survexfile.path %}">{{item.name}}</a><br/>{% endif %}
{% endfor %}</td> {% endfor %}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
{% endblock %} {% endblock %}

View File

@ -1,3 +1,3 @@
<img id="richardBanner" class="footer" src="{{ settings.MEDIA_URL }}expoBanner.gif" style="display: none;"/> <img id="richardBanner" class="footer" src="{{ settings.MEDIA_URL }}expoBanner.gif" style="display: none;"/>
<img id="timeMachine" class="footer" src="{{ settings.MEDIA_URL }}timemachine.gif" style="display: none;"/> <img id="timeMachine" class="footer" src="{{ settings.MEDIA_URL }}timemachine.gif" style="display: none;"/>
<img id="surveyHover" class="footer" src="{{ settings.MEDIA_URL }}surveyHover.gif" style="display: none;"/> <img id="surveyHover" class="footer" src="{{ settings.MEDIA_URL }}surveyHover.gif" style="display: none;"/>

View File

@ -1,18 +1,18 @@
<h2>Fileupload</h2> <h2>Fileupload</h2>
<ul> <ul>
{% for fileuploaded in filesuploaded %} {% for fileuploaded in filesuploaded %}
<li>UPLOADEDFILE: {{fileuploaded}} <li>UPLOADEDFILE: {{fileuploaded}}
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
<p>MESSAGE: {{message}} <p>MESSAGE: {{message}}
</p> </p>
{% if not filesuploaded %} {% if not filesuploaded %}
<form action="" method="POST"> <form action="" method="POST">
<p>file to upload</p> <p>file to upload</p>
<p><input type="file" name="file1"/></p> <p><input type="file" name="file1"/></p>
<p><input type="submit" name="submit" value="Submit" /></p> <p><input type="submit" name="submit" value="Submit" /></p>
</form> </form>
{% endif %} {% endif %}

View File

@ -1,68 +1,68 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Cambridge Expeditions to Austria{% endblock %} {% block title %}Cambridge Expeditions to Austria{% endblock %}
{% block related %} {% block related %}
<h2>Recent Actions</h2> <h2>Recent Actions</h2>
{% load log %} {% load log %}
{% get_admin_log 10 as admin_log %} {% get_admin_log 10 as admin_log %}
{% if not admin_log %} {% if not admin_log %}
<p>No recent actions</p> <p>No recent actions</p>
{% else %} {% else %}
<ul class="actionlist"> <ul class="actionlist">
{% for entry in admin_log %} {% for entry in admin_log %}
<li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}"> <li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}">
{% if entry.is_deletion %} {% if entry.is_deletion %}
{{ entry.object_repr }} {{ entry.object_repr }}
{% else %} {% else %}
<a href="admin/{{ entry.get_admin_url }}">{{ entry.object_repr }}</a> <a href="admin/{{ entry.get_admin_url }}">{{ entry.object_repr }}</a>
{% endif %} {% endif %}
<br/> <br/>
{% if entry.content_type %} {% if entry.content_type %}
<span class="mini quiet">{% filter capfirst %}{{entry.content_type.name}}{% endfilter %}</span> <span class="mini quiet">{% filter capfirst %}{{entry.content_type.name}}{% endfilter %}</span>
{% else %} {% else %}
<span class="mini quiet">Unknown content</span> <span class="mini quiet">Unknown content</span>
{% endif %} {% endif %}
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<div id="col1"> <div id="col1">
<h3>Welcome</h3> <h3>Welcome</h3>
<p class="indent"> <p class="indent">
This is Troggle, the information portal for Cambridge University Caving Club's Expeditions to Austria. This is Troggle, the information portal for Cambridge University Caving Club's Expeditions to Austria.
</p> </p>
<p class="indent"> <p class="indent">
Here you will find information about the {{expedition.objects.count}} expeditions the club has undertaken since 1976. Browse survey information, photos, and description wikis for {{cave.objects.count}} caves, {{subcave.objects.count}} areas within those caves, and {{extantqms.count}} going leads yet to be explored. We have {{photo.objects.count}} photos and {{logbookentry.objects.count}} logbook entries. Here you will find information about the {{expedition.objects.count}} expeditions the club has undertaken since 1976. Browse survey information, photos, and description wikis for {{cave.objects.count}} caves, {{subcave.objects.count}} areas within those caves, and {{extantqms.count}} going leads yet to be explored. We have {{photo.objects.count}} photos and {{logbookentry.objects.count}} logbook entries.
</p> </p>
<p class="indent"> <p class="indent">
If you are an expedition member, please sign up using the link to the top right and begin editing. If you are an expedition member, please sign up using the link to the top right and begin editing.
</p> </p>
<h3>News</h3> <h3>News</h3>
<p class="indent"> <p class="indent">
Everyone is gearing up for the 2009 expedition; please see the link below for the main expedition website. Everyone is gearing up for the 2009 expedition; please see the link below for the main expedition website.
</p> </p>
<h3>Troggle development</h3> <h3>Troggle development</h3>
<p class="indent"> <p class="indent">
Troggle is still under development. Check out the <a href="http://troggle.googlecode.com">development page</a> on google code, where you can file bug reports, make suggestions, and help develop the code. There is also an old todo list at <a href="{%url todo%}">here</a>. Troggle is still under development. Check out the <a href="http://troggle.googlecode.com">development page</a> on google code, where you can file bug reports, make suggestions, and help develop the code. There is also an old todo list at <a href="{%url todo%}">here</a>.
</p> </p>
</div> </div>
{% endblock content %} {% endblock content %}
{% block margins %} {% block margins %}
<img class="leftMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}eieshole.jpg"> <img class="leftMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}eieshole.jpg">
<img class="rightMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}goesser.jpg"> <img class="rightMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}goesser.jpg">
{% endblock margins %} {% endblock margins %}

View File

@ -1,59 +1,59 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Cambridge Expeditions to Austria{% endblock %} {% block title %}Cambridge Expeditions to Austria{% endblock %}
{% block content %} {% block content %}
<h2>The unfinished front page</h2> <h2>The unfinished front page</h2>
<ul> <ul>
<li><b>About {{totallogbookentries}} logbook entries have been loaded</b></li> <li><b>About {{totallogbookentries}} logbook entries have been loaded</b></li>
<li><b><a href="{% url personindex %}">List of People</a></b></li> <li><b><a href="{% url personindex %}">List of People</a></b></li>
<li><b><a href="{% url caveindex %}">List of Caves</a></b></li> <li><b><a href="{% url caveindex %}">List of Caves</a></b></li>
<li><a href="{% url jgtfile aaaa %}">JGT list of files</a> (temporary simple file list and tunnel use)</li> <li><a href="{% url jgtfile aaaa %}">JGT list of files</a> (temporary simple file list and tunnel use)</li>
<li><a href="{% url survey %}">Survey files</a></li> <li><a href="{% url survey %}">Survey files</a></li>
<li><a href="{% url svx all %}">Survex directory</a></li> <li><a href="{% url svx all %}">Survex directory</a></li>
<li><a href="{% url expedition 2008 %}">Expedition 2008</a></li> <li><a href="{% url expedition 2008 %}">Expedition 2008</a></li>
<li><a href="{% url expedition 2007 %}">Expedition 2007</a></li> <li><a href="{% url expedition 2007 %}">Expedition 2007</a></li>
<li><a href="{% url expedition 1992 %}">Expedition 1992</a> (earliest parsed)</li> <li><a href="{% url expedition 1992 %}">Expedition 1992</a> (earliest parsed)</li>
</ul> </ul>
<h2>Further work</h2> <h2>Further work</h2>
<p>Julian's work: <p>Julian's work:
<p>parse 1976-1991 logbooks; (esp top 161)</p> <p>parse 1976-1991 logbooks; (esp top 161)</p>
<p>detect T/U on log entries; </p> <p>detect T/U on log entries; </p>
<p>name matching and spelling in survex files; </p> <p>name matching and spelling in survex files; </p>
<p>Improve logbook wikihtml text</p> <p>Improve logbook wikihtml text</p>
<p>Other work:</p> <p>Other work:</p>
<p>surf through the tunnel sketches and images</p> <p>surf through the tunnel sketches and images</p>
<p>bugs with all.svx block (double dot) <p>bugs with all.svx block (double dot)
<p>render bitmap view of every survex block as a thumbnail</p> <p>render bitmap view of every survex block as a thumbnail</p>
<p>upload tunnel images and tunnel sketches</p> <p>upload tunnel images and tunnel sketches</p>
<p>where are the subcaves; </p> <p>where are the subcaves; </p>
<p>cave section entrance match for logbook entries</p> <p>cave section entrance match for logbook entries</p>
<p>simplify the survex parsing code (if necessary); </p> <p>simplify the survex parsing code (if necessary); </p>
<p>wiki survex stop linegap between comment lins</p> <p>wiki survex stop linegap between comment lins</p>
<p>links between logbooks and survex blocks to cave things; </p> <p>links between logbooks and survex blocks to cave things; </p>
<p>mini-tree of survexblocks; </p> <p>mini-tree of survexblocks; </p>
<p>connect sketches to caves to survey blocks and render thumbnailwise; </p> <p>connect sketches to caves to survey blocks and render thumbnailwise; </p>
<p>all images to start appearing in pages; and so on</p> <p>all images to start appearing in pages; and so on</p>
<h3>{{message}}</h3> <h3>{{message}}</h3>
<form action="" method="GET"> <form action="" method="GET">
<input type="submit" name="reloadexpos" value="Reload Expos"> <input type="submit" name="reloadexpos" value="Reload Expos">
<input type="submit" name="reloadsurvex" value="Reload Survex"> <input type="submit" name="reloadsurvex" value="Reload Survex">
</form> </form>
<ul id="expeditionlist"> <ul id="expeditionlist">
{% for expedition in expeditions %} {% for expedition in expeditions %}
<li> <li>
<a href="{% url expedition expedition.year %}">{{expedition.name}}</a> <a href="{% url expedition expedition.year %}">{{expedition.name}}</a>
- <b>{{expedition.logbookentry_set.count}}</b> logbook entries - <b>{{expedition.logbookentry_set.count}}</b> logbook entries
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endblock %} {% endblock %}

View File

@ -1,22 +1,22 @@
<h2>List file :{{file}}:</h2> <h2>List file :{{file}}:</h2>
<h3>Files</h3> <h3>Files</h3>
<ul> <ul>
{% for lf in listdirfiles %} {% for lf in listdirfiles %}
<li><a href="{% url jgtfile lf.0 %}">{{lf.1}}</a> ({{lf.2}} bytes)</li> <li><a href="{% url jgtfile lf.0 %}">{{lf.1}}</a> ({{lf.2}} bytes)</li>
{% endfor %} {% endfor %}
</ul> </ul>
<h3>Upperdirectories</h3> <h3>Upperdirectories</h3>
<ul> <ul>
{% for lf in upperdirs %} {% for lf in upperdirs %}
<li><a href="{% url jgtfile lf.0 %}">{{lf.1}}</a></li> <li><a href="{% url jgtfile lf.0 %}">{{lf.1}}</a></li>
{% endfor %} {% endfor %}
</ul> </ul>
<h3>Subdirectories</h3> <h3>Subdirectories</h3>
<ul> <ul>
{% for lf in listdirdirs %} {% for lf in listdirdirs %}
<li><a href="{% url jgtfile lf.0 %}">{{lf.1}}</a> ({{lf.2}} files)</li> <li><a href="{% url jgtfile lf.0 %}">{{lf.1}}</a> ({{lf.2}} files)</li>
{% endfor %} {% endfor %}
</ul> </ul>

View File

@ -1,26 +1,26 @@
<html> <html>
<head><title>{{logbook_entries.0.expedition}} Expo Logbook</title></head> <head><title>{{logbook_entries.0.expedition}} Expo Logbook</title></head>
<link rel="stylesheet" type="text/css" href="../../css/main2.css" /> <link rel="stylesheet" type="text/css" href="../../css/main2.css" />
<style type="text/css"> <style type="text/css">
.tripdate { float: left;} .tripdate { float: left;}
.trippeople { float: right;} .trippeople { float: right;}
.triptitle { font-size: 120%; text-align: center; font-weight: bold; clear: both } .triptitle { font-size: 120%; text-align: center; font-weight: bold; clear: both }
.timeug { text-align: right; font-weight: bold } .timeug { text-align: right; font-weight: bold }
p { clear: both } p { clear: both }
</style> </style>
<body> <body>
<h1>Expo {{logbook_entries.0.expedition}}</h1> <h1>Expo {{logbook_entries.0.expedition}}</h1>
{%for logbook_entry in logbook_entries%} {%for logbook_entry in logbook_entries%}
<hr /> <hr />
<div class="tripdate" id="t{{logbook_entry.date}}A">{{logbook_entry.date}}</div> <div class="tripdate" id="t{{logbook_entry.date}}A">{{logbook_entry.date}}</div>
<div class="trippeople"><u>{{logbook_entry.author.person}}</u> <div class="trippeople"><u>{{logbook_entry.author.person}}</u>
{% for persontrip in logbook_entry.persontrip_set.all %}{{ persontrip.personexpedition.person }} {{ persontrip.personexpedition.time_underground }}, {% endfor %} {% for persontrip in logbook_entry.persontrip_set.all %}{{ persontrip.personexpedition.person }} {{ persontrip.personexpedition.time_underground }}, {% endfor %}
</div> </div>
<div class="triptitle">{{logbook_entry.place}} - {{logbook_entry.title}}</div> <div class="triptitle">{{logbook_entry.place}} - {{logbook_entry.title}}</div>
{{logbook_entry.text|safe}} {{logbook_entry.text|safe}}
{% endfor %} {% endfor %}

View File

@ -1,6 +1,6 @@
=Expo {{logbook_entries.0.expedition}} logbook == =Expo {{logbook_entries.0.expedition}} logbook ==
{%for logbook_entry in logbook_entries%} {%for logbook_entry in logbook_entries%}
==={{logbook_entry.date}} | {{logbook_entry.place}} - {{logbook_entry.title}} | {% for persontrip in logbook_entry.persontrip_set.all %}{{ persontrip.person_expedition.person }} {{ persontrip.person_expedition.time_underground }}, {% endfor %}=== ==={{logbook_entry.date}} | {{logbook_entry.place}} - {{logbook_entry.title}} | {% for persontrip in logbook_entry.persontrip_set.all %}{{ persontrip.person_expedition.person }} {{ persontrip.person_expedition.time_underground }}, {% endfor %}===
{{logbook_entry.text|safe}} {{logbook_entry.text|safe}}
{% endfor %} {% endfor %}

View File

@ -1,77 +1,77 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Logbook {{logbookentry.id}}{% endblock %} {% block title %}Logbook {{logbookentry.id}}{% endblock %}
{% block editLink %}<a href={{logbookentry.get_admin_url}}>Edit logbook entry {{logbookentry|wiki_to_html_short}}</a>{% endblock %} {% block editLink %}<a href={{logbookentry.get_admin_url}}>Edit logbook entry {{logbookentry|wiki_to_html_short}}</a>{% endblock %}
{% block content %} {% block content %}
{% block related %}{% endblock %} {% block related %}{% endblock %}
{% block nav %}{% endblock %} {% block nav %}{% endblock %}
<h2>{{logbookentry.title}}</h2> <h2>{{logbookentry.title}}</h2>
<div id="related"> <div id="related">
<p><a href="{{ logbookentry.expedition.get_absolute_url }}">{{logbookentry.expedition.name}}</a></p> <p><a href="{{ logbookentry.expedition.get_absolute_url }}">{{logbookentry.expedition.name}}</a></p>
{% if logbookentry.cave %} {% if logbookentry.cave %}
<p>place: <a href="{{ logbookentry.cave.get_absolute_url }}">{{logbookentry.place}}</p> <p>place: <a href="{{ logbookentry.cave.get_absolute_url }}">{{logbookentry.place}}</p>
{% else %} {% else %}
<p>{{logbookentry.place}}</p> <p>{{logbookentry.place}}</p>
{% endif %} {% endif %}
<p> <p>
{% if logbookentry.get_previous_by_date %} {% if logbookentry.get_previous_by_date %}
<a href="{{ logbookentry.get_previous_by_date.get_absolute_url }}">{{logbookentry.get_previous_by_date.date}}</a> <a href="{{ logbookentry.get_previous_by_date.get_absolute_url }}">{{logbookentry.get_previous_by_date.date}}</a>
{% endif %} {% endif %}
{% if logbookentry.get_next_by_date %} {% if logbookentry.get_next_by_date %}
<a href="{{ logbookentry.get_next_by_date.get_absolute_url }}">{{logbookentry.get_next_by_date.date}}</a> <a href="{{ logbookentry.get_next_by_date.get_absolute_url }}">{{logbookentry.get_next_by_date.date}}</a>
{% endif %} {% endif %}
</p> </p>
<table class="cavers"> <table class="cavers">
<tr><th>Caver</th><th>T/U</th><th>Prev</th><th>Next</th></tr> <tr><th>Caver</th><th>T/U</th><th>Prev</th><th>Next</th></tr>
{% for persontrip in logbookentry.persontrip_set.all %} {% for persontrip in logbookentry.persontrip_set.all %}
<tr> <tr>
{% ifequal persontrip.personexpedition logbookentry.author %} {% ifequal persontrip.personexpedition logbookentry.author %}
<td class="author"> <td class="author">
{% else %} {% else %}
<td> <td>
{% endifequal %} {% endifequal %}
<a href="{{ persontrip.personexpedition.get_absolute_url }}">{{persontrip.personexpedition.person}}</a> <a href="{{ persontrip.personexpedition.get_absolute_url }}">{{persontrip.personexpedition.person}}</a>
</td> </td>
<td> <td>
{% if persontrip.timeunderground %} {% if persontrip.timeunderground %}
- T/U {{persontrip.timeunderground}}</p> - T/U {{persontrip.timeunderground}}</p>
{% endif %} {% endif %}
</td> </td>
<td> <td>
{% if persontrip.persontrip_prev %} {% if persontrip.persontrip_prev %}
<a href="{{ persontrip.persontrip_prev.logbook_entry.get_absolute_url }}">{{persontrip.persontrip_prev.logbook_entry.date}}</a> <a href="{{ persontrip.persontrip_prev.logbook_entry.get_absolute_url }}">{{persontrip.persontrip_prev.logbook_entry.date}}</a>
{% endif %} {% endif %}
</td> </td>
<td> <td>
{% if persontrip.persontrip_next %} {% if persontrip.persontrip_next %}
<a href="{{ persontrip.persontrip_next.logbook_entry.get_absolute_url }}">{{persontrip.persontrip_next.logbook_entry.date}}</a> <a href="{{ persontrip.persontrip_next.logbook_entry.get_absolute_url }}">{{persontrip.persontrip_next.logbook_entry.date}}</a>
{% endif %} {% endif %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
{% if newQMlink %} {% if newQMlink %}
<a href="{{newQMlink}}">Add QM found on this trip</a> <a href="{{newQMlink}}">Add QM found on this trip</a>
{% endif %} {% endif %}
</div> </div>
<div id="col1"> <div id="col1">
<div class="logbookentry"> <div class="logbookentry">
<b>{{logbookentry.date}}</b> <b>{{logbookentry.date}}</b>
{{logbookentry.text|wiki_to_html}}</div> {{logbookentry.text|wiki_to_html}}</div>
</div> </div>
</div> </div>
{% if logbookentry.filename %}<a href="{% url editLogBookEntry expeditionyear=logbookentry.expedition.year pdate=logbookentry.date pslug=logbookentry.slug %}">Edit</a> <a href="{% url deleteLogBookEntry expeditionyear=logbookentry.expedition.year date=logbookentry.date slug=logbookentry.slug %}">Delete</a>{%endif%} {% if logbookentry.filename %}<a href="{% url editLogBookEntry expeditionyear=logbookentry.expedition.year pdate=logbookentry.date pslug=logbookentry.slug %}">Edit</a> <a href="{% url deleteLogBookEntry expeditionyear=logbookentry.expedition.year date=logbookentry.date slug=logbookentry.slug %}">Delete</a>{%endif%}
{% endblock %} {% endblock %}

View File

@ -1,83 +1,83 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load csrffaker %} {% load csrffaker %}
{% block title %}Logbook {{logbookentry.id}}{% endblock %} {% block title %}Logbook {{logbookentry.id}}{% endblock %}
{% block head %} {% block head %}
<script> <script>
$(function() { $(function() {
$("#id_date").datepicker({dateFormat: "yy-mm-dd"}); $("#id_date").datepicker({dateFormat: "yy-mm-dd"});
$('.persontrips tbody tr').formset(); $('.persontrips tbody tr').formset();
$(":radio[name*='caveOrLocation']").change(setLocationType); $(":radio[name*='caveOrLocation']").change(setLocationType);
$(setLocationType()); $(setLocationType());
function setLocationType () { function setLocationType () {
$("#cave").hide(); $("#cave").hide();
$("#location").hide(); $("#location").hide();
$("#" + $(":radio[name*='caveOrLocation']:checked")[0].value).show(); $("#" + $(":radio[name*='caveOrLocation']:checked")[0].value).show();
}; };
}); });
</script> </script>
<link rel="stylesheet" href="{{ settings.MEDIA_URL }}css/ui-lightness/jquery-ui-1.8.12.custom.css" type="text/css" media="all" /> <link rel="stylesheet" href="{{ settings.MEDIA_URL }}css/ui-lightness/jquery-ui-1.8.12.custom.css" type="text/css" media="all" />
<script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script>
<script src="{{ settings.MEDIA_URL }}js/jquery.formset.min.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/jquery.formset.min.js" type="text/javascript"></script>
<script src="{{ settings.TINY_MCE_MEDIA_URL }}tiny_mce.js" type="text/javascript"></script> <script src="{{ settings.TINY_MCE_MEDIA_URL }}tiny_mce.js" type="text/javascript"></script>
{{ tripForm.media }} {{ tripForm.media }}
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<form action="" method="post">{% csrf_token %} <form action="" method="post">{% csrf_token %}
{{ tripForm.non_field_errors }} {{ tripForm.non_field_errors }}
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ tripForm.title.errors }} {{ tripForm.title.errors }}
<label for="id_title">Title:</label> <label for="id_title">Title:</label>
{{ tripForm.title }} {{ tripForm.title }}
</div> </div>
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ tripForm.date.errors }} {{ tripForm.date.errors }}
<label for="id_date">Date:</label> <label for="id_date">Date:</label>
{{ tripForm.date }} {{ tripForm.date }}
</div> </div>
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ tripForm.caveOrLocation.errors }} {{ tripForm.caveOrLocation.errors }}
<label for="id_caveOrLocation">Location Type:</label> <label for="id_caveOrLocation">Location Type:</label>
{{ tripForm.caveOrLocation }} {{ tripForm.caveOrLocation }}
</div> </div>
<div class="fieldWrapper" id="cave"> <div class="fieldWrapper" id="cave">
{{ tripForm.cave.errors }} {{ tripForm.cave.errors }}
<label for="id_cave">Cave:</label> <label for="id_cave">Cave:</label>
{{ tripForm.cave }} {{ tripForm.cave }}
</div> </div>
<div class="fieldWrapper" id="location"> <div class="fieldWrapper" id="location">
{{ tripForm.location.errors }} {{ tripForm.location.errors }}
<label for="id_location">Location:</label> <label for="id_location">Location:</label>
{{ tripForm.location }} {{ tripForm.location }}
</div> </div>
<table class="persontrips" border="0" cellpadding="0" cellspacing="0"> <table class="persontrips" border="0" cellpadding="0" cellspacing="0">
<tbody> <tbody>
<tr> <tr>
<th>Person</th> <th>Person</th>
<th>TU /hours</th> <th>TU /hours</th>
<th>Author</th> <th>Author</th>
<th></th> <th></th>
</tr> </tr>
{% for form in personTripFormSet.forms %} {% for form in personTripFormSet.forms %}
<tr> <tr>
<td>{{ form.name.errors }}{{ form.name }}</td> <td>{{ form.name.errors }}{{ form.name }}</td>
<td>{{ form.TU.errors }}{{ form.TU }}</td> <td>{{ form.TU.errors }}{{ form.TU }}</td>
<td>{{ form.author.errors }}{{ form.author }}</td> <td>{{ form.author.errors }}{{ form.author }}</td>
<td></td> <td></td>
{{ form.non_field_errors }} {{ form.non_field_errors }}
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
{{ personTripFormSet.management_form }} {{ personTripFormSet.management_form }}
<div class="fieldWrapper"> <div class="fieldWrapper">
{{ tripForm.html.errors }} {{ tripForm.html.errors }}
<label for="id_date">Content:</label> <label for="id_date">Content:</label>
{{ tripForm.html }} {{ tripForm.html }}
</div> </div>
<p><input type="submit" value="Sumbit Trip Report" /></p> <p><input type="submit" value="Sumbit Trip Report" /></p>
</form> </form>
{% endblock %} {% endblock %}

View File

@ -1,9 +1,9 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %} {% block title %}
{{instance}} is non-public {{instance}} is non-public
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<h3>Non-public object requested by anonymous user</h3> <h3>Non-public object requested by anonymous user</h3>
The object you requested, {{instance}}, is only viewable for logged-in users. This may be due to copyright or privacy concerns. The object you requested, {{instance}}, is only viewable for logged-in users. This may be due to copyright or privacy concerns.
{% endblock %} {% endblock %}

View File

@ -1,15 +1,15 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load link %} {% load link %}
{% block title %}Troggle: {{object_list.1.meta.object_name}} objects{%endblock%} {% block title %}Troggle: {{object_list.1.meta.object_name}} objects{%endblock%}
{% block contentheader %} {% block contentheader %}
<h1>{{object_list.0.object_name}} objects</h1> <h1>{{object_list.0.object_name}} objects</h1>
{% endblock contentheader %} {% endblock contentheader %}
{% block content %} {% block content %}
<ul> <ul>
{% for object in object_list %} {% for object in object_list %}
| {{ object|link }} | {{ object|link }}
{% endfor %} | {% endfor %} |
</ul> </ul>
{% endblock content %} {% endblock content %}

View File

@ -1,43 +1,43 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Person {{person|wiki_to_html_short}}{% endblock %} {% block title %}Person {{person|wiki_to_html_short}}{% endblock %}
{% block editLink %}| <a href={{person.get_admin_url}}>Edit person {{person|wiki_to_html_short}}</a>{% endblock %} {% block editLink %}| <a href={{person.get_admin_url}}>Edit person {{person|wiki_to_html_short}}</a>{% endblock %}
{% block contentheader %} {% block contentheader %}
<h2> {{person|wiki_to_html_short}} </h2> <h2> {{person|wiki_to_html_short}} </h2>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
{% if person.blurb %} {% if person.blurb %}
{{person.blurb|safe}} {{person.blurb|safe}}
{% endif %} {% endif %}
{% for pic in person.photo_set.all %} {% for pic in person.photo_set.all %}
{% if pic.is_mugshot %} {% if pic.is_mugshot %}
<div class="figure"> <div class="figure">
<p> <img src="{{ pic.thumbnail_image.url }}" class="thumbnail" /> <p> <img src="{{ pic.thumbnail_image.url }}" class="thumbnail" />
<p> {{ pic.caption }}</p> <p> {{ pic.caption }}</p>
<p> <a href="{{ pic.get_admin_url }}">edit {{pic}}</a> </> <p> <a href="{{ pic.get_admin_url }}">edit {{pic}}</a> </>
</p> </p>
</p> </p>
</div> </div>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
<br class="clearfloat" /> <br class="clearfloat" />
<h3>{{person|wiki_to_html_short}} has been on expo in the following years:</h3> <h3>{{person|wiki_to_html_short}} has been on expo in the following years:</h3>
<p> <p>
<ul> <ul>
{% for personexpedition in person.personexpedition_set.all %} {% for personexpedition in person.personexpedition_set.all %}
<li> <a href="{{ personexpedition.get_absolute_url }}">{{personexpedition.expedition.year}}</a> <li> <a href="{{ personexpedition.get_absolute_url }}">{{personexpedition.expedition.year}}</a>
<span style="padding-left:{{personexpedition.persontrip_set.all|length}}0px; background-color:red"></span> <span style="padding-left:{{personexpedition.persontrip_set.all|length}}0px; background-color:red"></span>
{{personexpedition.persontrip_set.all|length}} trips {{personexpedition.persontrip_set.all|length}} trips
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
</p> </p>
{% endblock %} {% endblock %}

View File

@ -1,6 +1,6 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
{{ form }} {{ form }}
{% endblock %} {% endblock %}

View File

@ -1,57 +1,57 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load link %} {% load link %}
{% block title %}Person {{personexpedition.person|wiki_to_html_short}} for {{personexpedition.expedition}}{% endblock %} {% block title %}Person {{personexpedition.person|wiki_to_html_short}} for {{personexpedition.expedition}}{% endblock %}
{% block content %} {% block content %}
<h1> <h1>
<a href="{{personexpedition.person.get_absolute_url}}">{{personexpedition.person}}</a> : <a href="{{personexpedition.person.get_absolute_url}}">{{personexpedition.person}}</a> :
<a href="{{personexpedition.expedition.get_absolute_url}}">{{personexpedition.expedition}}</a> <a href="{{personexpedition.expedition.get_absolute_url}}">{{personexpedition.expedition}}</a>
</h1> </h1>
<p>{{message}}</p> <p>{{message}}</p>
<p><b>Other years:</b> <p><b>Other years:</b>
{% for otherpersonexpedition in personexpedition.person.personexpedition_set.all %} {% for otherpersonexpedition in personexpedition.person.personexpedition_set.all %}
{% ifequal otherpersonexpedition personexpedition %} {% ifequal otherpersonexpedition personexpedition %}
| <b>{{otherpersonexpedition.expedition.year}}</b> | <b>{{otherpersonexpedition.expedition.year}}</b>
{% else %} {% else %}
| <a href="{{otherpersonexpedition.get_absolute_url}}">{{ otherpersonexpedition.expedition.year }}</a> | <a href="{{otherpersonexpedition.get_absolute_url}}">{{ otherpersonexpedition.expedition.year }}</a>
{% endifequal %} {% endifequal %}
{% endfor %} {% endfor %}
</p> </p>
<h3>Table of all trips and surveys aligned by date</h3> <h3>Table of all trips and surveys aligned by date</h3>
<div> <div>
<table class="survexcontibutions"> <table class="survexcontibutions">
<tr><th>Date</th><th colspan="2">Trips</th><th colspan="2">Surveys</th></tr> <tr><th>Date</th><th colspan="2">Trips</th><th colspan="2">Surveys</th></tr>
{% for persondate in personchronology %} {% for persondate in personchronology %}
<tr> <tr>
<td class="date">{{persondate.0}}</td> <td class="date">{{persondate.0}}</td>
{% if persondate.1 %} {% if persondate.1 %}
<td class="trip"><a href="{{ persondate.1.logbook_entry.get_absolute_url }}">{{persondate.1.logbook_entry.title|safe}}</a></td> <td class="trip"><a href="{{ persondate.1.logbook_entry.get_absolute_url }}">{{persondate.1.logbook_entry.title|safe}}</a></td>
<td><a href="{{ persondate.1.logbook_entry.cave.get_absolute_url }}">{{persondate.1.place|safe}}</a></td> <td><a href="{{ persondate.1.logbook_entry.cave.get_absolute_url }}">{{persondate.1.place|safe}}</a></td>
{% else %} {% else %}
<td colspan="2"> </td> <td colspan="2"> </td>
{% endif %} {% endif %}
{% if persondate.2 %} {% if persondate.2 %}
<td class="survexblock"><a href="{% url svx persondate.2.survexfile.path %}">{{persondate.2}}</a></td> <td class="survexblock"><a href="{% url svx persondate.2.survexfile.path %}">{{persondate.2}}</a></td>
<td class="roles"> <td class="roles">
{% for survexpersonrole in persondate.2.survexpersonrole_set.all %} {% for survexpersonrole in persondate.2.survexpersonrole_set.all %}
{{survexpersonrole.nrole}} {{survexpersonrole.nrole}}
{% endfor %} {% endfor %}
</td> </td>
{% else %} {% else %}
<td colspan="2"> </td> <td colspan="2"> </td>
{% endif %} {% endif %}
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div> </div>
{% endblock %} {% endblock %}

View File

@ -1,44 +1,44 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Person Index{% endblock %} {% block title %}Person Index{% endblock %}
{% block content %} {% block content %}
<h2>Notable expoers</h2> <h2>Notable expoers</h2>
<table class="searchable"> <table class="searchable">
<tr><th>Person</th><th>First</th><th>Last</th><th>Notability</th></tr> <tr><th>Person</th><th>First</th><th>Last</th><th>Notability</th></tr>
{% for person in notablepersons %} {% for person in notablepersons %}
<tr> <tr>
<td><a href="{{ person.get_absolute_url }}">{{person|wiki_to_html_short}}</a></td> <td><a href="{{ person.get_absolute_url }}">{{person|wiki_to_html_short}}</a></td>
<td><a href="{{ person.first.get_absolute_url }}">{{ person.first.expedition.year }}</a></td> <td><a href="{{ person.first.get_absolute_url }}">{{ person.first.expedition.year }}</a></td>
<td><a href="{{ person.last.get_absolute_url }}">{{ person.last.expedition.year }}</a></td> <td><a href="{{ person.last.get_absolute_url }}">{{ person.last.expedition.year }}</a></td>
<td>{{person.notability}}</td> <td>{{person.notability}}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
<h2>All expoers</h2> <h2>All expoers</h2>
<table class="searchable"> <table class="searchable">
<tr> <tr>
{% for persons in personss %} {% for persons in personss %}
<td> <td>
<table> <table>
<tr><th>Person</th><th>First</th><th>Last</th><th>Surveyed length</th></tr> <tr><th>Person</th><th>First</th><th>Last</th><th>Surveyed length</th></tr>
{% for person in persons %} {% for person in persons %}
<tr> <tr>
<td><a href="{{ person.get_absolute_url }}">{{person|wiki_to_html_short}}</a></td> <td><a href="{{ person.get_absolute_url }}">{{person|wiki_to_html_short}}</a></td>
<td><a href="{{ person.first.get_absolute_url }}">{{person.first.expedition.year}}</a></td> <td><a href="{{ person.first.get_absolute_url }}">{{person.first.expedition.year}}</a></td>
<td><a href="{{ person.last.get_absolute_url }}">{{person.last.expedition.year}}</a></td> <td><a href="{{ person.last.get_absolute_url }}">{{person.last.expedition.year}}</a></td>
<td>{{ person.surveyedleglength }}</td> <td>{{ person.surveyedleglength }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</td> </td>
{% endfor %} {% endfor %}
</tr> </tr>
</table> </table>
{% endblock %} {% endblock %}

View File

@ -1,13 +1,13 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<form method="post"> <form method="post">
{{ form.as_p }} {{ form.as_p }}
<input type="submit" /> <input type="submit" />
</form> </form>
{% if form.errors %} {% if form.errors %}
<p class="errornote">Please correct the errors below</p> <p class="errornote">Please correct the errors below</p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -1,13 +1,13 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<form method="post"> <form method="post">
{{ form.as_p }} {{ form.as_p }}
<input type="submit" /> <input type="submit" />
</form> </form>
{% if form.errors %} {% if form.errors %}
<p class="errornote">Please correct the errors below</p> <p class="errornote">Please correct the errors below</p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -1,14 +1,14 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block contentheader %} {% block contentheader %}
<h1>Profile for {{ profile }}</h1> <h1>Profile for {{ profile }}</h1>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
{{ profile }} {{ profile }}
{% if form.errors %} {% if form.errors %}
<p class="errornote">Please correct the errors below</p> <p class="errornote">Please correct the errors below</p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -1,40 +1,40 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<h2>Troggle profile selection page</h2> <h2>Troggle profile selection page</h2>
Hello, {{ user }}. Hello, {{ user }}.
<br /><br /> <br /><br />
{% if user.person %} {% if user.person %}
This is where you go to associate a new user account with a pre-existing profile from old expo data. This is where you go to associate a new user account with a pre-existing profile from old expo data.
<br /><br /> <br /><br />
However, you already have a profile- your name should be {{user.person.first_name}} {{user.person.last_name}}. If you don't believe me, go see it at: <br /><br /> <a href= {{ user.person.get_absolute_url }}> {{ user.person.get_absolute_url }} </a> <br /><br /> or edit it at: However, you already have a profile- your name should be {{user.person.first_name}} {{user.person.last_name}}. If you don't believe me, go see it at: <br /><br /> <a href= {{ user.person.get_absolute_url }}> {{ user.person.get_absolute_url }} </a> <br /><br /> or edit it at:
<br /><br /> <a href= {{ user.person.get_admin_url }}> {{ user.person.get_admin_url }} </a>.<br /><br /> <br /><br /> <a href= {{ user.person.get_admin_url }}> {{ user.person.get_admin_url }} </a>.<br /><br />
If your account is associated with the wrong person's profile due to inebriation or incompetance during account setup, click <a href="{{ user.person.get_absolute_url }}/?clear_profile=True">here</a> to dissasociate your profile from your user account. If your account is associated with the wrong person's profile due to inebriation or incompetance during account setup, click <a href="{{ user.person.get_absolute_url }}/?clear_profile=True">here</a> to dissasociate your profile from your user account.
{% else %} {% else %}
You have an account in the system, but no profile. If you have been on expo before, please choose yourself from the list below. You have an account in the system, but no profile. If you have been on expo before, please choose yourself from the list below.
<br /><br /> <br /><br />
<form method="post"> <form method="post">
{{ form.as_p }} {{ form.as_p }}
<input name="" type="submit" value="This is me!" /> <input name="" type="submit" value="This is me!" />
</form> </form>
<br /> <br />
Yes, you could choose the wrong person if you want. That would be lame. Instead, do something that's actually funny. For example, fry a random object or maybe take some mac and cheese somewhere it doesn't usually get to go. Perhaps you can start a new tradition of laminating the expo leader. Yes, you could choose the wrong person if you want. That would be lame. Instead, do something that's actually funny. For example, fry a random object or maybe take some mac and cheese somewhere it doesn't usually get to go. Perhaps you can start a new tradition of laminating the expo leader.
{% endif %} {% endif %}
{% if form.errors %} {% if form.errors %}
<p class="errornote">Please correct the errors below</p> <p class="errornote">Please correct the errors below</p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -1,49 +1,49 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load link %} {% load link %}
{% block title %} QM: {{qm|wiki_to_html_short}} {% endblock %} {% block title %} QM: {{qm|wiki_to_html_short}} {% endblock %}
{% block editLink %}| <a href={{qm.get_admin_url}}>Edit QM {{qm|wiki_to_html_short}}</a>{% endblock %} {% block editLink %}| <a href={{qm.get_admin_url}}>Edit QM {{qm|wiki_to_html_short}}</a>{% endblock %}
{% block contentheader %} {% block contentheader %}
<table id="cavepage"> <table id="cavepage">
<tr> <tr>
<th id="kat_no"><a href="{{qm.get_previous_by_id.get_absolute_url}}">Previous</a></th> <th id="kat_no"><a href="{{qm.get_previous_by_id.get_absolute_url}}">Previous</a></th>
<th id="name">{{qm|wiki_to_html_short}}</th> <th id="name">{{qm|wiki_to_html_short}}</th>
<th id="status"><a href="{{qm.get_next_by_id.get_absolute_url}}">Next</a></th> <th id="status"><a href="{{qm.get_next_by_id.get_absolute_url}}">Next</a></th>
</tr> </tr>
</table> </table>
{% endblock %} {% endblock %}
{% block related %} {% block related %}
{% endblock %} {% endblock %}
<h2>Related items</h2> <h2>Related items</h2>
Parent cave: {{qm.found_by.cave|link}} Parent cave: {{qm.found_by.cave|link}}
(todo: add parent survey and parent subcave) (todo: add parent survey and parent subcave)
{% block content %} {% block content %}
<h3>Location</h3> <h3>Location</h3>
{{qm.location_description}} {{qm.location_description}}
<h3>Creation</h3> <h3>Creation</h3>
Found by <a href="{{qm.found_by.get_absolute_url}}">{{qm.found_by}}</a> on {{qm.found_by.date}}. Found by <a href="{{qm.found_by.get_absolute_url}}">{{qm.found_by}}</a> on {{qm.found_by.date}}.
<h3>Completion</h3> <h3>Completion</h3>
{% if ticked_off_by %} {% if ticked_off_by %}
{{qm.completion_description}} {{qm.completion_description}}
Ticked off by: <a href="{{qm.ticked_off_by.get_absolute_url}}">{{qm.ticked_off_by}}</a><br /> Ticked off by: <a href="{{qm.ticked_off_by.get_absolute_url}}">{{qm.ticked_off_by}}</a><br />
Description: {{qm.completion_description}} Description: {{qm.completion_description}}
{% else %} {% else %}
None yet- STILL EXTANT. None yet- STILL EXTANT.
{% endif %} {% endif %}
<h3>Comment</h3> <h3>Comment</h3>
{{qm.comment}} {{qm.comment}}
{% endblock %} {% endblock %}

View File

@ -1,25 +1,25 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %} {% block title %}
New troggle account registered New troggle account registered
{% endblock %} {% endblock %}
{% block header %} {% block header %}
<h1>activate.html</h1> <h1>activate.html</h1>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
{% if account %} {% if account %}
<p> <p>
Hello, {{ account }}! Your account is now activated. Now you can <a href="{%url auth_login%}">log in</a> with the password you chose. Use the links in the upper right to control this in the future. Hello, {{ account }}! Your account is now activated. Now you can <a href="{%url auth_login%}">log in</a> with the password you chose. Use the links in the upper right to control this in the future.
</p> </p>
<p> <p>
If you have been on the expedition in the past, you already have a profile in the system; <a href={% url profiles_select_profile %}>click here </a> to find it and link it to your account. Otherwise, please <a href={% url profiles_create_profile %}> create yourself a new profile</a>. If you have been on the expedition in the past, you already have a profile in the system; <a href={% url profiles_select_profile %}>click here </a> to find it and link it to your account. Otherwise, please <a href={% url profiles_create_profile %}> create yourself a new profile</a>.
</p> </p>
{% else %} {% else %}
The activation key you entered has already been used or was invalid. The activation key you entered has already been used or was invalid.
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View File

@ -1,10 +1,10 @@
<P>Hello {{ form.user }},</P> <P>Hello {{ form.user }},</P>
<P>Glad you're joining the CUCC EXPO team! Please go to</P> <P>Glad you're joining the CUCC EXPO team! Please go to</P>
<P><a href="{{ site }}{% url registration_activate activation_key %}">{{ site }}{% url registration_activate activation_key %}</a></P> <P><a href="{{ site }}{% url registration_activate activation_key %}">{{ site }}{% url registration_activate activation_key %}</a></P>
<P>to activate your account. Do this within {{ expiration_days }} days, or else you'll have to sign up again.</P> <P>to activate your account. Do this within {{ expiration_days }} days, or else you'll have to sign up again.</P>
<P>Yours,<BR> <P>Yours,<BR>
The magical troggle</P> The magical troggle</P>

View File

@ -1,10 +1,10 @@
Hello {{ form.user }}, Hello {{ form.user }},
Glad you're joining the CUCC EXPO team! Please go to Glad you're joining the CUCC EXPO team! Please go to
{{ site }}{% url registration_activate activation_key %} {{ site }}{% url registration_activate activation_key %}
to activate your account. Do this within {{ expiration_days }} days, or else you'll have to sign up again. to activate your account. Do this within {{ expiration_days }} days, or else you'll have to sign up again.
Yours, Yours,
The magical troggle The magical troggle

View File

@ -1,20 +1,20 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load csrffaker %} {% load csrffaker %}
{% block content %} {% block content %}
{% if form.errors %} {% if form.errors %}
<p>Your username and password didn't match. Please try again.</p> <p>Your username and password didn't match. Please try again.</p>
{% endif %} {% endif %}
<form method="post" action=".">{% csrf_token %} <form method="post" action=".">{% csrf_token %}
<table> <table>
<tr><td>{{ form.username.label_tag }}</td><td>{{ form.username }}</td></tr> <tr><td>{{ form.username.label_tag }}</td><td>{{ form.username }}</td></tr>
<tr><td>{{ form.password.label_tag }}</td><td>{{ form.password }}</td></tr> <tr><td>{{ form.password.label_tag }}</td><td>{{ form.password }}</td></tr>
</table> </table>
<input type="submit" value="login" /> <input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" /> <input type="hidden" name="next" value="{{ next }}" />
</form> </form>
{% endblock %} {% endblock %}

View File

@ -1,4 +1,4 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
You have been logged out. You have been logged out.
{% endblock %} {% endblock %}

View File

@ -1,6 +1,6 @@
{% extends “base.html” %} {% extends “base.html” %}
{% block body %} {% block body %}
Hello {{ account }}! Hello {{ account }}!
Check your email to confirm the activation. There are {{ expiration_days }} days left to do it. Check your email to confirm the activation. There are {{ expiration_days }} days left to do it.
{% endblock %} {% endblock %}

View File

@ -1,13 +1,13 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %} {% block title %}
{{ block.super }}: registration complete {{ block.super }}: registration complete
{% endblock %} {% endblock %}
{% block contentheader %} {% block contentheader %}
<h1>Registration Complete</h1> <h1>Registration Complete</h1>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<p>Thank you for signing up. An email with the activation code has been sent to your inbox. </p> <p>Thank you for signing up. An email with the activation code has been sent to your inbox. </p>
{% endblock %} {% endblock %}

View File

@ -1,8 +1,8 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Database statistics{% endblock %} {% block title %}Database statistics{% endblock %}
{% block content %} {% block content %}
Over the course of {{ expoCount }} expeditions, {{ personCount }} people have contributed {{ caveCount }} caves and {{ logbookEntryCount }} logbook entries. Over the course of {{ expoCount }} expeditions, {{ personCount }} people have contributed {{ caveCount }} caves and {{ logbookEntryCount }} logbook entries.
{% endblock %} {% endblock %}

View File

@ -1,59 +1,59 @@
{% extends "cavebase.html" %} {% extends "cavebase.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load mptt_tags %} {% load mptt_tags %}
{% block title %} Subcave {{subcave}} {% endblock title %} {% block title %} Subcave {{subcave}} {% endblock title %}
{% block editLink %}<a href={{subcave.get_admin_url}}>Edit subcave {{subcave|wiki_to_html_short}}</a>{% endblock %} {% block editLink %}<a href={{subcave.get_admin_url}}>Edit subcave {{subcave|wiki_to_html_short}}</a>{% endblock %}
{% block contentheader %} {% block contentheader %}
{{subcave.title}} {{subcave.title}}
{% endblock contentheader %} {% endblock contentheader %}
{% block content %} {% block content %}
{% block related %} {% block related %}
<h2>Related places</h2> <h2>Related places</h2>
<h3>Parent</h3> <h3>Parent</h3>
<ul> <ul>
{% if subcave.parent %} {% if subcave.parent %}
<li><a href="{{subcave.parent.get_absolute_url}}">{{subcave.parent}}</a></li> <li><a href="{{subcave.parent.get_absolute_url}}">{{subcave.parent}}</a></li>
{% else %} {% else %}
<li><a href="{{subcave.cave.get_absolute_url}}">{{subcave.cave}}</a></li> <li><a href="{{subcave.cave.get_absolute_url}}">{{subcave.cave}}</a></li>
{% endif %} {% endif %}
</ul> </ul>
<h3>Connected subareas</h3> <h3>Connected subareas</h3>
<ul> <ul>
{% for sibling in subcave.adjoining.all%} {% for sibling in subcave.adjoining.all%}
<li><a href="{{sibling.get_absolute_url}}">{{silbling}}</a></li> <li><a href="{{sibling.get_absolute_url}}">{{silbling}}</a></li>
{% endfor %} {% endfor %}
</ul> </ul>
<h3>Children</h3> <h3>Children</h3>
<ul> <ul>
{% for child in subcave.children.all %} {% for child in subcave.children.all %}
<li><a href="{{child.get_absolute_url}}">{{child}}</a></li> <li><a href="{{child.get_absolute_url}}">{{child}}</a></li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endblock %} {% endblock %}
ok here comes the drilldown<br /> ok here comes the drilldown<br />
{% drilldown_tree_for_node subcave as drilldown %} {% drilldown_tree_for_node subcave as drilldown %}
{% for each in drilldown %} {% for each in drilldown %}
{{ each }}> {{ each }}>
{% endfor %} {% endfor %}
<h2>{{subcave}}</h2> <h2>{{subcave}}</h2>
<p> <p>
{{subcave.description}} {{subcave.description}}
</p> </p>
{% endblock content %} {% endblock content %}

View File

@ -1,49 +1,49 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load survex_markup %} {% load survex_markup %}
{% block title %}Survex Block{% endblock %} {% block title %}Survex Block{% endblock %}
{% block content %} {% block content %}
<h2>Survex Block {{survexblock.survexpath}}</h2> <h2>Survex Block {{survexblock.survexpath}}</h2>
<p>Link to <a href="{% url svx survexblock.survexfile.path %}">{{survexblock.survexfile.path}}</a></p> <p>Link to <a href="{% url svx survexblock.survexfile.path %}">{{survexblock.survexfile.path}}</a></p>
<p>Needs duplicates removed from right hand column</p> <p>Needs duplicates removed from right hand column</p>
<p>Needs links to survex file presentation</p> <p>Needs links to survex file presentation</p>
<p>Needs to start dealing with misspellings of names (prob by editing the originals)</p> <p>Needs to start dealing with misspellings of names (prob by editing the originals)</p>
<div id="col2"> <div id="col2">
{% if survexblock.parent %} {% if survexblock.parent %}
<p>Survey block above:</p> <p>Survey block above:</p>
<p class="indent"><a href="{% url survexblock survexblock.parent.survexpath %}">{{survexblock.parent.survexpath}}</a></p> <p class="indent"><a href="{% url survexblock survexblock.parent.survexpath %}">{{survexblock.parent.survexpath}}</a></p>
{% endif %} {% endif %}
{% if survexblock.survexblock_set.all %} {% if survexblock.survexblock_set.all %}
<p>Survey blocks below:</p> <p>Survey blocks below:</p>
{% for survexblockdown in survexblock.survexblock_set.all %} {% for survexblockdown in survexblock.survexblock_set.all %}
<p class="indent"><a href="{% url survexblock survexblockdown.survexpath %}">{{survexblockdown.survexpath}}</a></p> <p class="indent"><a href="{% url survexblock survexblockdown.survexpath %}">{{survexblockdown.survexpath}}</a></p>
{% endfor %} {% endfor %}
{% endif %} {% endif %}
<p>Date: {{survexblock.date}}</p> <p>Date: {{survexblock.date}}</p>
<table> <table>
{% for personrole in survexblock.GetPersonroles %} {% for personrole in survexblock.GetPersonroles %}
<tr> <tr>
<td><a href="{{personrole.person.get_absolute_url}}">{{personrole.person}}</a></td> <td><a href="{{personrole.person.get_absolute_url}}">{{personrole.person}}</a></td>
<td>{{personrole.roles}}</td> <td>{{personrole.roles}}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div> </div>
<div class="survexblock"> <div class="survexblock">
{{ftext|survex_to_html}} {{ftext|survex_to_html}}
</div> </div>
{% endblock %} {% endblock %}

View File

@ -1,33 +1,33 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load survex_markup %} {% load survex_markup %}
{% block title %}Survex Scans Folder{% endblock %} {% block title %}Survex Scans Folder{% endblock %}
{% block content %} {% block content %}
<h3>Survex Scans in: {{survexscansfolder.walletname}}</h3> <h3>Survex Scans in: {{survexscansfolder.walletname}}</h3>
<table> <table>
{% for survexscansingle in survexscansfolder.survexscansingle_set.all %} {% for survexscansingle in survexscansfolder.survexscansingle_set.all %}
<tr> <tr>
<td class="survexscansingle"><a href="{{survexscansingle.get_absolute_url}}">{{survexscansingle.name}}</a></td> <td class="survexscansingle"><a href="{{survexscansingle.get_absolute_url}}">{{survexscansingle.name}}</a></td>
<td> <td>
{% for survexblock in survexscansingle.survexblock_set.all %} {% for survexblock in survexscansingle.survexblock_set.all %}
{{survexblock}} {{survexblock}}
{% endfor %} {% endfor %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
<h3>Surveys referring to this wallet</h3> <h3>Surveys referring to this wallet</h3>
<table> <table>
{% for survexblock in survexscansfolder.survexblock_set.all %} {% for survexblock in survexscansfolder.survexblock_set.all %}
<tr> <tr>
<td><a href="{% url svx survexblock.survexfile.path %}">{{survexblock}}</a></td> <td><a href="{% url svx survexblock.survexfile.path %}">{{survexblock}}</a></td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
{% endblock %} {% endblock %}

View File

@ -1,25 +1,25 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load survex_markup %} {% load survex_markup %}
{% block title %}All Survex scans folders{% endblock %} {% block title %}All Survex scans folders{% endblock %}
{% block content %} {% block content %}
<h3>All Survex scans folders</h3> <h3>All Survex scans folders</h3>
<table> <table>
<tr><th>Scans folder</th><th>Files</th><th>Survex blocks</th></tr> <tr><th>Scans folder</th><th>Files</th><th>Survex blocks</th></tr>
{% for survexscansfolder in survexscansfolders %} {% for survexscansfolder in survexscansfolders %}
<tr> <tr>
<td><a href="{{survexscansfolder.get_absolute_url}}">{{survexscansfolder.walletname}}</a></td> <td><a href="{{survexscansfolder.get_absolute_url}}">{{survexscansfolder.walletname}}</a></td>
<td>{{survexscansfolder.survexscansingle_set.all|length}}</td> <td>{{survexscansfolder.survexscansingle_set.all|length}}</td>
<td> <td>
{% for survexblock in survexscansfolder.survexblock_set.all %} {% for survexblock in survexscansfolder.survexblock_set.all %}
<a href="{% url svx survexblock.survexfile.path %}">{{survexblock}}</a> <a href="{% url svx survexblock.survexfile.path %}">{{survexblock}}</a>
{% endfor %} {% endfor %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
{% endblock %} {% endblock %}

View File

@ -1,193 +1,193 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}CUCC Virtual Survey Binder: {{ current_expedition }}{{ current_survey }}{%endblock%} {% block title %}CUCC Virtual Survey Binder: {{ current_expedition }}{{ current_survey }}{%endblock%}
{% block head %} {% block head %}
<link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/nav.css" /> <link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/nav.css" />
<script language="javascript"> <script language="javascript">
blankColor = "rgb(153, 153, 153)" blankColor = "rgb(153, 153, 153)"
highlightedColor = "rgb(125, 125, 125)" highlightedColor = "rgb(125, 125, 125)"
chosenColor = "rgb(255, 255, 255)" chosenColor = "rgb(255, 255, 255)"
$(document).ready(function() { $(document).ready(function() {
$(".menuBarItem").click(function() { $(".menuBarItem").click(function() {
$("#"+this.id+"Content").toggle(); $("#"+this.id+"Content").toggle();
if ($(this).hasClass('on')){ if ($(this).hasClass('on')){
$(this).removeClass('on');} $(this).removeClass('on');}
else { else {
$(this).addClass('on'); $(this).addClass('on');
} }
}); });
}); });
function redirectSurvey(){ function redirectSurvey(){
window.location = "{% url survey %}" + '/' + document.getElementById("expeditionChooser").value + "%23" + document.getElementById("surveyChooser").value; window.location = "{% url survey %}" + '/' + document.getElementById("expeditionChooser").value + "%23" + document.getElementById("surveyChooser").value;
} }
function redirectYear(){ function redirectYear(){
window.location = "{% url survey %}" + '/' + document.getElementById("expeditionChooser").value + "%23"; window.location = "{% url survey %}" + '/' + document.getElementById("expeditionChooser").value + "%23";
} }
</script> </script>
{% endblock %} {% endblock %}
<div id="currentLocation"> <div id="currentLocation">
CUCC Expo virtual survey binder: CUCC Expo virtual survey binder:
{% if current_survey %} {% if current_survey %}
{{current_survey}} {{current_survey}}
{% else %} {% else %}
{{current_expedition}} {{current_expedition}}
{% endif %} {% endif %}
</div> </div>
{% block nav %} {% block nav %}
<br /> <br />
<h3>Choose a year</h3> <h3>Choose a year</h3>
<center> <center>
<select id="expeditionChooser" class="centre" onChange="redirectYear()"> <select id="expeditionChooser" class="centre" onChange="redirectYear()">
<option value=""/> <option value=""/>
{% for expedition in expeditions %} {% for expedition in expeditions %}
<option label="{{ expedition }}" value="{{ expedition }}" {% ifequal expedition current_expedition %}selected{% endifequal %}> <option label="{{ expedition }}" value="{{ expedition }}" {% ifequal expedition current_expedition %}selected{% endifequal %}>
{{ expedition }} {{ expedition }}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
</center> </center>
<div> <div>
<!-- <h4>Click to toggle:</h4>--> <!-- <h4>Click to toggle:</h4>-->
<div id="progressTable" class="menuBarItem"> {% if current_expedition.survey_set.all %}&#10003;{% endif %} <div id="progressTable" class="menuBarItem"> {% if current_expedition.survey_set.all %}&#10003;{% endif %}
survey progress table </div> survey progress table </div>
</div> </div>
{% if current_expedition %} {% if current_expedition %}
<h3>Choose a wallet number </h3> <h3>Choose a wallet number </h3>
<center> <center>
<select id="surveyChooser" class="centre" onChange="redirectSurvey()"> <select id="surveyChooser" class="centre" onChange="redirectSurvey()">
<option label="show all" value=""> <option label="show all" value="">
</option> </option>
{% for survey in current_expedition.survey_set.all %} {% for survey in current_expedition.survey_set.all %}
<option label="{{ survey }}" value="{{ survey.wallet_number }}" <option label="{{ survey }}" value="{{ survey.wallet_number }}"
{% ifequal survey current_survey %} {% ifequal survey current_survey %}
selected selected
{% endifequal %}> {% endifequal %}>
{{ survey }} {{ survey }}
</option> </option>
{% endfor %} {% endfor %}
<option label="add" value="add"> <option label="add" value="add">
</select> </select>
</center> </center>
<h4>Click to toggle:</h4> <h4>Click to toggle:</h4>
<div id="surveyWalletNav"> <div id="surveyWalletNav">
<div id="notes" class="menuBarItem"> {% if notes %}&#10003;{% endif %} <div id="notes" class="menuBarItem"> {% if notes %}&#10003;{% endif %}
scanned notes </div> scanned notes </div>
<div id="survexFile" class="menuBarItem"> {% if current_survey.survex_file %}&#10003;{% endif %} <div id="survexFile" class="menuBarItem"> {% if current_survey.survex_file %}&#10003;{% endif %}
survex file </div> survex file </div>
<div id="printedCentreline" class="menuBarItem"> {% if current_survey.centreline_printed_on %}&#10003;{% endif %} <div id="printedCentreline" class="menuBarItem"> {% if current_survey.centreline_printed_on %}&#10003;{% endif %}
printed centreline </div> printed centreline </div>
<div id="scannedPassageSketch" class="menuBarItem"> {% if planSketches %}&#10003;{% endif %} <div id="scannedPassageSketch" class="menuBarItem"> {% if planSketches %}&#10003;{% endif %}
scanned passage sketch </div> scanned passage sketch </div>
<div id="tunnelXMLfile" class="menuBarItem">tunnel xml file</div> <div id="tunnelXMLfile" class="menuBarItem">tunnel xml file</div>
<div id="mainSketchIntegration" class="menuBarItem">add to main sketch</div> <div id="mainSketchIntegration" class="menuBarItem">add to main sketch</div>
</div> </div>
</div> </div>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<div id="mainContent" style="background:white"> <div id="mainContent" style="background:white">
<div id="progressTableContent" class="behind"> <div id="progressTableContent" class="behind">
<h3>Survey progress table for {{ current_expedition }}</h3> <h3>Survey progress table for {{ current_expedition }}</h3>
{% if current_expedition.survey_set.all %} <!-- if there are any surveys in the expedition, make the table --> {% if current_expedition.survey_set.all %} <!-- if there are any surveys in the expedition, make the table -->
<table class="centre"> <table class="centre">
<tr> <tr>
<th> </th> <th> </th>
{% for survey in current_expedition.survey_set.all %} {% for survey in current_expedition.survey_set.all %}
<th> {{ survey.wallet_number }} </th> <th> {{ survey.wallet_number }} </th>
{% endfor %} </tr> {% endfor %} </tr>
<tr> <tr>
<td> Notes </td> <td> Notes </td>
{% for survey in current_expedition.survey_set.all %} {% for survey in current_expedition.survey_set.all %}
<td> {% if survey.notes %} <td> {% if survey.notes %}
&#10003; &#10003;
{% endif %} </td> {% endif %} </td>
{% endfor %} </tr> {% endfor %} </tr>
<tr> <tr>
<td> Survex file </td> <td> Survex file </td>
{% for survey in current_expedition.survey_set.all %} {% for survey in current_expedition.survey_set.all %}
<td> {% if survey.survex_file %} <td> {% if survey.survex_file %}
&#10003; &#10003;
{% endif %} </td> {% endif %} </td>
{% endfor %} </tr> {% endfor %} </tr>
<tr> <tr>
<td> Plans </td> <td> Plans </td>
{% for survey in current_expedition.survey_set.all %} {% for survey in current_expedition.survey_set.all %}
<td> {% if survey.plans %} <td> {% if survey.plans %}
&#10003; &#10003;
{% endif %} </td> {% endif %} </td>
{% endfor %} </tr> {% endfor %} </tr>
<tr> <tr>
<td> Elevations </td> <td> Elevations </td>
{% for survey in current_expedition.survey_set.all %} {% for survey in current_expedition.survey_set.all %}
<td> {% if survey.elevations %} <td> {% if survey.elevations %}
&#10003; &#10003;
{% endif %} </td> {% endif %} </td>
{% endfor %} </tr> {% endfor %} </tr>
</table> </table>
{% else %} {% else %}
<center>[ There are no surveys in the database for this year. Put link in to add one. ]</center> <center>[ There are no surveys in the database for this year. Put link in to add one. ]</center>
{% endif %} {% endif %}
</div> </div>
<div id="notesContent" class="behind" > <div id="notesContent" class="behind" >
<h3>Scanned notes for {{ current_survey }}.</h3> <h3>Scanned notes for {{ current_survey }}.</h3>
{% for noteItem in notes %} {% for noteItem in notes %}
<div class="figure"> <div class="figure">
<p> <img src="{{ noteItem.thumbnail_image.url }}" class="thumbnail"> <p> <img src="{{ noteItem.thumbnail_image.url }}" class="thumbnail">
<p> File at: <a href="{{ noteItem.correctURL }}"> {{ noteItem.file.name }} </a> <br /> <p> File at: <a href="{{ noteItem.correctURL }}"> {{ noteItem.file.name }} </a> <br />
Scanned by: {{ noteItem.scanned_by }} <br /> Scanned by: {{ noteItem.scanned_by }} <br />
On: {{ noteItem.scanned_on }} <br /> On: {{ noteItem.scanned_on }} <br />
</p> </p>
</p> </p>
</div> </div>
{% endfor %} {% endfor %}
<div class="figure"> <a href="{{ settings.URL_ROOT }}/admin/expo/scannedimage/add/"> <img src="{{ settings.URL_ROOT }}{{ settings.ADMIN_MEDIA_PREFIX }}img/admin/icon_addlink.gif" /> Add a new scanned notes page. </a> </div> <div class="figure"> <a href="{{ settings.URL_ROOT }}/admin/expo/scannedimage/add/"> <img src="{{ settings.URL_ROOT }}{{ settings.ADMIN_MEDIA_PREFIX }}img/admin/icon_addlink.gif" /> Add a new scanned notes page. </a> </div>
</div> </div>
<br class="clearfloat" /> <br class="clearfloat" />
<div id="survexFileContent" class="behind"> survex file editor, keeping file in original structure <br /> <div id="survexFileContent" class="behind"> survex file editor, keeping file in original structure <br />
who entered by </div> who entered by </div>
<div id="printedCentrelineContent" class="behind"> centreline </div> <div id="printedCentrelineContent" class="behind"> centreline </div>
<div id="scannedPassageSketchContent" class="behind"> <div id="scannedPassageSketchContent" class="behind">
<h3>Scanned plan sketch files for {{ current_survey }}.</h3> <h3>Scanned plan sketch files for {{ current_survey }}.</h3>
{% for sketchItem in planSketches %} {% for sketchItem in planSketches %}
<div class="figure"> <div class="figure">
<p> <img src="{{ sketchItem.thumbnail_image.url }}" class="thumbnail" /> <p> <img src="{{ sketchItem.thumbnail_image.url }}" class="thumbnail" />
<p> File at: <a href="{{ sketchItem.correctURL }}"> {{ sketchItem.file.name }} </a> <br /> <p> File at: <a href="{{ sketchItem.correctURL }}"> {{ sketchItem.file.name }} </a> <br />
Scanned by: {{ sketchItem.scanned_by }} <br /> Scanned by: {{ sketchItem.scanned_by }} <br />
On: {{ sketchItem.scanned_on }} <br /> On: {{ sketchItem.scanned_on }} <br />
</p> </p>
</p> </p>
</div> </div>
{% endfor %} {% endfor %}
<div class="figure"> <a href="{{ settings.URL_ROOT }}/admin/expo/scannedimage/add/"> <img src="{{ settings.URL_ROOT }}{{ settings.ADMIN_MEDIA_PREFIX }}img/admin/icon_addlink.gif" /> Add a new scanned sketch. </a> </div> <div class="figure"> <a href="{{ settings.URL_ROOT }}/admin/expo/scannedimage/add/"> <img src="{{ settings.URL_ROOT }}{{ settings.ADMIN_MEDIA_PREFIX }}img/admin/icon_addlink.gif" /> Add a new scanned sketch. </a> </div>
</div> </div>
<div id="tunnelXMLfileContent" class="behind"> link to tunnel xml file. potentially instance of tunnel applet... </div> <div id="tunnelXMLfileContent" class="behind"> link to tunnel xml file. potentially instance of tunnel applet... </div>
<div id="mainSketchIntegrationContent" class="behind"> link to main sketch file </div> <div id="mainSketchIntegrationContent" class="behind"> link to main sketch file </div>
<!-- end #mainContent --> <!-- end #mainContent -->
</div> </div>
<br class="clearfloat" /> <br class="clearfloat" />
{% endblock %} {% endblock %}

View File

@ -1,81 +1,81 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load link %} {% load link %}
{% block title %}List of survex files{% endblock %} {% block title %}List of survex files{% endblock %}
{% block content %} {% block content %}
<h1>Surveys for {{cave}}</h1> <h1>Surveys for {{cave}}</h1>
<p> <p>
{% for survexdirectory in cave.survexdirectory_set.all %} {% for survexdirectory in cave.survexdirectory_set.all %}
<a href="#T_{{survexdirectory.primarysurvexfile.path}}">{{survexdirectory.path}}</a> <a href="#T_{{survexdirectory.primarysurvexfile.path}}">{{survexdirectory.path}}</a>
{% endfor %} {% endfor %}
</p> </p>
{% for survexdirectory in cave.survexdirectory_set.all %} {% for survexdirectory in cave.survexdirectory_set.all %}
<h3 id="T_{{survexdirectory.primarysurvexfile.path}}">{{survexdirectory.path}}</h3> <h3 id="T_{{survexdirectory.primarysurvexfile.path}}">{{survexdirectory.path}}</h3>
<table> <table>
<tr><th>Survex file</th><th>Block</th><th>Date</th><th>Explorers</th><th>length</th><th>Titles</th><th>Scans</th></tr> <tr><th>Survex file</th><th>Block</th><th>Date</th><th>Explorers</th><th>length</th><th>Titles</th><th>Scans</th></tr>
{% for survexfile in survexdirectory.survexfile_set.all %} {% for survexfile in survexdirectory.survexfile_set.all %}
<tr> <tr>
{% if survexfile.exists %} {% if survexfile.exists %}
<td rowspan="{{survexfile.survexblock_set.all|length|plusone}}"> <td rowspan="{{survexfile.survexblock_set.all|length|plusone}}">
{% else %} {% else %}
<td class="survexnewfile" rowspan="{{survexfile.survexblock_set.all|length|plusone}}"> <td class="survexnewfile" rowspan="{{survexfile.survexblock_set.all|length|plusone}}">
{% endif %} {% endif %}
{% ifequal survexfile survexdirectory.primarysurvexfile %} {% ifequal survexfile survexdirectory.primarysurvexfile %}
<a href="{% url svx survexfile.path %}"><b>{{survexfile.path}}</b></a> <a href="{% url svx survexfile.path %}"><b>{{survexfile.path}}</b></a>
{% else %} {% else %}
<a href="{% url svx survexfile.path %}">{{survexfile.path}}</a> <a href="{% url svx survexfile.path %}">{{survexfile.path}}</a>
{% endifequal %} {% endifequal %}
</td> </td>
</tr> </tr>
{% for survexblock in survexfile.survexblock_set.all %} {% for survexblock in survexfile.survexblock_set.all %}
<tr> <tr>
<td>{{survexblock.name}}</td> <td>{{survexblock.name}}</td>
<td> <td>
{% if survexblock.expedition %} {% if survexblock.expedition %}
<a href="{{survexblock.expedition.get_absolute_url}}">{{survexblock.date}}</a> <a href="{{survexblock.expedition.get_absolute_url}}">{{survexblock.date}}</a>
{% else %} {% else %}
{{survexblock.date}} {{survexblock.date}}
{% endif %} {% endif %}
</td> </td>
<td> <td>
{% for personrole in survexblock.personrole_set.all %} {% for personrole in survexblock.personrole_set.all %}
{% if personrole.personexpedition %} {% if personrole.personexpedition %}
<a href="{{personrole.personexpedition.get_absolute_url}}">{{personrole.personname}}</a> <a href="{{personrole.personexpedition.get_absolute_url}}">{{personrole.personname}}</a>
{% else %} {% else %}
{{personrole.personname}} {{personrole.personname}}
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</td> </td>
<td>{{survexblock.totalleglength}}</td> <td>{{survexblock.totalleglength}}</td>
<td> <td>
{% for survextitle in survexblock.survextitle_set.all %} {% for survextitle in survexblock.survextitle_set.all %}
{{survextitle.title}} {{survextitle.title}}
{% endfor %} {% endfor %}
</td> </td>
<td> <td>
{% if survexblock.survexscansfolder %} {% if survexblock.survexscansfolder %}
<b><a href="{{survexblock.survexscansfolder.get_absolute_url}}">{{survexblock.survexscansfolder.walletname}}</a></b> <b><a href="{{survexblock.survexscansfolder.get_absolute_url}}">{{survexblock.survexscansfolder.walletname}}</a></b>
{% endif %} {% endif %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
{% endfor %} {% endfor %}
</table> </table>
{% endfor %} {% endfor %}
{% endblock %} {% endblock %}

View File

@ -1,76 +1,76 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load survex_markup %} {% load survex_markup %}
{% block title %}{{ title }}{% endblock %} {% block title %}{{ title }}{% endblock %}
{% block head %} {% block head %}
<script src="{{ settings.MEDIA_URL }}js/base.js" type="text/javascript"></script> <script src="{{ settings.MEDIA_URL }}js/base.js" type="text/javascript"></script>
<script type="text/javascript" src="{{settings.MEDIA_URL}}js/jquery.form.js"></script> <script type="text/javascript" src="{{settings.MEDIA_URL}}js/jquery.form.js"></script>
<script type="text/javascript" src="{{settings.MEDIA_URL}}CodeMirror-0.62/js/codemirror.js"></script> <script type="text/javascript" src="{{settings.MEDIA_URL}}CodeMirror-0.62/js/codemirror.js"></script>
<script type="text/javascript"> <script type="text/javascript">
var codeeditor; var codeeditor;
$(document).ready(function() $(document).ready(function()
{ {
codeeditor = CodeMirror.fromTextArea("id_code", codeeditor = CodeMirror.fromTextArea("id_code",
{ {
parserfile: ["parsesurvex.js"], parserfile: ["parsesurvex.js"],
stylesheet: "{{settings.MEDIA_URL}}CodeMirror-0.62/css/survexcolors.css", stylesheet: "{{settings.MEDIA_URL}}CodeMirror-0.62/css/survexcolors.css",
path: "{{settings.MEDIA_URL}}CodeMirror-0.62/js/", path: "{{settings.MEDIA_URL}}CodeMirror-0.62/js/",
textWrapping: false, textWrapping: false,
lineNumbers: false, lineNumbers: false,
indentUnit: 4, indentUnit: 4,
tabMode: "spaces" tabMode: "spaces"
}); });
$("#id_outputtype").val("ajax"); $("#id_outputtype").val("ajax");
var options = var options =
{ {
target: '#difflistajax', target: '#difflistajax',
beforeSubmit: function() { $("textarea#id_code").value = codeeditor.getCode().length; }, beforeSubmit: function() { $("textarea#id_code").value = codeeditor.getCode().length; },
success: function() { codeeditor.focus(); } success: function() { codeeditor.focus(); }
}; };
$('#codewikiform').ajaxForm(options); // bind form using 'ajaxForm' $('#codewikiform').ajaxForm(options); // bind form using 'ajaxForm'
}); });
</script> </script>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<h1>Survex File: {{ title }}</h1> <h1>Survex File: {{ title }}</h1>
{% if svxincludes %} {% if svxincludes %}
<p><b>Included files:</b> <p><b>Included files:</b>
{% for svxinclude in svxincludes %} {% for svxinclude in svxincludes %}
<a href="{{svxinclude}}.svx">{{svxinclude}}</a> <a href="{{svxinclude}}.svx">{{svxinclude}}</a>
{% endfor %} {% endfor %}
</p> </p>
{% endif %} {% endif %}
<form id="codewikiform" action="" method="POST"> <form id="codewikiform" action="" method="POST">
<div class="codeframebit">{{form.code}}</div> <div class="codeframebit">{{form.code}}</div>
<div style="display:none">{{form.filename}} {{form.dirname}} {{form.datetime}} {{form.outputtype}}</div> <div style="display:none">{{form.filename}} {{form.dirname}} {{form.datetime}} {{form.outputtype}}</div>
<input type="submit" name="diff" value="Diffy" /> <input type="submit" name="diff" value="Diffy" />
<input type="submit" name="save" value="Save"/> <input type="submit" name="save" value="Save"/>
<input type="submit" name="process" value="Process" title="executes cavern"/> <input type="submit" name="process" value="Process" title="executes cavern"/>
</form> </form>
<div id="difflistajax"> <div id="difflistajax">
<pre> <pre>
{% for diffline in difflist %}{{diffline}} {% for diffline in difflist %}{{diffline}}
{% endfor %} {% endfor %}
</pre> </pre>
{% if logmessage %} {% if logmessage %}
{% if has_3d %} {% if has_3d %}
<p><a href="{% url threed title %}">3d file</a></p> <p><a href="{% url threed title %}">3d file</a></p>
{% else %} {% else %}
<p><b>No 3d file</b></p> <p><b>No 3d file</b></p>
{% endif %} {% endif %}
<pre> <pre>
LOGMESSAGES LOGMESSAGES
{{logmessage}} {{logmessage}}
</pre> </pre>
{% endif %} {% endif %}
</div> </div>
{% endblock %} {% endblock %}

View File

@ -1,66 +1,66 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load link %} {% load link %}
{% block title %}List of survex files{% endblock %} {% block title %}List of survex files{% endblock %}
{% block content %} {% block content %}
<p><a href="#cdir">caves with subdirectories</a> | <a href="#cmult">caves with multiple files</a> | <a href="#csing">caves with single files</a></p> <p><a href="#cdir">caves with subdirectories</a> | <a href="#cmult">caves with multiple files</a> | <a href="#csing">caves with single files</a></p>
<h3><a href="/survexfile/all.svx">Link to all.svx for processing</a></h3> <h3><a href="/survexfile/all.svx">Link to all.svx for processing</a></h3>
<h2 id="cdir">Caves with subdirectories</h2> <h2 id="cdir">Caves with subdirectories</h2>
{% for subdircave, cavefiles, subsurvdirs in subdircaves %} {% for subdircave, cavefiles, subsurvdirs in subdircaves %}
<h3>{{cavefiles.0.1}} - <a href="{% url survexcavessingle cavefiles.0.1 %}">dates and explorers</a></h3> <h3>{{cavefiles.0.1}} - <a href="{% url survexcavessingle cavefiles.0.1 %}">dates and explorers</a></h3>
<table> <table>
<tr> <tr>
<td><b><a href="{% url svx cavefiles.0.0 %}">{{cavefiles.0.1}}</a></b></td> <td><b><a href="{% url svx cavefiles.0.0 %}">{{cavefiles.0.1}}</a></b></td>
<td> <td>
{% for cavepath, cavename in cavefiles.1 %} {% for cavepath, cavename in cavefiles.1 %}
<a href="{% url svx cavepath %}">{{cavename}}</a> <a href="{% url svx cavepath %}">{{cavename}}</a>
{% endfor %} {% endfor %}
</td> </td>
</tr> </tr>
{% for primarycavefile, subcavefiles in subsurvdirs %} {% for primarycavefile, subcavefiles in subsurvdirs %}
<tr> <tr>
<td><a href="{% url svx primarycavefile.0 %}">{{primarycavefile.1}}</a></td> <td><a href="{% url svx primarycavefile.0 %}">{{primarycavefile.1}}</a></td>
<td> <td>
{% for cavepath, cavename in subcavefiles %} {% for cavepath, cavename in subcavefiles %}
<a href="{% url svx cavepath %}">{{cavename}}</a> <a href="{% url svx cavepath %}">{{cavename}}</a>
{% endfor %} {% endfor %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
{% endfor %} {% endfor %}
<h2 id="cmult">Caves of multiple files</h2> <h2 id="cmult">Caves of multiple files</h2>
<table> <table>
<tr><th>Dates and explorers</th><th>Survex files</th></tr> <tr><th>Dates and explorers</th><th>Survex files</th></tr>
{% for primarycavefile, subcavefiles in multifilecaves %} {% for primarycavefile, subcavefiles in multifilecaves %}
<tr> <tr>
<td> <td>
<a href="{% url survexcavessingle primarycavefile.1 %}">{{primarycavefile.1}}</a> <a href="{% url survexcavessingle primarycavefile.1 %}">{{primarycavefile.1}}</a>
</td> </td>
<td> <td>
<a href="{% url svx primarycavefile.0 %}">{{primarycavefile.1}}</a> - <a href="{% url svx primarycavefile.0 %}">{{primarycavefile.1}}</a> -
{% for cavepath, cavename in subcavefiles %} {% for cavepath, cavename in subcavefiles %}
<a href="{% url svx cavepath %}">{{cavename}}</a> <a href="{% url svx cavepath %}">{{cavename}}</a>
{% endfor %} {% endfor %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
<h2 id="csing">Caves of one file</h2> <h2 id="csing">Caves of one file</h2>
<p> <p>
{% for cavepath, cavename in onefilecaves %} {% for cavepath, cavename in onefilecaves %}
<a href="{% url svx cavepath %}">{{cavename}}</a> <a href="{% url svx cavepath %}">{{cavename}}</a>
{% endfor %} {% endfor %}
</p> </p>
{% endblock %} {% endblock %}

View File

@ -1,18 +1,18 @@
<pre> <pre>
using difflistonly.html using difflistonly.html
{% for diffline in difflist %}{{diffline}} {% for diffline in difflist %}{{diffline}}
{% endfor %} {% endfor %}
</pre> </pre>
{% if logmessage %} {% if logmessage %}
{% if has_3d %} {% if has_3d %}
<p><a href="{% url threed title %}">3d file</a></p> <p><a href="{% url threed title %}">3d file</a></p>
{% else %} {% else %}
<p><b>No 3d file</b></p> <p><b>No 3d file</b></p>
{% endif %} {% endif %}
<pre> <pre>
LOGMESSAGES LOGMESSAGES
{{logmessage}} {{logmessage}}
</pre> </pre>
{% endif %} {% endif %}

View File

@ -1,39 +1,39 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load link %} {% load link %}
{% block title %}Cambridge Expeditions to Austria{% endblock %} {% block title %}Cambridge Expeditions to Austria{% endblock %}
{% block content %} {% block content %}
<h2>Expo member tasks</h2> <h2>Expo member tasks</h2>
<h3>Add new data</h3> <h3>Add new data</h3>
<li><a href="">Upload a photo</a></li> <li><a href="">Upload a photo</a></li>
<li><a href="">Record a new trip</a></li> <li><a href="">Record a new trip</a></li>
<h3>Your unfinished business</h3> <h3>Your unfinished business</h3>
{% for survey in surveys_unfinished %} {% for survey in surveys_unfinished %}
<li>{{survey|link}}</li> <li>{{survey|link}}</li>
{% endfor %} {% endfor %}
<h3>General unfinished business</h3> <h3>General unfinished business</h3>
add wikilinks add wikilinks
<h3>Caving recommendations</h3> <h3>Caving recommendations</h3>
{% for qm in qms_recommended %} {% for qm in qms_recommended %}
<li>{{qm|link}}</li> <li>{{qm|link}}</li>
{% endfor %} {% endfor %}
<h3>Profile tasks</h3> <h3>Profile tasks</h3>
<li>Dates present on expo</li> <li>Dates present on expo</li>
<li>Mugshot</li> <li>Mugshot</li>
<li>Blurb</li> <li>Blurb</li>
{% endblock content %} {% endblock content %}
{% block margins %} {% block margins %}
<img class="leftMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}eieshole.jpg"> <img class="leftMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}eieshole.jpg">
<img class="rightMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}goesser.jpg"> <img class="rightMargin eyeCandy fadeIn" src="{{ settings.MEDIA_URL }}goesser.jpg">
{% endblock margins %} {% endblock margins %}

View File

@ -1,61 +1,61 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% block title %}Cambridge Expeditions to Austria{% endblock %} {% block title %}Cambridge Expeditions to Austria{% endblock %}
{% block content %} {% block content %}
<h2>The unfinished front page</h2> <h2>The unfinished front page</h2>
<ul> <ul>
<li><b>About {{totallogbookentries}} logbook entries have been loaded</b></li> <li><b>About {{totallogbookentries}} logbook entries have been loaded</b></li>
<li><b><a href="{% url personindex %}">List of People</a></b></li> <li><b><a href="{% url personindex %}">List of People</a></b></li>
<li><b><a href="{% url caveindex %}">List of Caves</a></b></li> <li><b><a href="{% url caveindex %}">List of Caves</a></b></li>
<li><a href="{% url jgtfile aaaa %}">JGT list of files</a> (temporary simple file list and tunnel use)</li> <li><a href="{% url jgtfile aaaa %}">JGT list of files</a> (temporary simple file list and tunnel use)</li>
<li><a href="{% url survey %}">Survey files</a></li> <li><a href="{% url survey %}">Survey files</a></li>
<li><a href="{% url survexindex all %}">Survex directory</a></li> <li><a href="{% url survexindex all %}">Survex directory</a></li>
<li><a href="{% url expedition 2008 %}">Expedition 2008</a></li> <li><a href="{% url expedition 2008 %}">Expedition 2008</a></li>
<li><a href="{% url expedition 2007 %}">Expedition 2007</a></li> <li><a href="{% url expedition 2007 %}">Expedition 2007</a></li>
<li><a href="{% url expedition 1993 %}">Expedition 1993</a> (earliest parsed)</li> <li><a href="{% url expedition 1993 %}">Expedition 1993</a> (earliest parsed)</li>
</ul> </ul>
<h2>Further work</h2> <h2>Further work</h2>
<p>Please see the <a href="http://code.google.com/p/troggle/issues/list">issues</a> tracker on google code. You can contribute new feature requests and bug reports.</p> <p>Please see the <a href="http://code.google.com/p/troggle/issues/list">issues</a> tracker on google code. You can contribute new feature requests and bug reports.</p>
<p>Julian's work: <p>Julian's work:
<p>parse 1992-1976 logbooks; (esp top 161)</p> <p>parse 1992-1976 logbooks; (esp top 161)</p>
<p>detect T/U on log entries; </p> <p>detect T/U on log entries; </p>
<p>name matching and spelling in survex files; </p> <p>name matching and spelling in survex files; </p>
<p>Improve logbook wikihtml text</p> <p>Improve logbook wikihtml text</p>
<p>Other work:</p> <p>Other work:</p>
<p>surf through the tunnel sketches and images</p> <p>surf through the tunnel sketches and images</p>
<p>bugs with all.svx block (double dot) <p>bugs with all.svx block (double dot)
<p>render bitmap view of every survex block as a thumbnail</p> <p>render bitmap view of every survex block as a thumbnail</p>
<p>upload tunnel images and tunnel sketches</p> <p>upload tunnel images and tunnel sketches</p>
<p>where are the subcaves; </p> <p>where are the subcaves; </p>
<p>cave section entrance match for logbook entries</p> <p>cave section entrance match for logbook entries</p>
<p>simplify the survex parsing code (if necessary); </p> <p>simplify the survex parsing code (if necessary); </p>
<p>wiki survex stop linegap between comment lins</p> <p>wiki survex stop linegap between comment lins</p>
<p>links between logbooks and survex blocks to cave things; </p> <p>links between logbooks and survex blocks to cave things; </p>
<p>mini-tree of survexblocks; </p> <p>mini-tree of survexblocks; </p>
<p>connect sketches to caves to survey blocks and render thumbnailwise; </p> <p>connect sketches to caves to survey blocks and render thumbnailwise; </p>
<p>all images to start appearing in pages; and so on</p> <p>all images to start appearing in pages; and so on</p>
<h3>{{message}}</h3> <h3>{{message}}</h3>
<form action="" method="GET"> <form action="" method="GET">
<input type="submit" name="reloadexpos" value="Reload Expos"> <input type="submit" name="reloadexpos" value="Reload Expos">
<input type="submit" name="reloadsurvex" value="Reload Survex"> <input type="submit" name="reloadsurvex" value="Reload Survex">
</form> </form>
<ul id="expeditionlist"> <ul id="expeditionlist">
{% for expedition in expeditions %} {% for expedition in expeditions %}
<li> <li>
<a href="{% url expedition expedition.year %}">{{expedition.name}}</a> <a href="{% url expedition expedition.year %}">{{expedition.name}}</a>
- <b>{{expedition.logbookentry_set.count}}</b> logbook entries - <b>{{expedition.logbookentry_set.count}}</b> logbook entries
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endblock %} {% endblock %}

View File

@ -1,43 +1,43 @@
{% extends "base.html" %} {% extends "base.html" %}
{% load wiki_markup %} {% load wiki_markup %}
{% load survex_markup %} {% load survex_markup %}
{% block title %}Tunnel files{% endblock %} {% block title %}Tunnel files{% endblock %}
{% block content %} {% block content %}
<h3>All Tunnel files</h3> <h3>All Tunnel files</h3>
<table> <table>
<tr><th>File</th><th>Font</th><th>SurvexBlocks</th><th>Size</th><th>Paths</th><th>Scans folder</th><th>Scan files</th><th>Frames</th></tr> <tr><th>File</th><th>Font</th><th>SurvexBlocks</th><th>Size</th><th>Paths</th><th>Scans folder</th><th>Scan files</th><th>Frames</th></tr>
{% for tunnelfile in tunnelfiles %} {% for tunnelfile in tunnelfiles %}
<tr> <tr>
<td><a href="{% url tunnelfile tunnelfile.tunnelpath %}">{{tunnelfile.tunnelpath}}</a></td> <td><a href="{% url tunnelfile tunnelfile.tunnelpath %}">{{tunnelfile.tunnelpath}}</a></td>
<td>{{tunnelfile.bfontcolours}}</td> <td>{{tunnelfile.bfontcolours}}</td>
<td></td> <td></td>
<td>{{tunnelfile.filesize}}</td> <td>{{tunnelfile.filesize}}</td>
<td>{{tunnelfile.npaths}}</td> <td>{{tunnelfile.npaths}}</td>
<td> <td>
{% for survexscansfolder in tunnelfile.survexscansfolders.all %} {% for survexscansfolder in tunnelfile.survexscansfolders.all %}
<a href="{{survexscansfolder.get_absolute_url}}">{{survexscansfolder.walletname}}</a> <a href="{{survexscansfolder.get_absolute_url}}">{{survexscansfolder.walletname}}</a>
{% endfor %} {% endfor %}
</td> </td>
<td> <td>
{% for survexscansingle in tunnelfile.survexscans.all %} {% for survexscansingle in tunnelfile.survexscans.all %}
<a href="{{survexscansingle.get_absolute_url}}">{{survexscansingle.name}}</a> <a href="{{survexscansingle.get_absolute_url}}">{{survexscansingle.name}}</a>
{% endfor %} {% endfor %}
</td> </td>
<td> <td>
{% for rtunnelfile in tunnelfile.tunnelcontains.all %} {% for rtunnelfile in tunnelfile.tunnelcontains.all %}
<a href="{% url tunnelfile rtunnelfile.tunnelpath %}">{{rtunnelfile.tunnelpath}}</a> <a href="{% url tunnelfile rtunnelfile.tunnelpath %}">{{rtunnelfile.tunnelpath}}</a>
{% endfor %} {% endfor %}
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
{% endblock %} {% endblock %}