repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
leth/SpecGen
a395e0b13d506966c8db2a48e26fb58acfd6a778
all tests pass again now
diff --git a/run_tests.py b/run_tests.py index cdd4079..92ba2d4 100755 --- a/run_tests.py +++ b/run_tests.py @@ -1,430 +1,455 @@ #!/usr/bin/env python # # Tests for specgen. # # What is this, and how can you help? # # This is the test script for a rewrite of the FOAF spec generation # tool. It uses Pure python rdflib for parsing. That makes it easier to # install than the previous tools which required successful compilation # and installation of Redland and its language bindings (Ruby, Python ...). # # Everything is in public SVN. Ask danbri for an account or password reminder if # you're contributing. # # Code: svn co http://svn.foaf-project.org/foaftown/specgen/ # # Run tests (with verbose flag): # ./run_tests.py -v # # What it does: # The FOAF spec is essentially built from an index.rdf file, plus a collection of per-term *.en HTML fragments. # This filetree includes a copy of the FOAF index.rdf and markup-fragment files (see examples/foaf/ and examples/foaf/doc/). # # Code overview: # # The class Vocab represents a parsed RDF vocabulary. VocabReport represents the spec we're generating from a Vocab. # We can at least load the RDF and poke around it with SPARQL. The ideal target output can be seen by looking at the # current spec, basically we get to a "Version 1.0" when something 99% the same as the current spec can be built using this # toolset, and tested as having done so. # # Rough notes follow: # trying to test using ... # http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html # http://docs.python.org/library/unittest.html # TODO: convert debug print statements to appropriate testing / verbosity logger API # TODO: make frozen snapshots of some more namespace RDF files # TODO: find an idiom for conditional tests, eg. if we have xmllint handy for checking output, or rdfa ... FOAFSNAPSHOT = 'examples/foaf/index-20081211.rdf' # a frozen copy for sanity' sake DOAPSNAPSHOT = 'examples/doap/doap-en.rdf' # maybe we should use dated url / frozen files for all SIOCSNAPSHOT = 'examples/sioc/sioc.rdf' import libvocab from libvocab import Vocab from libvocab import VocabReport from libvocab import Term from libvocab import Class from libvocab import Property from libvocab import SIOC from libvocab import OWL from libvocab import FOAF from libvocab import RDFS from libvocab import RDF from libvocab import DOAP from libvocab import XFN # used in SPARQL queries below bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"owl": OWL, u"doap": DOAP, u"sioc": SIOC, u"foaf": FOAF } import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query import unittest class testSpecgen(unittest.TestCase): """a test class for Specgen""" def setUp(self): """set up data used in the tests. Called before each test function execution.""" def testFOAFns(self): foaf_spec = Vocab(FOAFSNAPSHOT) foaf_spec.index() foaf_spec.uri = FOAF # print "FOAF should be "+FOAF self.assertEqual(str(foaf_spec.uri), 'http://xmlns.com/foaf/0.1/') def testSIOCns(self): sioc_spec = Vocab('examples/sioc/sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) self.assertEqual(sioc_spec.uri, 'http://rdfs.org/sioc/ns#') def testDOAPWrongns(self): doap_spec = Vocab('examples/doap/doap-en.rdf') doap_spec.index() doap_spec.uri = str(DOAP) self.assertNotEqual(doap_spec.uri, 'http://example.com/DELIBERATE_MISTAKE_HERE') def testDOAPns(self): doap_spec = Vocab('examples/doap/doap-en.rdf') doap_spec.index() doap_spec.uri = str(DOAP) self.assertEqual(doap_spec.uri, 'http://usefulinc.com/ns/doap#') #reading list: http://tomayko.com/writings/getters-setters-fuxors def testCanUseNonStrURI(self): """If some fancy object used with a string-oriented setter, we just take the string.""" doap_spec = Vocab('examples/doap/doap-en.rdf') print "[1]" doap_spec.index() doap_spec.uri = Namespace('http://usefulinc.com/ns/doap#') # likely a common mistake self.assertEqual(doap_spec.uri, 'http://usefulinc.com/ns/doap#') def testFOAFminprops(self): """Check we found at least 50 FOAF properties.""" foaf_spec = Vocab('examples/foaf/index-20081211.rdf') foaf_spec.index() foaf_spec.uri = str(FOAF) c = len(foaf_spec.properties) self.failUnless(c > 50 , "FOAF has more than 50 properties. count: "+str(c)) def testFOAFmaxprops(self): - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() c = len(foaf_spec.properties) self.failUnless(c < 100 , "FOAF has less than 100 properties. count: "+str(c)) def testSIOCmaxprops(self): """sioc max props: not more than 500 properties in SIOC""" - sioc_spec = Vocab('examples/sioc/sioc.rdf') + sioc_spec = Vocab(dir='examples/sioc/sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) c = len(sioc_spec.properties) - # print "SIOC property count: ",c + #print "SIOC property count: ",c self.failUnless(c < 500 , "SIOC has less than 500 properties. count was "+str(c)) # work in progress. def testDOAPusingFOAFasExternal(self): """when DOAP mentions a FOAF class, the API should let us know it is external""" - doap_spec = Vocab('examples/doap/doap.rdf') + doap_spec = Vocab(dir='examples/doap/doap.rdf') doap_spec.index() doap_spec.uri = str(DOAP) for t in doap_spec.classes: # print "is class "+t+" external? " # print t.is_external(doap_spec) '' # work in progress. def testFOAFusingDCasExternal(self): """FOAF using external vocabs""" - foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec = Vocab(dir=FOAFSNAPSHOT) foaf_spec.index() foaf_spec.uri = str(FOAF) for t in foaf_spec.terms: # print "is term "+t+" external? ", t.is_external(foaf_spec) '' def testniceName_1foafmyprop(self): """simple test of nicename for a known namespace (FOAF), unknown property""" - foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec = Vocab(dir=FOAFSNAPSHOT) u = 'http://xmlns.com/foaf/0.1/myprop' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'foaf:myprop', "Didn't extract nicename. input is"+u+"output was"+nn) # we test behaviour for real vs fake properties, just in case... def testniceName_2foafhomepage(self): """simple test of nicename for a known namespace (FOAF), known property.""" foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec.index() u = 'http://xmlns.com/foaf/0.1/homepage' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'foaf:homepage', "Didn't extract nicename") def testniceName_3mystery(self): """simple test of nicename for an unknown namespace""" foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec.index() u = 'http:/example.com/mysteryns/myprop' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'http:/example.com/mysteryns/:myprop', "Didn't extract verbose nicename") def testniceName_3baduri(self): """niceName should return same string if passed a non-URI (but log a warning?)""" foaf_spec = Vocab(FOAFSNAPSHOT) + foaf_spec.index() u = 'thisisnotauri' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == u, "niceName didn't return same string when given a non-URI") def test_set_uri_in_constructor(self): """v = Vocab( uri=something ) can be used to set the Vocab's URI. """ u = 'http://example.com/test_set_uri_in_constructor' foaf_spec = Vocab(FOAFSNAPSHOT,uri=u) + foaf_spec.index() self.failUnless( foaf_spec.uri == u, "Vocab's URI was supposed to be "+u+" but was "+foaf_spec.uri) def test_set_bad_uri_in_constructor(self): """v = Vocab( uri=something ) can be used to set the Vocab's URI to a bad URI (but should warn). """ u = 'notauri' foaf_spec = Vocab(FOAFSNAPSHOT,uri=u) + foaf_spec.index() self.failUnless( foaf_spec.uri == u, "Vocab's URI was supposed to be "+u+" but was "+foaf_spec.uri) def test_getset_uri(self): """getting and setting a Vocab uri property""" foaf_spec = Vocab(FOAFSNAPSHOT,uri='http://xmlns.com/foaf/0.1/') + foaf_spec.index() u = 'http://foaf.tv/example#' # print "a) foaf_spec.uri is: ", foaf_spec.uri foaf_spec.uri = u # print "b) foaf_spec.uri is: ", foaf_spec.uri # print self.failUnless( foaf_spec.uri == u, "Failed to change uri.") def test_ns_split(self): from libvocab import ns_split a,b = ns_split('http://example.com/foo/bar/fee') self.failUnless( a=='http://example.com/foo/bar/') self.failUnless( b=='fee') # is this a bad idiom? use AND in a single assertion instead? def test_lookup_Person(self): """find a term given it's uri""" - foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec.index() p = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person') # print "lookup for Person: ",p self.assertNotEqual(p.uri, None, "Couldn't find person class in FOAF") def test_lookup_Wombat(self): """fail to a bogus term given it's uri""" - foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec.index() p = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Wombat') # No Wombats in FOAF yet. self.assertEqual(p, None, "lookup for Wombat should return None") def test_label_for_foaf_Person(self): """check we can get the label for foaf's Person class""" - foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec.index() l = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person').label # print "Label for foaf Person is "+l self.assertEqual(l,"Person") def test_label_for_sioc_Community(self): """check we can get the label for sioc's Community class""" - sioc_spec = Vocab(f=SIOCSNAPSHOT, uri=SIOC) + sioc_spec = Vocab(dir=SIOCSNAPSHOT, uri=SIOC) + sioc_spec.index() l = sioc_spec.lookup(SIOC+'Community').label self.assertEqual(l,"Community") def test_label_for_foaf_workplaceHomepage(self): """check we can get the label for foaf's workplaceHomepage property""" - foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec.index() l = foaf_spec.lookup('http://xmlns.com/foaf/0.1/workplaceHomepage').label # print "Label for foaf workplaceHomepage is "+l self.assertEqual(l,"workplace homepage") def test_status_for_foaf_Person(self): """check we can get the status for foaf's Person class""" - foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') + foaf_spec.index() s = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person').status self.assertEqual(s,"stable") # http://usefulinc.com/ns/doap#Repository def test_status_for_doap_Repository(self): """check we can get the computed 'unknown' status for doap's Repository class""" - doap_spec = Vocab(f=DOAPSNAPSHOT, uri='http://usefulinc.com/ns/doap#') + doap_spec = Vocab(dir=DOAPSNAPSHOT, uri='http://usefulinc.com/ns/doap#') + doap_spec.index() s = doap_spec.lookup('http://usefulinc.com/ns/doap#Repository').status self.assertEqual(s,"unknown", "if vs:term_status isn't used, we set t.status to 'unknown'") def test_reindexing_not_fattening(self): "Indexing on construction and then a couple more times shouldn't affect property count." foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() - foaf_spec.index() c = len(foaf_spec.properties) self.failUnless(c < 100 , "After indexing 3 times, foaf property count should still be < 100: "+str(c)) def test_got_sioc(self): sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) + sioc_spec.index() cr = sioc_spec.lookup('http://rdfs.org/sioc/ns#creator_of') # print("Looked up creator_of in sioc. result: "+cr) # print("Looked up creator_of comment: "+cr.comment) # print "Sioc spec with comment has size: ", len(sioc_spec.properties) def testSIOCminprops(self): """Check we found at least 20 SIOC properties (which means matching OWL properties)""" sioc_spec = Vocab('examples/sioc/sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) c = len(sioc_spec.properties) self.failUnless(c > 20 , "SIOC has more than 20 properties. count was "+str(c)) def testSIOCminprops_v2(self): """Check we found at least 10 SIOC properties.""" - sioc_spec = Vocab(f='examples/sioc/sioc.rdf', uri = SIOC) + sioc_spec = Vocab(dir='examples/sioc/sioc.rdf', uri = SIOC) + sioc_spec.index() c = len(sioc_spec.properties) self.failUnless(c > 10 , "SIOC has more than 10 properties. count was "+str(c)) def testSIOCminprops_v3(self): """Check we found at least 5 SIOC properties.""" - # sioc_spec = Vocab(f='examples/sioc/sioc.rdf', uri = SIOC) - sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) + # sioc_spec = Vocab(dir='examples/sioc/sioc.rdf', uri = SIOC) + sioc_spec = Vocab(dir=SIOCSNAPSHOT, uri = SIOC) + sioc_spec.index() c = len(sioc_spec.properties) self.failUnless(c > 5 , "SIOC has more than 10 properties. count was "+str(c)) def testSIOCmin_classes(self): """Check we found at least 5 SIOC classes.""" - sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) + sioc_spec = Vocab(dir=SIOCSNAPSHOT, uri = SIOC) + sioc_spec.index() c = len(sioc_spec.classes) self.failUnless(c > 5 , "SIOC has more than 10 classes. count was "+str(c)) def testFOAFmin_classes(self): """Check we found at least 5 FOAF classes.""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() c = len(foaf_spec.classes) self.failUnless(c > 5 , "FOAF has more than 10 classes. count was "+str(c)) def testHTMLazlistExists(self): """Check we have some kind of azlist. Note that this shouldn't really be HTML from Vocab API ultimately.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() az = foaf_spec.azlist() # print "AZ list is ", az self.assertNotEqual (az != None, "We should have an azlist.") def testOutputHTML(self): """Check HTML output formatter does something""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() page = VocabReport(foaf_spec) az = page.az() self.failUnless(az) def testGotRDFa(self): """Check HTML output formatter rdfa method returns some text""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() page = VocabReport(foaf_spec) rdfa = page.rdfa() self.failUnless(rdfa) def testTemplateLoader(self): """Check we can load a template file.""" basedir = './examples/' temploc = 'template.html' f = open(basedir + temploc, "r") template = f.read() self.failUnless(template != None) def testTemplateLoader2(self): """Check we can load a template file thru constructors.""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template # print "Page template is: ", tpl self.failUnless(tpl != None) def testTemplateLoader3(self): """Check loaded template isn't default string.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template self.assertNotEqual(tpl, "no template loaded") # TODO: check this fails appropriately: # IOError: [Errno 2] No such file or directory: './examples/nonsuchfile.html' # # def testTemplateLoader4(self): # """Check loaded template isn't default string when using bad filename.""" # foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) # page = VocabReport(foaf_spec, basedir='./examples/', temploc='nonsuchfile.html') # tpl = page.template # self.assertNotEqual(tpl, "no template loaded") def testGenerateReport(self): """Use the template to generate our report page.""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template final = page.generate() rdfa = page.rdfa() self.assertNotEqual(final, "Nope!") def testSimpleReport(self): """Use the template to generate a simple test report in txt.""" - foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) + foaf_spec = Vocab(dir=FOAFSNAPSHOT, uri = FOAF) + foaf_spec.index() page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') simple = page.report() print "Simple report: ", simple self.assertNotEqual(simple, "Nope!") def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(testSpecgen)) return suite if __name__ == '__main__': print "Running tests..." suiteFew = unittest.TestSuite() # Add things we know should pass to a subset suite # (only skip things we have explained with a todo) # ##libby suiteFew.addTest(testSpecgen("testFOAFns")) ##libby suiteFew.addTest(testSpecgen("testSIOCns")) suiteFew.addTest(testSpecgen("testDOAPns")) # suiteFew.addTest(testSpecgen("testCanUseNonStrURI")) # todo: ensure .uri etc can't be non-str suiteFew.addTest(testSpecgen("testFOAFminprops")) # suiteFew.addTest(testSpecgen("testSIOCminprops")) # todo: improve .index() to read more OWL vocab suiteFew.addTest(testSpecgen("testSIOCmaxprops")) # run tests we expect to pass: # unittest.TextTestRunner(verbosity=2).run(suiteFew) # run tests that should eventually pass: # unittest.TextTestRunner(verbosity=2).run(suite()) # # or we can run everything: # http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html g = foafspec.graph #q= 'SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = owl:ObjectProperty || ?type = owl:DatatypeProperty || ?type = rdf:Property || ?type = owl:FunctionalProperty || ?type = owl:InverseFunctionalProperty) } ' #query = Parse(q) #relations = g.query(query, initNs=bindings) #for (term, label, comment) in relations: # p = Property(term) # print "property: "+str(p) + "label: "+str(label)+ " comment: "+comment if __name__ == '__main__': unittest.main()
leth/SpecGen
75413f76e64a32666f9cc4d8833334507da6a0c0
fixed one test anyway
diff --git a/libvocab.py b/libvocab.py index 1189dc2..23081f3 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,729 +1,732 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path import cgi import operator bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir - self.filename = os.path.join(dir, f) + if not dir: + self.filename = os.path.join(dir, f) + else: + self.filename = dir self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos", "http://purl.org/NET/c4dm/event.owl#" : "event" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) self.terms.sort(key=operator.attrgetter('id')) self.classes.sort(key=operator.attrgetter('id')) self.properties.sort(key=operator.attrgetter('id')) # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: #print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" def codelink(self, s): reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" queries = '' c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#term_%s">permalink</a>] [<a href="#queries_%s">validation queries</a>] [<a href="#glance">back to top</a>]</p> <br/> </div>""" # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<a href="#term_%s">%s</a>\n""" % (dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<a href="#term_%s">%s</a>\n""" % (ran.id, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, sub.id, label) # tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: sub = Term(subclass) ss = """<a href="#term_%s">%s</a>\n""" % (sub.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo5 = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' #queries filename = os.path.join(dn, term.id+".sparql") ss = '' try: f = open ( filename, "r") ss = f.read() ss = "<h4><a name=\"queries_"+term.id+"\"></a>"+term.id+" Validation Query</h4><pre>"+cgi.escape(ss)+"</pre>" except: ss='' queries = queries +"\n"+ ss # s = s+"\n"+ss sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s,term.id, term.id) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: dom = Term(domain) ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, dom.id, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ran = Term(range) ss = """<span rel="rdfs:range" href="%s"<a href="#term_%s">%s</a></span>\n""" % (range, ran.id, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # inverse functional property foo5 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" foo5 = "%s <td> %s </td></tr>" % (sss, ss) # functonal property diff --git a/run_tests.py b/run_tests.py index 6f99631..cdd4079 100755 --- a/run_tests.py +++ b/run_tests.py @@ -1,429 +1,430 @@ #!/usr/bin/env python # # Tests for specgen. # # What is this, and how can you help? # # This is the test script for a rewrite of the FOAF spec generation # tool. It uses Pure python rdflib for parsing. That makes it easier to # install than the previous tools which required successful compilation # and installation of Redland and its language bindings (Ruby, Python ...). # # Everything is in public SVN. Ask danbri for an account or password reminder if # you're contributing. # # Code: svn co http://svn.foaf-project.org/foaftown/specgen/ # # Run tests (with verbose flag): # ./run_tests.py -v # # What it does: # The FOAF spec is essentially built from an index.rdf file, plus a collection of per-term *.en HTML fragments. # This filetree includes a copy of the FOAF index.rdf and markup-fragment files (see examples/foaf/ and examples/foaf/doc/). # # Code overview: # # The class Vocab represents a parsed RDF vocabulary. VocabReport represents the spec we're generating from a Vocab. # We can at least load the RDF and poke around it with SPARQL. The ideal target output can be seen by looking at the # current spec, basically we get to a "Version 1.0" when something 99% the same as the current spec can be built using this # toolset, and tested as having done so. # # Rough notes follow: # trying to test using ... # http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html # http://docs.python.org/library/unittest.html # TODO: convert debug print statements to appropriate testing / verbosity logger API # TODO: make frozen snapshots of some more namespace RDF files # TODO: find an idiom for conditional tests, eg. if we have xmllint handy for checking output, or rdfa ... FOAFSNAPSHOT = 'examples/foaf/index-20081211.rdf' # a frozen copy for sanity' sake DOAPSNAPSHOT = 'examples/doap/doap-en.rdf' # maybe we should use dated url / frozen files for all SIOCSNAPSHOT = 'examples/sioc/sioc.rdf' import libvocab from libvocab import Vocab from libvocab import VocabReport from libvocab import Term from libvocab import Class from libvocab import Property from libvocab import SIOC from libvocab import OWL from libvocab import FOAF from libvocab import RDFS from libvocab import RDF from libvocab import DOAP from libvocab import XFN # used in SPARQL queries below bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"owl": OWL, u"doap": DOAP, u"sioc": SIOC, u"foaf": FOAF } import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query import unittest class testSpecgen(unittest.TestCase): """a test class for Specgen""" def setUp(self): """set up data used in the tests. Called before each test function execution.""" def testFOAFns(self): foaf_spec = Vocab(FOAFSNAPSHOT) foaf_spec.index() foaf_spec.uri = FOAF # print "FOAF should be "+FOAF self.assertEqual(str(foaf_spec.uri), 'http://xmlns.com/foaf/0.1/') def testSIOCns(self): sioc_spec = Vocab('examples/sioc/sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) self.assertEqual(sioc_spec.uri, 'http://rdfs.org/sioc/ns#') def testDOAPWrongns(self): doap_spec = Vocab('examples/doap/doap-en.rdf') doap_spec.index() doap_spec.uri = str(DOAP) self.assertNotEqual(doap_spec.uri, 'http://example.com/DELIBERATE_MISTAKE_HERE') def testDOAPns(self): doap_spec = Vocab('examples/doap/doap-en.rdf') doap_spec.index() doap_spec.uri = str(DOAP) self.assertEqual(doap_spec.uri, 'http://usefulinc.com/ns/doap#') #reading list: http://tomayko.com/writings/getters-setters-fuxors def testCanUseNonStrURI(self): """If some fancy object used with a string-oriented setter, we just take the string.""" doap_spec = Vocab('examples/doap/doap-en.rdf') + print "[1]" doap_spec.index() doap_spec.uri = Namespace('http://usefulinc.com/ns/doap#') # likely a common mistake self.assertEqual(doap_spec.uri, 'http://usefulinc.com/ns/doap#') def testFOAFminprops(self): """Check we found at least 50 FOAF properties.""" foaf_spec = Vocab('examples/foaf/index-20081211.rdf') foaf_spec.index() foaf_spec.uri = str(FOAF) c = len(foaf_spec.properties) self.failUnless(c > 50 , "FOAF has more than 50 properties. count: "+str(c)) def testFOAFmaxprops(self): foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) c = len(foaf_spec.properties) self.failUnless(c < 100 , "FOAF has less than 100 properties. count: "+str(c)) def testSIOCmaxprops(self): """sioc max props: not more than 500 properties in SIOC""" sioc_spec = Vocab('examples/sioc/sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) c = len(sioc_spec.properties) # print "SIOC property count: ",c self.failUnless(c < 500 , "SIOC has less than 500 properties. count was "+str(c)) # work in progress. def testDOAPusingFOAFasExternal(self): """when DOAP mentions a FOAF class, the API should let us know it is external""" doap_spec = Vocab('examples/doap/doap.rdf') doap_spec.index() doap_spec.uri = str(DOAP) for t in doap_spec.classes: # print "is class "+t+" external? " # print t.is_external(doap_spec) '' # work in progress. def testFOAFusingDCasExternal(self): """FOAF using external vocabs""" foaf_spec = Vocab(FOAFSNAPSHOT) foaf_spec.index() foaf_spec.uri = str(FOAF) for t in foaf_spec.terms: # print "is term "+t+" external? ", t.is_external(foaf_spec) '' def testniceName_1foafmyprop(self): """simple test of nicename for a known namespace (FOAF), unknown property""" foaf_spec = Vocab(FOAFSNAPSHOT) u = 'http://xmlns.com/foaf/0.1/myprop' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'foaf:myprop', "Didn't extract nicename. input is"+u+"output was"+nn) # we test behaviour for real vs fake properties, just in case... def testniceName_2foafhomepage(self): """simple test of nicename for a known namespace (FOAF), known property.""" foaf_spec = Vocab(FOAFSNAPSHOT) u = 'http://xmlns.com/foaf/0.1/homepage' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'foaf:homepage', "Didn't extract nicename") def testniceName_3mystery(self): """simple test of nicename for an unknown namespace""" foaf_spec = Vocab(FOAFSNAPSHOT) u = 'http:/example.com/mysteryns/myprop' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == 'http:/example.com/mysteryns/:myprop', "Didn't extract verbose nicename") def testniceName_3baduri(self): """niceName should return same string if passed a non-URI (but log a warning?)""" foaf_spec = Vocab(FOAFSNAPSHOT) u = 'thisisnotauri' nn = foaf_spec.niceName(u) # print "nicename for ",u," is: ",nn self.failUnless(nn == u, "niceName didn't return same string when given a non-URI") def test_set_uri_in_constructor(self): """v = Vocab( uri=something ) can be used to set the Vocab's URI. """ u = 'http://example.com/test_set_uri_in_constructor' foaf_spec = Vocab(FOAFSNAPSHOT,uri=u) self.failUnless( foaf_spec.uri == u, "Vocab's URI was supposed to be "+u+" but was "+foaf_spec.uri) def test_set_bad_uri_in_constructor(self): """v = Vocab( uri=something ) can be used to set the Vocab's URI to a bad URI (but should warn). """ u = 'notauri' foaf_spec = Vocab(FOAFSNAPSHOT,uri=u) self.failUnless( foaf_spec.uri == u, "Vocab's URI was supposed to be "+u+" but was "+foaf_spec.uri) def test_getset_uri(self): """getting and setting a Vocab uri property""" foaf_spec = Vocab(FOAFSNAPSHOT,uri='http://xmlns.com/foaf/0.1/') u = 'http://foaf.tv/example#' # print "a) foaf_spec.uri is: ", foaf_spec.uri foaf_spec.uri = u # print "b) foaf_spec.uri is: ", foaf_spec.uri # print self.failUnless( foaf_spec.uri == u, "Failed to change uri.") def test_ns_split(self): from libvocab import ns_split a,b = ns_split('http://example.com/foo/bar/fee') self.failUnless( a=='http://example.com/foo/bar/') self.failUnless( b=='fee') # is this a bad idiom? use AND in a single assertion instead? def test_lookup_Person(self): """find a term given it's uri""" foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') p = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person') # print "lookup for Person: ",p self.assertNotEqual(p.uri, None, "Couldn't find person class in FOAF") def test_lookup_Wombat(self): """fail to a bogus term given it's uri""" foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') p = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Wombat') # No Wombats in FOAF yet. self.assertEqual(p, None, "lookup for Wombat should return None") def test_label_for_foaf_Person(self): """check we can get the label for foaf's Person class""" foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') l = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person').label # print "Label for foaf Person is "+l self.assertEqual(l,"Person") def test_label_for_sioc_Community(self): """check we can get the label for sioc's Community class""" sioc_spec = Vocab(f=SIOCSNAPSHOT, uri=SIOC) l = sioc_spec.lookup(SIOC+'Community').label self.assertEqual(l,"Community") def test_label_for_foaf_workplaceHomepage(self): """check we can get the label for foaf's workplaceHomepage property""" foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') l = foaf_spec.lookup('http://xmlns.com/foaf/0.1/workplaceHomepage').label # print "Label for foaf workplaceHomepage is "+l self.assertEqual(l,"workplace homepage") def test_status_for_foaf_Person(self): """check we can get the status for foaf's Person class""" foaf_spec = Vocab(f=FOAFSNAPSHOT, uri='http://xmlns.com/foaf/0.1/') s = foaf_spec.lookup('http://xmlns.com/foaf/0.1/Person').status self.assertEqual(s,"stable") # http://usefulinc.com/ns/doap#Repository def test_status_for_doap_Repository(self): """check we can get the computed 'unknown' status for doap's Repository class""" doap_spec = Vocab(f=DOAPSNAPSHOT, uri='http://usefulinc.com/ns/doap#') s = doap_spec.lookup('http://usefulinc.com/ns/doap#Repository').status self.assertEqual(s,"unknown", "if vs:term_status isn't used, we set t.status to 'unknown'") def test_reindexing_not_fattening(self): "Indexing on construction and then a couple more times shouldn't affect property count." foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) foaf_spec.index() foaf_spec.index() c = len(foaf_spec.properties) self.failUnless(c < 100 , "After indexing 3 times, foaf property count should still be < 100: "+str(c)) def test_got_sioc(self): sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) cr = sioc_spec.lookup('http://rdfs.org/sioc/ns#creator_of') # print("Looked up creator_of in sioc. result: "+cr) # print("Looked up creator_of comment: "+cr.comment) # print "Sioc spec with comment has size: ", len(sioc_spec.properties) def testSIOCminprops(self): """Check we found at least 20 SIOC properties (which means matching OWL properties)""" sioc_spec = Vocab('examples/sioc/sioc.rdf') sioc_spec.index() sioc_spec.uri = str(SIOC) c = len(sioc_spec.properties) self.failUnless(c > 20 , "SIOC has more than 20 properties. count was "+str(c)) def testSIOCminprops_v2(self): """Check we found at least 10 SIOC properties.""" sioc_spec = Vocab(f='examples/sioc/sioc.rdf', uri = SIOC) c = len(sioc_spec.properties) self.failUnless(c > 10 , "SIOC has more than 10 properties. count was "+str(c)) def testSIOCminprops_v3(self): """Check we found at least 5 SIOC properties.""" # sioc_spec = Vocab(f='examples/sioc/sioc.rdf', uri = SIOC) sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) c = len(sioc_spec.properties) self.failUnless(c > 5 , "SIOC has more than 10 properties. count was "+str(c)) def testSIOCmin_classes(self): """Check we found at least 5 SIOC classes.""" sioc_spec = Vocab(SIOCSNAPSHOT, uri = SIOC) c = len(sioc_spec.classes) self.failUnless(c > 5 , "SIOC has more than 10 classes. count was "+str(c)) def testFOAFmin_classes(self): """Check we found at least 5 FOAF classes.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) c = len(foaf_spec.classes) self.failUnless(c > 5 , "FOAF has more than 10 classes. count was "+str(c)) def testHTMLazlistExists(self): """Check we have some kind of azlist. Note that this shouldn't really be HTML from Vocab API ultimately.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) az = foaf_spec.azlist() # print "AZ list is ", az self.assertNotEqual (az != None, "We should have an azlist.") def testOutputHTML(self): """Check HTML output formatter does something""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) page = VocabReport(foaf_spec) az = page.az() self.failUnless(az) def testGotRDFa(self): """Check HTML output formatter rdfa method returns some text""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) page = VocabReport(foaf_spec) rdfa = page.rdfa() self.failUnless(rdfa) def testTemplateLoader(self): """Check we can load a template file.""" basedir = './examples/' temploc = 'template.html' f = open(basedir + temploc, "r") template = f.read() self.failUnless(template != None) def testTemplateLoader2(self): """Check we can load a template file thru constructors.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template # print "Page template is: ", tpl self.failUnless(tpl != None) def testTemplateLoader3(self): """Check loaded template isn't default string.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template self.assertNotEqual(tpl, "no template loaded") # TODO: check this fails appropriately: # IOError: [Errno 2] No such file or directory: './examples/nonsuchfile.html' # # def testTemplateLoader4(self): # """Check loaded template isn't default string when using bad filename.""" # foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) # page = VocabReport(foaf_spec, basedir='./examples/', temploc='nonsuchfile.html') # tpl = page.template # self.assertNotEqual(tpl, "no template loaded") def testGenerateReport(self): """Use the template to generate our report page.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') tpl = page.template final = page.generate() rdfa = page.rdfa() self.assertNotEqual(final, "Nope!") def testSimpleReport(self): """Use the template to generate a simple test report in txt.""" foaf_spec = Vocab(FOAFSNAPSHOT, uri = FOAF) page = VocabReport(foaf_spec, basedir='./examples/', temploc='template.html') simple = page.report() print "Simple report: ", simple self.assertNotEqual(simple, "Nope!") def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(testSpecgen)) return suite if __name__ == '__main__': print "Running tests..." suiteFew = unittest.TestSuite() # Add things we know should pass to a subset suite # (only skip things we have explained with a todo) # ##libby suiteFew.addTest(testSpecgen("testFOAFns")) ##libby suiteFew.addTest(testSpecgen("testSIOCns")) suiteFew.addTest(testSpecgen("testDOAPns")) # suiteFew.addTest(testSpecgen("testCanUseNonStrURI")) # todo: ensure .uri etc can't be non-str suiteFew.addTest(testSpecgen("testFOAFminprops")) # suiteFew.addTest(testSpecgen("testSIOCminprops")) # todo: improve .index() to read more OWL vocab suiteFew.addTest(testSpecgen("testSIOCmaxprops")) # run tests we expect to pass: # unittest.TextTestRunner(verbosity=2).run(suiteFew) # run tests that should eventually pass: # unittest.TextTestRunner(verbosity=2).run(suite()) # # or we can run everything: # http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html g = foafspec.graph #q= 'SELECT ?x ?l ?c ?type WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = owl:ObjectProperty || ?type = owl:DatatypeProperty || ?type = rdf:Property || ?type = owl:FunctionalProperty || ?type = owl:InverseFunctionalProperty) } ' #query = Parse(q) #relations = g.query(query, initNs=bindings) #for (term, label, comment) in relations: # p = Property(term) # print "property: "+str(p) + "label: "+str(label)+ " comment: "+comment if __name__ == '__main__': unittest.main()
leth/SpecGen
20cb9a230a0e52e3e1690a0c09d6e878bf1f6d33
example VU events ontology
diff --git a/examples/vuevents/_tmp_spec.html b/examples/vuevents/_tmp_spec.html new file mode 100644 index 0000000..4a790cd --- /dev/null +++ b/examples/vuevents/_tmp_spec.html @@ -0,0 +1,519 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" + xmlns:owl="http://www.w3.org/2002/07/owl#" + xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#" + xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:wot="http://xmlns.com/wot/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:ao="http://purl.org/ontology/ao/" +> +<head> + <head> + <link type="text/css" rel="stylesheet" href="style/programmes.css"> + </head> + <body> + <h2 id="glance">VU Events at a glance</h2> + + <div class="azlist"> +<p>Classes: | <a href="#term_Actor">Actor</a> | <a href="#term_ActorType">ActorType</a> | <a href="#term_Event">Event</a> | <a href="#term_EventType">EventType</a> | <a href="#term_Object">Object</a> | <a href="#term_ObjectType">ObjectType</a> | <a href="#term_Place">Place</a> | <a href="#term_PlaceType">PlaceType</a> | <a href="#term_Role">Role</a> | <a href="#term_RoleType">RoleType</a> | <a href="#term_TimeStampedEntity">TimeStampedEntity</a> | <a href="#term_Type">Type</a> | +</p> +<p>Properties: | <a href="#term_actorType">actorType</a> | <a href="#term_beginsAt">beginsAt</a> | <a href="#term_beginsInPlace">beginsInPlace</a> | <a href="#term_childOfType">childOfType</a> | <a href="#term_directPartOfEvent">directPartOfEvent</a> | <a href="#term_directPartOfPlace">directPartOfPlace</a> | <a href="#term_endsAt">endsAt</a> | <a href="#term_endsInPlace">endsInPlace</a> | <a href="#term_eventType">eventType</a> | <a href="#term_hasPart">hasPart</a> | <a href="#term_hasRole">hasRole</a> | <a href="#term_hasType">hasType</a> | <a href="#term_involvedIn">involvedIn</a> | <a href="#term_involves">involves</a> | <a href="#term_objectInPlace">objectInPlace</a> | <a href="#term_objectType">objectType</a> | <a href="#term_parentOfType">parentOfType</a> | <a href="#term_partOf">partOf</a> | <a href="#term_partOfDirect">partOfDirect</a> | <a href="#term_partOfEvent">partOfEvent</a> | <a href="#term_partOfPlace">partOfPlace</a> | <a href="#term_participatesIn">participatesIn</a> | <a href="#term_participatesInAsRole">participatesInAsRole</a> | <a href="#term_placeType">placeType</a> | <a href="#term_roleInPlace">roleInPlace</a> | <a href="#term_roleType">roleType</a> | <a href="#term_takesPlaceIn">takesPlaceIn</a> | <a href="#term_timeStampedAt">timeStampedAt</a> | +</p> +</div> + + <div class="termlist"><h3>Classes and Properties (full detail)</h3> +<div class='termdetails'><br /> + + <div class="specterm" id="term_Actor" about="http://semanticweb.cs.vu.nl/2009/04/event/Actor" typeof="rdfs:Class"> + <h3>Class: event:Actor</h3> + <em>Actor</em> - A thing, animate or inanimate, physical or non-physical, that plays a part in an "Event". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity"><a href="#term_TimeStampedEntity">Time-stamped entity</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Actor">permalink</a>] [<a href="#queries_Actor">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_ActorType" about="http://semanticweb.cs.vu.nl/2009/04/event/ActorType" typeof="rdfs:Class"> + <h3>Class: event:ActorType</h3> + <em>Actor type</em> - an "actorType" is a non-mandatory definition of an intrinsic type, inherent to the "Actor" him/her/itself, and not to his/her/its "Role": an "Actor" can be Caucasian, independently from the role that he or she has in a certain time span of his/her life. Specifying an "ActorType" is not mandatory but recommended. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/Type"><a href="#term_Type">Types</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_ActorType">permalink</a>] [<a href="#queries_ActorType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Event" about="http://semanticweb.cs.vu.nl/2009/04/event/Event" typeof="rdfs:Class"> + <h3>Class: event:Event</h3> + <em>Event</em> - Something significant that happens at a specified place and time; the semantics of what this event is should be defined as an "Event Type", enabling multiple (possibly external) hierarchies of events. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity"><a href="#term_TimeStampedEntity">Time-stamped entity</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Event">permalink</a>] [<a href="#queries_Event">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_EventType" about="http://semanticweb.cs.vu.nl/2009/04/event/EventType" typeof="rdfs:Class"> + <h3>Class: event:EventType</h3> + <em>Event type</em> - "eventType"s can be the Storming of the Bastille, an auction, a ship entering a harbor or The Birth of Venus. Specifying an "EventType" is not mandatory but recommended. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/Type"><a href="#term_Type">Types</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_EventType">permalink</a>] [<a href="#queries_EventType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Object" about="http://semanticweb.cs.vu.nl/2009/04/event/Object" typeof="rdfs:Class"> + <h3>Class: event:Object</h3> + <em>Object</em> - A thing, animate or inaminate, that is a relevant instrument of an "Event" but does not play a role per se. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity"><a href="#term_TimeStampedEntity">Time-stamped entity</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Object">permalink</a>] [<a href="#queries_Object">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_ObjectType" about="http://semanticweb.cs.vu.nl/2009/04/event/ObjectType" typeof="rdfs:Class"> + <h3>Class: event:ObjectType</h3> + <em>Object type</em> - an "ObjectType" can be a crown, a ritual sword, a container ship etc. Specifying an "ObjectType" is not mandatory but recommended. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/Type"><a href="#term_Type">Types</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_ObjectType">permalink</a>] [<a href="#queries_ObjectType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Place" about="http://semanticweb.cs.vu.nl/2009/04/event/Place" typeof="rdfs:Class"> + <h3>Class: event:Place</h3> + <em>Place</em> - A physical or non-physical (or even mythical) location where "Event"s can take place and where "Role"s can be played. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity"><a href="#term_TimeStampedEntity">Time-stamped entity</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Place">permalink</a>] [<a href="#queries_Place">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_PlaceType" about="http://semanticweb.cs.vu.nl/2009/04/event/PlaceType" typeof="rdfs:Class"> + <h3>Class: event:PlaceType</h3> + <em>Place type</em> - a "PlaceType" can be a Place of Interest, countries, geo-spatial areas like a forest or points defined by geo-coordinates. Hence, the "PlaceType"s can be defined externally and independently from the Core VUevent Model. Specifying a "PlaceType" is not mandatory but recommended. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/Type"><a href="#term_Type">Types</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_PlaceType">permalink</a>] [<a href="#queries_PlaceType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Role" about="http://semanticweb.cs.vu.nl/2009/04/event/Role" typeof="rdfs:Class"> + <h3>Class: event:Role</h3> + <em>Role</em> - A "Role" specifies the temporal boundary of an "Actor"'s "RoleType". For example, Napoleon Bonaparte was only Emperor for a specific part of his life. The specification of a "Role" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity"><a href="#term_TimeStampedEntity">Time-stamped entity</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Role">permalink</a>] [<a href="#queries_Role">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_RoleType" about="http://semanticweb.cs.vu.nl/2009/04/event/RoleType" typeof="rdfs:Class"> + <h3>Class: event:RoleType</h3> + <em>Role type</em> - The semantic definition of the "Role" that an "Acctor" is plating in a certain "Event": Emperor, King, Pirate, Painter, NGO, Nation etc. Specifying an "RoleType" is not mandatory but recommended. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://semanticweb.cs.vu.nl/2009/04/event/Type"><a href="#term_Type">Types</a></span> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_RoleType">permalink</a>] [<a href="#queries_RoleType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_TimeStampedEntity" about="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity" typeof="rdfs:Class"> + <h3>Class: event:TimeStampedEntity</h3> + <em>Time-stamped entity</em> - This can be anything, physical, or non-physical, an object, or a process, as long as it has a specified time where it exists. Instances of this class have a denotated time. For example, a range of time that "beginsAt" a certain moment and "endsAt" a certain moment. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>has subclass</th> + <td> <a href="#term_Actor">Actor</a> + <a href="#term_Place">Place</a> + <a href="#term_Event">Event</a> + <a href="#term_Object">Object</a> + <a href="#term_Role">Role</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_TimeStampedEntity">permalink</a>] [<a href="#queries_TimeStampedEntity">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Type" about="http://semanticweb.cs.vu.nl/2009/04/event/Type" typeof="rdfs:Class"> + <h3>Class: event:Type</h3> + <em>Types</em> - Non time-stamped specified types of "Event"s, "Actor"s, "Object"s, "Place"s, etc. Specifying a "Type" is not mandatory but recommended. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + <tr><th>has subclass</th> + <td> <a href="#term_ActorType">Actor type</a> + <a href="#term_EventType">Event type</a> + <a href="#term_ObjectType">Object type</a> + <a href="#term_PlaceType">Place type</a> + <a href="#term_RoleType">Role type</a> + </td></tr> + </table> + + <p style="float: right; font-size: small;">[<a href="#term_Type">permalink</a>] [<a href="#queries_Type">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_roleInPlace" about="http://semanticweb.cs.vu.nl/2009/04/event/roleInPlace" typeof="rdf:Property"> + <h3>Property: event:roleInPlace</h3> + <em>Role played in Event in Place</em> - A "Role" can be directly linked to a "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_roleInPlace">permalink</a>] [<a href="#queries_roleInPlace">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_takesPlaceIn" about="http://semanticweb.cs.vu.nl/2009/04/event/takesPlaceIn" typeof="rdf:Property"> + <h3>Property: event:takesPlaceIn</h3> + <em>takes place in</em> - An "Event" "takesPlaceIn" a "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_takesPlaceIn">permalink</a>] [<a href="#queries_takesPlaceIn">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_childOfType" about="http://semanticweb.cs.vu.nl/2009/04/event/childOfType" typeof="rdf:Property"> + <h3>Property: event:childOfType</h3> + <em>child of type</em> - The "childOfType" property states that all entities of the child's "Type" are also of this "Type". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_childOfType">permalink</a>] [<a href="#queries_childOfType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_directPartOfPlace" about="http://semanticweb.cs.vu.nl/2009/04/event/directPartOfPlace" typeof="rdf:Property"> + <h3>Property: event:directPartOfPlace</h3> + <em>direct part of place</em> - "Place"s can be a "directPartOf" an other "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_directPartOfPlace">permalink</a>] [<a href="#queries_directPartOfPlace">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_parentOfType" about="http://semanticweb.cs.vu.nl/2009/04/event/parentOfType" typeof="rdf:Property"> + <h3>Property: event:parentOfType</h3> + <em>parent of type</em> - The "parentOfType" property states that all entities of that "Type" are also of the parent's "Type". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_parentOfType">permalink</a>] [<a href="#queries_parentOfType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_participatesIn" about="http://semanticweb.cs.vu.nl/2009/04/event/participatesIn" typeof="rdf:Property"> + <h3>Property: event:participatesIn</h3> + <em>participates in</em> - An "Actor" "participatesIn" an "Event". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_participatesIn">permalink</a>] [<a href="#queries_participatesIn">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_objectType" about="http://semanticweb.cs.vu.nl/2009/04/event/objectType" typeof="rdf:Property"> + <h3>Property: event:objectType</h3> + <em>has object type</em> - The "Type" of an "Object". For example, "crown", or "book". Specifically, a passive object, not an "Actor". The specification of a "Type" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_objectType">permalink</a>] [<a href="#queries_objectType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_placeType" about="http://semanticweb.cs.vu.nl/2009/04/event/placeType" typeof="rdf:Property"> + <h3>Property: event:placeType</h3> + <em>has place type</em> - The "Type" of a "Place". For example, "The Dutch coast"; "A city". The specification of a "Type" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_placeType">permalink</a>] [<a href="#queries_placeType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_objectInPlace" about="http://semanticweb.cs.vu.nl/2009/04/event/objectInPlace" typeof="rdf:Property"> + <h3>Property: event:objectInPlace</h3> + <em>Object involved in Event in Place</em> - An "Object" can be directly linked to a "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_objectInPlace">permalink</a>] [<a href="#queries_objectInPlace">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_hasType" about="http://semanticweb.cs.vu.nl/2009/04/event/hasType" typeof="rdf:Property"> + <h3>Property: event:hasType</h3> + <em>has type</em> - this property enables to make the distinction between a 'global' type, like "Role", and domain-specific types, like Pope, King, Pirate, Painter, NGO etc. For the users who do not wish to make this distinction, the type of the different classes of teh model can be specified directly with the rdf:type property. The specification of a "Type" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_hasType">permalink</a>] [<a href="#queries_hasType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_partOfEvent" about="http://semanticweb.cs.vu.nl/2009/04/event/partOfEvent" typeof="rdf:Property"> + <h3>Property: event:partOfEvent</h3> + <em>part of event</em> - "Event"s can be "partOf" an other "Event". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_partOfEvent">permalink</a>] [<a href="#queries_partOfEvent">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_hasRole" about="http://semanticweb.cs.vu.nl/2009/04/event/hasRole" typeof="rdf:Property"> + <h3>Property: event:hasRole</h3> + <em>has role</em> - An "Actor", "Object" and a "Place" can assume a "Role". It is a recommended practice to specify which "Role" they play when participating in the "Event" . <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_hasRole">permalink</a>] [<a href="#queries_hasRole">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_beginsAt" about="http://semanticweb.cs.vu.nl/2009/04/event/beginsAt" typeof="rdf:Property"> + <h3>Property: event:beginsAt</h3> + <em>begins at</em> - The moment at which a "TimeStamp" starts. In case of a point in time, the value of this property should be equivalent to the "endsAt" value. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_beginsAt">permalink</a>] [<a href="#queries_beginsAt">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_directPartOfEvent" about="http://semanticweb.cs.vu.nl/2009/04/event/directPartOfEvent" typeof="rdf:Property"> + <h3>Property: event:directPartOfEvent</h3> + <em>direct part of event</em> - "Event"s can be a "directPartOf" an other "Event". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_directPartOfEvent">permalink</a>] [<a href="#queries_directPartOfEvent">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_beginsInPlace" about="http://semanticweb.cs.vu.nl/2009/04/event/beginsInPlace" typeof="rdf:Property"> + <h3>Property: event:beginsInPlace</h3> + <em>begins in place</em> - An "Event" starts at a certain "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_beginsInPlace">permalink</a>] [<a href="#queries_beginsInPlace">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_participatesInAsRole" about="http://semanticweb.cs.vu.nl/2009/04/event/participatesInAsRole" typeof="rdf:Property"> + <h3>Property: event:participatesInAsRole</h3> + <em>participates in as role</em> - An "Actor" "participatesIn" an "Event" within the context of a certain "Role". The specification of a "Role" is not mandatory but a highly recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_participatesInAsRole">permalink</a>] [<a href="#queries_participatesInAsRole">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_partOfDirect" about="http://semanticweb.cs.vu.nl/2009/04/event/partOfDirect" typeof="rdf:Property"> + <h3>Property: event:partOfDirect</h3> + <em>part of direct</em> - "TimeStampedEntiti"es can be directecly related to others with the "partOf" property. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_partOfDirect">permalink</a>] [<a href="#queries_partOfDirect">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_involvedIn" about="http://semanticweb.cs.vu.nl/2009/04/event/involvedIn" typeof="rdf:Property"> + <h3>Property: event:involvedIn</h3> + <em>involved in</em> - "Object"s are "involvedIn" an "Event". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_involvedIn">permalink</a>] [<a href="#queries_involvedIn">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_timeStampedAt" about="http://semanticweb.cs.vu.nl/2009/04/event/timeStampedAt" typeof="rdf:Property"> + <h3>Property: event:timeStampedAt</h3> + <em>time stamped at</em> - A property to specify the time of a TimeStampedEntity. The type of the values is not specified, but could be a TIMEX string. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_timeStampedAt">permalink</a>] [<a href="#queries_timeStampedAt">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_eventType" about="http://semanticweb.cs.vu.nl/2009/04/event/eventType" typeof="rdf:Property"> + <h3>Property: event:eventType</h3> + <em>has event type</em> - The "Type" of an "Event". For example, "The coronation of Napoleon"; "A ship anchoring"; "A specimen being observed"; or a news event, like "The fall of the Berlin wall". The specification of a "Type" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_eventType">permalink</a>] [<a href="#queries_eventType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_roleType" about="http://semanticweb.cs.vu.nl/2009/04/event/roleType" typeof="rdf:Property"> + <h3>Property: event:roleType</h3> + <em>has role type</em> - The "Type" of a "Role". For example, "captain", "painter", or "instigator", "ritual object", "capital" for a city, etc. The specification of a "Type" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_roleType">permalink</a>] [<a href="#queries_roleType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_partOfPlace" about="http://semanticweb.cs.vu.nl/2009/04/event/partOfPlace" typeof="rdf:Property"> + <h3>Property: event:partOfPlace</h3> + <em>part of place</em> - "Place"s can be "partOf" an other "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_partOfPlace">permalink</a>] [<a href="#queries_partOfPlace">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_partOf" about="http://semanticweb.cs.vu.nl/2009/04/event/partOf" typeof="rdf:Property"> + <h3>Property: event:partOf</h3> + <em>part of</em> - "TimeStampedEntities" can be "partOf" an other "TimeStampedEntities". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_partOf">permalink</a>] [<a href="#queries_partOf">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_endsAt" about="http://semanticweb.cs.vu.nl/2009/04/event/endsAt" typeof="rdf:Property"> + <h3>Property: event:endsAt</h3> + <em>ends at</em> - The moment at which a "TimeStamp" starts. In case of a point in time, the value of this property should be equivalent to the "beginsAt" value. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_endsAt">permalink</a>] [<a href="#queries_endsAt">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_hasPart" about="http://semanticweb.cs.vu.nl/2009/04/event/hasPart" typeof="rdf:Property"> + <h3>Property: event:hasPart</h3> + <em>has part</em> - An "Event" can "hasPart" another "Event", which defines the second "Event" to be a subprocess of the first. For example, an "Event" can play a part in another "Event" or an "Event" can be seminal to a "Movement". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_hasPart">permalink</a>] [<a href="#queries_hasPart">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_endsInPlace" about="http://semanticweb.cs.vu.nl/2009/04/event/endsInPlace" typeof="rdf:Property"> + <h3>Property: event:endsInPlace</h3> + <em>ends in place</em> - An "Event" ends at a certain "Place". <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_endsInPlace">permalink</a>] [<a href="#queries_endsInPlace">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_involves" about="http://semanticweb.cs.vu.nl/2009/04/event/involves" typeof="rdf:Property"> + <h3>Property: event:involves</h3> + <em>involves</em> - "Event"s can "involves" "Object"(s). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_involves">permalink</a>] [<a href="#queries_involves">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_actorType" about="http://semanticweb.cs.vu.nl/2009/04/event/actorType" typeof="rdf:Property"> + <h3>Property: event:actorType</h3> + <em>has actor type</em> - The "Type" of an "Actor". For example, "Person"; "Organisation". The specification of a "Type" is not mandatory but a recommended practice. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unknown">unknown</span></td></tr> + + + </table> + + <p style="float: right; font-size: small;">[<a href="#term_actorType">permalink</a>] [<a href="#queries_actorType">validation queries</a>] [<a href="#glance">back to top</a>]</p> + <br/> + </div> + + + + + + + + + + + + +</div> +</div> + + </body> +</html> diff --git a/examples/vuevents/index.rdf b/examples/vuevents/index.rdf new file mode 100644 index 0000000..2fb6688 --- /dev/null +++ b/examples/vuevents/index.rdf @@ -0,0 +1,387 @@ +<?xml version="1.0"?> +<rdf:RDF xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:wgs84="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:em="http://semanticweb.cs.vu.nl/2009/04/event/"> + <owl:Ontology rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/"> + <rdfs:comment>VUevent Model, Vrije Universiteit Amsterdam, version draft 14 + This model is based on or inspired from (and will asap be linked to) the following models: + DOLCE (Descriptive Ontology for Linguistic and Cognitive Engineering, http://www.loa-cnr.it/Ontologies.html) and its related Description and Situation extension (http://www.loa-cnr.it/Papers/ODBASE-CONTEXT.pdf) + CIDOC-Conceptual Reference Model (http://cidoc.ics.forth.gr/official_release_cidoc.html) + MPEG-7 Semantic DS and the COMM ontology (http://comm.semanticweb.org/) + the Event model (http://motools.sourceforge.net/event/event.html) + </rdfs:comment> + </owl:Ontology> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/Actor"> + <rdfs:label xml:lang="en">Actor</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">A thing, animate or inanimate, physical or non-physical, that plays a part in an "Event".</rdfs:comment> + <rdfs:subClassOf> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity"> + <rdfs:label xml:lang="en">Time-stamped entity</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">This can be anything, physical, or non-physical, an object, or a process, as long as it has a specified time where it exists. Instances of this class have a denotated time. For example, a range of time that "beginsAt" a certain moment and "endsAt" a certain moment.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://www.w3.org/2002/07/owl#Thing" /> + </owl:Class> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Actor" can only "participateIn" an "Event"</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/Event"> + <rdfs:label xml:lang="en">Event</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Something significant that happens at a specified place and time; the semantics of what this event is should be defined as an "Event Type", enabling multiple (possibly external) hierarchies of events.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity" /> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>"Event"s can only have "EventType" as "eventType"; "eventType"s can be the Storming of the Bastille, an auction, a ship entering a harbor or The Birth of Venus.</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/EventType"> + <rdfs:comment>"eventType"s can be the Storming of the Bastille, an auction, a ship entering a harbor or The Birth of Venus. Specifying an "EventType" is not mandatory but recommended.</rdfs:comment> + <rdfs:label xml:lang="en">Event type</rdfs:label> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Type" /> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/eventType"> + <rdfs:label xml:lang="en">has event type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "Type" of an "Event". For example, "The coronation of Napoleon"; "A ship anchoring"; "A specimen being observed"; or a news event, like "The fall of the Berlin wall". The specification of a "Type" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:subPropertyOf> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/hasType"> + <rdfs:comment>this property enables to make the distinction between a 'global' type, like "Role", and domain-specific types, like Pope, King, Pirate, Painter, NGO etc. For the users who do not wish to make this distinction, the type of the different classes of teh model can be specified directly with the rdf:type property. The specification of a "Type" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:label xml:lang="en">has type</rdfs:label> + <rdfs:subPropertyOf rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" /> + </owl:ObjectProperty> + </rdfs:subPropertyOf> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>"Event"s can only "takePlaceIn" "Place"s; "Place"s have "PlaceType"s which can be Places of Interest, countries, geo-spatial areas like a forest or points defined by geo-coordinates. Hence, the "PlaceType"s can be defined externally and independently from the Core VUevent Model.</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/Place"> + <rdfs:label xml:lang="en">Place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">A physical or non-physical (or even mythical) location where "Event"s can take place and where "Role"s can be played.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity" /> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>a "Place" can only have a "PlaceType" as "placeType"; a "PlaceType" can be a Place of Interest, countries, geo-spatial areas like a forest or points defined by geo-coordinates. Hence, the "PlaceType"s can be defined externally and independently from the Core VUevent Model.</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/PlaceType"> + <rdfs:comment>a "PlaceType" can be a Place of Interest, countries, geo-spatial areas like a forest or points defined by geo-coordinates. Hence, the "PlaceType"s can be defined externally and independently from the Core VUevent Model. Specifying a "PlaceType" is not mandatory but recommended.</rdfs:comment> + <rdfs:label xml:lang="en">Place type</rdfs:label> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Type" /> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/placeType"> + <rdfs:label xml:lang="en">has place type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "Type" of a "Place". For example, "The Dutch coast"; "A city". The specification of a "Type" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasType" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>a "Place" can only "hasRole" a "Role", this "Role" links a "Place" with the qualification of the "Place" under which the "Event" takes place: for example Amsterdam can have the "Role" CapitalCity, which is valid for a specific time span only. The concept of "Role" enables to define the time-span during which the "RoleType" holds.</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Role" /> + <owl:onProperty rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasRole" /> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>a "Place" can only have a "Place" as "partOfPlace".</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Place" /> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/partOfPlace"> + <rdfs:label xml:lang="en">part of place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"Place"s can be "partOf" an other "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/partOf" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/takesPlaceIn"> + <rdfs:label xml:lang="en">takes place in</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Event" "takesPlaceIn" a "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>"Event"s can only have "Event"s as "partOfEvent" </rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Event" /> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/partOfEvent"> + <rdfs:label xml:lang="en">part of event</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"Event"s can be "partOf" an other "Event".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/partOf" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/participatesIn"> + <rdfs:label xml:lang="en">participates in</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Actor" "participatesIn" an "Event".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Actor" can only "hasRole" a "Role", this "Role" links an "Actor" with the qualification under which he/she/it is "participatingIn" the "Event": for example Joseph Alois Ratzinger can be "participatingIn" an "Event" as a Vatican citizen or as the Pope Benedict XVI, which are both "roleType"s, related to "Role"s that can have an overlapping time span. The concept of "Role" enables to define the time-span during which the "RoleType" holds.</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/Role"> + <rdfs:label xml:lang="en">Role</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">A "Role" specifies the temporal boundary of an "Actor"'s "RoleType". For example, Napoleon Bonaparte was only Emperor for a specific part of his life. The specification of a "Role" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity" /> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>a "Role" can only have "RoleType" as "roleType" .</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/RoleType"> + <rdfs:comment>The semantic definition of the "Role" that an "Acctor" is plating in a certain "Event": Emperor, King, Pirate, Painter, NGO, Nation etc. Specifying an "RoleType" is not mandatory but recommended.</rdfs:comment> + <rdfs:label xml:lang="en">Role type</rdfs:label> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Type" /> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/roleType"> + <rdfs:label xml:lang="en">has role type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "Type" of a "Role". For example, "captain", "painter", or "instigator", "ritual object", "capital" for a city, etc. The specification of a "Type" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasType" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>a "Role" can only be "roleInPlace" in a "Place" .</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Place" /> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/roleInPlace"> + <rdfs:label xml:lang="en">Role played in Event in Place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">A "Role" can be directly linked to a "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>a "Role" can only "participatesInAsRole" in an "Event" .</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Event" /> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/participatesInAsRole"> + <rdfs:label xml:lang="en">participates in as role</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Actor" "participatesIn" an "Event" within the context of a certain "Role". The specification of a "Role" is not mandatory but a highly recommended practice.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/hasRole"> + <rdfs:label xml:lang="en">has role</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Actor", "Object" and a "Place" can assume a "Role". It is a recommended practice to specify which "Role" they play when participating in the "Event" .</rdfs:comment> + <rdfs:subPropertyOf> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/related"> + <rdfs:label xml:lang="en">related to</rdfs:label> + </owl:ObjectProperty> + </rdfs:subPropertyOf> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Actor" can only have "ActorType" as an "actorType" .</rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/ActorType"> + <rdfs:comment>an "actorType" is a non-mandatory definition of an intrinsic type, inherent to the "Actor" him/her/itself, and not to his/her/its "Role": an "Actor" can be Caucasian, independently from the role that he or she has in a certain time span of his/her life. Specifying an "ActorType" is not mandatory but recommended. </rdfs:comment> + <rdfs:label xml:lang="en">Actor type</rdfs:label> + <rdfs:subClassOf> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/Type"> + <rdfs:label xml:lang="en">Types</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Non time-stamped specified types of "Event"s, "Actor"s, "Object"s, "Place"s, etc. Specifying a "Type" is not mandatory but recommended.</rdfs:comment> + </owl:Class> + </rdfs:subClassOf> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/actorType"> + <rdfs:label xml:lang="en">has actor type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "Type" of an "Actor". For example, "Person"; "Organisation". The specification of a "Type" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasType" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + </owl:Class> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/Object"> + <rdfs:label xml:lang="en">Object</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">A thing, animate or inaminate, that is a relevant instrument of an "Event" but does not play a role per se.</rdfs:comment> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/TimeStampedEntity" /> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Object" can only be "involvedIn" an "Event".</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Event" /> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/involvedIn"> + <rdfs:label xml:lang="en">involved in</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"Object"s are "involvedIn" an "Event".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + <owl:inverseOf> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/involves"> + <rdfs:label xml:lang="en">involves</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"Event"s can "involves" "Object"(s).</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + <owl:inverseOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/involvedIn" /> + </owl:ObjectProperty> + </owl:inverseOf> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Object" can only be "objectInPlace" a "Place".</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Place" /> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/objectInPlace"> + <rdfs:label xml:lang="en">Object involved in Event in Place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Object" can be directly linked to a "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/related" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Object" can only "hasRole" a "Role", this "Role" links an "Object" with the qualification under which he/she/it is "involvedIn" the "Event": for example a sword can be "involvedIn" an "Event" as a ritual object.</rdfs:comment> + <owl:allValuesFrom rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Role" /> + <owl:onProperty rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasRole" /> + </owl:Restriction> + </rdfs:subClassOf> + <rdfs:subClassOf> + <owl:Restriction> + <rdfs:comment>an "Object" can only have an "ObjectType" as "objectType"; an "ObjectType" can be a crown, a ritual sword, a container ship etc. </rdfs:comment> + <owl:allValuesFrom> + <owl:Class rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/ObjectType"> + <rdfs:comment>an "ObjectType" can be a crown, a ritual sword, a container ship etc. Specifying an "ObjectType" is not mandatory but recommended.</rdfs:comment> + <rdfs:label xml:lang="en">Object type</rdfs:label> + <rdfs:subClassOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/Type" /> + </owl:Class> + </owl:allValuesFrom> + <owl:onProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/objectType"> + <rdfs:label xml:lang="en">has object type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "Type" of an "Object". For example, "crown", or "book". Specifically, a passive object, not an "Actor". The specification of a "Type" is not mandatory but a recommended practice.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasType" /> + </owl:ObjectProperty> + </owl:onProperty> + </owl:Restriction> + </rdfs:subClassOf> + </owl:Class> + <owl:DatatypeProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/beginsAt"> + <rdfs:label xml:lang="en">begins at</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The moment at which a "TimeStamp" starts. In case of a point in time, the value of this property should be equivalent to the "endsAt" value.</rdfs:comment> + <rdfs:subPropertyOf> + <owl:DatatypeProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/timeStampedAt"> + <rdfs:label xml:lang="en">time stamped at</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">A property to specify the time of a TimeStampedEntity. The type of the values is not specified, but could be a TIMEX string.</rdfs:comment> + </owl:DatatypeProperty> + </rdfs:subPropertyOf> + </owl:DatatypeProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/broader"> + <rdfs:label xml:lang="en">has broader</rdfs:label> + <owl:inverseOf> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/narrower"> + <rdfs:label xml:lang="en">has narrower</rdfs:label> + <owl:inverseOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/broader" /> + </owl:ObjectProperty> + </owl:inverseOf> + </owl:ObjectProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/childOfType"> + <rdfs:label xml:lang="en">child of type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "childOfType" property states that all entities of the child's "Type" are also of this "Type".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/broader" /> + <owl:inverseOf> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/parentOfType"> + <rdfs:label xml:lang="en">parent of type</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The "parentOfType" property states that all entities of that "Type" are also of the parent's "Type".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/narrower" /> + <owl:inverseOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/childOfType" /> + </owl:ObjectProperty> + </owl:inverseOf> + </owl:ObjectProperty> + <owl:DatatypeProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/endsAt"> + <rdfs:label xml:lang="en">ends at</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The moment at which a "TimeStamp" starts. In case of a point in time, the value of this property should be equivalent to the "beginsAt" value.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/timeStampedAt" /> + </owl:DatatypeProperty> + <owl:TransitiveProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/hasPart"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty" /> + <rdfs:label xml:lang="en">has part</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Event" can "hasPart" another "Event", which defines the second "Event" to be a subprocess of the first. For example, an "Event" can play a part in another "Event" or an "Event" can be seminal to a "Movement".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/narrower" /> + <owl:inverseOf> + <owl:TransitiveProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/partOf"> + <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#ObjectProperty" /> + <rdfs:label xml:lang="en">part of</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"TimeStampedEntities" can be "partOf" an other "TimeStampedEntities".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/broader" /> + <owl:inverseOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasPart" /> + </owl:TransitiveProperty> + </owl:inverseOf> + </owl:TransitiveProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/partOfDirect"> + <rdfs:label xml:lang="en">part of direct</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"TimeStampedEntiti"es can be directecly related to others with the "partOf" property.</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/partOf" /> + </owl:ObjectProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/directPartOfEvent"> + <rdfs:label xml:lang="en">direct part of event</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"Event"s can be a "directPartOf" an other "Event".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/partOfDirect" /> + </owl:ObjectProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/directPartOfPlace"> + <rdfs:label xml:lang="en">direct part of place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">"Place"s can be a "directPartOf" an other "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/partOfDirect" /> + </owl:ObjectProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/beginsInPlace"> + <rdfs:label xml:lang="en">begins in place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Event" starts at a certain "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/takesPlaceIn" /> + </owl:ObjectProperty> + <owl:ObjectProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/endsInPlace"> + <rdfs:label xml:lang="en">ends in place</rdfs:label> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">An "Event" ends at a certain "Place".</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/takesPlaceIn" /> + </owl:ObjectProperty> + <owl:DatatypeProperty rdf:about="http://semanticweb.cs.vu.nl/2009/04/event/hasCoordinates"> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Defines the coordinates of a "TimeStampedEntity".</rdfs:comment> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://www.w3.org/2003/01/geo/wgs84_pos#alt"> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The WGS84 altitude of a SpatialThing (decimal meters above the local reference ellipsoid).</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasCoordinates" /> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://www.w3.org/2003/01/geo/wgs84_pos#lat"> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The WGS84 latitude of a SpatialThing (decimal degrees).</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasCoordinates" /> + </owl:DatatypeProperty> + <owl:DatatypeProperty rdf:about="http://www.w3.org/2003/01/geo/wgs84_pos#long"> + <rdfs:comment rdf:datatype="http://www.w3.org/2001/XMLSchema#string">The WGS84 longitude of a SpatialThing (decimal degrees).</rdfs:comment> + <rdfs:subPropertyOf rdf:resource="http://semanticweb.cs.vu.nl/2009/04/event/hasCoordinates" /> + </owl:DatatypeProperty> +</rdf:RDF> diff --git a/examples/vuevents/style/programmes.css b/examples/vuevents/style/programmes.css new file mode 100644 index 0000000..c83c262 --- /dev/null +++ b/examples/vuevents/style/programmes.css @@ -0,0 +1,70 @@ +div#blq-main { + font-size: 1.5em; + line-height: 1.5em; + + margin-bottom: 1em; +} + +div#blq-main p { + margin-bottom: 1em; +} + +div#blq-main h1 { + font-size: 2.0em; + line-height: 2.0em; +} + +div#blq-main h2 { + clear: both; + margin-top: 1em; + font-size: 1.5em; + line-height: 1.5em; +} +div#blq-main h3 { + margin-top: 1em; +} + +div#blq-main dl dt { + width: 20%; + float: left; +} + +div#blq-main table { + margin-top: 1em; +} +div#blq-main tr { + border-top: solid 1px ; +} + +div#blq-main td { + padding-left: 0.5em; +} +div#blq-main td { + padding-left: 0.5em; +} + +div#blq-main div#glance ul { + margin-top: -1em; +} +div#blq-main div#glance li { + display: inline; + margin-left: 1em; +} + +div.specterm { + clear: both; + border-top: solid 1px; +} + +div.specterm dl { + width: 90%; +} +div.specterm dl dt { + clear: both; + width: 10em; + float: left; +} +div.specterm dl dd { + float: left; + margin-left: 0.5em; +} diff --git a/examples/vuevents/template.html b/examples/vuevents/template.html new file mode 100644 index 0000000..5f1d731 --- /dev/null +++ b/examples/vuevents/template.html @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" + xmlns:owl="http://www.w3.org/2002/07/owl#" + xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#" + xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:wot="http://xmlns.com/wot/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:ao="http://purl.org/ontology/ao/" +> +<head> + <head> + <link type="text/css" rel="stylesheet" href="style/programmes.css"> + </head> + <body> + <h2 id="glance">VU Events at a glance</h2> + + %s + + %s + + </body> +</html>
leth/SpecGen
4c3b4adfba8cf9d323a3cccccb7e74d268981751
added special treatment for code element containing foaf terms
diff --git a/libvocab.py b/libvocab.py index 7c1f404..6234e92 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,769 +1,774 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) # self.terms.sort() # self.classes.sort() # self.properties.sort() # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: # print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" + # text.gsub(/<code>foaf:(\w+)<\/code>/){ defurl($1) } return "<code><a href=\"#term_#{term}\">foaf:#{term}</a></code>" + def codelink(self, s): + reg1 = re.compile(r"""<code>foaf:(\w+)<\/code>""") + return(re.sub(reg1, r"""<code><a href="#term_\1">foaf:\1</a></code>""", s)) + def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div>""" # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Disjoint With:</th>\n' tt = '' for (disjointWith, label) in relations: ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo5 = "%s <td> %s </td></tr>" % (sss, tt) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s) + zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, self.codelink(s)) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ss = """<span rel="rdfs:range" href="%s"<a href="#term_%s">%s</a></span>\n""" % (range, label, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # inverse functional property foo5 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" foo5 = "%s <td> %s </td></tr>" % (sss, ss) # functonal property # inverse functional property foo6 = '' q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th colspan="2">Functional Property</th>\n' if (len(relations) > 0): ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" foo6 = "%s <td> %s </td></tr>" % (sss, ss) # end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4+foo5+foo6, s) + zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4+foo5+foo6, self.codelink(s)) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
06f9f45162e47455551e49f77a487c939d135928
drafting-test
diff --git a/foaf-live/_tmp_spec.html b/foaf-live/_tmp_spec.html index 33fa92e..90961a9 100644 --- a/foaf-live/_tmp_spec.html +++ b/foaf-live/_tmp_spec.html @@ -177,2902 +177,3086 @@ As usual, see the <a href="#sec-changes">changes</a> section for details of the <li><a href="#term_depiction">depiction</a> (<a href= "#term_depicts">depicts</a>)</li> <li><a href="#term_surname">surname</a></li> <li><a href="#term_family_name">family_name</a></li> <li><a href="#term_givenname">givenname</a></li> <li><a href="#term_firstName">firstName</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Personal Info</h3> <ul> <li><a href="#term_weblog">weblog</a></li> <li><a href="#term_knows">knows</a></li> <li><a href="#term_interest">interest</a></li> <li><a href="#term_currentProject">currentProject</a></li> <li><a href="#term_pastProject">pastProject</a></li> <li><a href="#term_plan">plan</a></li> <li><a href="#term_based_near">based_near</a></li> <li><a href= "#term_workplaceHomepage">workplaceHomepage</a></li> <li><a href= "#term_workInfoHomepage">workInfoHomepage</a></li> <li><a href="#term_schoolHomepage">schoolHomepage</a></li> <li><a href="#term_topic_interest">topic_interest</a></li> <li><a href="#term_publications">publications</a></li> <li><a href="#term_geekcode">geekcode</a></li> <li><a href="#term_myersBriggs">myersBriggs</a></li> <li><a href="#term_dnaChecksum">dnaChecksum</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Online Accounts / IM</h3> <ul> <li><a href="#term_OnlineAccount">OnlineAccount</a></li> <li><a href= "#term_OnlineChatAccount">OnlineChatAccount</a></li> <li><a href= "#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a></li> <li><a href= "#term_OnlineGamingAccount">OnlineGamingAccount</a></li> <li><a href="#term_holdsAccount">holdsAccount</a></li> <li><a href= "#term_accountServiceHomepage">accountServiceHomepage</a></li> <li><a href="#term_accountName">accountName</a></li> <li><a href="#term_icqChatID">icqChatID</a></li> <li><a href="#term_msnChatID">msnChatID</a></li> <li><a href="#term_aimChatID">aimChatID</a></li> <li><a href="#term_jabberID">jabberID</a></li> <li><a href="#term_yahooChatID">yahooChatID</a></li> </ul> </div> <div style="clear: left;"></div> <div class="rdf-proplist"> <h3>Projects and Groups</h3> <ul> <li><a href="#term_Project">Project</a></li> <li><a href="#term_Organization">Organization</a></li> <li><a href="#term_Group">Group</a></li> <li><a href="#term_member">member</a></li> <li><a href= "#term_membershipClass">membershipClass</a></li> <li><a href="#term_fundedBy">fundedBy</a></li> <li><a href="#term_theme">theme</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Documents and Images</h3> <ul> <li><a href="#term_Document">Document</a></li> <li><a href="#term_Image">Image</a></li> <li><a href= "#term_PersonalProfileDocument">PersonalProfileDocument</a></li> <li><a href="#term_topic">topic</a> (<a href= "#term_page">page</a>)</li> <li><a href="#term_primaryTopic">primaryTopic</a></li> <li><a href="#term_tipjar">tipjar</a></li> <li><a href="#term_sha1">sha1</a></li> <li><a href="#term_made">made</a> (<a href= "#term_maker">maker</a>)</li> <li><a href="#term_thumbnail">thumbnail</a></li> <li><a href="#term_logo">logo</a></li> </ul> </div> </div> <div style="clear: left;"></div> <h2 id="sec-example">Example</h2> <p>Here is a very basic document describing a person:</p> <div class="example"> <pre> &lt;foaf:Person rdf:about="#me" xmlns:foaf="http://xmlns.com/foaf/0.1/"&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:mbox_sha1sum&gt;241021fb0e6289f92815fc210f9e9137262c252e&lt;/foaf:mbox_sha1sum&gt; &lt;foaf:homepage rdf:resource="http://danbri.org/" /&gt; &lt;foaf:img rdf:resource="/images/me.jpg" /&gt; &lt;/foaf:Person&gt; </pre> </div> <p>This brief example introduces the basics of FOAF. It basically says, "there is a <a href="#term_Person">foaf:Person</a> with a <a href="#term_name">foaf:name</a> property of 'Dan Brickley' and a <a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a> property of 241021fb0e6289f92815fc210f9e9137262c252e; this person stands in a <a href="#term_homepage">foaf:homepage</a> relationship to a thing called http://danbri.org/ and a <a href= "#term_img">foaf:img</a> relationship to a thing referenced by a relative URI of /images/me.jpg</p> <div style="clear: left;"></div> <!-- ================================================================== --> <h2 id="sec-intro">1 Introduction: FOAF Basics</h2> <h3 id="sec-sw">The Semantic Web</h3> <blockquote> <p> <em> To a computer, the Web is a flat, boring world, devoid of meaning. This is a pity, as in fact documents on the Web describe real objects and imaginary concepts, and give particular relationships between them. For example, a document might describe a person. The title document to a house describes a house and also the ownership relation with a person. Adding semantics to the Web involves two things: allowing documents which have information in machine-readable forms, and allowing links to be created with relationship values. Only when we have this extra level of semantics will we be able to use computer power to help us exploit the information to a greater extent than our own reading. </em> - Tim Berners-Lee &quot;W3 future directions&quot; keynote, 1st World Wide Web Conference Geneva, May 1994 </p> </blockquote> <h3 id="sec-foafsw">FOAF and the Semantic Web</h3> <p> FOAF, like the Web itself, is a linked information system. It is built using decentralised <a href="http://www.w3.org/2001/sw/">Semantic Web</a> technology, and has been designed to allow for integration of data across a variety of applications, Web sites and services, and software systems. To achieve this, FOAF takes a liberal approach to data exchange. It does not require you to say anything at all about yourself or others, nor does it place any limits on the things you can say or the variety of Semantic Web vocabularies you may use in doing so. This current specification provides a basic "dictionary" of terms for talking about people and the things they make and do.</p> <p>FOAF was designed to be used alongside other such dictionaries ("schemas" or "ontologies"), and to beusable with the wide variety of generic tools and services that have been created for the Semantic Web. For example, the W3C work on <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a> provides us with a rich query language for consulting databases of FOAF data, while the <a href="http://www.w3.org/2004/02/skos/">SKOS</a> initiative explores in more detail than FOAF the problem of describing topics, categories, "folksonomies" and subject hierarchies. Meanwhile, other W3C groups are working on improved mechanisms for encoding all kinds of RDF data (including but not limited to FOAF) within Web pages: see the work of the <a href="http://www.w3.org/2001/sw/grddl-wg/">GRDDL</a> and <a href="http://www.w3.org/TR/xhtml-rdfa-primer/">RDFa</a> efforts for more detail. The Semantic Web provides us with an <em>architecture for collaboration</em>, allowing complex technical challenges to be shared by a loosely-coordinated community of developers. </p> <p>The FOAF project is based around the use of <em>machine readable</em> Web homepages for people, groups, companies and other kinds of thing. To achieve this we use the "FOAF vocabulary" to provide a collection of basic terms that can be used in these Web pages. At the heart of the FOAF project is a set of definitions designed to serve as a dictionary of terms that can be used to express claims about the world. The initial focus of FOAF has been on the description of people, since people are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on.</p> <p>The FOAF Vocabulary definitions presented here are written using a computer language (RDF/OWL) that makes it easy for software to process some basic facts about the terms in the FOAF vocabulary, and consequently about the things described in FOAF documents. A FOAF document, unlike a traditional Web page, can be combined with other FOAF documents to create a unified database of information. FOAF is a <a href="http://www.w3.org/DesignIssues/LinkedData.html">Linked Data</a> system, in that it based around the idea of linking together a Web of decentralised descriptions.</p> <h3 id="sec-basicidea">The Basic Idea</h3> <p>The basic idea is pretty simple. If people publish information in the FOAF document format, machines will be able to make use of that information. If those files contain "see also" references to other such documents in the Web, we will have a machine-friendly version of today's hypertext Web. Computer programs will be able to scutter around a Web of documents designed for machines rather than humans, storing the information they find, keeping a list of "see also" pointers to other documents, checking digital signatures (for the security minded) and building Web pages and question-answering services based on the harvested documents.</p> <p>So, what is the 'FOAF document format'? FOAF files are just text documents (well, Unicode documents). They are written in XML syntax, and adopt the conventions of the Resource Description Framework (RDF). In addition, the FOAF vocabulary defines some useful constructs that can appear in FOAF files, alongside other RDF vocabularies defined elsewhere. For example, FOAF defines categories ('classes') such as <code>foaf:Person</code>, <code>foaf:Document</code>, <code>foaf:Image</code>, alongside some handy properties of those things, such as <code>foaf:name</code>, <code>foaf:mbox</code> (ie. an internet mailbox), <code>foaf:homepage</code> etc., as well as some useful kinds of relationship that hold between members of these categories. For example, one interesting relationship type is <code>foaf:depiction</code>. This relates something (eg. a <code>foaf:Person</code>) to a <code>foaf:Image</code>. The FOAF demos that feature photos and listings of 'who is in which picture' are based on software tools that parse RDF documents and make use of these properties.</p> <p>The specific contents of the FOAF vocabulary are detailed in this <a href="http://xmlns.com/foaf/0.1/">FOAF namespace document</a>. In addition to the FOAF vocabulary, one of the most interesting features of a FOAF file is that it can contain "see Also" pointers to other FOAF files. This provides a basis for automatic harvesting tools to traverse a Web of interlinked files, and learn about new people, documents, services, data...</p> <p>The remainder of this specification describes how to publish and interpret descriptions such as these on the Web, using RDF/XML for syntax (file format) and terms from FOAF. It introduces a number of categories (RDF classes such as 'Person') and properties (relationship and attribute types such as 'mbox' or 'workplaceHomepage'). Each term definition is provided in both human and machine-readable form, hyperlinked for quick reference.</p> <h2 id="sec-for">What's FOAF for?</h2> <p>For a good general introduction to FOAF, see Edd Dumbill's article, <a href= "http://www-106.ibm.com/developerworks/xml/library/x-foaf.html">XML Watch: Finding friends with XML and RDF</a> (June 2002, IBM developerWorks). Information about the use of FOAF <a href= "http://rdfweb.org/2002/01/photo/">with image metadata</a> is also available.</p> <p>The <a href= "http://rdfweb.org/2002/01/photo/">co-depiction</a> experiment shows a fun use of the vocabulary. Jim Ley's <a href= "http://www.jibbering.com/svg/AnnotateImage.html">SVG image annotation tool</a> show the use of FOAF with detailed image metadata, and provide tools for labelling image regions within a Web browser. To create a FOAF document, you can use Leigh Dodd's <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">FOAF-a-matic</a> javascript tool. To query a FOAF dataset via IRC, you can use Edd Dumbill's <a href="http://usefulinc.com/foaf/foafbot">FOAFbot</a> tool, an IRC 'community support agent'. For more information on FOAF and related projects, see the <a href= "http://rdfweb.org/foaf/">FOAF project home page</a>. </p> <h2 id="sec-bg">Background</h2> <p>FOAF is a collaborative effort amongst Semantic Web developers on the FOAF ([email protected]) mailing list. The name 'FOAF' is derived from traditional internet usage, an acronym for 'Friend of a Friend'.</p> <p>The name was chosen to reflect our concern with social networks and the Web, urban myths, trust and connections. Other uses of the name continue, notably in the documentation and investigation of Urban Legends (eg. see the <a href= "http://www.urbanlegends.com/">alt.folklore.urban archive</a> or <a href="http://www.snopes.com/">snopes.com</a>), and other FOAF stories. Our use of the name 'FOAF' for a Web vocabulary and document format is intended to complement, rather than replace, these prior uses. FOAF documents describe the characteristics and relationships amongst friends of friends, and their friends, and the stories they tell.</p> <h2 id="sec-standards">FOAF and Standards</h2> <p>It is important to understand that the FOAF <em>vocabulary</em> as specified in this document is not a standard in the sense of <a href= "http://www.iso.ch/iso/en/ISOOnline.openerpage">ISO Standardisation</a>, or that associated with <a href= "http://www.w3.org/">W3C</a> <a href= "http://www.w3.org/Consortium/Process/">Process</a>.</p> <p>FOAF depends heavily on W3C's standards work, specifically on XML, XML Namespaces, RDF, and OWL. All FOAF <em>documents</em> must be well-formed RDF/XML documents. The FOAF vocabulary, by contrast, is managed more in the style of an <a href= "http://www.opensource.org/">Open Source</a> or <a href= "http://www.gnu.org/philosophy/free-sw.html">Free Software</a> project than as an industry standardarisation effort (eg. see <a href="http://www.jabber.org/jeps/jep-0001.html">Jabber JEPs</a>).</p> <p>This specification contributes a vocabulary, "FOAF", to the Semantic Web, specifying it using W3C's <a href= "http://www.w3.org/RDF/">Resource Description Framework</a> (RDF). As such, FOAF adopts by reference both a syntax (using XML) a data model (RDF graphs) and a mathematically grounded definition for the rules that underpin the FOAF design.</p> <h2 id="sec-nsdoc">The FOAF Vocabulary Description</h2> <p>This specification serves as the FOAF "namespace document". As such it describes the FOAF vocabulary and the terms (<a href= "http://www.w3.org/RDF/">RDF</a> classes and properties) that constitute it, so that <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> applications can use those terms in a variety of RDF-compatible document formats and applications.</p> <p>This document presents FOAF as a <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> vocabulary or <em>Ontology</em>. The FOAF vocabulary is pretty simple, pragmatic and designed to allow simultaneous deployment and extension. FOAF is intended for widescale use, but its authors make no commitments regarding its suitability for any particular purpose.</p> <h3 id="sec-evolution">Evolution and Extension of FOAF</h3> <p>The FOAF vocabulary is identified by the namespace URI '<code>http://xmlns.com/foaf/0.1/</code>'. Revisions and extensions of FOAF are conducted through edits to this document, which by convention is accessible in the Web via the namespace URI. For practical and deployment reasons, note that <b>we do not update the namespace URI as the vocabulary matures</b>. </p> <p>The core of FOAF now is considered stable, and the version number of <em>this specification</em> reflects this stability. However, it long ago became impractical to update the namespace URI without causing huge disruption to both producers and consumers of FOAF data. We are therefore left with the digits "0.1" in our URI. This stands as a warning to all those who might embed metadata in their vocabulary identifiers. </p> <p> The evolution of FOAF is best considered in terms of the stability of individual vocabulary terms, rather than the specification as a whole. As terms stabilise in usage and documentation, they progress through the categories '<strong>unstable</strong>', '<strong>testing</strong>' and '<strong>stable</strong>'.</p><!--STATUSINFO--> <p>The properties and types defined here provide some basic useful concepts for use in FOAF descriptions. Other vocabulary (eg. the <a href="http://dublincore.org/">Dublin Core</a> metadata elements for simple bibliographic description), RSS 1.0 etc can also be mixed in with FOAF terms, as can local extensions. FOAF is designed to be extended. The <a href= "http://wiki.foaf-project.org/FoafVocab">FoafVocab</a> page in the FOAF wiki lists a number of extension vocabularies that are particularly applicable to use with FOAF.</p> <h2 id="sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</h2> <p>If you publish a FOAF self-description (eg. using <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">foaf-a-matic</a>) you can make it easier for tools to find your FOAF by putting markup in the <code>head</code> of your HTML homepage. It doesn't really matter what filename you choose for your FOAF document, although <code>foaf.rdf</code> is a common choice. The linking markup is as follows:</p> <div class="example"> <pre> &lt;link rel="meta" type="application/rdf+xml" title="FOAF" href="<em>http://example.com/~you/foaf.rdf</em>"/&gt; </pre> </div> <p>...although of course change the <em>URL</em> to point to your own FOAF document. See also: more on <a href= "http://rdfweb.org/mt/foaflog/archives/000041.html">FOAF autodiscovery</a> and services that make use of it.</p> <h2 id="sec-foafandrdf">FOAF and RDF</h2> <p>Why does FOAF use <a href= "http://www.w3.org/RDF/">RDF</a>?</p> <p>FOAF is an application of the Resource Description Framework (RDF) because the subject area we're describing -- people -- has so many competing requirements that a standalone format could not do them all justice. By using RDF, FOAF gains a powerful extensibility mechanism, allowing FOAF-based descriptions can be mixed with claims made in <em>any other RDF vocabulary</em></p> <p>People are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on. Consequently, there are many many things that we might want to say about people, not to mention these related objects (ie. documents, photos, meetings etc).</p> <p>FOAF as a vocabulary cannot incorporate everything we might want to talk about that is related to people, or it would be as large as a full dictionary. Instead of covering all topics within FOAF itself, we buy into a larger framework - RDF - that allows us to take advantage of work elsewhere on more specific description vocabularies (eg. for geographical / mapping data).</p> <p>RDF provides FOAF with a way to mix together different descriptive vocabularies in a consistent way. Vocabularies can be created by different communites and groups as appropriate and mixed together as required, without needing any centralised agreement on how terms from different vocabularies can be written down in XML.</p> <p>This mixing happens in two ways: firstly, RDF provides an underlying model of (typed) objects and their attributes or relationships. <code>foaf:Person</code> is an example of a type of object (a "<em>class</em>"), while <code>foaf:knows</code> and <code>foaf:name</code> are examples of a relationship and an attribute of an <code>foaf:Person</code>; in RDF we call these "<em>properties</em>". Any vocabulary described in RDF shares this basic model, which is discernable in the syntax for RDF, and which removes one level of confusion in <em>understanding</em> a given vocabulary, making it simpler to comprehend and therefore reuse a vocabulary that you have not written yourself. This is the minimal <em>self-documentation</em> that RDF gives you.</p> <p>Secondly, there are mechanisms for saying which RDF properties are connected to which classes, and how different classes are related to each other, using RDF Syntax and OWL. These can be quite general (all RDF properties by default come from an <code>rdf:Resource</code> for example) or very specific and precise (for example by using <a href= "http://www.w3.org/2001/sw/WebOnt/">OWL</a> constructs, as in the <code>foaf:Group</code> example below. This is another form of self-documentation, which allows you to connect different vocabularies together as you please. An example of this is given below where the <code>foaf:based_near</code> property has a domain and range (types of class at each end of the property) from a different namespace altogether.</p> <p>In summary then, RDF is self-documenting in ways which enable the creation and combination of vocabularies in a devolved manner. This is particularly important for a vocabulary which describes people, since people connect to many other domains of interest, which it would be impossible (as well as suboptimal) for a single group to describe adequately in non-geological time.</p> <p>RDF is usually written using XML syntax, but behaves in rather different ways to 'vanilla' XML: the same RDF can be written in many different ways in XML. This means that SAX and DOM XML parsers are not adequate to deal with RDF/XML. If you want to process the data, you will need to use one of the many RDF toolkits available, such as Jena (Java) or Redland (C). <a href= "http://lists.w3.org/Archives/Public/www-rdf-interest/">RDF Interest Group</a> members can help with issues which may arise; there is also the <a href= "http://rdfweb.org/mailman/listinfo/rdfweb-dev">[email protected]</a> mailing list which is the main list for FOAF, and two active and friendly <a href= "http://esw.w3.org/topic/InternetRelayChat">IRC</a> channels: <a href="irc://irc.freenode.net/#rdfig">#rdfig</a> and <a href= "irc://irc.freenode.net/#foaf">#foaf</a> on <a href= "http://www.freenode.net/">freenode</a>.</p> <h2 id="sec-crossref">FOAF cross-reference: Listing FOAF Classes and Properties</h2> <p>FOAF introduces the following classes and properties. View this document's source markup to see the RDF/XML version.</p> <!-- the following is the script-generated list of classes and properties --> <div class="azlist"> <p>Classes: | <a href="#term_Agent">Agent</a> | <a href="#term_Document">Document</a> | <a href="#term_Group">Group</a> | <a href="#term_Image">Image</a> | <a href="#term_OnlineAccount">OnlineAccount</a> | <a href="#term_OnlineChatAccount">OnlineChatAccount</a> | <a href="#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a> | <a href="#term_OnlineGamingAccount">OnlineGamingAccount</a> | <a href="#term_Organization">Organization</a> | <a href="#term_Person">Person</a> | <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> | <a href="#term_Project">Project</a> | </p> -<p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_openid">openid</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | +<p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_age">age</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | </p> </div> <div class="termlist"><h3>Classes and Properties (full detail)</h3> <div class='termdetails'><br /> - <div class="specterm" id="term_OnlineEcommerceAccount"> - <h3>Class: foaf:OnlineEcommerceAccount</h3> - <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> + <div class="specterm" id="term_OnlineChatAccount" about="http://xmlns.com/foaf/0.1/OnlineChatAccount" typeof="rdfs:Class"> + <h3>Class: foaf:OnlineChatAccount</h3> + <em>Online Chat Account</em> - An online chat account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>subClassOf</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/OnlineAccount"><a href="#term_Online Account">Online Account</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -A <code>foaf:OnlineEcommerceAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -buying and/or selling of goods, services etc. Examples include <a -href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a -href="http://www.paypal.com/">PayPal</a>, <a -href="http://www.thinkgeek.com/">thinkgeek</a>, etc. +A <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> is a <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> devoted to +chat / instant messaging. +</p> + +<p> +This is a generalization of the FOAF Chat ID properties, +<code><a href="#term_jabberID">foaf:jabberID</a></code>, <code><a href="#term_aimChatID">foaf:aimChatID</a></code>, +<code><a href="#term_msnChatID">foaf:msnChatID</a></code>, <code><a href="#term_icqChatID">foaf:icqChatID</a></code> and +<code><a href="#term_yahooChatID">foaf:yahooChatID</a></code>. +</p> + +<p> +Unlike those simple properties, <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> and associated FOAF terms +allows us to describe a great variety of online accounts, without having to anticipate +them in the FOAF vocabulary. +</p> + +<p> +For example, here is a description of an IRC chat account, specific to the Freenode IRC +network: </p> +<div class="example"> +<pre> +&lt;foaf:Person&gt; + &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:holdsAccount&gt; + &lt;foaf:OnlineAccount&gt; + &lt;rdf:type rdf:resource="http://xmlns.com/foaf/0.1/OnlineChatAccount"/&gt; + &lt;foaf:accountServiceHomepage rdf:resource="http://www.freenode.net/irc_servers.shtml"/&gt; + &lt;foaf:accountName&gt;danbri&lt;/foaf:accountName&gt; + &lt;/foaf:OnlineAccount&gt; + &lt;/foaf:holdsAccount&gt; +&lt;/foaf:Person&gt; +</pre> +</div> + +<p> +Note that it may be impolite to carelessly reveal someone else's chat identifier (which +might also serve as an indicate of email address) As with email, there are privacy and +anti-SPAM considerations. FOAF does not currently provide a way to represent an +obfuscated chat ID (ie. there is no parallel to the <code><a href="#term_mbox">foaf:mbox</a></code> / +<code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> mapping). +</p> +<p> +In addition to the generic <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> and +<code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> mechanisms, +FOAF also provides several convenience chat ID properties +(<code><a href="#term_jabberID">foaf:jabberID</a></code>, <code><a href="#term_aimChatID">foaf:aimChatID</a></code>, <code><a href="#term_icqChatID">foaf:icqChatID</a></code>, +<code><a href="#term_msnChatID">foaf:msnChatID</a></code>,<code><a href="#term_yahooChatID">foaf:yahooChatID</a></code>). +These serve as as a shorthand for some common cases; their use may not always be +appropriate. +</p> +<p class="editorial"> +We should specify some mappings between the abbreviated and full representations of +<a href="http://www.jabber.org/">Jabber</a>, <a href="http://www.aim.com/">AIM</a>, <a +href="http://chat.msn.com/">MSN</a>, <a href="http://web.icq.com/icqchat/">ICQ</a>, <a +href="http://chat.yahoo.com/">Yahoo!</a> and <a href="http://chat.msn.com/">MSN</a> chat +accounts. This requires us to identify an appropriate <code><a href="#term_accountServiceHomepage">foaf:accountServiceHomepage</a></code> for each. If we +wanted to make the <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> mechanism even more generic, we could +invent a relationship that holds between a <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> instance and a +convenience property. To continue the example above, we could describe how <a +href="http://www.freenode.net/">Freenode</a> could define a property 'fn:freenodeChatID' +corresponding to Freenode online accounts. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_OnlineAccount"> + </div> <div class="specterm" id="term_OnlineAccount" about="http://xmlns.com/foaf/0.1/OnlineAccount" typeof="rdfs:Class"> <h3>Class: foaf:OnlineAccount</h3> <em>Online Account</em> - An online account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_account service homepage">account service homepage</a> - <a href="#term_account name">account name</a> + <td> <a href="#term_account name">account name</a> + <a href="#term_account service homepage">account service homepage</a> </td></tr> <tr><th>in-range-of:</th> <td> <a href="#term_holds account">holds account</a> -</td></tr> <tr><th>has subclass</th> - <td> <a href="#term_Online E-commerce Account">Online E-commerce Account</a> - <a href="#term_Online Gaming Account">Online Gaming Account</a> +</td></tr> <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> + </td></tr><tr><th>has subclass</th> + <td> <a href="#term_Online Gaming Account">Online Gaming Account</a> + <a href="#term_Online E-commerce Account">Online E-commerce Account</a> <a href="#term_Online Chat Account">Online Chat Account</a> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -A <code>foaf:OnlineAccount</code> represents the provision of some form of online +A <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> represents the provision of some form of online service, by some party (indicated indirectly via a -<code>foaf:accountServiceHomepage</code>) to some <code>foaf:Agent</code>. The -<code>foaf:holdsAccount</code> property of the agent is used to indicate accounts that are +<code><a href="#term_accountServiceHomepage">foaf:accountServiceHomepage</a></code>) to some <code><a href="#term_Agent">foaf:Agent</a></code>. The +<code><a href="#term_holdsAccount">foaf:holdsAccount</a></code> property of the agent is used to indicate accounts that are associated with the agent. </p> <p> -See <code>foaf:OnlineChatAccount</code> for an example. Other sub-classes include -<code>foaf:OnlineEcommerceAccount</code> and <code>foaf:OnlineGamingAccount</code>. +See <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> for an example. Other sub-classes include +<code><a href="#term_OnlineEcommerceAccount">foaf:OnlineEcommerceAccount</a></code> and <code><a href="#term_OnlineGamingAccount">foaf:OnlineGamingAccount</a></code>. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineEcommerceAccount" about="http://xmlns.com/foaf/0.1/OnlineEcommerceAccount" typeof="rdfs:Class"> + <h3>Class: foaf:OnlineEcommerceAccount</h3> + <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/OnlineAccount"><a href="#term_Online Account">Online Account</a></span> + </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +A <code><a href="#term_OnlineEcommerceAccount">foaf:OnlineEcommerceAccount</a></code> is a <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> devoted to +buying and/or selling of goods, services etc. Examples include <a +href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a +href="http://www.paypal.com/">PayPal</a>, <a +href="http://www.thinkgeek.com/">thinkgeek</a>, etc. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineGamingAccount" about="http://xmlns.com/foaf/0.1/OnlineGamingAccount" typeof="rdfs:Class"> + <h3>Class: foaf:OnlineGamingAccount</h3> + <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/OnlineAccount"><a href="#term_Online Account">Online Account</a></span> + </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +A <code><a href="#term_OnlineGamingAccount">foaf:OnlineGamingAccount</a></code> is a <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> devoted to +online gaming. +</p> + +<p> +Examples might include <a href="http://everquest.station.sony.com/">EverQuest</a>, +<a href="http://www.xbox.com/live/">Xbox live</a>, <a +href="http://nwn.bioware.com/">Neverwinter Nights</a>, etc., as well as older text-based +systems (MOOs, MUDs and suchlike). +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Agent"> + </div> <div class="specterm" id="term_Agent" about="http://xmlns.com/foaf/0.1/Agent" typeof="rdfs:Class"> <h3>Class: foaf:Agent</h3> <em>Agent</em> - An agent (eg. person, group, software or physical artifact). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> - <a href="#term_birthday">birthday</a> + <td> <a href="#term_age">age</a> + <a href="#term_weblog">weblog</a> + <a href="#term_gender">gender</a> <a href="#term_Yahoo chat ID">Yahoo chat ID</a> - <a href="#term_holds account">holds account</a> + <a href="#term_birthday">birthday</a> + <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> <a href="#term_tipjar">tipjar</a> - <a href="#term_weblog">weblog</a> + <a href="#term_MSN chat ID">MSN chat ID</a> + <a href="#term_ICQ chat ID">ICQ chat ID</a> <a href="#term_jabber ID">jabber ID</a> + <a href="#term_AIM chat ID">AIM chat ID</a> <a href="#term_made">made</a> - <a href="#term_gender">gender</a> <a href="#term_personal mailbox">personal mailbox</a> - <a href="#term_openid">openid</a> - <a href="#term_ICQ chat ID">ICQ chat ID</a> - <a href="#term_MSN chat ID">MSN chat ID</a> - <a href="#term_AIM chat ID">AIM chat ID</a> + <a href="#term_holds account">holds account</a> </td></tr> <tr><th>in-range-of:</th> - <td> <a href="#term_member">member</a> - <a href="#term_maker">maker</a> + <td> <a href="#term_maker">maker</a> + <a href="#term_member">member</a> </td></tr> <tr><th>has subclass</th> - <td> <a href="#term_Person">Person</a> - <a href="#term_Organization">Organization</a> + <td> <a href="#term_Organization">Organization</a> + <a href="#term_Person">Person</a> <a href="#term_Group">Group</a> + </td></tr><tr><th>Disjoint With:</th> + <td> <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td></tr> </table> <p> -The <code>foaf:Agent</code> class is the class of agents; things that do stuff. A well -known sub-class is <code>foaf:Person</code>, representing people. Other kinds of agents -include <code>foaf:Organization</code> and <code>foaf:Group</code>. +The <code><a href="#term_Agent">foaf:Agent</a></code> class is the class of agents; things that do stuff. A well +known sub-class is <code><a href="#term_Person">foaf:Person</a></code>, representing people. Other kinds of agents +include <code><a href="#term_Organization">foaf:Organization</a></code> and <code><a href="#term_Group">foaf:Group</a></code>. </p> <p> -The <code>foaf:Agent</code> class is useful in a few places in FOAF where -<code>foaf:Person</code> would have been overly specific. For example, the IM chat ID +The <code><a href="#term_Agent">foaf:Agent</a></code> class is useful in a few places in FOAF where +<code><a href="#term_Person">foaf:Person</a></code> would have been overly specific. For example, the IM chat ID properties such as <code>jabberID</code> are typically associated with people, but sometimes belong to software bots. </p> <!-- todo: write rdfs:domain statements for those properties --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Organization"> - <h3>Class: foaf:Organization</h3> - <em>Organization</em> - An organization. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_Project" about="http://xmlns.com/foaf/0.1/Project" typeof="rdfs:Class"> + <h3>Class: foaf:Project</h3> + <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>subClassOf</th> - <td> <a href="#term_Agent">Agent</a> + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th>Disjoint With:</th> + <td> <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> + <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> </table> <p> -The <code>foaf:Organization</code> class represents a kind of <code>foaf:Agent</code> -corresponding to social instititutions such as companies, societies etc. +The <code><a href="#term_Project">foaf:Project</a></code> class represents the class of things that are 'projects'. These +may be formal or informal, collective or individual. It is often useful to indicate the +<code><a href="#term_homepage">foaf:homepage</a></code> of a <code><a href="#term_Project">foaf:Project</a></code>. </p> <p class="editorial"> -This is a more 'solid' class than <code>foaf:Group</code>, which allows -for more ad-hoc collections of individuals. These terms, like the corresponding -natural language concepts, have some overlap, but different emphasis. +Further work is needed to specify the connections between this class and the FOAF properties +<code><a href="#term_currentProject">foaf:currentProject</a></code> and <code><a href="#term_pastProject">foaf:pastProject</a></code>. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Document"> + </div> <div class="specterm" id="term_Document" about="http://xmlns.com/foaf/0.1/Document" typeof="rdfs:Class"> <h3>Class: foaf:Document</h3> <em>Document</em> - A document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_topic">topic</a> + <td> <a href="#term_sha1sum (hex)">sha1sum (hex)</a> <a href="#term_primary topic">primary topic</a> - <a href="#term_sha1sum (hex)">sha1sum (hex)</a> + <a href="#term_topic">topic</a> </td></tr> <tr><th>in-range-of:</th> - <td> <a href="#term_account service homepage">account service homepage</a> - <a href="#term_publications">publications</a> - <a href="#term_workplace homepage">workplace homepage</a> - <a href="#term_schoolHomepage">schoolHomepage</a> - <a href="#term_is primary topic of">is primary topic of</a> - <a href="#term_tipjar">tipjar</a> + <td> <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_account service homepage">account service homepage</a> + <a href="#term_homepage">homepage</a> <a href="#term_weblog">weblog</a> + <a href="#term_page">page</a> + <a href="#term_is primary topic of">is primary topic of</a> <a href="#term_interest">interest</a> - <a href="#term_openid">openid</a> - <a href="#term_homepage">homepage</a> <a href="#term_work info homepage">work info homepage</a> - <a href="#term_page">page</a> + <a href="#term_tipjar">tipjar</a> + <a href="#term_workplace homepage">workplace homepage</a> + <a href="#term_publications">publications</a> </td></tr> <tr><th>has subclass</th> <td> <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> + </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th>Disjoint With:</th> + <td> <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Organization"><a href="#term_Organization">Organization</a></span> + <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> + <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Project"><a href="#term_Project">Project</a></span> </td></tr> </table> <p> -The <code>foaf:Document</code> class represents those things which are, broadly conceived, +The <code><a href="#term_Document">foaf:Document</a></code> class represents those things which are, broadly conceived, 'documents'. </p> <p> -The <code>foaf:Image</code> class is a sub-class of <code>foaf:Document</code>, since all images +The <code><a href="#term_Image">foaf:Image</a></code> class is a sub-class of <code><a href="#term_Document">foaf:Document</a></code>, since all images are documents. </p> <p class="editorial"> We do not (currently) distinguish precisely between physical and electronic documents, or between copies of a work and the abstraction those copies embody. The relationship between -documents and their byte-stream representation needs clarification (see <code>foaf:sha1</code> +documents and their byte-stream representation needs clarification (see <code><a href="#term_sha1">foaf:sha1</a></code> for related issues). </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Image"> + </div> <div class="specterm" id="term_Image" about="http://xmlns.com/foaf/0.1/Image" typeof="rdfs:Class"> <h3>Class: foaf:Image</h3> <em>Image</em> - An image. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>in-domain-of:</th> <td> <a href="#term_thumbnail">thumbnail</a> <a href="#term_depicts">depicts</a> </td></tr> <tr><th>in-range-of:</th> <td> <a href="#term_image">image</a> <a href="#term_thumbnail">thumbnail</a> <a href="#term_depiction">depiction</a> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The class <code>foaf:Image</code> is a sub-class of <code>foaf:Document</code> +The class <code><a href="#term_Image">foaf:Image</a></code> is a sub-class of <code><a href="#term_Document">foaf:Document</a></code> corresponding to those documents which are images. </p> <p> Digital images (such as JPEG, PNG, GIF bitmaps, SVG diagrams etc.) are examples of -<code>foaf:Image</code>. +<code><a href="#term_Image">foaf:Image</a></code>. </p> <!-- much more we could/should say here --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_PersonalProfileDocument"> + </div> <div class="specterm" id="term_Person" about="http://xmlns.com/foaf/0.1/Person" typeof="rdfs:Class"> + <h3>Class: foaf:Person</h3> + <em>Person</em> - A person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_knows">knows</a> + <a href="#term_image">image</a> + <a href="#term_Surname">Surname</a> + <a href="#term_myersBriggs">myersBriggs</a> + <a href="#term_interest_topic">interest_topic</a> + <a href="#term_interest">interest</a> + <a href="#term_firstName">firstName</a> + <a href="#term_work info homepage">work info homepage</a> + <a href="#term_family_name">family_name</a> + <a href="#term_geekcode">geekcode</a> + <a href="#term_publications">publications</a> + <a href="#term_plan">plan</a> + <a href="#term_current project">current project</a> + <a href="#term_workplace homepage">workplace homepage</a> + <a href="#term_past project">past project</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_knows">knows</a> +</td></tr> <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://www.w3.org/2000/10/swap/pim/contact#Person"><a href="#term_Person">Person</a></span> + <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> + <span rel="rdfs:subClassOf" href="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"><a href="#term_Spatial Thing">Spatial Thing</a></span> + </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th>Disjoint With:</th> + <td> <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Organization"><a href="#term_Organization">Organization</a></span> + <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> + <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Project"><a href="#term_Project">Project</a></span> + </td></tr> + </table> + <p> +The <code><a href="#term_Person">foaf:Person</a></code> class represents people. Something is a +<code><a href="#term_Person">foaf:Person</a></code> if it is a person. We don't nitpic about whether they're +alive, dead, real, or imaginary. The <code><a href="#term_Person">foaf:Person</a></code> class is a sub-class of the +<code><a href="#term_Agent">foaf:Agent</a></code> class, since all people are considered 'agents' in FOAF. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Organization" about="http://xmlns.com/foaf/0.1/Organization" typeof="rdfs:Class"> + <h3>Class: foaf:Organization</h3> + <em>Organization</em> - An organization. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> + + <tr><th>subClassOf</th> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> + </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th>Disjoint With:</th> + <td> <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> + <span rel="owl:disjointWith" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> + </td></tr> + </table> + <p> +The <code><a href="#term_Organization">foaf:Organization</a></code> class represents a kind of <code><a href="#term_Agent">foaf:Agent</a></code> +corresponding to social instititutions such as companies, societies etc. +</p> + +<p class="editorial"> +This is a more 'solid' class than <code><a href="#term_Group">foaf:Group</a></code>, which allows +for more ad-hoc collections of individuals. These terms, like the corresponding +natural language concepts, have some overlap, but different emphasis. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_PersonalProfileDocument" about="http://xmlns.com/foaf/0.1/PersonalProfileDocument" typeof="rdfs:Class"> <h3>Class: foaf:PersonalProfileDocument</h3> <em>PersonalProfileDocument</em> - A personal profile RDF document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>subClassOf</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td></tr> </table> <p> -The <code>foaf:PersonalProfileDocument</code> class represents those -things that are a <code>foaf:Document</code>, and that use RDF to -describe properties of the person who is the <code>foaf:maker</code> -of the document. There is just one <code>foaf:Person</code> described in +The <code><a href="#term_PersonalProfileDocument">foaf:PersonalProfileDocument</a></code> class represents those +things that are a <code><a href="#term_Document">foaf:Document</a></code>, and that use RDF to +describe properties of the person who is the <code><a href="#term_maker">foaf:maker</a></code> +of the document. There is just one <code><a href="#term_Person">foaf:Person</a></code> described in the document, ie. -the person who <code>foaf:made</code> it and who will be its -<code>foaf:primaryTopic</code>. +the person who <code><a href="#term_made">foaf:made</a></code> it and who will be its +<code><a href="#term_primaryTopic">foaf:primaryTopic</a></code>. </p> <p> -The <code>foaf:PersonalProfileDocument</code> class, and FOAF's +The <code><a href="#term_PersonalProfileDocument">foaf:PersonalProfileDocument</a></code> class, and FOAF's associated conventions for describing it, captures an important deployment pattern for the FOAF vocabulary. FOAF is very often used in public RDF documents made available through the Web. There is a colloquial notion that these "FOAF files" are often <em>somebody's</em> -FOAF file. Through <code>foaf:PersonalProfileDocument</code> we provide +FOAF file. Through <code><a href="#term_PersonalProfileDocument">foaf:PersonalProfileDocument</a></code> we provide a machine-readable expression of this concept, providing a basis for FOAF documents to make claims about their maker and topic. </p> <p> -When describing a <code>foaf:PersonalProfileDocument</code> it is -typical (and useful) to describe its associated <code>foaf:Person</code> -using the <code>foaf:maker</code> property. Anything that is a -<code>foaf:Person</code> and that is the <code>foaf:maker</code> of some -<code>foaf:Document</code> will be the <code>foaf:primaryTopic</code> of -that <code>foaf:Document</code>. Although this can be inferred, it is +When describing a <code><a href="#term_PersonalProfileDocument">foaf:PersonalProfileDocument</a></code> it is +typical (and useful) to describe its associated <code><a href="#term_Person">foaf:Person</a></code> +using the <code><a href="#term_maker">foaf:maker</a></code> property. Anything that is a +<code><a href="#term_Person">foaf:Person</a></code> and that is the <code><a href="#term_maker">foaf:maker</a></code> of some +<code><a href="#term_Document">foaf:Document</a></code> will be the <code><a href="#term_primaryTopic">foaf:primaryTopic</a></code> of +that <code><a href="#term_Document">foaf:Document</a></code>. Although this can be inferred, it is helpful to include this information explicitly within the -<code>foaf:PersonalProfileDocument</code>. +<code><a href="#term_PersonalProfileDocument">foaf:PersonalProfileDocument</a></code>. </p> <p> For example, here is a fragment of a personal profile document which describes its author explicitly: </p> <div class="example"> <pre> &lt;foaf:Person rdf:nodeID="p1"&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; - &lt;foaf:homepage rdf:resource="http://rdfweb.org/people/danbri/"/&gt; + &lt;foaf:homepage rdf:resource="http://danbri.org/"/&gt; &lt;!-- etc... --&gt; &lt;/foaf:Person&gt; &lt;foaf:PersonalProfileDocument rdf:about=""&gt; &lt;foaf:maker rdf:nodeID="p1"/&gt; &lt;foaf:primaryTopic rdf:nodeID="p1"/&gt; &lt;/foaf:PersonalProfileDocument&gt; </pre> </div> <p> -Note that a <code>foaf:PersonalProfileDocument</code> will have some +Note that a <code><a href="#term_PersonalProfileDocument">foaf:PersonalProfileDocument</a></code> will have some representation as RDF. Typically this will be in W3C's RDF/XML syntax, however we leave open the possibility for the use of other notations, or representational conventions including automated transformations from HTML (<a href="http://www.w3.org/2004/01/rdxh/spec">GRDDL</a> spec for one such technique). </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_OnlineGamingAccount"> - <h3>Class: foaf:OnlineGamingAccount</h3> - <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - <tr><th>subClassOf</th> - <td> <a href="#term_Online Account">Online Account</a> - </td></tr> - </table> - <p> -A <code>foaf:OnlineGamingAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -online gaming. -</p> - -<p> -Examples might include <a href="http://everquest.station.sony.com/">EverQuest</a>, -<a href="http://www.xbox.com/live/">Xbox live</a>, <a -href="http://nwn.bioware.com/">Neverwinter Nights</a>, etc., as well as older text-based -systems (MOOs, MUDs and suchlike). -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_Person"> - <h3>Class: foaf:Person</h3> - <em>Person</em> - A person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>stable</td></tr> - <tr><th>in-domain-of:</th> - <td> <a href="#term_knows">knows</a> - <a href="#term_myersBriggs">myersBriggs</a> - <a href="#term_interest">interest</a> - <a href="#term_publications">publications</a> - <a href="#term_Surname">Surname</a> - <a href="#term_firstName">firstName</a> - <a href="#term_workplace homepage">workplace homepage</a> - <a href="#term_schoolHomepage">schoolHomepage</a> - <a href="#term_image">image</a> - <a href="#term_family_name">family_name</a> - <a href="#term_plan">plan</a> - <a href="#term_interest_topic">interest_topic</a> - <a href="#term_geekcode">geekcode</a> - <a href="#term_work info homepage">work info homepage</a> - <a href="#term_current project">current project</a> - <a href="#term_past project">past project</a> - </td></tr> - <tr><th>in-range-of:</th> - <td> <a href="#term_knows">knows</a> -</td></tr> <tr><th>subClassOf</th> - <td> <a href="#term_Agent">Agent</a> - </td></tr> - </table> - <p> -The <code>foaf:Person</code> class represents people. Something is a -<code>foaf:Person</code> if it is a person. We don't nitpic about whether they're -alive, dead, real, or imaginary. The <code>foaf:Person</code> class is a sub-class of the -<code>foaf:Agent</code> class, since all people are considered 'agents' in FOAF. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_Group"> + </div> <div class="specterm" id="term_Group" about="http://xmlns.com/foaf/0.1/Group" typeof="rdfs:Class"> <h3>Class: foaf:Group</h3> <em>Group</em> - A class of Agents. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> <tr><th>in-domain-of:</th> <td> <a href="#term_member">member</a> </td></tr> <tr><th>subClassOf</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:subClassOf" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> </table> <p> -The <code>foaf:Group</code> class represents a collection of individual agents (and may -itself play the role of a <code>foaf:Agent</code>, ie. something that can perform actions). +The <code><a href="#term_Group">foaf:Group</a></code> class represents a collection of individual agents (and may +itself play the role of a <code><a href="#term_Agent">foaf:Agent</a></code>, ie. something that can perform actions). </p> <p> This concept is intentionally quite broad, covering informal and ad-hoc groups, long-lived communities, organizational groups within a workplace, etc. Some such groups may have associated characteristics which could be captured in RDF (perhaps a -<code>foaf:homepage</code>, <code>foaf:name</code>, mailing list etc.). +<code><a href="#term_homepage">foaf:homepage</a></code>, <code><a href="#term_name">foaf:name</a></code>, mailing list etc.). </p> <p> -While a <code>foaf:Group</code> has the characteristics of a <code>foaf:Agent</code>, it -is also associated with a number of other <code>foaf:Agent</code>s (typically people) who -constitute the <code>foaf:Group</code>. FOAF provides a mechanism, the -<code>foaf:membershipClass</code> property, which relates a <code>foaf:Group</code> to a -sub-class of the class <code>foaf:Agent</code> who are members of the group. This is a +While a <code><a href="#term_Group">foaf:Group</a></code> has the characteristics of a <code><a href="#term_Agent">foaf:Agent</a></code>, it +is also associated with a number of other <code><a href="#term_Agent">foaf:Agent</a></code>s (typically people) who +constitute the <code><a href="#term_Group">foaf:Group</a></code>. FOAF provides a mechanism, the +<code><a href="#term_membershipClass">foaf:membershipClass</a></code> property, which relates a <code><a href="#term_Group">foaf:Group</a></code> to a +sub-class of the class <code><a href="#term_Agent">foaf:Agent</a></code> who are members of the group. This is a little complicated, but allows us to make group membership rules explicit. </p> <p>The markup (shown below) for defining a group is both complex and powerful. It allows group membership rules to match against any RDF-describable characteristics of the potential group members. As FOAF and similar vocabularies become more expressive in their ability to -describe individuals, the <code>foaf:Group</code> mechanism for categorising them into +describe individuals, the <code><a href="#term_Group">foaf:Group</a></code> mechanism for categorising them into groups also becomes more powerful. </p> <p> -While the formal description of membership criteria for a <code>foaf:Group</code> may -be complex, the basic mechanism for saying that someone is in a <code>foaf:Group</code> is -very simple. We simply use a <code>foaf:member</code> property of the -<code>foaf:Group</code> to indicate the agents that are members of the group. For example: +While the formal description of membership criteria for a <code><a href="#term_Group">foaf:Group</a></code> may +be complex, the basic mechanism for saying that someone is in a <code><a href="#term_Group">foaf:Group</a></code> is +very simple. We simply use a <code><a href="#term_member">foaf:member</a></code> property of the +<code><a href="#term_Group">foaf:Group</a></code> to indicate the agents that are members of the group. For example: </p> <div class="example"> <pre> &lt;foaf:Group&gt; &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; &lt;foaf:member&gt; &lt;foaf:Person&gt; &lt;foaf:name&gt;Libby Miller&lt;/foaf:name&gt; &lt;foaf:homepage rdf:resource="http://ilrt.org/people/libby/"/&gt; &lt;foaf:workplaceHomepage rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; &lt;/foaf:Person&gt; &lt;/foaf:member&gt; &lt;/foaf:Group&gt; </pre> </div> <p> Behind the scenes, further RDF statements can be used to express the rules for being a member of this group. End-users of FOAF need not pay attention to these details. </p> <p> -Here is an example. We define a <code>foaf:Group</code> representing those people who -are ILRT staff members. The <code>foaf:membershipClass</code> property connects the group (conceived of as a social +Here is an example. We define a <code><a href="#term_Group">foaf:Group</a></code> representing those people who +are ILRT staff members. The <code><a href="#term_membershipClass">foaf:membershipClass</a></code> property connects the group (conceived of as a social entity and agent in its own right) with the class definition for those people who constitute it. In this case, the rule is that all group members are in the ILRTStaffPerson class, which is in turn populated by all those things that are a -<code>foaf:Person</code> and which have a <code>foaf:workplaceHomepage</code> of +<code><a href="#term_Person">foaf:Person</a></code> and which have a <code><a href="#term_workplaceHomepage">foaf:workplaceHomepage</a></code> of http://www.ilrt.bris.ac.uk/. This is typical: FOAF groups are created by -specifying a sub-class of <code>foaf:Agent</code> (in fact usually this -will be a sub-class of <code>foaf:Person</code>), and giving criteria +specifying a sub-class of <code><a href="#term_Agent">foaf:Agent</a></code> (in fact usually this +will be a sub-class of <code><a href="#term_Person">foaf:Person</a></code>), and giving criteria for which things fall in or out of the sub-class. For this, we use the <code>owl:onProperty</code> and <code>owl:hasValue</code> properties, indicating the property/value pairs which must be true of matching agents. </p> <div class="example"> <pre> &lt;!-- here we see a FOAF group described. each foaf group may be associated with an OWL definition specifying the class of agents that constitute the group's membership --&gt; &lt;foaf:Group&gt; &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; &lt;foaf:membershipClass&gt; &lt;owl:Class rdf:about="http://ilrt.example.com/groups#ILRTStaffPerson"&gt; &lt;rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Person"/&gt; &lt;rdfs:subClassOf&gt; &lt;owl:Restriction&gt; &lt;owl:onProperty rdf:resource="http://xmlns.com/foaf/0.1/workplaceHomepage"/&gt; &lt;owl:hasValue rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; &lt;/owl:Restriction&gt; &lt;/rdfs:subClassOf&gt; &lt;/owl:Class&gt; &lt;/foaf:membershipClass&gt; &lt;/foaf:Group&gt; </pre> </div> <p> Note that while these example OWL rules for being in the eg:ILRTStaffPerson class are -based on a <code>foaf:Person</code> having a particular -<code>foaf:workplaceHomepage</code>, this places no obligations on the authors of actual +based on a <code><a href="#term_Person">foaf:Person</a></code> having a particular +<code><a href="#term_workplaceHomepage">foaf:workplaceHomepage</a></code>, this places no obligations on the authors of actual FOAF documents to include this information. If the information <em>is</em> included, then generic OWL tools may infer that some person is an eg:ILRTStaffPerson. To go the extra -step and infer that some eg:ILRTStaffPerson is a <code>foaf:member</code> of the group -whose <code>foaf:name</code> is "ILRT staff", tools will need some knowledge of the way +step and infer that some eg:ILRTStaffPerson is a <code><a href="#term_member">foaf:member</a></code> of the group +whose <code><a href="#term_name">foaf:name</a></code> is "ILRT staff", tools will need some knowledge of the way FOAF deals with groups. In other words, generic OWL technology gets us most of the way, -but the full <code>foaf:Group</code> machinery requires extra work for implimentors. +but the full <code><a href="#term_Group">foaf:Group</a></code> machinery requires extra work for implimentors. </p> <p> The current design names the relationship as pointing <em>from</em> the group, to the member. This is convenient when writing XML/RDF that encloses the members within markup that describes the group. Alternate representations of the same content are allowed in RDF, so you can write claims about the Person and the Group without having to nest either description inside the other. For (brief) example: </p> <div class="example"> <pre> &lt;foaf:Group&gt; &lt;foaf:member rdf:nodeID="libby"/&gt; &lt;!-- more about the group here --&gt; &lt;/foaf:Group&gt; &lt;foaf:Person rdf:nodeID="libby"&gt; &lt;!-- more about libby here --&gt; &lt;/foaf:Person&gt; </pre> </div> <p> -There is a FOAF <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> +There is a FOAF <a href="http://wiki.foaf-project.org/IssueTracker">issue tracker</a> associated with this FOAF term. A design goal is to make the most of W3C's <a href="http://www.w3.org/2001/sw/WebOnt">OWL</a> language for representing group-membership criteria, while also making it easy to leverage existing groups and datasets available online (eg. buddylists, mailing list membership lists etc). Feedback on the current design is solicited! Should we consider using SPARQL queries instead, for example? </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Project"> - <h3>Class: foaf:Project</h3> - <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_knows" about="http://xmlns.com/foaf/0.1/knows" typeof="rdf:Property"> + <h3>Property: foaf:knows</h3> + <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - - + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Person"<a href="#term_Person">Person</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:Project</code> class represents the class of things that are 'projects'. These -may be formal or informal, collective or individual. It is often useful to indicate the -<code>foaf:homepage</code> of a <code>foaf:Project</code>. +The <code><a href="#term_knows">foaf:knows</a></code> property relates a <code><a href="#term_Person">foaf:Person</a></code> to another +<code><a href="#term_Person">foaf:Person</a></code> that he or she knows. </p> -<p class="editorial"> -Further work is needed to specify the connections between this class and the FOAF properties -<code>foaf:currentProject</code> and <code>foaf:pastProject</code>. +<p> +We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. +stalkers need not apply). Since social attitudes and conventions on this topic vary +greatly between communities, counties and cultures, it is not appropriate for FOAF to be +overly-specific here. +</p> + +<p> +If someone <code><a href="#term_knows">foaf:knows</a></code> a person, it would be usual for +the relation to be reciprocated. However this doesn't mean that there is any obligation +for either party to publish FOAF describing this relationship. A <code><a href="#term_knows">foaf:knows</a></code> +relationship does not imply friendship, endorsement, or that a face-to-face meeting +has taken place: phone, fax, email, and smoke signals are all perfectly +acceptable ways of communicating with people you know. +</p> +<p> +You probably know hundreds of people, yet might only list a few in your public FOAF file. +That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not +list anyone else in it at all. +This illustrates the Semantic Web principle of partial description: RDF documents +rarely describe the entire picture. There is always more to be said, more information +living elsewhere in the Web (or in our heads...). +</p> + +<p> +Since <code><a href="#term_knows">foaf:knows</a></code> is vague by design, it may be suprising that it has uses. +Typically these involve combining other RDF properties. For example, an application might +look at properties of each <code><a href="#term_weblog">foaf:weblog</a></code> that was <code><a href="#term_made">foaf:made</a></code> by +someone you "<code><a href="#term_knows">foaf:knows</a></code>". Or check the newsfeed of the online photo archive +for each of these people, to show you recent photos taken by people you know. +</p> + +<p> +To provide additional levels of representation beyond mere 'knows', FOAF applications +can do several things. +</p> +<p> +They can use more precise relationships than <code><a href="#term_knows">foaf:knows</a></code> to relate people to +people. The original FOAF design included two of these ('knowsWell','friend') which we +removed because they were somewhat <em>awkward</em> to actually use, bringing an +inappopriate air of precision to an intrinsically vague concept. Other extensions have +been proposed, including Eric Vitiello's <a +href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for +FOAF. +</p> + +<p> +In addition to using more specialised inter-personal relationship types +(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states +of affairs which imply particular kinds of relationship. So for example, two people who +have the same value for their <code><a href="#term_workplaceHomepage">foaf:workplaceHomepage</a></code> property are +typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, +but the facts can be written in FOAF nevertheless. Similarly, if there exists a +<code><a href="#term_Document">foaf:Document</a></code> that has two people listed as its <code><a href="#term_maker">foaf:maker</a></code>s, +then they are probably collaborators of some kind. Or if two people appear in 100s of +digital photos together, there's a good chance they're friends and/or colleagues. </p> +<p> +So FOAF is quite pluralistic in its approach to representing relationships between people. +FOAF is built on top of a general purpose machine language for representing relationships +(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. +The problems are generally social rather than technical; deciding on appropriate ways of +describing these interconnections is a subtle art. +</p> + +<p> +Perhaps the most important use of <code><a href="#term_knows">foaf:knows</a></code> is, alongside the +<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF +file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more +interesting, with each FOAF file saying a little more about people, places, documents, things... +By mentioning other people (via <code><a href="#term_knows">foaf:knows</a></code> or other relationships), and by +providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for +FOAF indexing tools ('<a href="http://wiki.foaf-project.org/ScutterSpec">scutters</a>') to find +your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they +mention, and so on. This makes it possible to build FOAF aggregators without the need for +a centrally managed directory of FOAF files... +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_OnlineChatAccount"> - <h3>Class: foaf:OnlineChatAccount</h3> - <em>Online Chat Account</em> - An online chat account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_membershipClass" about="http://xmlns.com/foaf/0.1/membershipClass" typeof="rdf:Property"> + <h3>Property: foaf:membershipClass</h3> + <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> - <tr><th>subClassOf</th> - <td> <a href="#term_Online Account">Online Account</a> - </td></tr> + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -A <code>foaf:OnlineChatAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -chat / instant messaging. +The <code><a href="#term_membershipClass">foaf:membershipClass</a></code> property relates a <code><a href="#term_Group">foaf:Group</a></code> to an RDF +class representing a sub-class of <code><a href="#term_Agent">foaf:Agent</a></code> whose instances are all the +agents that are a <code><a href="#term_member">foaf:member</a></code> of the <code><a href="#term_Group">foaf:Group</a></code>. </p> <p> -This is a generalization of the FOAF Chat ID properties, -<code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, -<code>foaf:msnChatID</code>, <code>foaf:icqChatID</code> and -<code>foaf:yahooChatID</code>. +See <code><a href="#term_Group">foaf:Group</a></code> for details and examples. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_depiction" about="http://xmlns.com/foaf/0.1/depiction" typeof="rdf:Property"> + <h3>Property: foaf:depiction</h3> + <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Image"<a href="#term_Image">Image</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_depiction">foaf:depiction</a></code> property is a relationship between a thing and an +<code><a href="#term_Image">foaf:Image</a></code> that depicts it. As such it is an inverse of the +<code><a href="#term_depicts">foaf:depicts</a></code> relationship. </p> <p> -Unlike those simple properties, <code>foaf:OnlineAccount</code> and associated FOAF terms -allows us to describe a great variety of online accounts, without having to anticipate -them in the FOAF vocabulary. +A common use of <code><a href="#term_depiction">foaf:depiction</a></code> (and <code><a href="#term_depicts">foaf:depicts</a></code>) is to indicate +the contents of a digital image, for example the people or objects represented in an +online photo gallery. </p> <p> -For example, here is a description of an IRC chat account, specific to the Freenode IRC -network: +Extensions to this basic idea include '<a +href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in +photos), as well as richer photo metadata through the mechanism of using SVG paths to +indicate the <em>regions</em> of an image which depict some particular thing. See <a +href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> +for tools and details. +</p> + +<p> +The basic notion of 'depiction' could also be extended to deal with multimedia content +(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. +</p> + +<p> +The <code><a href="#term_depiction">foaf:depiction</a></code> property is a super-property of the more specific property +<code><a href="#term_img">foaf:img</a></code>, which is used more sparingly. You stand in a +<code><a href="#term_depiction">foaf:depiction</a></code> relation to <em>any</em> <code><a href="#term_Image">foaf:Image</a></code> that depicts +you, whereas <code><a href="#term_img">foaf:img</a></code> is typically used to indicate a few images that are +particularly representative. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_surname" about="http://xmlns.com/foaf/0.1/surname" typeof="rdf:Property"> + <h3>Property: foaf:surname</h3> + <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> +</td></tr> + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code><a href="#term_firstName">foaf:firstName</a></code>, +<code><a href="#term_givenname">foaf:givenname</a></code>, and <code><a href="#term_surname">foaf:surname</a></code>. These are not currently +stable or consistent; see the <a href="http://wiki.foaf-project.org/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. +</p> + +<p> +There is also a simple <code><a href="#term_name">foaf:name</a></code> property. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_maker" about="http://xmlns.com/foaf/0.1/maker" typeof="rdf:Property"> + <h3>Property: foaf:maker</h3> + <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Agent"<a href="#term_Agent">Agent</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_maker">foaf:maker</a></code> property relates something to a +<code><a href="#term_Agent">foaf:Agent</a></code> that <code><a href="#term_made">foaf:made</a></code> it. As such it is an +inverse of the <code><a href="#term_made">foaf:made</a></code> property. +</p> + +<p> +The <code><a href="#term_name">foaf:name</a></code> (or other <code>rdfs:label</code>) of the +<code><a href="#term_maker">foaf:maker</a></code> of something can be described as the +<code>dc:creator</code> of that thing.</p> + +<p> +For example, if the thing named by the URI +http://danbri.org/ has a +<code><a href="#term_maker">foaf:maker</a></code> that is a <code><a href="#term_Person">foaf:Person</a></code> whose +<code><a href="#term_name">foaf:name</a></code> is 'Dan Brickley', we can conclude that +http://danbri.org/ has a <code>dc:creator</code> of 'Dan +Brickley'. +</p> + +<p> +FOAF descriptions are encouraged to use <code>dc:creator</code> only for +simple textual names, and to use <code><a href="#term_maker">foaf:maker</a></code> to indicate +creators, rather than risk confusing creators with their names. This +follows most Dublin Core usage. See <a +href="http://wiki.foaf-project.org/UsingDublinCoreCreator">UsingDublinCoreCreator</a> +for details. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_pastProject" about="http://xmlns.com/foaf/0.1/pastProject" typeof="rdf:Property"> + <h3>Property: foaf:pastProject</h3> + <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p>After a <code><a href="#term_Person">foaf:Person</a></code> is no longer involved with a +<code><a href="#term_currentProject">foaf:currentProject</a></code>, or has been inactive for some time, a +<code><a href="#term_pastProject">foaf:pastProject</a></code> relationship can be used. This indicates that +the <code><a href="#term_Person">foaf:Person</a></code> was involved with the described project at one +point. +</p> + +<p> +If the <code><a href="#term_Person">foaf:Person</a></code> has stopped working on a project because it +has been completed (successfully or otherwise), <code><a href="#term_pastProject">foaf:pastProject</a></code> is +applicable. In general, <code><a href="#term_currentProject">foaf:currentProject</a></code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code><a href="#term_pastProject">foaf:pastProject</a></code> describes what they've previously been doing. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_workplaceHomepage" about="http://xmlns.com/foaf/0.1/workplaceHomepage" typeof="rdf:Property"> + <h3>Property: foaf:workplaceHomepage</h3> + <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_workplaceHomepage">foaf:workplaceHomepage</a></code> of a <code><a href="#term_Person">foaf:Person</a></code> is a +<code><a href="#term_Document">foaf:Document</a></code> that is the <code><a href="#term_homepage">foaf:homepage</a></code> of a +<code><a href="#term_Organization">foaf:Organization</a></code> that they work for. +</p> + +<p> +By directly relating people to the homepages of their workplace, we have a simple convention +that takes advantage of a set of widely known identifiers, while taking care not to confuse the +things those identifiers identify (ie. organizational homepages) with the actual organizations +those homepages describe. </p> <div class="example"> +<p> +For example, Dan Brickley works at W3C. Dan is a <code><a href="#term_Person">foaf:Person</a></code> with a +<code><a href="#term_homepage">foaf:homepage</a></code> of http://danbri.org/; W3C is a +<code><a href="#term_Organization">foaf:Organization</a></code> with a <code><a href="#term_homepage">foaf:homepage</a></code> of http://www.w3.org/. This +allows us to say that Dan has a <code><a href="#term_workplaceHomepage">foaf:workplaceHomepage</a></code> of http://www.w3.org/. +</p> + <pre> &lt;foaf:Person&gt; - &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; - &lt;foaf:holdsAccount&gt; - &lt;foaf:OnlineAccount&gt; - &lt;rdf:type rdf:resource="http://xmlns.com/foaf/0.1/OnlineChatAccount"/&gt; - &lt;foaf:accountServiceHomepage rdf:resource="http://www.freenode.net/irc_servers.shtml"/&gt; - &lt;foaf:accountName&gt;danbri&lt;/foaf:accountName&gt; - &lt;/foaf:OnlineAccount&gt; - &lt;/foaf:holdsAccount&gt; + &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; &lt;/foaf:Person&gt; </pre> </div> + <p> -Note that it may be impolite to carelessly reveal someone else's chat identifier (which -might also serve as an indicate of email address) As with email, there are privacy and -anti-SPAM considerations. FOAF does not currently provide a way to represent an -obfuscated chat ID (ie. there is no parallel to the <code>foaf:mbox</code> / -<code>foaf:mbox_sha1sum</code> mapping). +Note that several other FOAF properties work this way; +<code><a href="#term_schoolHomepage">foaf:schoolHomepage</a></code> is the most similar. In general, FOAF often indirectly +identifies things via Web page identifiers where possible, since these identifiers are widely +used and known. FOAF does not currently have a term for the name of the relation (eg. +"workplace") that holds +between a <code><a href="#term_Person">foaf:Person</a></code> and an <code><a href="#term_Organization">foaf:Organization</a></code> that they work for. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_fundedBy" about="http://xmlns.com/foaf/0.1/fundedBy" typeof="rdf:Property"> + <h3>Property: foaf:fundedBy</h3> + <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_fundedBy">foaf:fundedBy</a></code> property relates something to something else that has provided +funding for it. +</p> + +<p class="editorial"> +This property is under-specified, experimental, and should be considered liable to change. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_publications" about="http://xmlns.com/foaf/0.1/publications" typeof="rdf:Property"> + <h3>Property: foaf:publications</h3> + <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_publications">foaf:publications</a></code> property indicates a <code><a href="#term_Document">foaf:Document</a></code> +listing (primarily in human-readable form) some publications associated with the +<code><a href="#term_Person">foaf:Person</a></code>. Such documents are typically published alongside one's +<code><a href="#term_homepage">foaf:homepage</a></code>. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_schoolHomepage" about="http://xmlns.com/foaf/0.1/schoolHomepage" typeof="rdf:Property"> + <h3>Property: foaf:schoolHomepage</h3> + <em>schoolHomepage</em> - A homepage of a school attended by the person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code>schoolHomepage</code> property relates a <code><a href="#term_Person">foaf:Person</a></code> to a +<code><a href="#term_Document">foaf:Document</a></code> that is the <code><a href="#term_homepage">foaf:homepage</a></code> of a School that the +person attended. +</p> + +<p> +FOAF does not (currently) define a class for 'School' (if it did, it would probably be as +a sub-class of <code><a href="#term_Organization">foaf:Organization</a></code>). The original application area for +<code><a href="#term_schoolHomepage">foaf:schoolHomepage</a></code> was for 'schools' in the British-English sense; however +American-English usage has dominated, and it is now perfectly reasonable to describe +Universities, Colleges and post-graduate study using <code><a href="#term_schoolHomepage">foaf:schoolHomepage</a></code>. </p> + <p> -In addition to the generic <code>foaf:OnlineAccount</code> and -<code>foaf:OnlineChatAccount</code> mechanisms, -FOAF also provides several convenience chat ID properties -(<code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, <code>foaf:icqChatID</code>, -<code>foaf:msnChatID</code>,<code>foaf:yahooChatID</code>). -These serve as as a shorthand for some common cases; their use may not always be -appropriate. -</p> -<p class="editorial"> -We should specify some mappings between the abbreviated and full representations of -<a href="http://www.jabber.org/">Jabber</a>, <a href="http://www.aim.com/">AIM</a>, <a -href="http://chat.msn.com/">MSN</a>, <a href="http://web.icq.com/icqchat/">ICQ</a>, <a -href="http://chat.yahoo.com/">Yahoo!</a> and <a href="http://chat.msn.com/">MSN</a> chat -accounts. This requires us to identify an appropriate <code>foaf:accountServiceHomepage</code> for each. If we -wanted to make the <code>foaf:OnlineAccount</code> mechanism even more generic, we could -invent a relationship that holds between a <code>foaf:OnlineAccount</code> instance and a -convenience property. To continue the example above, we could describe how <a -href="http://www.freenode.net/">Freenode</a> could define a property 'fn:freenodeChatID' -corresponding to Freenode online accounts. +This very basic facility provides a basis for a low-cost, decentralised approach to +classmate-reunion and suchlike. Instead of requiring a central database, we can use FOAF +to express claims such as 'I studied <em>here</em>' simply by mentioning a +school's homepage within FOAF files. Given the homepage of a school, it is easy for +FOAF aggregators to lookup this property in search of people who attended that school. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_myersBriggs"> - <h3>Property: foaf:myersBriggs</h3> - <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_homepage" about="http://xmlns.com/foaf/0.1/homepage" typeof="rdf:Property"> + <h3>Property: foaf:homepage</h3> + <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> </td></tr> - + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> - <!-- todo: expand acronym --> - -<p> -The <code>foaf:myersBriggs</code> property represents the Myers Briggs (MBTI) approach to -personality taxonomy. It is included in FOAF as an example of a property -that takes certain constrained values, and to give some additional detail to the FOAF -files of those who choose to include it. The <code>foaf:myersBriggs</code> property applies only to the -<code>foaf:Person</code> class; wherever you see it, you can infer it is being applied to -a person. + <p> +The <code><a href="#term_homepage">foaf:homepage</a></code> property relates something to a homepage about it. </p> <p> -The <code>foaf:myersBriggs</code> property is interesting in that it illustrates how -FOAF can serve as a carrier for various kinds of information, without necessarily being -commited to any associated worldview. Not everyone will find myersBriggs (or star signs, -or blood types, or the four humours) a useful perspective on human behaviour and -personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses -the underlying theory, any more than the existence of <code>foaf:weblog</code> is an -endorsement of soapboxes. +Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but +constrains <code><a href="#term_homepage">foaf:homepage</a></code> so that there can be only one thing that has any +particular homepage. </p> <p> -The values for <code>foaf:myersBriggs</code> are the following 16 4-letter textual codes: -ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, -ENTP, ISFJ. If multiple of these properties are applicable, they are represented by -applying multiple properties to a person. +A 'homepage' in this sense is a public Web document, typically but not necessarily +available in HTML format. The page has as a <code><a href="#term_topic">foaf:topic</a></code> the thing whose +homepage it is. The homepage is usually controlled, edited or published by the thing whose +homepage it is; as such one might look to a homepage for information on its owner from its +owner. This works for people, companies, organisations etc. </p> <p> -For further reading on MBTI, see various online sources (eg. <a -href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There -are various online sites which offer quiz-based tools for determining a person's MBTI -classification. The owners of the MBTI trademark have probably not approved of these. +The <code><a href="#term_homepage">foaf:homepage</a></code> property is a sub-property of the more general +<code><a href="#term_page">foaf:page</a></code> property for relating a thing to a page about that thing. See also +<code><a href="#term_topic">foaf:topic</a></code>, the inverse of the <code><a href="#term_page">foaf:page</a></code> property. </p> -<p> -This FOAF property suggests some interesting uses, some of which could perhaps be used to -test the claims made by proponents of the MBTI (eg. an analysis of weblog postings -filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are -self-selecting; MBTI categories may not be uniformly appealing to the people they -describe. Further, there is probably a degree of cultural specificity implicit in the -assumptions made by many questionaire-based MBTI tools; the MBTI system may not make -sense in cultural settings beyond those it was created for. -</p> -<p> -See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a -href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> -for further background and examples. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_page" about="http://xmlns.com/foaf/0.1/page" typeof="rdf:Property"> + <h3>Property: foaf:page</h3> + <em>page</em> - A page or document about this thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_page">foaf:page</a></code> property relates a thing to a document about that thing. </p> <p> -Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting -Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the -trademark in the UK. +As such it is an inverse of the <code><a href="#term_topic">foaf:topic</a></code> property, which relates a document +to a thing that the document is about. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_mbox_sha1sum"> - <h3>Property: foaf:mbox_sha1sum</h3> - <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_msnChatID" about="http://xmlns.com/foaf/0.1/msnChatID" typeof="rdf:Property"> + <h3>Property: foaf:msnChatID</h3> + <em>MSN chat ID</em> - An MSN chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> <p> -A <code>foaf:mbox_sha1sum</code> of a <code>foaf:Person</code> is a textual representation of -the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an -Internet mailbox that they stand in a <code>foaf:mbox</code> relationship to. +The <code><a href="#term_msnChatID">foaf:msnChatID</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to a textual +identifier assigned to them in the MSN online Chat system. +See Microsoft's the <a href="http://chat.msn.com/">MSN chat</a> site for more details (or for a +message saying <em>"MSN Chat is not currently compatible with your Internet browser and/or +computer operating system"</em> if your computing platform is deemed unsuitable). </p> -<p> -In other words, if you have a mailbox (<code>foaf:mbox</code>) but don't want to reveal its -address, you can take that address and generate a <code>foaf:mbox_sha1sum</code> representation -of it. Just as a <code>foaf:mbox</code> can be used as an indirect identifier for its owner, we -can do the same with <code>foaf:mbox_sha1sum</code> since there is only one -<code>foaf:Person</code> with any particular value for that property. +<p class="editorial"> +It is not currently clear how MSN chat IDs relate to the more general Microsoft Passport +identifiers. </p> -<p> -Many FOAF tools use <code>foaf:mbox_sha1sum</code> in preference to exposing mailbox -information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques -include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's -documentation</a>) and the use of <a -href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for -mail filtering. +<p>See <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> (and <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> -<p> -Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a -href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's -weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing -whitespace, when computing a <code>foaf:mbox_sha1sum</code> property. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_made" about="http://xmlns.com/foaf/0.1/made" typeof="rdf:Property"> + <h3>Property: foaf:made</h3> + <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_made">foaf:made</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> +to something <code><a href="#term_made">foaf:made</a></code> by it. As such it is an +inverse of the <code><a href="#term_maker">foaf:maker</a></code> property, which relates a thing to +something that made it. See <code><a href="#term_made">foaf:made</a></code> for more details on the +relationship between these FOAF terms and related Dublin Core vocabulary. </p> -<!-- what about Javascript. move refs to wiki maybe. --> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_aimChatID"> - <h3>Property: foaf:aimChatID</h3> - <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_logo" about="http://xmlns.com/foaf/0.1/logo" typeof="rdf:Property"> + <h3>Property: foaf:logo</h3> + <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> </td></tr> - + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:aimChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. -See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM -screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a -href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. +The <code><a href="#term_logo">foaf:logo</a></code> property is used to indicate a graphical logo of some kind. +<em>It is probably underspecified...</em> </p> -<p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_age" about="http://xmlns.com/foaf/0.1/age" typeof="rdf:Property"> + <h3>Property: foaf:age</h3> + <em>age</em> - The age in years of some agent. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span> </td></tr> + </table> + <p> +The <code><a href="#term_age">foaf:age</a></code> property is a relationship between a <code><a href="#term_Agent">foaf:Agent</a></code> +and a string representing the year in which they were born (Gregorian calendar). +See also <code><a href="#term_birthday">foaf:birthday</a></code>. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_firstName"> - <h3>Property: foaf:firstName</h3> - <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_mbox_sha1sum" about="http://xmlns.com/foaf/0.1/mbox_sha1sum" typeof="rdf:Property"> + <h3>Property: foaf:mbox_sha1sum</h3> + <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> - + <p> +A <code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> of a <code><a href="#term_Person">foaf:Person</a></code> is a textual representation of +the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an +Internet mailbox that they stand in a <code><a href="#term_mbox">foaf:mbox</a></code> relationship to. +</p> -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. +<p> +In other words, if you have a mailbox (<code><a href="#term_mbox">foaf:mbox</a></code>) but don't want to reveal its +address, you can take that address and generate a <code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> representation +of it. Just as a <code><a href="#term_mbox">foaf:mbox</a></code> can be used as an indirect identifier for its owner, we +can do the same with <code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> since there is only one +<code><a href="#term_Person">foaf:Person</a></code> with any particular value for that property. +</p> + +<p> +Many FOAF tools use <code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> in preference to exposing mailbox +information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques +include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's +documentation</a>) and the use of <a +href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for +mail filtering. </p> <p> -There is also a simple <code>foaf:name</code> property. +Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a +href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's +weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing +whitespace, when computing a <code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> property. </p> +<!-- what about Javascript. move refs to wiki maybe. --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_tipjar"> - <h3>Property: foaf:tipjar</h3> - <em>tipjar</em> - A tipjar document for this agent, describing means for payment and reward. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_thumbnail" about="http://xmlns.com/foaf/0.1/thumbnail" typeof="rdf:Property"> + <h3>Property: foaf:thumbnail</h3> + <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Image"><a href="#term_Image">Image</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Image"<a href="#term_Image">Image</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:tipjar</code> property relates an <code>foaf:Agent</code> -to a <code>foaf:Document</code> that describes some mechanisms for -paying or otherwise rewarding that agent. + <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> + +<p> +The <code><a href="#term_thumbnail">foaf:thumbnail</a></code> property is a relationship between a +full-size <code><a href="#term_Image">foaf:Image</a></code> and a smaller, representative <code><a href="#term_Image">foaf:Image</a></code> +that has been derrived from it. </p> <p> -The <code>foaf:tipjar</code> property was created following <a -href="http://rdfweb.org/mt/foaflog/archives/2004/02/12/20.07.32/">discussions</a> -about simple, lightweight mechanisms that could be used to encourage -rewards and payment for content exchanged online. An agent's -<code>foaf:tipjar</code> page(s) could describe informal ("Send me a -postcard!", "here's my book, music and movie wishlist") or formal -(machine-readable micropayment information) information about how that -agent can be paid or rewarded. The reward is not associated with any -particular action or content from the agent concerned. A link to -a service such as <a href="http://www.paypal.com/">PayPal</a> is the -sort of thing we might expect to find in a tipjar document. +It is typical in FOAF to express <code><a href="#term_img">foaf:img</a></code> and <code><a href="#term_depiction">foaf:depiction</a></code> +relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). +A <code><a href="#term_thumbnail">foaf:thumbnail</a></code> might be clipped or otherwise reduced such that it does not +depict everything that the full image depicts. Therefore FOAF does not specify that a +thumbnail <code><a href="#term_depicts">foaf:depicts</a></code> everything that the image it is derrived from depicts. +However, FOAF does expect that anything depicted in the thumbnail will also be depicted in +the source image. </p> +<!-- todo: add RDF rules here showing this --> + <p> -Note that the value of a <code>foaf:tipjar</code> property is just a -document (which can include anchors into HTML pages). We expect, but -do not currently specify, that this will evolve into a hook -for finding more machine-readable information to support payments, -rewards. The <code>foaf:OnlineAccount</code> machinery is also relevant, -although the information requirements for automating payments are not -currently clear. +A <code><a href="#term_thumbnail">foaf:thumbnail</a></code> is typically small enough that it can be +loaded and viewed quickly before a viewer decides to download the larger +version. They are often used in online photo gallery applications. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_yahooChatID"> - <h3>Property: foaf:yahooChatID</h3> - <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_birthday" about="http://xmlns.com/foaf/0.1/birthday" typeof="rdf:Property"> + <h3>Property: foaf:birthday</h3> + <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:yahooChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the Yahoo online Chat system. -See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their -service. Yahoo chat IDs are also used across several other Yahoo services, including email and -<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. +The <code><a href="#term_birthday">foaf:birthday</a></code> property is a relationship between a <code><a href="#term_Agent">foaf:Agent</a></code> +and a string representing the month and day in which they were born (Gregorian calendar). +See <a href="http://wiki.foaf-project.org/BirthdayIssue">BirthdayIssue</a> for details of related properties that can +be used to describe such things in more flexible ways. </p> -<p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_dnaChecksum"> - <h3>Property: foaf:dnaChecksum</h3> - <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_weblog" about="http://xmlns.com/foaf/0.1/weblog" typeof="rdf:Property"> + <h3>Property: foaf:weblog</h3> + <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - - + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:dnaChecksum</code> property is mostly a joke, but -also a reminder that there will be lots of different identifying -properties for people, some of which we might find disturbing. +The <code><a href="#term_weblog">foaf:weblog</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to a weblog of +that agent. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_mbox"> - <h3>Property: foaf:mbox</h3> - <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_depicts" about="http://xmlns.com/foaf/0.1/depicts" typeof="rdf:Property"> + <h3>Property: foaf:depicts</h3> + <em>depicts</em> - A thing depicted in this representation. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Image"><a href="#term_Image">Image</a></span> </td></tr> - + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:mbox</code> property is a relationship between the owner of a mailbox and -a mailbox. These are typically identified using the mailto: URI scheme (see <a -href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). -</p> - -<p> -Note that there are many mailboxes (eg. shared ones) which are not the -<code>foaf:mbox</code> of anyone. Furthermore, a person can have multiple -<code>foaf:mbox</code> properties. +The <code><a href="#term_depicts">foaf:depicts</a></code> property is a relationship between a <code><a href="#term_Image">foaf:Image</a></code> +and something that the image depicts. As such it is an inverse of the +<code><a href="#term_depiction">foaf:depiction</a></code> relationship. See <code><a href="#term_depiction">foaf:depiction</a></code> for further notes. </p> -<p> -In FOAF, we often see <code>foaf:mbox</code> used as an indirect way of identifying its -owner. This works even if the mailbox is itself out of service (eg. 10 years old), since -the property is defined in terms of its primary owner, and doesn't require the mailbox to -actually be being used for anything. -</p> -<p> -Many people are wary of sharing information about their mailbox addresses in public. To -address such concerns whilst continuing the FOAF convention of indirectly identifying -people by referring to widely known properties, FOAF also provides the -<code>foaf:mbox_sha1sum</code> mechanism, which is a relationship between a person and -the value you get from passing a mailbox URI to the SHA1 mathematical function. -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_img"> - <h3>Property: foaf:img</h3> - <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_primaryTopic" about="http://xmlns.com/foaf/0.1/primaryTopic" typeof="rdf:Property"> + <h3>Property: foaf:primaryTopic</h3> + <em>primary topic</em> - The primary topic of some page or document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:img</code> property relates a <code>foaf:Person</code> to a -<code>foaf:Image</code> that represents them. Unlike its super-property -<code>foaf:depiction</code>, we only use <code>foaf:img</code> when an image is -particularly representative of some person. The analogy is with the image(s) that might -appear on someone's homepage, rather than happen to appear somewhere in their photo album. +The <code><a href="#term_primaryTopic">foaf:primaryTopic</a></code> property relates a document to the +main thing that the document is about. </p> <p> -Unlike the more general <code>foaf:depiction</code> property (and its inverse, -<code>foaf:depicts</code>), the <code>foaf:img</code> property is only used with -representations of people (ie. instances of <code>foaf:Person</code>). So you can't use -it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more -restricted than <code>foaf:depiction</code> so we can have a useful way of picking out a -reasonable image to represent someone. FOAF defines <code>foaf:img</code> as a -sub-property of <code>foaf:depiction</code>, which means that the latter relationship is -implied whenever two things are related by the former. +The <code><a href="#term_primaryTopic">foaf:primaryTopic</a></code> property is <em>functional</em>: for +any document it applies to, it can have at most one value. This is +useful, as it allows for data merging. In many cases it may be difficult +for third parties to determine the primary topic of a document, but in +a useful number of cases (eg. descriptions of movies, restaurants, +politicians, ...) it should be reasonably obvious. Documents are very +often the most authoritative source of information about their own +primary topics, although this cannot be guaranteed since documents cannot be +assumed to be accurate, honest etc. </p> <p> -Note that <code>foaf:img</code> does not have any restrictions on the dimensions, colour -depth, format etc of the <code>foaf:Image</code> it references. +It is an inverse of the <code><a href="#term_isPrimaryTopicOf">foaf:isPrimaryTopicOf</a></code> property, which relates a +thing to a document <em>primarily</em> about that thing. The choice between these two +properties is purely pragmatic. When describing documents, we +use <code><a href="#term_primaryTopic">foaf:primaryTopic</a></code> former to point to the things they're about. When +describing things (people etc.), it is useful to be able to directly cite documents which +have those things as their main topic - so we use <code><a href="#term_isPrimaryTopicOf">foaf:isPrimaryTopicOf</a></code>. In this +way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a +href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they +have descriptions of. </p> -<p> -Terminology: note that <code>foaf:img</code> is a property (ie. relationship), and that -<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It -might have been more helpful to call <code>foaf:img</code> 'mugshot' or similar; instead -it is named by analogy to the HTML IMG element. -</p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_depicts"> - <h3>Property: foaf:depicts</h3> - <em>depicts</em> - A thing depicted in this representation. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_interest" about="http://xmlns.com/foaf/0.1/interest" typeof="rdf:Property"> + <h3>Property: foaf:interest</h3> + <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Image">Image</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> - + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:depicts</code> property is a relationship between a <code>foaf:Image</code> -and something that the image depicts. As such it is an inverse of the -<code>foaf:depiction</code> relationship. See <code>foaf:depiction</code> for further notes. +The <code><a href="#term_interest">foaf:interest</a></code> property represents an interest of a +<code><a href="#term_Agent">foaf:Agent</a></code>, through +indicating a <code><a href="#term_Document">foaf:Document</a></code> whose <code><a href="#term_topic">foaf:topic</a></code>(s) broadly +characterises that interest.</p> + +<p class="example"> +For example, we might claim that a person or group has an interest in RDF by saying they +stand in a <code><a href="#term_interest">foaf:interest</a></code> relationship to the <a +href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying +<em>"this agent is interested in the topic of this page"</em>. +</p> + +<p class="example"> +Uses of <code><a href="#term_interest">foaf:interest</a></code> include a variety of filtering and resource discovery +applications. It could be used, for example, to help find answers to questions such as +"Find me members of this organisation with an interest in XML who have also contributed to +<a href="http://www.cpan.org/">CPAN</a>)". +</p> + +<p> +This approach to characterising interests is intended to compliment other mechanisms (such +as the use of controlled vocabulary). It allows us to use a widely known set of unique +identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled +syntax, this makes data merging much easier than the use of free-text characterisations of +interest. </p> +<p> +Note that interest does not imply expertise, and that this FOAF term provides no support +for characterising levels of interest: passing fads and lifelong quests are both examples +of someone's <code><a href="#term_interest">foaf:interest</a></code>. Describing interests in full is a complex +undertaking; <code><a href="#term_interest">foaf:interest</a></code> provides one basic component of FOAF's approach to +these problems. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_holdsAccount"> - <h3>Property: foaf:holdsAccount</h3> - <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_topic_interest" about="http://xmlns.com/foaf/0.1/topic_interest" typeof="rdf:Property"> + <h3>Property: foaf:topic_interest</h3> + <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:holdsAccount</code> property relates a <code>foaf:Agent</code> to an -<code>foaf:OnlineAccount</code> for which they are the sole account holder. See -<code>foaf:OnlineAccount</code> for usage details. + <p class="editorial"> +The <code><a href="#term_topic_interest">foaf:topic_interest</a></code> property is generally found to be confusing and ill-defined +and is a candidate for removal. The goal was to be link a person to some thing that is a topic +of their interests (rather than, per <code><a href="#term_interest">foaf:interest</a></code> to a page that is about such a +topic). </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_gender"> - <h3>Property: foaf:gender</h3> - <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_firstName" about="http://xmlns.com/foaf/0.1/firstName" typeof="rdf:Property"> + <h3>Property: foaf:firstName</h3> + <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:gender</code> property relates a <code>foaf:Agent</code> (typically a -<code>foaf:Person</code>) to a string representing its gender. In most cases the value -will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). -Like all FOAF properties, there is in general no requirement to use -<code>foaf:gender</code> in any particular document or description. Values other than -'male' and 'female' may be used, but are not enumerated here. The <code>foaf:gender</code> -mechanism is not intended to capture the full variety of biological, social and sexual -concepts associated with the word 'gender'. -</p> - -<p> -Anything that has a <code>foaf:gender</code> property will be some kind of -<code>foaf:Agent</code>. However there are kinds of <code>foaf:Agent</code> to -which the concept of gender isn't applicable (eg. a <code>foaf:Group</code>). FOAF does not -currently include a class corresponding directly to "the type of thing that has a gender". -At any point in time, a <code>foaf:Agent</code> has at most one value for -<code>foaf:gender</code>. FOAF does not treat <code>foaf:gender</code> as a -<em>static</em> property; the same individual may have different values for this property -at different times. -</p> + -<p> -Note that FOAF's notion of gender isn't defined biologically or anatomically - this would -be tricky since we have a broad notion that applies to all <code>foaf:Agent</code>s -(including robots - eg. Bender from Futurama is 'male'). As stressed above, -FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated -with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise -between the clinical and the social/psychological. In general, a person will be the best -authority on their <code>foaf:gender</code>. Feedback on this design is -particularly welcome (via the FOAF mailing list, -<a href="http://rdfweb.org/mailman/listinfo/rdfweb-dev">rdfweb-dev</a>). We have tried to -be respectful of diversity without attempting to catalogue or enumerate that diversity. +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code><a href="#term_firstName">foaf:firstName</a></code>, +<code><a href="#term_givenname">foaf:givenname</a></code>, and <code><a href="#term_surname">foaf:surname</a></code>. These are not currently +stable or consistent; see the <a href="http://wiki.foaf-project.org/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> <p> -This may also be a good point for a periodic reminder: as with all FOAF properties, -documents that use '<code>foaf:gender</code>' will on occassion be innacurate, misleading -or outright false. FOAF, like all open means of communication, supports <em>lying</em>. - Application authors using -FOAF data should always be cautious in their presentation of unverified information, but be -particularly sensitive to issues and risks surrounding sex and gender (including privacy -and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit -<code>foaf:gender</code> when describing themselves and others, and to allow at least for -values other than 'male' and 'female' as options. Users of information -conveyed via FOAF (as via information conveyed through mobile phone text messages, email, -Internet chat, HTML pages etc.) should be skeptical of unverified information. +There is also a simple <code><a href="#term_name">foaf:name</a></code> property. </p> - -<!-- -b/g article currently offline. -http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 ---> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_geekcode"> - <h3>Property: foaf:geekcode</h3> - <em>geekcode</em> - A textual geekcode for this person, see http://www.geekcode.com/geek.html <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_aimChatID" about="http://xmlns.com/foaf/0.1/aimChatID" typeof="rdf:Property"> + <h3>Property: foaf:aimChatID</h3> + <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:geekcode</code> property is used to represent a 'Geek Code' for some -<code>foaf:Person</code>. +The <code><a href="#term_aimChatID">foaf:aimChatID</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to a textual +identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. +See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM +screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a +href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. </p> <p> -See the <a href="http://www.geekcode.com/geek.html">Code of the Geeks</a> specification for -details of the code, which provides a somewhat frivolous and willfully obscure mechanism for -characterising technical expertise, interests and habits. The <code>foaf:geekcode</code> -property is not bound to any particular version of the code. The last published version -of the code was v3.12 in March 1996. +See <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> (and <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> -<p> -As the <a href="http://www.geekcode.com/">Geek Code</a> website notes, the code played a small -(but amusing) part in the history of the Internet. The <code>foaf:geekcode</code> property -exists in acknowledgement of this history. It'll never be 1996 again. -</p> -<p> -Note that the Geek Code is a densely packed collections of claims about the person it applies -to; to express these claims explicitly in RDF/XML would be incredibly verbose. The syntax of the -Geek Code allows for '&lt;' and '&gt;' characters, which have special meaning in RDF/XML. -Consequently these should be carefully escaped in markup. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_isPrimaryTopicOf" about="http://xmlns.com/foaf/0.1/isPrimaryTopicOf" typeof="rdf:Property"> + <h3>Property: foaf:isPrimaryTopicOf</h3> + <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> + </table> + <p> +The <code><a href="#term_isPrimaryTopicOf">foaf:isPrimaryTopicOf</a></code> property relates something to a document that is +mainly about it. </p> -<p> -An example Geek Code: -</p> -<p class="example"> - GED/J d-- s:++>: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++>$ -PE++>$ Y++ PGP++ t- 5+++ X++ R+++>$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** -</p> <p> -...would be written in FOAF RDF/XML as follows: +The <code><a href="#term_isPrimaryTopicOf">foaf:isPrimaryTopicOf</a></code> property is <em>inverse functional</em>: for +any document that is the value of this property, there is at most one thing in the world +that is the primary topic of that document. This is useful, as it allows for data +merging, as described in the documentation for its inverse, <code><a href="#term_primaryTopic">foaf:primaryTopic</a></code>. </p> -<p class="example"> -&lt;foaf:geekcode&gt; - GED/J d-- s:++&amp;gt;: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ - w--- O- M+ V-- PS++&amp;gt;$ PE++&amp;gt;$ Y++ PGP++ t- 5+++ X++ R+++&amp;gt;$ - tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** -&lt;/foaf:geekcode&gt; +<p> +<code><a href="#term_page">foaf:page</a></code> is a super-property of <code><a href="#term_isPrimaryTopicOf">foaf:isPrimaryTopicOf</a></code>. The change +of terminology between the two property names reflects the utility of 'primaryTopic' and its +inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation +to some document X, also has a <code><a href="#term_page">foaf:page</a></code> relationship to it. </p> - - <p> -See also the <a href="http://www.everything2.com/index.pl?node=GEEK%20CODE">geek code</a> entry -in <a href="http://www.everything2.com/">everything2</a>, which tells us that <em>the -geek code originated in 1993; it was inspired (according to the inventor) by previous "bear", -"smurf" and "twink" style-and-sexual-preference codes from lesbian and gay newsgroups</em>. -There is also a <a href="http://www.ebb.org/ungeek/">Geek Code Decoder Page</a> and a form-based -<a href="http://www.joereiss.net/geek/geek.html">generator</a>. +Note that <code><a href="#term_homepage">foaf:homepage</a></code>, is a sub-property of both <code><a href="#term_page">foaf:page</a></code> and +<code><a href="#term_isPrimarySubjectOf">foaf:isPrimarySubjectOf</a></code>. The awkwardly named +<code><a href="#term_isPrimarySubjectOf">foaf:isPrimarySubjectOf</a></code> is less specific, and can be used with any document +that is primarily about the thing of interest (ie. not just on homepages). </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_birthday"> - <h3>Property: foaf:birthday</h3> - <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_workInfoHomepage" about="http://xmlns.com/foaf/0.1/workInfoHomepage" typeof="rdf:Property"> + <h3>Property: foaf:workInfoHomepage</h3> + <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> - + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:birthday</code> property is a relationship between a <code>foaf:Agent</code> -and a string representing the month and day in which they were born (Gregorian calendar). -See <a href="http://rdfweb.org/topic/BirthdayIssue">BirthdayIssue</a> for details of related properties that can -be used to describe such things in more flexible ways. +The <code><a href="#term_workInfoHomepage">foaf:workInfoHomepage</a></code> of a <code><a href="#term_Person">foaf:Person</a></code> is a +<code><a href="#term_Document">foaf:Document</a></code> that describes their work. It is generally (but not necessarily) a +different document from their <code><a href="#term_homepage">foaf:homepage</a></code>, and from any +<code><a href="#term_workplaceHomepage">foaf:workplaceHomepage</a></code>(s) they may have. </p> +<p> +The purpose of this property is to distinguish those pages you often see, which describe +someone's professional role within an organisation or project. These aren't really homepages, +although they share some characterstics. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_theme"> + </div> <div class="specterm" id="term_theme" about="http://xmlns.com/foaf/0.1/theme" typeof="rdf:Property"> <h3>Property: foaf:theme</h3> <em>theme</em> - A theme. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - - + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:theme</code> property is rarely used and under-specified. The intention was +The <code><a href="#term_theme">foaf:theme</a></code> property is rarely used and under-specified. The intention was to use it to characterise interest / themes associated with projects and groups. Further work is needed to meet these goals. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_family_name"> - <h3>Property: foaf:family_name</h3> - <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_yahooChatID" about="http://xmlns.com/foaf/0.1/yahooChatID" typeof="rdf:Property"> + <h3>Property: foaf:yahooChatID</h3> + <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> - - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. + <p> +The <code><a href="#term_yahooChatID">foaf:yahooChatID</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to a textual +identifier assigned to them in the Yahoo online Chat system. +See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their +service. Yahoo chat IDs are also used across several other Yahoo services, including email and +<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. </p> <p> -There is also a simple <code>foaf:name</code> property. +See <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> (and <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_phone"> - <h3>Property: foaf:phone</h3> - <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_title" about="http://xmlns.com/foaf/0.1/title" typeof="rdf:Property"> + <h3>Property: foaf:title</h3> + <em>title</em> - Title (Mr, Mrs, Ms, Dr. etc) <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:phone</code> of something is a phone, typically identified using the tel: URI -scheme. +The approriate values for <code><a href="#term_title">foaf:title</a></code> are not formally constrained, and will +vary across community and context. Values such as 'Mr', 'Mrs', 'Ms', 'Dr' etc. are +expected. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_plan"> - <h3>Property: foaf:plan</h3> - <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_img" about="http://xmlns.com/foaf/0.1/img" typeof="rdf:Property"> + <h3>Property: foaf:img</h3> + <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> - - </table> - <!-- orig contrib'd by Cardinal --> - -<p>The <code>foaf:plan</code> property provides a space for a -<code>foaf:Person</code> to hold some arbitrary content that would appear in -a traditional '.plan' file. The plan file was stored in a user's home -directory on a UNIX machine, and displayed to people when the user was -queried with the finger utility.</p> - -<p>A plan file could contain anything. Typical uses included brief -comments, thoughts, or remarks on what a person had been doing lately. Plan -files were also prone to being witty or simply osbscure. Others may be more -creative, writing any number of seemingly random compositions in their plan -file for people to stumble upon.</p> - -<p> -See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the -Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The -<code>foaf:geekcode</code> property may also be of interest. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_depiction"> - <h3>Property: foaf:depiction</h3> - <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> -</td> </tr> - </table> - <p> -The <code>foaf:depiction</code> property is a relationship between a thing and an -<code>foaf:Image</code> that depicts it. As such it is an inverse of the -<code>foaf:depicts</code> relationship. -</p> - -<p> -A common use of <code>foaf:depiction</code> (and <code>foaf:depicts</code>) is to indicate -the contents of a digital image, for example the people or objects represented in an -online photo gallery. + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Image"<a href="#term_Image">Image</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + <p> +The <code><a href="#term_img">foaf:img</a></code> property relates a <code><a href="#term_Person">foaf:Person</a></code> to a +<code><a href="#term_Image">foaf:Image</a></code> that represents them. Unlike its super-property +<code><a href="#term_depiction">foaf:depiction</a></code>, we only use <code><a href="#term_img">foaf:img</a></code> when an image is +particularly representative of some person. The analogy is with the image(s) that might +appear on someone's homepage, rather than happen to appear somewhere in their photo album. </p> <p> -Extensions to this basic idea include '<a -href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in -photos), as well as richer photo metadata through the mechanism of using SVG paths to -indicate the <em>regions</em> of an image which depict some particular thing. See <a -href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> -for tools and details. +Unlike the more general <code><a href="#term_depiction">foaf:depiction</a></code> property (and its inverse, +<code><a href="#term_depicts">foaf:depicts</a></code>), the <code><a href="#term_img">foaf:img</a></code> property is only used with +representations of people (ie. instances of <code><a href="#term_Person">foaf:Person</a></code>). So you can't use +it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more +restricted than <code><a href="#term_depiction">foaf:depiction</a></code> so we can have a useful way of picking out a +reasonable image to represent someone. FOAF defines <code><a href="#term_img">foaf:img</a></code> as a +sub-property of <code><a href="#term_depiction">foaf:depiction</a></code>, which means that the latter relationship is +implied whenever two things are related by the former. </p> <p> -The basic notion of 'depiction' could also be extended to deal with multimedia content -(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. +Note that <code><a href="#term_img">foaf:img</a></code> does not have any restrictions on the dimensions, colour +depth, format etc of the <code><a href="#term_Image">foaf:Image</a></code> it references. </p> <p> -The <code>foaf:depiction</code> property is a super-property of the more specific property -<code>foaf:img</code>, which is used more sparingly. You stand in a -<code>foaf:depiction</code> relation to <em>any</em> <code>foaf:Image</code> that depicts -you, whereas <code>foaf:img</code> is typically used to indicate a few images that are -particularly representative. -</p> +Terminology: note that <code><a href="#term_img">foaf:img</a></code> is a property (ie. relationship), and that +<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It +might have been more helpful to call <code><a href="#term_img">foaf:img</a></code> 'mugshot' or similar; instead +it is named by analogy to the HTML IMG element. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_nick"> + </div> <div class="specterm" id="term_nick" about="http://xmlns.com/foaf/0.1/nick" typeof="rdf:Property"> <h3>Property: foaf:nick</h3> <em>nickname</em> - A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:nick</code> property relates a <code>foaf:Person</code> to a short (often +The <code><a href="#term_nick">foaf:nick</a></code> property relates a <code><a href="#term_Person">foaf:Person</a></code> to a short (often abbreviated) nickname, such as those use in IRC chat, online accounts, and computer logins. </p> <p> This property is necessarily vague, because it does not indicate any particular naming control authority, and so cannot distinguish a person's login from their (possibly various) IRC nicknames or other similar identifiers. However it has some utility, since many people use the same string (or slight variants) across a variety of such environments. </p> <p> For specific controlled sets of names (relating primarily to Instant Messanger accounts), -FOAF provides some convenience properties: <code>foaf:jabberID</code>, -<code>foaf:aimChatID</code>, <code>foaf:msnChatID</code> and -<code>foaf:icqChatID</code>. Beyond this, the problem of representing such accounts is not +FOAF provides some convenience properties: <code><a href="#term_jabberID">foaf:jabberID</a></code>, +<code><a href="#term_aimChatID">foaf:aimChatID</a></code>, <code><a href="#term_msnChatID">foaf:msnChatID</a></code> and +<code><a href="#term_icqChatID">foaf:icqChatID</a></code>. Beyond this, the problem of representing such accounts is not peculiar to Instant Messanging, and it is not scaleable to attempt to enumerate each -naming database as a distinct FOAF property. The <code>foaf:OnlineAccount</code> term (and +naming database as a distinct FOAF property. The <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> term (and supporting vocabulary) are provided as a more verbose and more expressive generalisation of these properties. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_page"> - <h3>Property: foaf:page</h3> - <em>page</em> - A page or document about this thing. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:page</code> property relates a thing to a document about that thing. -</p> - -<p> -As such it is an inverse of the <code>foaf:topic</code> property, which relates a document -to a thing that the document is about. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_isPrimaryTopicOf"> - <h3>Property: foaf:isPrimaryTopicOf</h3> - <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_mbox" about="http://xmlns.com/foaf/0.1/mbox" typeof="rdf:Property"> + <h3>Property: foaf:mbox</h3> + <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:isPrimaryTopicOf</code> property relates something to a document that is -mainly about it. -</p> - - -<p> -The <code>foaf:isPrimaryTopicOf</code> property is <em>inverse functional</em>: for -any document that is the value of this property, there is at most one thing in the world -that is the primary topic of that document. This is useful, as it allows for data -merging, as described in the documentation for its inverse, <code>foaf:primaryTopic</code>. -</p> - -<p> -<code>foaf:page</code> is a super-property of <code>foaf:isPrimaryTopicOf</code>. The change -of terminology between the two property names reflects the utility of 'primaryTopic' and its -inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation -to some document X, also has a <code>foaf:page</code> relationship to it. -</p> -<p> -Note that <code>foaf:homepage</code>, is a sub-property of both <code>foaf:page</code> and -<code>foaf:isPrimarySubjectOf</code>. The awkwardly named -<code>foaf:isPrimarySubjectOf</code> is less specific, and can be used with any document -that is primarily about the thing of interest (ie. not just on homepages). +The <code><a href="#term_mbox">foaf:mbox</a></code> property is a relationship between the owner of a mailbox and +a mailbox. These are typically identified using the mailto: URI scheme (see <a +href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_name"> - <h3>Property: foaf:name</h3> - <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> - <p>The <code>foaf:name</code> of something is a simple textual string.</p> - <p> -XML language tagging may be used to indicate the language of the name. For example: +Note that there are many mailboxes (eg. shared ones) which are not the +<code><a href="#term_mbox">foaf:mbox</a></code> of anyone. Furthermore, a person can have multiple +<code><a href="#term_mbox">foaf:mbox</a></code> properties. </p> -<div class="example"> -<code> -&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; -</code> -</div> - <p> -FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it -does provide a basic level of interoperability. See the <a -href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for status of work on this issue. +In FOAF, we often see <code><a href="#term_mbox">foaf:mbox</a></code> used as an indirect way of identifying its +owner. This works even if the mailbox is itself out of service (eg. 10 years old), since +the property is defined in terms of its primary owner, and doesn't require the mailbox to +actually be being used for anything. </p> <p> -The <code>foaf:name</code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped -values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. +Many people are wary of sharing information about their mailbox addresses in public. To +address such concerns whilst continuing the FOAF convention of indirectly identifying +people by referring to widely known properties, FOAF also provides the +<code><a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a></code> mechanism, which is a relationship between a person and +the value you get from passing a mailbox URI to the SHA1 mathematical function. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_topic"> - <h3>Property: foaf:topic</h3> - <em>topic</em> - A topic of some page or document. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_geekcode" about="http://xmlns.com/foaf/0.1/geekcode" typeof="rdf:Property"> + <h3>Property: foaf:geekcode</h3> + <em>geekcode</em> - A textual geekcode for this person, see http://www.geekcode.com/geek.html <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:topic</code> property relates a document to a thing that the document is -about. +The <code><a href="#term_geekcode">foaf:geekcode</a></code> property is used to represent a 'Geek Code' for some +<code><a href="#term_Person">foaf:Person</a></code>. </p> <p> -As such it is an inverse of the <code>foaf:page</code> property, which relates a thing to -a document about that thing. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_interest"> - <h3>Property: foaf:interest</h3> - <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:interest</code> property represents an interest of a -<code>foaf:Agent</code>, through -indicating a <code>foaf:Document</code> whose <code>foaf:topic</code>(s) broadly -characterises that interest.</p> - -<p class="example"> -For example, we might claim that a person or group has an interest in RDF by saying they -stand in a <code>foaf:interest</code> relationship to the <a -href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying -<em>"this agent is interested in the topic of this page"</em>. +See the <a href="http://www.geekcode.com/geek.html">Code of the Geeks</a> specification for +details of the code, which provides a somewhat frivolous and willfully obscure mechanism for +characterising technical expertise, interests and habits. The <code><a href="#term_geekcode">foaf:geekcode</a></code> +property is not bound to any particular version of the code. The last published version +of the code was v3.12 in March 1996. </p> -<p class="example"> -Uses of <code>foaf:interest</code> include a variety of filtering and resource discovery -applications. It could be used, for example, to help find answers to questions such as -"Find me members of this organisation with an interest in XML who have also contributed to -<a href="http://www.cpan.org/">CPAN</a>)". +<p> +As the <a href="http://www.geekcode.com/">Geek Code</a> website notes, the code played a small +(but amusing) part in the history of the Internet. The <code><a href="#term_geekcode">foaf:geekcode</a></code> property +exists in acknowledgement of this history. It'll never be 1996 again. </p> <p> -This approach to characterising interests is intended to compliment other mechanisms (such -as the use of controlled vocabulary). It allows us to use a widely known set of unique -identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled -syntax, this makes data merging much easier than the use of free-text characterisations of -interest. +Note that the Geek Code is a densely packed collections of claims about the person it applies +to; to express these claims explicitly in RDF/XML would be incredibly verbose. The syntax of the +Geek Code allows for '&lt;' and '&gt;' characters, which have special meaning in RDF/XML. +Consequently these should be carefully escaped in markup. </p> - <p> -Note that interest does not imply expertise, and that this FOAF term provides no support -for characterising levels of interest: passing fads and lifelong quests are both examples -of someone's <code>foaf:interest</code>. Describing interests in full is a complex -undertaking; <code>foaf:interest</code> provides one basic component of FOAF's approach to -these problems. +An example Geek Code: </p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_pastProject"> - <h3>Property: foaf:pastProject</h3> - <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - <p>After a <code>foaf:Person</code> is no longer involved with a -<code>foaf:currentProject</code>, or has been inactive for some time, a -<code>foaf:pastProject</code> relationship can be used. This indicates that -the <code>foaf:Person</code> was involved with the described project at one -point. +<p class="example"> + GED/J d-- s:++>: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++>$ +PE++>$ Y++ PGP++ t- 5+++ X++ R+++>$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** </p> <p> -If the <code>foaf:Person</code> has stopped working on a project because it -has been completed (successfully or otherwise), <code>foaf:pastProject</code> is -applicable. In general, <code>foaf:currentProject</code> is used to indicate -someone's current efforts (and implied interests, concerns etc.), while -<code>foaf:pastProject</code> describes what they've previously been doing. +...would be written in FOAF RDF/XML as follows: </p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_workInfoHomepage"> - <h3>Property: foaf:workInfoHomepage</h3> - <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:workInfoHomepage</code> of a <code>foaf:Person</code> is a -<code>foaf:Document</code> that describes their work. It is generally (but not necessarily) a -different document from their <code>foaf:homepage</code>, and from any -<code>foaf:workplaceHomepage</code>(s) they may have. +<p class="example"> +&lt;foaf:geekcode&gt; + GED/J d-- s:++&amp;gt;: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ + w--- O- M+ V-- PS++&amp;gt;$ PE++&amp;gt;$ Y++ PGP++ t- 5+++ X++ R+++&amp;gt;$ + tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** +&lt;/foaf:geekcode&gt; </p> + <p> -The purpose of this property is to distinguish those pages you often see, which describe -someone's professional role within an organisation or project. These aren't really homepages, -although they share some characterstics. +See also the <a href="http://www.everything2.com/index.pl?node=GEEK%20CODE">geek code</a> entry +in <a href="http://www.everything2.com/">everything2</a>, which tells us that <em>the +geek code originated in 1993; it was inspired (according to the inventor) by previous "bear", +"smurf" and "twink" style-and-sexual-preference codes from lesbian and gay newsgroups</em>. +There is also a <a href="http://www.ebb.org/ungeek/">Geek Code Decoder Page</a> and a form-based +<a href="http://www.joereiss.net/geek/geek.html">generator</a>. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_publications"> - <h3>Property: foaf:publications</h3> - <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_accountServiceHomepage" about="http://xmlns.com/foaf/0.1/accountServiceHomepage" typeof="rdf:Property"> + <h3>Property: foaf:accountServiceHomepage</h3> + <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/OnlineAccount"><a href="#term_Online Account">Online Account</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:publications</code> property indicates a <code>foaf:Document</code> -listing (primarily in human-readable form) some publications associated with the -<code>foaf:Person</code>. Such documents are typically published alongside one's -<code>foaf:homepage</code>. +The <code><a href="#term_accountServiceHomepage">foaf:accountServiceHomepage</a></code> property indicates a relationship between a +<code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> and the homepage of the supporting service provider. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_sha1"> - <h3>Property: foaf:sha1</h3> - <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_myersBriggs" about="http://xmlns.com/foaf/0.1/myersBriggs" typeof="rdf:Property"> + <h3>Property: foaf:myersBriggs</h3> + <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:sha1</code> property relates a <code>foaf:Document</code> to the textual form of -a SHA1 hash of (some representation of) its contents. + <!-- todo: expand acronym --> + +<p> +The <code><a href="#term_myersBriggs">foaf:myersBriggs</a></code> property represents the Myers Briggs (MBTI) approach to +personality taxonomy. It is included in FOAF as an example of a property +that takes certain constrained values, and to give some additional detail to the FOAF +files of those who choose to include it. The <code><a href="#term_myersBriggs">foaf:myersBriggs</a></code> property applies only to the +<code><a href="#term_Person">foaf:Person</a></code> class; wherever you see it, you can infer it is being applied to +a person. </p> -<p class="editorial"> -The design for this property is neither complete nor coherent. The <code>foaf:Document</code> -class is currently used in a way that allows multiple instances at different URIs to have the -'same' contents (and hence hash). If <code>foaf:sha1</code> is an owl:InverseFunctionalProperty, -we could deduce that several such documents were the self-same thing. A more careful design is -needed, which distinguishes documents in a broad sense from byte sequences. +<p> +The <code><a href="#term_myersBriggs">foaf:myersBriggs</a></code> property is interesting in that it illustrates how +FOAF can serve as a carrier for various kinds of information, without necessarily being +commited to any associated worldview. Not everyone will find myersBriggs (or star signs, +or blood types, or the four humours) a useful perspective on human behaviour and +personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses +the underlying theory, any more than the existence of <code><a href="#term_weblog">foaf:weblog</a></code> is an +endorsement of soapboxes. </p> +<p> +The values for <code><a href="#term_myersBriggs">foaf:myersBriggs</a></code> are the following 16 4-letter textual codes: +ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, +ENTP, ISFJ. If multiple of these properties are applicable, they are represented by +applying multiple properties to a person. +</p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_membershipClass"> - <h3>Property: foaf:membershipClass</h3> - <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - - </table> - <p> -The <code>foaf:membershipClass</code> property relates a <code>foaf:Group</code> to an RDF -class representing a sub-class of <code>foaf:Agent</code> whose instances are all the -agents that are a <code>foaf:member</code> of the <code>foaf:Group</code>. +<p> +For further reading on MBTI, see various online sources (eg. <a +href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There +are various online sites which offer quiz-based tools for determining a person's MBTI +classification. The owners of the MBTI trademark have probably not approved of these. +</p> + +<p> +This FOAF property suggests some interesting uses, some of which could perhaps be used to +test the claims made by proponents of the MBTI (eg. an analysis of weblog postings +filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are +self-selecting; MBTI categories may not be uniformly appealing to the people they +describe. Further, there is probably a degree of cultural specificity implicit in the +assumptions made by many questionaire-based MBTI tools; the MBTI system may not make +sense in cultural settings beyond those it was created for. +</p> + +<p> +See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a +href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> +for further background and examples. </p> <p> -See <code>foaf:Group</code> for details and examples. +Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting +Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the +trademark in the UK. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_based_near"> + </div> <div class="specterm" id="term_based_near" about="http://xmlns.com/foaf/0.1/based_near" typeof="rdf:Property"> <h3>Property: foaf:based_near</h3> <em>based near</em> - A location that something is based near, for some broadly human notion of near. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - - + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"><a href="#term_Spatial Thing">Spatial Thing</a></span> +</td></tr> + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing"<a href="#term_Spatial Thing">Spatial Thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <!-- note: is this mis-specified? perhaps range ought to also be SpatialThing, so we can have multiple labels on the same point? --> -<p>The <code>foaf:based_near</code> relationship relates two "spatial +<p>The <code><a href="#term_based_near">foaf:based_near</a></code> relationship relates two "spatial things" (anything that can <em>be somewhere</em>), the latter typically described using the geo:lat / geo:long <a href="http://www.w3.org/2003/01/geo/wgs84_pos#">geo-positioning vocabulary</a> (See <a href="http://esw.w3.org/topic/GeoInfo">GeoInfo</a> in the W3C semweb wiki for details). This allows us to say describe the typical latitute and longitude of, say, a Person (people are spatial things - they can be places) without implying that a precise location has been given. </p> <p>We do not say much about what 'near' means in this context; it is a 'rough and ready' concept. For a more precise treatment, see <a href="http://esw.w3.org/topic/GeoOnion">GeoOnion vocab</a> design discussions, which are aiming to produce a more sophisticated vocabulary for such purposes. </p> <p> FOAF files often make use of the <code>contact:nearestAirport</code> property. This illustrates the distinction between FOAF documents (which may make claims using <em>any</em> RDF vocabulary) and the core FOAF vocabulary defined by this specification. For further reading on the use of <code>nearestAirport</code> see <a -href="http://rdfweb.org/topic/UsingContactNearestAirport">UsingContactNearestAirport</a> in the +href="http://wiki.foaf-project.org/UsingContactNearestAirport">UsingContactNearestAirport</a> in the FOAF wiki. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_jabberID"> - <h3>Property: foaf:jabberID</h3> - <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_family_name" about="http://xmlns.com/foaf/0.1/family_name" typeof="rdf:Property"> + <h3>Property: foaf:family_name</h3> + <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:jabberID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging -system. -See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber -protocols and tools. -</p> - -<p> -Jabber, unlike several other online messaging systems, is based on an open, publically -documented protocol specification, and has a variety of open source implementations. Jabber IDs -can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For -the purposes of FOAF, these are all considered to be kinds of <code>foaf:Agent</code> (ie. -things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The -<code>foaf:jabberID</code> property is provided as a basic hook to help support RDF description -of Jabber users and services. -</p> - -<p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_thumbnail"> - <h3>Property: foaf:thumbnail</h3> - <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Image">Image</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> -</td> </tr> - </table> - <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> - -<p> -The <code>foaf:thumbnail</code> property is a relationship between a -full-size <code>foaf:Image</code> and a smaller, representative <code>foaf:Image</code> -that has been derrived from it. -</p> + -<p> -It is typical in FOAF to express <code>foaf:img</code> and <code>foaf:depiction</code> -relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). -A <code>foaf:thumbnail</code> might be clipped or otherwise reduced such that it does not -depict everything that the full image depicts. Therefore FOAF does not specify that a -thumbnail <code>foaf:depicts</code> everything that the image it is derrived from depicts. -However, FOAF does expect that anything depicted in the thumbnail will also be depicted in -the source image. +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code><a href="#term_firstName">foaf:firstName</a></code>, +<code><a href="#term_givenname">foaf:givenname</a></code>, and <code><a href="#term_surname">foaf:surname</a></code>. These are not currently +stable or consistent; see the <a href="http://wiki.foaf-project.org/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> -<!-- todo: add RDF rules here showing this --> - <p> -A <code>foaf:thumbnail</code> is typically small enough that it can be -loaded and viewed quickly before a viewer decides to download the larger -version. They are often used in online photo gallery applications. +There is also a simple <code><a href="#term_name">foaf:name</a></code> property. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_fundedBy"> - <h3>Property: foaf:fundedBy</h3> - <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_phone" about="http://xmlns.com/foaf/0.1/phone" typeof="rdf:Property"> + <h3>Property: foaf:phone</h3> + <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:fundedBy</code> property relates something to something else that has provided -funding for it. -</p> - -<p class="editorial"> -This property is under-specified, experimental, and should be considered liable to change. +The <code><a href="#term_phone">foaf:phone</a></code> of something is a phone, typically identified using the tel: URI +scheme. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_icqChatID"> + </div> <div class="specterm" id="term_icqChatID" about="http://xmlns.com/foaf/0.1/icqChatID" typeof="rdf:Property"> <h3>Property: foaf:icqChatID</h3> <em>ICQ chat ID</em> - An ICQ chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:icqChatID</code> property relates a <code>foaf:Agent</code> to a textual +The <code><a href="#term_icqChatID">foaf:icqChatID</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to a textual identifier assigned to them in the ICQ Chat system. See the <a href="http://web.icq.com/icqchat/">icq chat</a> site for more details of the 'icq' service. Their "<a href="http://www.icq.com/products/whatisicq.html">What is ICQ?</a>" document provides a basic overview, while their "<a href="http://company.icq.com/info/">About Us</a> page notes that ICQ has been acquired by AOL. Despite the relationship with AOL, ICQ is at the time of writing maintained as a separate identity from the AIM brand (see -<code>foaf:aimChatID</code>). +<code><a href="#term_aimChatID">foaf:aimChatID</a></code>). </p> <p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +See <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> (and <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code>) for a more general (and verbose) mechanism for describing IM and chat accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_surname"> - <h3>Property: foaf:surname</h3> - <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. -</p> - -<p> -There is also a simple <code>foaf:name</code> property. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_msnChatID"> - <h3>Property: foaf:msnChatID</h3> - <em>MSN chat ID</em> - An MSN chat ID <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:msnChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the MSN online Chat system. -See Microsoft's the <a href="http://chat.msn.com/">MSN chat</a> site for more details (or for a -message saying <em>"MSN Chat is not currently compatible with your Internet browser and/or -computer operating system"</em> if your computing platform is deemed unsuitable). -</p> - -<p class="editorial"> -It is not currently clear how MSN chat IDs relate to the more general Microsoft Passport -identifiers. -</p> - -<p>See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_title"> - <h3>Property: foaf:title</h3> - <em>title</em> - Title (Mr, Mrs, Ms, Dr. etc) <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> - <p> -The approriate values for <code>foaf:title</code> are not formally constrained, and will -vary across community and context. Values such as 'Mr', 'Mrs', 'Ms', 'Dr' etc. are -expected. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_openid"> - <h3>Property: foaf:openid</h3> - <em>openid</em> - An OpenID for an Agent. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_topic" about="http://xmlns.com/foaf/0.1/topic" typeof="rdf:Property"> + <h3>Property: foaf:topic</h3> + <em>topic</em> - A topic of some page or document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -A <code>foaf:openid</code> is a property of a <code>foaf:Agent</code> that associates it with a document that can be used as an <a -href="http://www.w3.org/TR/webarch/#indirect-identification">indirect identifier</a> in the manner of the <a href="http://openid.net/specs/openid-authentication-1_1.html">OpenID</a> - "Identity URL". As the OpenID 1.1 specification notes, OpenID itself"<em>does not provide any mechanism to -exchange profile information, though Consumers of an Identity can learn more about an End User from any public, semantically -interesting documents linked thereunder (FOAF, RSS, Atom, vCARD, etc.)</em>". In this way, FOAF and OpenID complement each other; -neither provides a stand-alone approach to online "trust", but combined they can address interesting parts of this larger problem -space. -</p> - -<p> -The <code>foaf:openid</code> property is "inverse functional", meaning that anything that is the foaf:openid of something, is the -<code>foaf:openid</code> of no more than one thing. FOAF is agnostic as to whether there are (according to the relevant OpenID -specifications) OpenID URIs that are equally associated with multiple Agents. FOAF offers sub-classes of Agent, ie. -<code>foaf:Organization</code> and <code>foaf:Group</code>, that allow for such scenarios to be consistent with the notion that any -foaf:openid is the foaf:openid of just one <code>foaf:Agent</code>. +The <code><a href="#term_topic">foaf:topic</a></code> property relates a document to a thing that the document is +about. </p> <p> -FOAF does not mandate any particular URI scheme for use as <code>foaf:openid</code> values. The OpenID 1.1 specification includes a <a -href="http://openid.net/specs/openid-authentication-1_1.html#delegating_authentication">delegation model</a> that is often used to -allow a weblog or homepage document to also serve in OpenID authentication via "link rel" HTML markup. This deployment model provides a -convenient connection to FOAF, since a similar <a href="http://xmlns.com/foaf/spec/#sec-autodesc">technique</a> is used for FOAF -autodiscovery in HTML. A single document can, for example, serve both as a homepage and an OpenID identity URL. +As such it is an inverse of the <code><a href="#term_page">foaf:page</a></code> property, which relates a thing to +a document about that thing. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_maker"> - <h3>Property: foaf:maker</h3> - <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_jabberID" about="http://xmlns.com/foaf/0.1/jabberID" typeof="rdf:Property"> + <h3>Property: foaf:jabberID</h3> + <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Agent">Agent</a> -</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Inverse Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:maker</code> property relates something to a -<code>foaf:Agent</code> that <code>foaf:made</code> it. As such it is an -inverse of the <code>foaf:made</code> property. +The <code><a href="#term_jabberID">foaf:jabberID</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to a textual +identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging +system. +See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber +protocols and tools. </p> <p> -The <code>foaf:name</code> (or other <code>rdfs:label</code>) of the -<code>foaf:maker</code> of something can be described as the -<code>dc:creator</code> of that thing.</p> - -<p> -For example, if the thing named by the URI -http://rdfweb.org/people/danbri/ has a -<code>foaf:maker</code> that is a <code>foaf:Person</code> whose -<code>foaf:name</code> is 'Dan Brickley', we can conclude that -http://rdfweb.org/people/danbri/ has a <code>dc:creator</code> of 'Dan -Brickley'. +Jabber, unlike several other online messaging systems, is based on an open, publically +documented protocol specification, and has a variety of open source implementations. Jabber IDs +can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For +the purposes of FOAF, these are all considered to be kinds of <code><a href="#term_Agent">foaf:Agent</a></code> (ie. +things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The +<code><a href="#term_jabberID">foaf:jabberID</a></code> property is provided as a basic hook to help support RDF description +of Jabber users and services. </p> <p> -FOAF descriptions are encouraged to use <code>dc:creator</code> only for -simple textual names, and to use <code>foaf:maker</code> to indicate -creators, rather than risk confusing creators with their names. This -follows most Dublin Core usage. See <a -href="http://rdfweb.org/topic/UsingDublinCoreCreator">UsingDublinCoreCreator</a> -for details. +See <code><a href="#term_OnlineChatAccount">foaf:OnlineChatAccount</a></code> (and <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_workplaceHomepage"> - <h3>Property: foaf:workplaceHomepage</h3> - <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_name" about="http://xmlns.com/foaf/0.1/name" typeof="rdf:Property"> + <h3>Property: foaf:name</h3> + <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://www.w3.org/2002/07/owl#Thing"><a href="#term_A thing">A thing</a></span> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:workplaceHomepage</code> of a <code>foaf:Person</code> is a -<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a -<code>foaf:Organization</code> that they work for. -</p> + <p>The <code><a href="#term_name">foaf:name</a></code> of something is a simple textual string.</p> <p> -By directly relating people to the homepages of their workplace, we have a simple convention -that takes advantage of a set of widely known identifiers, while taking care not to confuse the -things those identifiers identify (ie. organizational homepages) with the actual organizations -those homepages describe. +XML language tagging may be used to indicate the language of the name. For example: </p> <div class="example"> -<p> -For example, Dan Brickley works at W3C. Dan is a <code>foaf:Person</code> with a -<code>foaf:homepage</code> of http://rdfweb.org/people/danbri/; W3C is a -<code>foaf:Organization</code> with a <code>foaf:homepage</code> of http://www.w3.org/. This -allows us to say that Dan has a <code>foaf:workplaceHomepage</code> of http://www.w3.org/. -</p> - -<pre> -&lt;foaf:Person&gt; - &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; - &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; -&lt;/foaf:Person&gt; -</pre> +<code> +&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; +</code> </div> - -<p> -Note that several other FOAF properties work this way; -<code>foaf:schoolHomepage</code> is the most similar. In general, FOAF often indirectly -identifies things via Web page identifiers where possible, since these identifiers are widely -used and known. FOAF does not currently have a term for the name of the relation (eg. -"workplace") that holds -between a <code>foaf:Person</code> and an <code>foaf:Organization</code> that they work for. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_homepage"> - <h3>Property: foaf:homepage</h3> - <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>stable</td></tr> - - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:homepage</code> property relates something to a homepage about it. -</p> - -<p> -Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but -constrains <code>foaf:homepage</code> so that there can be only one thing that has any -particular homepage. -</p> - <p> -A 'homepage' in this sense is a public Web document, typically but not necessarily -available in HTML format. The page has as a <code>foaf:topic</code> the thing whose -homepage it is. The homepage is usually controlled, edited or published by the thing whose -homepage it is; as such one might look to a homepage for information on its owner from its -owner. This works for people, companies, organisations etc. +FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it +does provide a basic level of interoperability. See the <a +href="http://wiki.foaf-project.org/IssueTracker">issue tracker</a> for status of work on this issue. </p> <p> -The <code>foaf:homepage</code> property is a sub-property of the more general -<code>foaf:page</code> property for relating a thing to a page about that thing. See also -<code>foaf:topic</code>, the inverse of the <code>foaf:page</code> property. +The <code><a href="#term_name">foaf:name</a></code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped +values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_accountName"> - <h3>Property: foaf:accountName</h3> - <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_sha1" about="http://xmlns.com/foaf/0.1/sha1" typeof="rdf:Property"> + <h3>Property: foaf:sha1</h3> + <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Document"><a href="#term_Document">Document</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:accountName</code> property of a <code>foaf:OnlineAccount</code> is a -textual representation of the account name (unique ID) associated with that account. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_topic_interest"> - <h3>Property: foaf:topic_interest</h3> - <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - <p class="editorial"> -The <code>foaf:topic_interest</code> property is generally found to be confusing and ill-defined -and is a candidate for removal. The goal was to be link a person to some thing that is a topic -of their interests (rather than, per <code>foaf:interest</code> to a page that is about such a -topic). +The <code><a href="#term_sha1">foaf:sha1</a></code> property relates a <code><a href="#term_Document">foaf:Document</a></code> to the textual form of +a SHA1 hash of (some representation of) its contents. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_givenname"> - <h3>Property: foaf:givenname</h3> - <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> - - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. +<p class="editorial"> +The design for this property is neither complete nor coherent. The <code><a href="#term_Document">foaf:Document</a></code> +class is currently used in a way that allows multiple instances at different URIs to have the +'same' contents (and hence hash). If <code><a href="#term_sha1">foaf:sha1</a></code> is an owl:InverseFunctionalProperty, +we could deduce that several such documents were the self-same thing. A more careful design is +needed, which distinguishes documents in a broad sense from byte sequences. </p> -<p> -There is also a simple <code>foaf:name</code> property. -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_logo"> - <h3>Property: foaf:logo</h3> - <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_gender" about="http://xmlns.com/foaf/0.1/gender" typeof="rdf:Property"> + <h3>Property: foaf:gender</h3> + <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + <tr><th>Domain:</th> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> +</td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + <tr><th colspan="2">Functional Property</th> + <td> <span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span> </td></tr> </table> <p> -The <code>foaf:logo</code> property is used to indicate a graphical logo of some kind. -<em>It is probably underspecified...</em> +The <code><a href="#term_gender">foaf:gender</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> (typically a +<code><a href="#term_Person">foaf:Person</a></code>) to a string representing its gender. In most cases the value +will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). +Like all FOAF properties, there is in general no requirement to use +<code><a href="#term_gender">foaf:gender</a></code> in any particular document or description. Values other than +'male' and 'female' may be used, but are not enumerated here. The <code><a href="#term_gender">foaf:gender</a></code> +mechanism is not intended to capture the full variety of biological, social and sexual +concepts associated with the word 'gender'. +</p> + +<p> +Anything that has a <code><a href="#term_gender">foaf:gender</a></code> property will be some kind of +<code><a href="#term_Agent">foaf:Agent</a></code>. However there are kinds of <code><a href="#term_Agent">foaf:Agent</a></code> to +which the concept of gender isn't applicable (eg. a <code><a href="#term_Group">foaf:Group</a></code>). FOAF does not +currently include a class corresponding directly to "the type of thing that has a gender". +At any point in time, a <code><a href="#term_Agent">foaf:Agent</a></code> has at most one value for +<code><a href="#term_gender">foaf:gender</a></code>. FOAF does not treat <code><a href="#term_gender">foaf:gender</a></code> as a +<em>static</em> property; the same individual may have different values for this property +at different times. +</p> + +<p> +Note that FOAF's notion of gender isn't defined biologically or anatomically - this would +be tricky since we have a broad notion that applies to all <code><a href="#term_Agent">foaf:Agent</a></code>s +(including robots - eg. Bender from Futurama is 'male'). As stressed above, +FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated +with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise +between the clinical and the social/psychological. In general, a person will be the best +authority on their <code><a href="#term_gender">foaf:gender</a></code>. Feedback on this design is +particularly welcome (via the FOAF mailing list, +<a href="http://lists.foaf-project.org/mailman/listinfo/foaf-dev">foaf-dev</a>). We have tried to +be respectful of diversity without attempting to catalogue or enumerate that diversity. </p> +<p> +This may also be a good point for a periodic reminder: as with all FOAF properties, +documents that use '<code><a href="#term_gender">foaf:gender</a></code>' will on occassion be innacurate, misleading +or outright false. FOAF, like all open means of communication, supports <em>lying</em>. + Application authors using +FOAF data should always be cautious in their presentation of unverified information, but be +particularly sensitive to issues and risks surrounding sex and gender (including privacy +and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit +<code><a href="#term_gender">foaf:gender</a></code> when describing themselves and others, and to allow at least for +values other than 'male' and 'female' as options. Users of information +conveyed via FOAF (as via information conveyed through mobile phone text messages, email, +Internet chat, HTML pages etc.) should be skeptical of unverified information. +</p> + +<!-- +b/g article currently offline. +http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 +--> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_currentProject"> + </div> <div class="specterm" id="term_currentProject" about="http://xmlns.com/foaf/0.1/currentProject" typeof="rdf:Property"> <h3>Property: foaf:currentProject</h3> <em>current project</em> - A current project this person works on. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> - + <tr><th>Range:</th> + <td> <span rel="rdfs:range" href="http://www.w3.org/2002/07/owl#Thing"<a href="#term_A thing">A thing</a></span> +</td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <!-- originally contrib'd by Cardinal --> -<p>A <code>foaf:currentProject</code> relates a <code>foaf:Person</code> -to a <code>foaf:Document</code> indicating some collaborative or +<p>A <code><a href="#term_currentProject">foaf:currentProject</a></code> relates a <code><a href="#term_Person">foaf:Person</a></code> +to a <code><a href="#term_Document">foaf:Document</a></code> indicating some collaborative or individual undertaking. This relationship -indicates that the <code>foaf:Person</code> has some active role in the +indicates that the <code><a href="#term_Person">foaf:Person</a></code> has some active role in the project, such as development, coordination, or support.</p> -<p>When a <code>foaf:Person</code> is no longer involved with a project, or +<p>When a <code><a href="#term_Person">foaf:Person</a></code> is no longer involved with a project, or perhaps is inactive for some time, the relationship becomes a -<code>foaf:pastProject</code>.</p> +<code><a href="#term_pastProject">foaf:pastProject</a></code>.</p> <p> -If the <code>foaf:Person</code> has stopped working on a project because it -has been completed (successfully or otherwise), <code>foaf:pastProject</code> is -applicable. In general, <code>foaf:currentProject</code> is used to indicate +If the <code><a href="#term_Person">foaf:Person</a></code> has stopped working on a project because it +has been completed (successfully or otherwise), <code><a href="#term_pastProject">foaf:pastProject</a></code> is +applicable. In general, <code><a href="#term_currentProject">foaf:currentProject</a></code> is used to indicate someone's current efforts (and implied interests, concerns etc.), while -<code>foaf:pastProject</code> describes what they've previously been doing. +<code><a href="#term_pastProject">foaf:pastProject</a></code> describes what they've previously been doing. </p> <!-- -<p>Generally speaking, anything that a <code>foaf:Person</code> has -<code>foaf:made</code> could also qualify as a -<code>foaf:currentProject</code> or <code>foaf:pastProject</code>.</p> +<p>Generally speaking, anything that a <code><a href="#term_Person">foaf:Person</a></code> has +<code><a href="#term_made">foaf:made</a></code> could also qualify as a +<code><a href="#term_currentProject">foaf:currentProject</a></code> or <code><a href="#term_pastProject">foaf:pastProject</a></code>.</p> --> <p class="editorial"> Note that this property requires further work. There has been confusion about whether it points to a thing (eg. something you've made; a homepage for a project, -ie. a <code>foaf:Document</code> or to instances of the class <code>foaf:Project</code>, -which might themselves have a <code>foaf:homepage</code>. In practice, it seems to have been -used in a similar way to <code>foaf:interest</code>, referencing homepages of ongoing projects. +ie. a <code><a href="#term_Document">foaf:Document</a></code> or to instances of the class <code><a href="#term_Project">foaf:Project</a></code>, +which might themselves have a <code><a href="#term_homepage">foaf:homepage</a></code>. In practice, it seems to have been +used in a similar way to <code><a href="#term_interest">foaf:interest</a></code>, referencing homepages of ongoing projects. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_member"> - <h3>Property: foaf:member</h3> - <em>member</em> - Indicates a member of a Group <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_dnaChecksum" about="http://xmlns.com/foaf/0.1/dnaChecksum" typeof="rdf:Property"> + <h3>Property: foaf:dnaChecksum</h3> + <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Group">Group</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Agent">Agent</a> -</td> </tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> + + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:member</code> property relates a <code>foaf:Group</code> to a -<code>foaf:Agent</code> that is a member of that group. +The <code><a href="#term_dnaChecksum">foaf:dnaChecksum</a></code> property is mostly a joke, but +also a reminder that there will be lots of different identifying +properties for people, some of which we might find disturbing. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_givenname" about="http://xmlns.com/foaf/0.1/givenname" typeof="rdf:Property"> + <h3>Property: foaf:givenname</h3> + <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> + + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code><a href="#term_firstName">foaf:firstName</a></code>, +<code><a href="#term_givenname">foaf:givenname</a></code>, and <code><a href="#term_surname">foaf:surname</a></code>. These are not currently +stable or consistent; see the <a href="http://wiki.foaf-project.org/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> <p> -See <code>foaf:Group</code> for details and examples. +There is also a simple <code><a href="#term_name">foaf:name</a></code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_schoolHomepage"> - <h3>Property: foaf:schoolHomepage</h3> - <em>schoolHomepage</em> - A homepage of a school attended by the person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_tipjar" about="http://xmlns.com/foaf/0.1/tipjar" typeof="rdf:Property"> + <h3>Property: foaf:tipjar</h3> + <em>tipjar</em> - A tipjar document for this agent, describing means for payment and reward. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Document"<a href="#term_Document">Document</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>schoolHomepage</code> property relates a <code>foaf:Person</code> to a -<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a School that the -person attended. +The <code><a href="#term_tipjar">foaf:tipjar</a></code> property relates an <code><a href="#term_Agent">foaf:Agent</a></code> +to a <code><a href="#term_Document">foaf:Document</a></code> that describes some mechanisms for +paying or otherwise rewarding that agent. </p> <p> -FOAF does not (currently) define a class for 'School' (if it did, it would probably be as -a sub-class of <code>foaf:Organization</code>). The original application area for -<code>foaf:schoolHomepage</code> was for 'schools' in the British-English sense; however -American-English usage has dominated, and it is now perfectly reasonable to describe -Universities, Colleges and post-graduate study using <code>foaf:schoolHomepage</code>. +The <code><a href="#term_tipjar">foaf:tipjar</a></code> property was created following <a +href="http://rdfweb.org/mt/foaflog/archives/2004/02/12/20.07.32/">discussions</a> +about simple, lightweight mechanisms that could be used to encourage +rewards and payment for content exchanged online. An agent's +<code><a href="#term_tipjar">foaf:tipjar</a></code> page(s) could describe informal ("Send me a +postcard!", "here's my book, music and movie wishlist") or formal +(machine-readable micropayment information) information about how that +agent can be paid or rewarded. The reward is not associated with any +particular action or content from the agent concerned. A link to +a service such as <a href="http://www.paypal.com/">PayPal</a> is the +sort of thing we might expect to find in a tipjar document. </p> <p> -This very basic facility provides a basis for a low-cost, decentralised approach to -classmate-reunion and suchlike. Instead of requiring a central database, we can use FOAF -to express claims such as 'I studied <em>here</em>' simply by mentioning a -school's homepage within FOAF files. Given the homepage of a school, it is easy for -FOAF aggregators to lookup this property in search of people who attended that school. +Note that the value of a <code><a href="#term_tipjar">foaf:tipjar</a></code> property is just a +document (which can include anchors into HTML pages). We expect, but +do not currently specify, that this will evolve into a hook +for finding more machine-readable information to support payments, +rewards. The <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> machinery is also relevant, +although the information requirements for automating payments are not +currently clear. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_weblog"> - <h3>Property: foaf:weblog</h3> - <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_member" about="http://xmlns.com/foaf/0.1/member" typeof="rdf:Property"> + <h3>Property: foaf:member</h3> + <em>member</em> - Indicates a member of a Group <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#stable">stable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Group"><a href="#term_Group">Group</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/Agent"<a href="#term_Agent">Agent</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:weblog</code> property relates a <code>foaf:Agent</code> to a weblog of -that agent. +The <code><a href="#term_member">foaf:member</a></code> property relates a <code><a href="#term_Group">foaf:Group</a></code> to a +<code><a href="#term_Agent">foaf:Agent</a></code> that is a member of that group. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_made"> - <h3>Property: foaf:made</h3> - <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>stable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:made</code> property relates a <code>foaf:Agent</code> -to something <code>foaf:made</code> by it. As such it is an -inverse of the <code>foaf:maker</code> property, which relates a thing to -something that made it. See <code>foaf:made</code> for more details on the -relationship between these FOAF terms and related Dublin Core vocabulary. +<p> +See <code><a href="#term_Group">foaf:Group</a></code> for details and examples. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_primaryTopic"> - <h3>Property: foaf:primaryTopic</h3> - <em>primary topic</em> - The primary topic of some page or document. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_accountName" about="http://xmlns.com/foaf/0.1/accountName" typeof="rdf:Property"> + <h3>Property: foaf:accountName</h3> + <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/OnlineAccount"><a href="#term_Online Account">Online Account</a></span> </td></tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:primaryTopic</code> property relates a document to the -main thing that the document is about. -</p> - -<p> -The <code>foaf:primaryTopic</code> property is <em>functional</em>: for -any document it applies to, it can have at most one value. This is -useful, as it allows for data merging. In many cases it may be difficult -for third parties to determine the primary topic of a document, but in -a useful number of cases (eg. descriptions of movies, restaurants, -politicians, ...) it should be reasonably obvious. Documents are very -often the most authoritative source of information about their own -primary topics, although this cannot be guaranteed since documents cannot be -assumed to be accurate, honest etc. -</p> - -<p> -It is an inverse of the <code>foaf:isPrimaryTopicOf</code> property, which relates a -thing to a document <em>primarily</em> about that thing. The choice between these two -properties is purely pragmatic. When describing documents, we -use <code>foaf:primaryTopic</code> former to point to the things they're about. When -describing things (people etc.), it is useful to be able to directly cite documents which -have those things as their main topic - so we use <code>foaf:isPrimaryTopicOf</code>. In this -way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a -href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they -have descriptions of. +The <code><a href="#term_accountName">foaf:accountName</a></code> property of a <code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> is a +textual representation of the account name (unique ID) associated with that account. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_knows"> - <h3>Property: foaf:knows</h3> - <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_holdsAccount" about="http://xmlns.com/foaf/0.1/holdsAccount" typeof="rdf:Property"> + <h3>Property: foaf:holdsAccount</h3> + <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#unstable">unstable</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Agent"><a href="#term_Agent">Agent</a></span> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Person">Person</a> + <td> <span rel="rdfs:range" href="http://xmlns.com/foaf/0.1/OnlineAccount"<a href="#term_Online Account">Online Account</a></span> </td> </tr> + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> <p> -The <code>foaf:knows</code> property relates a <code>foaf:Person</code> to another -<code>foaf:Person</code> that he or she knows. -</p> - -<p> -We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. -stalkers need not apply). Since social attitudes and conventions on this topic vary -greatly between communities, counties and cultures, it is not appropriate for FOAF to be -overly-specific here. -</p> - -<p> -If someone <code>foaf:knows</code> a person, it would be usual for -the relation to be reciprocated. However this doesn't mean that there is any obligation -for either party to publish FOAF describing this relationship. A <code>foaf:knows</code> -relationship does not imply friendship, endorsement, or that a face-to-face meeting -has taken place: phone, fax, email, and smoke signals are all perfectly -acceptable ways of communicating with people you know. -</p> -<p> -You probably know hundreds of people, yet might only list a few in your public FOAF file. -That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not -list anyone else in it at all. -This illustrates the Semantic Web principle of partial description: RDF documents -rarely describe the entire picture. There is always more to be said, more information -living elsewhere in the Web (or in our heads...). -</p> - -<p> -Since <code>foaf:knows</code> is vague by design, it may be suprising that it has uses. -Typically these involve combining other RDF properties. For example, an application might -look at properties of each <code>foaf:weblog</code> that was <code>foaf:made</code> by -someone you "<code>foaf:knows</code>". Or check the newsfeed of the online photo archive -for each of these people, to show you recent photos taken by people you know. -</p> - -<p> -To provide additional levels of representation beyond mere 'knows', FOAF applications -can do several things. -</p> -<p> -They can use more precise relationships than <code>foaf:knows</code> to relate people to -people. The original FOAF design included two of these ('knowsWell','friend') which we -removed because they were somewhat <em>awkward</em> to actually use, bringing an -inappopriate air of precision to an intrinsically vague concept. Other extensions have -been proposed, including Eric Vitiello's <a -href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for -FOAF. -</p> - -<p> -In addition to using more specialised inter-personal relationship types -(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states -of affairs which imply particular kinds of relationship. So for example, two people who -have the same value for their <code>foaf:workplaceHomepage</code> property are -typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, -but the facts can be written in FOAF nevertheless. Similarly, if there exists a -<code>foaf:Document</code> that has two people listed as its <code>foaf:maker</code>s, -then they are probably collaborators of some kind. Or if two people appear in 100s of -digital photos together, there's a good chance they're friends and/or colleagues. -</p> - -<p> -So FOAF is quite pluralistic in its approach to representing relationships between people. -FOAF is built on top of a general purpose machine language for representing relationships -(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. -The problems are generally social rather than technical; deciding on appropriate ways of -describing these interconnections is a subtle art. -</p> - -<p> -Perhaps the most important use of <code>foaf:knows</code> is, alongside the -<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF -file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more -interesting, with each FOAF file saying a little more about people, places, documents, things... -By mentioning other people (via <code>foaf:knows</code> or other relationships), and by -providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for -FOAF indexing tools ('<a href="http://rdfweb.org/topic/ScutterSpec">scutters</a>') to find -your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they -mention, and so on. This makes it possible to build FOAF aggregators without the need for -a centrally managed directory of FOAF files... +The <code><a href="#term_holdsAccount">foaf:holdsAccount</a></code> property relates a <code><a href="#term_Agent">foaf:Agent</a></code> to an +<code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> for which they are the sole account holder. See +<code><a href="#term_OnlineAccount">foaf:OnlineAccount</a></code> for usage details. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_accountServiceHomepage"> - <h3>Property: foaf:accountServiceHomepage</h3> - <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_plan" about="http://xmlns.com/foaf/0.1/plan" typeof="rdf:Property"> + <h3>Property: foaf:plan</h3> + <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#testing">testing</span></td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <span rel="rdfs:domain" href="http://xmlns.com/foaf/0.1/Person"><a href="#term_Person">Person</a></span> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> + + <span rel="rdfs:isDefinedBy" href="http://xmlns.com/foaf/0.1/" /> + </table> - <p> -The <code>foaf:accountServiceHomepage</code> property indicates a relationship between a -<code>foaf:OnlineAccount</code> and the homepage of the supporting service provider. + <!-- orig contrib'd by Cardinal --> + +<p>The <code><a href="#term_plan">foaf:plan</a></code> property provides a space for a +<code><a href="#term_Person">foaf:Person</a></code> to hold some arbitrary content that would appear in +a traditional '.plan' file. The plan file was stored in a user's home +directory on a UNIX machine, and displayed to people when the user was +queried with the finger utility.</p> + +<p>A plan file could contain anything. Typical uses included brief +comments, thoughts, or remarks on what a person had been doing lately. Plan +files were also prone to being witty or simply osbscure. Others may be more +creative, writing any number of seemingly random compositions in their plan +file for people to stumble upon.</p> + +<p> +See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the +Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The +<code><a href="#term_geekcode">foaf:geekcode</a></code> property may also be of interest. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> </div> </div> </body> </html>
leth/SpecGen
c01ea48a81db344d6da25e79a8c0fbb1f1c590a3
added functional and inverse functional properties in the RDFa and made dijoint with visible to humans
diff --git a/libvocab.py b/libvocab.py index 3707715..7c1f404 100755 --- a/libvocab.py +++ b/libvocab.py @@ -94,646 +94,676 @@ class Term(object): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) # self.terms.sort() # self.classes.sort() # self.properties.sort() # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: # print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s" about="%s" typeof="%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td><span rel="vs:status" href="http://www.w3.org/2003/06/sw-vocab-status/ns#%s">%s</span></td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div>""" # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: ss = """<span rel="rdfs:subClassOf" href="%s"><a href="#term_%s">%s</a></span>\n""" % (subclass, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) # disjoint with foo5 = '' - q = 'SELECT ?dj WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj } ' % (term.uri) + q = 'SELECT ?dj ?l WHERE { <%s> <http://www.w3.org/2002/07/owl#disjointWith> ?dj . ?dj rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) - sss = '\n' + sss = '<tr><th>Disjoint With:</th>\n' tt = '' - for (disjointWith) in relations: - ss = """<span rel="owl:disjointWith" href="%s" />\n""" % (disjointWith) + for (disjointWith, label) in relations: + ss = """<span rel="owl:disjointWith" href="%s"><a href="#term_%s">%s</a></span>\n""" % (disjointWith, label, label) tt = "%s %s" % (tt, ss) if tt != "": - foo5 = "%s %s " % (sss, tt) - + foo5 = "%s <td> %s </td></tr>" % (sss, tt) +# end dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id,term.uri,"rdfs:Class","Class", sn, term.label, term.comment, term.status,term.status,foo,foo1+foo2+foo3+foo4+foo5, s) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: ss = """<span rel="rdfs:domain" href="%s"><a href="#term_%s">%s</a></span>\n""" % (domain, label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ss = """<span rel="rdfs:range" href="%s"<a href="#term_%s">%s</a></span>\n""" % (range, label, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) # is defined by foo4 = '' q = 'SELECT ?idb WHERE { <%s> rdfs:isDefinedBy ?idb } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '\n' tt = '' for (isdefinedby) in relations: ss = """<span rel="rdfs:isDefinedBy" href="%s" />\n""" % (isdefinedby) tt = "%s %s" % (tt, ss) if tt != "": foo4 = "%s %s " % (sss, tt) +# inverse functional property + + foo5 = '' + + q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#InverseFunctionalProperty> } ' % (term.uri) + query = Parse(q) + relations = g.query(query, initNs=bindings) + sss = '<tr><th colspan="2">Inverse Functional Property</th>\n' + + if (len(relations) > 0): + ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#InverseFunctionalProperty"></span>""" + foo5 = "%s <td> %s </td></tr>" % (sss, ss) + +# functonal property + +# inverse functional property + + foo6 = '' + + q = 'SELECT * WHERE { <%s> rdf:type <http://www.w3.org/2002/07/owl#FunctionalProperty> } ' % (term.uri) + query = Parse(q) + relations = g.query(query, initNs=bindings) + sss = '<tr><th colspan="2">Functional Property</th>\n' + + if (len(relations) > 0): + ss = """<span rel="rdf:type" href="http://www.w3.org/2002/07/owl#FunctionalProperty"></span>""" + foo6 = "%s <td> %s </td></tr>" % (sss, ss) + +# end + dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) - zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4, s) + zz = eg % (term.id, term.uri,"rdf:Property","Property", sn, term.label, term.comment, term.status,term.status, foo, foo1+foo4+foo5+foo6, s) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed return(tl+"\n</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
87279007422d09352dd41f60d2b6592ce30d1962
readding index.rdf file
diff --git a/foaf-live/index.rdf b/foaf-live/index.rdf new file mode 120000 index 0000000..8ef8803 --- /dev/null +++ b/foaf-live/index.rdf @@ -0,0 +1 @@ +/Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/spec/index.rdf \ No newline at end of file
leth/SpecGen
ff9fc764e78a8178717cd2dd4a4c07aa3dc1e894
dir for foaf site live work
diff --git a/foaf-live/_tmp_spec.html b/foaf-live/_tmp_spec.html new file mode 100644 index 0000000..33fa92e --- /dev/null +++ b/foaf-live/_tmp_spec.html @@ -0,0 +1,3078 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:foaf="http://xmlns.com/foaf/0.1/" + xmlns:dc="http://purl.org/dc/elements/1.1/"> +<head> + <title>FOAF Vocabulary Specification</title> + <link href="http://xmlns.com/xmlns-style.css" rel="stylesheet" + type="text/css" /> + <link href="style.css" rel="stylesheet" + type="text/css" /> + <link href="http://xmlns.com/foaf/spec/index.rdf" rel="alternate" + type="application/rdf+xml" /> +</head> + +<body> + <h1>FOAF Vocabulary Specification 0.91<br /></h1> + + <h2>Namespace Document 2 November 2007 - <em>OpenID Edition</em></h2> + + <dl> + + <dt>This version:</dt> + + <dd><a href= + "http://xmlns.com/foaf/spec/20071002.html">http://xmlns.com/foaf/spec/20071002.html</a> (<a href="20071002.rdf">rdf</a>)</dd> + + <dt>Latest version:</dt> + <dd><a href="http://xmlns.com/foaf/spec/">http://xmlns.com/foaf/spec/</a> (<a href="index.rdf">rdf</a>)</dd> + + <dt>Previous version:</dt> + <dd><a href="20070524.html">http://xmlns.com/foaf/spec/20070524.html</a> (<a href="20070524.rdf">rdf</a>)</dd> + + <dt>Authors:</dt> + <dd><a href="mailto:[email protected]">Dan Brickley</a>, + <a href="mailto:[email protected]">Libby Miller</a></dd> + + <dt>Contributors:</dt> + + <dd>Members of the FOAF mailing list (<a href= + "http://lists.foaf-project.org/">[email protected]</a>) + and the wider <a href="http://www.w3.org/2001/sw/interest/">RDF + and SemWeb developer community</a>. See <a href= + "#sec-ack">acknowledgements</a>.</dd> + </dl> + + <p class="copyright">Copyright &copy; 2000-2007 Dan + Brickley and Libby Miller<br /> + <br /> + + <!-- Creative Commons License --> + <a href="http://creativecommons.org/licenses/by/1.0/"><img alt= + "Creative Commons License" style="border: 0; float: right; padding: 10px;" src= + "somerights.gif" /></a> This work is licensed under a <a href= + "http://creativecommons.org/licenses/by/1.0/">Creative Commons + Attribution License</a>. This copyright applies to the <em>FOAF + Vocabulary Specification</em> and accompanying documentation in RDF. + Regarding underlying technology, FOAF uses W3C's <a href="http://www.w3.org/RDF/">RDF</a> technology, an + open Web standard that can be freely used by anyone.</p> + + <hr /> + + +<h2 id="sec-status">Abstract</h2> +<p> +This specification describes the FOAF language, defined as a dictionary of named +properties and classes using W3C's RDF technology. +</p> + + <div class="status"> + <h2>Status of This Document</h2> + + <p> +FOAF has been evolving gradually since its creation in mid-2000. There is now a stable core of classes and properties +that will not be changed, beyond modest adjustments to their documentation to track +implementation feedback and emerging best practices. New terms may be +added at any time (as with a natural-language dictionary), and consequently this specification +is an evolving work. The FOAF RDF namespace, by contrast, is fixed and it's +identifier is not expected to <a href="#sec-evolution">change</a>. Furthermore, efforts are +underway to ensure the long-term preservation of the FOAF namespace, its xmlns.com +domain name and associated documentation. +</p> + + +<p> This document is created by combining the <a href="index.rdf">RDFS/OWL</a> machine-readable + FOAF ontology with a set of <a href="../doc/">per-term</a> documents. Future versions may + incorporate <a href="http://svn.foaf-project.org/foaftown/foaf18n/">multilingual translations</a> of the + term definitions. The RDF version of the specification is also embedded in the HTML of this + document, or available directly from the namespace URI by content negotiation. +</p> +<p> + The FOAF specification is produced as part of the <a href= + "http://www.foaf-project.org/">FOAF project</a>, to provide + authoritative documentation of the contents, status and purpose + of the RDF/XML vocabulary and document formats known informally + as 'FOAF'.</p> + + <p>The authors welcome comments on this document, preferably via the public FOAF developers list <a href= + "mailto:[email protected]">[email protected]</a>; + <a href="http://lists.foaf-project.org">public archives</a> are + available. A historical backlog of known technical issues is acknowledged, and available for discussion in the + <a href="http://wiki.foaf-project.org/IssueTracker">FOAF wiki</a>. Proposals for resolving these issues are welcomed, + either on foaf-dev or via the wiki. Further work is also needed on the explanatory text in this specification and on the + <a href="http://www.foaf-project.org/">FOAF website</a>; progress towards this will be measured in the version number of + future revisions to the FOAF specification. + </p> + +<p>This revision of the specification includes a first draft description of the new <a href="#term_openid">foaf:openid</a> property. +The prose description of this property is likely to evolve, but the basic mechanism seems robust. To accompany this support for OpenID +in the FOAF specification, the <a href="http://wiki.foaf-project.org/">FOAF wiki</a> has also been updated to support usage of OpenID +by members of the developer community. This revision of the spec also involves a change in the DTD declared at the top of the document. +This is a foundation for using inline <a href="http://en.wikipedia.org/wiki/RDFa">RDFa</a> markup in future versions. The current +version however does not yet validate according to this document format; it contains RDF/XML markup describing FOAF in machine-readable +form. We welcome feedback on whether to retain this markup at the expense of DTD-based validation. +</p> +<p> +As usual, see the <a href="#sec-changes">changes</a> section for details of the changes in this version of the specification. +</p> + + + <h2 id="sec-toc">Table of Contents</h2> + + <ul> + <li><a href="#sec-glance">FOAF at a glance</a></li> + <li><a href="#sec-intro">Introduction</a></li> + <li><a href="#sec-sw">The Semantic Web</a></li> + <li><a href="#sec-foafsw">FOAF and the Semantic Web</a></li> + <li><a href="#sec-for">What's FOAF for?</a></li> + <li><a href="#sec-bg">Background</a></li> + <li><a href="#sec-standards">FOAF and Standards</a></li> + <li><a href="#sec-evolution">Evolution and Extension of FOAF</a></li> + <li><a href="#sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</a></li> + <li><a href="#sec-foafandrdf">FOAF and RDF</a></li> + <li><a href="#sec-crossref">FOAF cross-reference: Listing FOAF Classes and Properties</a></li> + <li><a href="#sec-ack">Acknowledgments</a></li> + <li><a href="#sec-changes">Recent Changes</a></li> + </ul> + + + + <h2 id="glance">FOAF at a glance</h2> + + <p>An a-z index of FOAF terms, by class (categories or types) and + by property.</p> + + +<div style="padding: 5px; border: solid; background-color: #ddd;"> +<p>Classes: | <a href="#term_Agent">Agent</a> | <a href="#term_Document">Document</a> | <a href="#term_Group">Group</a> | <a href="#term_Image">Image</a> | <a href="#term_OnlineAccount">OnlineAccount</a> | <a href="#term_OnlineChatAccount">OnlineChatAccount</a> | <a href="#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a> | <a href="#term_OnlineGamingAccount">OnlineGamingAccount</a> | <a href="#term_Organization">Organization</a> | <a href="#term_Person">Person</a> | <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> | <a href="#term_Project">Project</a> | +</p> +<p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_openid">openid</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | +</p> +</div> + + + + <p>FOAF terms, grouped in broad categories.</p> + <div class="rdf-proplist"> + <h3>FOAF Basics</h3> + + <ul> + <li><a href="#term_Agent">Agent</a></li> + + <li><a href="#term_Person">Person</a></li> + + <li><a href="#term_name">name</a></li> + + <li><a href="#term_nick">nick</a></li> + + <li><a href="#term_title">title</a></li> + + <li><a href="#term_homepage">homepage</a></li> + + <li><a href="#term_mbox">mbox</a></li> + + <li><a href="#term_mbox_sha1sum">mbox_sha1sum</a></li> + + <li><a href="#term_img">img</a></li> + <li><a href="#term_depiction">depiction</a> (<a href= + "#term_depicts">depicts</a>)</li> + + <li><a href="#term_surname">surname</a></li> + + <li><a href="#term_family_name">family_name</a></li> + + <li><a href="#term_givenname">givenname</a></li> + + <li><a href="#term_firstName">firstName</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Personal Info</h3> + + <ul> + <li><a href="#term_weblog">weblog</a></li> + <li><a href="#term_knows">knows</a></li> + <li><a href="#term_interest">interest</a></li> + <li><a href="#term_currentProject">currentProject</a></li> + <li><a href="#term_pastProject">pastProject</a></li> + <li><a href="#term_plan">plan</a></li> + <li><a href="#term_based_near">based_near</a></li> + <li><a href= + "#term_workplaceHomepage">workplaceHomepage</a></li> + <li><a href= + "#term_workInfoHomepage">workInfoHomepage</a></li> + <li><a href="#term_schoolHomepage">schoolHomepage</a></li> + <li><a href="#term_topic_interest">topic_interest</a></li> + <li><a href="#term_publications">publications</a></li> + <li><a href="#term_geekcode">geekcode</a></li> + <li><a href="#term_myersBriggs">myersBriggs</a></li> + <li><a href="#term_dnaChecksum">dnaChecksum</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Online Accounts / IM</h3> + + <ul> + <li><a href="#term_OnlineAccount">OnlineAccount</a></li> + + <li><a href= + "#term_OnlineChatAccount">OnlineChatAccount</a></li> + + <li><a href= + "#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a></li> + + <li><a href= + "#term_OnlineGamingAccount">OnlineGamingAccount</a></li> + + <li><a href="#term_holdsAccount">holdsAccount</a></li> + + <li><a href= + "#term_accountServiceHomepage">accountServiceHomepage</a></li> + + <li><a href="#term_accountName">accountName</a></li> + + <li><a href="#term_icqChatID">icqChatID</a></li> + + <li><a href="#term_msnChatID">msnChatID</a></li> + + <li><a href="#term_aimChatID">aimChatID</a></li> + + <li><a href="#term_jabberID">jabberID</a></li> + + <li><a href="#term_yahooChatID">yahooChatID</a></li> + </ul> + </div> + <div style="clear: left;"></div> + + <div class="rdf-proplist"> + <h3>Projects and Groups</h3> + + <ul> + <li><a href="#term_Project">Project</a></li> + + <li><a href="#term_Organization">Organization</a></li> + + <li><a href="#term_Group">Group</a></li> + + <li><a href="#term_member">member</a></li> + + <li><a href= + "#term_membershipClass">membershipClass</a></li> + + <li><a href="#term_fundedBy">fundedBy</a></li> + + <li><a href="#term_theme">theme</a></li> + </ul> + </div> + + <div class="rdf-proplist"> + <h3>Documents and Images</h3> + + <ul> + <li><a href="#term_Document">Document</a></li> + + <li><a href="#term_Image">Image</a></li> + + <li><a href= + "#term_PersonalProfileDocument">PersonalProfileDocument</a></li> + + <li><a href="#term_topic">topic</a> (<a href= + "#term_page">page</a>)</li> + + <li><a href="#term_primaryTopic">primaryTopic</a></li> + + <li><a href="#term_tipjar">tipjar</a></li> + + <li><a href="#term_sha1">sha1</a></li> + + <li><a href="#term_made">made</a> (<a href= + "#term_maker">maker</a>)</li> + + <li><a href="#term_thumbnail">thumbnail</a></li> + + <li><a href="#term_logo">logo</a></li> + </ul> + </div> + </div> + + <div style="clear: left;"></div> + + <h2 id="sec-example">Example</h2> + + <p>Here is a very basic document describing a person:</p> + + <div class="example"> + <pre> +&lt;foaf:Person rdf:about="#me" xmlns:foaf="http://xmlns.com/foaf/0.1/"&gt; + &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:mbox_sha1sum&gt;241021fb0e6289f92815fc210f9e9137262c252e&lt;/foaf:mbox_sha1sum&gt; + &lt;foaf:homepage rdf:resource="http://danbri.org/" /&gt; + &lt;foaf:img rdf:resource="/images/me.jpg" /&gt; +&lt;/foaf:Person&gt; +</pre> + </div> + + <p>This brief example introduces the basics of FOAF. It basically + says, "there is a <a href="#term_Person">foaf:Person</a> with a + <a href="#term_name">foaf:name</a> property of 'Dan Brickley' and + a <a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a> property of + 241021fb0e6289f92815fc210f9e9137262c252e; this person stands in a + <a href="#term_homepage">foaf:homepage</a> relationship to a + thing called http://danbri.org/ and a <a href= + "#term_img">foaf:img</a> relationship to a thing referenced by a relative URI of /images/me.jpg</p> + + <div style="clear: left;"></div> + + + <!-- ================================================================== --> + + + <h2 id="sec-intro">1 Introduction: FOAF Basics</h2> + + <h3 id="sec-sw">The Semantic Web</h3> +<blockquote> +<p> +<em> + To a computer, the Web is a flat, boring world, devoid of meaning. + This is a pity, as in fact documents on the Web describe real objects and + imaginary concepts, and give particular relationships between them. For + example, a document might describe a person. The title document to a house describes a house and also the ownership relation + with a person. Adding semantics to the Web involves two things: allowing documents which have information + in machine-readable forms, and allowing links to be created with relationship + values. Only when we have this extra level of semantics will we be able to use computer power + to help us exploit the information to a greater extent than our own reading. +</em> +- Tim Berners-Lee &quot;W3 future directions&quot; keynote, 1st World Wide Web Conference Geneva, May 1994 +</p> +</blockquote> + +<h3 id="sec-foafsw">FOAF and the Semantic Web</h3> + +<p> +FOAF, like the Web itself, is a linked information system. It is built using decentralised <a +href="http://www.w3.org/2001/sw/">Semantic Web</a> technology, and has been designed to allow for integration of data across +a variety of applications, Web sites and services, and software systems. To achieve this, FOAF takes a liberal approach to data +exchange. It does not require you to say anything at all about yourself or others, nor does it place any limits on the things you can +say or the variety of Semantic Web vocabularies you may use in doing so. This current specification provides a basic "dictionary" of +terms for talking about people and the things they make and do.</p> + +<p>FOAF was designed to be used alongside other such dictionaries ("schemas" or "ontologies"), and to beusable with the wide variety +of generic tools and services that have been created for the Semantic Web. For example, the W3C work on <a +href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a> provides us with a rich query language for consulting databases of FOAF data, +while the <a href="http://www.w3.org/2004/02/skos/">SKOS</a> initiative explores in more detail than FOAF the problem of describing +topics, categories, "folksonomies" and subject hierarchies. Meanwhile, other W3C groups are working on improved mechanisms for encoding +all kinds of RDF data (including but not limited to FOAF) within Web pages: see the work of the <a +href="http://www.w3.org/2001/sw/grddl-wg/">GRDDL</a> and <a href="http://www.w3.org/TR/xhtml-rdfa-primer/">RDFa</a> efforts for more +detail. The Semantic Web provides us with an <em>architecture for collaboration</em>, allowing complex technical challenges to be +shared by a loosely-coordinated community of developers. +</p> + + <p>The FOAF project is based around the use of <em>machine + readable</em> Web homepages for people, groups, companies and + other kinds of thing. To achieve this we use the "FOAF + vocabulary" to provide a collection of basic terms that can be + used in these Web pages. At the heart of the FOAF project is a + set of definitions designed to serve as a dictionary of terms + that can be used to express claims about the world. The initial + focus of FOAF has been on the description of people, since people + are the things that link together most of the other kinds of + things we describe in the Web: they make documents, attend + meetings, are depicted in photos, and so on.</p> + + <p>The FOAF Vocabulary definitions presented here are written + using a computer language (RDF/OWL) that makes it easy for + software to process some basic facts about the terms in the FOAF + vocabulary, and consequently about the things described in FOAF + documents. A FOAF document, unlike a traditional Web page, can be + combined with other FOAF documents to create a unified database + of information. FOAF is a <a + href="http://www.w3.org/DesignIssues/LinkedData.html">Linked + Data</a> system, in that it based around the idea of linking together + a Web of decentralised descriptions.</p> + + + <h3 id="sec-basicidea">The Basic Idea</h3> + + <p>The basic idea is pretty simple. If people publish information + in the FOAF document format, machines will be able to make use of + that information. If those files contain "see also" references to + other such documents in the Web, we will have a machine-friendly + version of today's hypertext Web. Computer programs will be able + to scutter around a Web of documents designed for machines rather + than humans, storing the information they find, keeping a list of + "see also" pointers to other documents, checking digital + signatures (for the security minded) and building Web pages and + question-answering services based on the harvested documents.</p> + + <p>So, what is the 'FOAF document format'? FOAF files are just + text documents (well, Unicode documents). They are written in XML + syntax, and adopt the conventions of the Resource Description + Framework (RDF). In addition, the FOAF vocabulary defines some + useful constructs that can appear in FOAF files, alongside other + RDF vocabularies defined elsewhere. For example, FOAF defines + categories ('classes') such as <code>foaf:Person</code>, + <code>foaf:Document</code>, <code>foaf:Image</code>, alongside + some handy properties of those things, such as + <code>foaf:name</code>, <code>foaf:mbox</code> (ie. an internet + mailbox), <code>foaf:homepage</code> etc., as well as some useful + kinds of relationship that hold between members of these + categories. For example, one interesting relationship type is + <code>foaf:depiction</code>. This relates something (eg. a + <code>foaf:Person</code>) to a <code>foaf:Image</code>. The FOAF + demos that feature photos and listings of 'who is in which + picture' are based on software tools that parse RDF documents and + make use of these properties.</p> + + <p>The specific contents of the FOAF vocabulary are detailed in + this <a href="http://xmlns.com/foaf/0.1/">FOAF namespace + document</a>. In addition to the FOAF vocabulary, one of the most + interesting features of a FOAF file is that it can contain "see + Also" pointers to other FOAF files. This provides a basis for + automatic harvesting tools to traverse a Web of interlinked + files, and learn about new people, documents, services, + data...</p> + + <p>The remainder of this specification describes how to publish + and interpret descriptions such as these on the Web, using + RDF/XML for syntax (file format) and terms from FOAF. It + introduces a number of categories (RDF classes such as 'Person') + and properties (relationship and attribute types such as 'mbox' + or 'workplaceHomepage'). Each term definition is provided in both + human and machine-readable form, hyperlinked for quick + reference.</p> + + <h2 id="sec-for">What's FOAF for?</h2> + + <p>For a good general introduction to FOAF, see Edd Dumbill's + article, <a href= + "http://www-106.ibm.com/developerworks/xml/library/x-foaf.html">XML + Watch: Finding friends with XML and RDF</a> (June 2002, IBM + developerWorks). Information about the use of FOAF <a href= + "http://rdfweb.org/2002/01/photo/">with image metadata</a> is + also available.</p> + + <p>The <a href= "http://rdfweb.org/2002/01/photo/">co-depiction</a> + experiment shows a fun use of the vocabulary. Jim Ley's <a href= + "http://www.jibbering.com/svg/AnnotateImage.html">SVG image + annotation tool</a> show the use of FOAF with detailed image + metadata, and provide tools for labelling image regions within a + Web browser. To create a FOAF document, you can use Leigh Dodd's + <a href= + "http://www.ldodds.com/foaf/foaf-a-matic.html">FOAF-a-matic</a> + javascript tool. To query a FOAF dataset via IRC, you can use Edd + Dumbill's <a href="http://usefulinc.com/foaf/foafbot">FOAFbot</a> + tool, an IRC 'community support agent'. For more information on + FOAF and related projects, see the <a href= + "http://rdfweb.org/foaf/">FOAF project home page</a>. +</p> + + <h2 id="sec-bg">Background</h2> + + <p>FOAF is a collaborative effort amongst Semantic Web + developers on the FOAF ([email protected]) mailing + list. The name 'FOAF' is derived from traditional internet usage, + an acronym for 'Friend of a Friend'.</p> + + <p>The name was chosen to reflect our concern with social + networks and the Web, urban myths, trust and connections. Other + uses of the name continue, notably in the documentation and + investigation of Urban Legends (eg. see the <a href= + "http://www.urbanlegends.com/">alt.folklore.urban archive</a> or + <a href="http://www.snopes.com/">snopes.com</a>), and other FOAF + stories. Our use of the name 'FOAF' for a Web vocabulary and + document format is intended to complement, rather than replace, + these prior uses. FOAF documents describe the characteristics and + relationships amongst friends of friends, and their friends, and + the stories they tell.</p> + + <h2 id="sec-standards">FOAF and Standards</h2> + + <p>It is important to understand that the FOAF + <em>vocabulary</em> as specified in this document is not a + standard in the sense of <a href= + "http://www.iso.ch/iso/en/ISOOnline.openerpage">ISO + Standardisation</a>, or that associated with <a href= + "http://www.w3.org/">W3C</a> <a href= + "http://www.w3.org/Consortium/Process/">Process</a>.</p> + + <p>FOAF depends heavily on W3C's standards work, specifically on + XML, XML Namespaces, RDF, and OWL. All FOAF <em>documents</em> + must be well-formed RDF/XML documents. The FOAF vocabulary, by + contrast, is managed more in the style of an <a href= + "http://www.opensource.org/">Open Source</a> or <a href= + "http://www.gnu.org/philosophy/free-sw.html">Free Software</a> + project than as an industry standardarisation effort (eg. see + <a href="http://www.jabber.org/jeps/jep-0001.html">Jabber + JEPs</a>).</p> + + <p>This specification contributes a vocabulary, "FOAF", to the + Semantic Web, specifying it using W3C's <a href= + "http://www.w3.org/RDF/">Resource Description Framework</a> + (RDF). As such, FOAF adopts by reference both a syntax (using + XML) a data model (RDF graphs) and a mathematically grounded + definition for the rules that underpin the FOAF design.</p> + + <h2 id="sec-nsdoc">The FOAF Vocabulary Description</h2> + + <p>This specification serves as the FOAF "namespace document". As + such it describes the FOAF vocabulary and the terms (<a href= + "http://www.w3.org/RDF/">RDF</a> classes and properties) that + constitute it, so that <a href= + "http://www.w3.org/2001/sw/">Semantic Web</a> applications can + use those terms in a variety of RDF-compatible document formats + and applications.</p> + + <p>This document presents FOAF as a <a href= + "http://www.w3.org/2001/sw/">Semantic Web</a> vocabulary or + <em>Ontology</em>. The FOAF vocabulary is pretty simple, + pragmatic and designed to allow simultaneous deployment and + extension. FOAF is intended for widescale use, but its authors + make no commitments regarding its suitability for any particular + purpose.</p> + + <h3 id="sec-evolution">Evolution and Extension of FOAF</h3> + + <p>The FOAF vocabulary is identified by the namespace URI + '<code>http://xmlns.com/foaf/0.1/</code>'. Revisions and + extensions of FOAF are conducted through edits to this document, + which by convention is accessible in the Web via the namespace URI. + For practical and deployment reasons, note that <b>we do not + update the namespace URI as the vocabulary matures</b>. + </p> + <p>The core of FOAF now is considered stable, and the version number of + <em>this specification</em> reflects this stability. However, it + long ago became impractical to update the namespace URI without + causing huge disruption to both producers and consumers of FOAF + data. We are therefore left with the digits "0.1" in our URI. This + stands as a warning to all those who might embed metadata in their + vocabulary identifiers. +</p> + +<p> + The evolution of FOAF is best considered in terms of the + stability of individual vocabulary terms, rather than the + specification as a whole. As terms stabilise in usage and + documentation, they progress through the categories + '<strong>unstable</strong>', '<strong>testing</strong>' and + '<strong>stable</strong>'.</p><!--STATUSINFO--> + + <p>The properties and types defined here provide some basic + useful concepts for use in FOAF descriptions. Other vocabulary + (eg. the <a href="http://dublincore.org/">Dublin Core</a> + metadata elements for simple bibliographic description), RSS 1.0 + etc can also be mixed in with FOAF terms, as can local + extensions. FOAF is designed to be extended. The <a href= + "http://wiki.foaf-project.org/FoafVocab">FoafVocab</a> page in the + FOAF wiki lists a number of extension vocabularies that are + particularly applicable to use with FOAF.</p> + + <h2 id="sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</h2> + + <p>If you publish a FOAF self-description (eg. using <a href= + "http://www.ldodds.com/foaf/foaf-a-matic.html">foaf-a-matic</a>) + you can make it easier for tools to find your FOAF by putting + markup in the <code>head</code> of your HTML homepage. It doesn't + really matter what filename you choose for your FOAF document, + although <code>foaf.rdf</code> is a common choice. The linking + markup is as follows:</p> + + <div class="example"> +<pre> + &lt;link rel="meta" type="application/rdf+xml" title="FOAF" + href="<em>http://example.com/~you/foaf.rdf</em>"/&gt; +</pre> + </div> + + <p>...although of course change the <em>URL</em> to point to your + own FOAF document. See also: more on <a href= + "http://rdfweb.org/mt/foaflog/archives/000041.html">FOAF + autodiscovery</a> and services that make use of it.</p> + + <h2 id="sec-foafandrdf">FOAF and RDF</h2> + + <p>Why does FOAF use <a href= + "http://www.w3.org/RDF/">RDF</a>?</p> + + <p>FOAF is an application of the Resource Description Framework + (RDF) because the subject area we're describing -- people -- has + so many competing requirements that a standalone format could not + do them all justice. By using RDF, FOAF gains a powerful + extensibility mechanism, allowing FOAF-based descriptions can be + mixed with claims made in <em>any other RDF vocabulary</em></p> + + <p>People are the things that link together most of the other + kinds of things we describe in the Web: they make documents, + attend meetings, are depicted in photos, and so on. Consequently, + there are many many things that we might want to say about + people, not to mention these related objects (ie. documents, + photos, meetings etc).</p> + + <p>FOAF as a vocabulary cannot incorporate everything we might + want to talk about that is related to people, or it would be as + large as a full dictionary. Instead of covering all topics within + FOAF itself, we buy into a larger framework - RDF - that allows + us to take advantage of work elsewhere on more specific + description vocabularies (eg. for geographical / mapping + data).</p> + + <p>RDF provides FOAF with a way to mix together different + descriptive vocabularies in a consistent way. Vocabularies can be + created by different communites and groups as appropriate and + mixed together as required, without needing any centralised + agreement on how terms from different vocabularies can be written + down in XML.</p> + + <p>This mixing happens in two ways: firstly, RDF provides an + underlying model of (typed) objects and their attributes or + relationships. <code>foaf:Person</code> is an example of a type + of object (a "<em>class</em>"), while <code>foaf:knows</code> and + <code>foaf:name</code> are examples of a relationship and an + attribute of an <code>foaf:Person</code>; in RDF we call these + "<em>properties</em>". Any vocabulary described in RDF shares + this basic model, which is discernable in the syntax for RDF, and + which removes one level of confusion in <em>understanding</em> a + given vocabulary, making it simpler to comprehend and therefore + reuse a vocabulary that you have not written yourself. This is + the minimal <em>self-documentation</em> that RDF gives you.</p> + + <p>Secondly, there are mechanisms for saying which RDF properties + are connected to which classes, and how different classes are + related to each other, using RDF Syntax and OWL. These can be + quite general (all RDF properties by default come from an + <code>rdf:Resource</code> for example) or very specific and + precise (for example by using <a href= + "http://www.w3.org/2001/sw/WebOnt/">OWL</a> constructs, as in the + <code>foaf:Group</code> example below. This is another form of + self-documentation, which allows you to connect different + vocabularies together as you please. An example of this is given + below where the <code>foaf:based_near</code> property has a + domain and range (types of class at each end of the property) + from a different namespace altogether.</p> + + <p>In summary then, RDF is self-documenting in ways which enable + the creation and combination of vocabularies in a devolved + manner. This is particularly important for a vocabulary which + describes people, since people connect to many other domains of + interest, which it would be impossible (as well as suboptimal) + for a single group to describe adequately in non-geological + time.</p> + + <p>RDF is usually written using XML syntax, but behaves in rather + different ways to 'vanilla' XML: the same RDF can be written in + many different ways in XML. This means that SAX and DOM XML + parsers are not adequate to deal with RDF/XML. If you want to + process the data, you will need to use one of the many RDF + toolkits available, such as Jena (Java) or Redland (C). <a href= + "http://lists.w3.org/Archives/Public/www-rdf-interest/">RDF + Interest Group</a> members can help with issues which may arise; + there is also the <a href= + "http://rdfweb.org/mailman/listinfo/rdfweb-dev">[email protected]</a> + mailing list which is the main list for FOAF, and two active and + friendly <a href= + "http://esw.w3.org/topic/InternetRelayChat">IRC</a> channels: + <a href="irc://irc.freenode.net/#rdfig">#rdfig</a> and <a href= + "irc://irc.freenode.net/#foaf">#foaf</a> on <a href= + "http://www.freenode.net/">freenode</a>.</p> + + <h2 id="sec-crossref">FOAF cross-reference: Listing FOAF Classes and + Properties</h2> + + <p>FOAF introduces the following classes and properties. View + this document's source markup to see the RDF/XML version.</p> + <!-- the following is the script-generated list of classes and properties --> + +<div class="azlist"> +<p>Classes: | <a href="#term_Agent">Agent</a> | <a href="#term_Document">Document</a> | <a href="#term_Group">Group</a> | <a href="#term_Image">Image</a> | <a href="#term_OnlineAccount">OnlineAccount</a> | <a href="#term_OnlineChatAccount">OnlineChatAccount</a> | <a href="#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a> | <a href="#term_OnlineGamingAccount">OnlineGamingAccount</a> | <a href="#term_Organization">Organization</a> | <a href="#term_Person">Person</a> | <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> | <a href="#term_Project">Project</a> | +</p> +<p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_openid">openid</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | +</p> +</div> + + +<div class="termlist"><h3>Classes and Properties (full detail)</h3> +<div class='termdetails'><br /> + + <div class="specterm" id="term_OnlineEcommerceAccount"> + <h3>Class: foaf:OnlineEcommerceAccount</h3> + <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Online Account">Online Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineEcommerceAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +buying and/or selling of goods, services etc. Examples include <a +href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a +href="http://www.paypal.com/">PayPal</a>, <a +href="http://www.thinkgeek.com/">thinkgeek</a>, etc. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineAccount"> + <h3>Class: foaf:OnlineAccount</h3> + <em>Online Account</em> - An online account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_account service homepage">account service homepage</a> + <a href="#term_account name">account name</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_holds account">holds account</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Online E-commerce Account">Online E-commerce Account</a> + <a href="#term_Online Gaming Account">Online Gaming Account</a> + <a href="#term_Online Chat Account">Online Chat Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineAccount</code> represents the provision of some form of online +service, by some party (indicated indirectly via a +<code>foaf:accountServiceHomepage</code>) to some <code>foaf:Agent</code>. The +<code>foaf:holdsAccount</code> property of the agent is used to indicate accounts that are +associated with the agent. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> for an example. Other sub-classes include +<code>foaf:OnlineEcommerceAccount</code> and <code>foaf:OnlineGamingAccount</code>. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Agent"> + <h3>Class: foaf:Agent</h3> + <em>Agent</em> - An agent (eg. person, group, software or physical artifact). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> + <a href="#term_birthday">birthday</a> + <a href="#term_Yahoo chat ID">Yahoo chat ID</a> + <a href="#term_holds account">holds account</a> + <a href="#term_tipjar">tipjar</a> + <a href="#term_weblog">weblog</a> + <a href="#term_jabber ID">jabber ID</a> + <a href="#term_made">made</a> + <a href="#term_gender">gender</a> + <a href="#term_personal mailbox">personal mailbox</a> + <a href="#term_openid">openid</a> + <a href="#term_ICQ chat ID">ICQ chat ID</a> + <a href="#term_MSN chat ID">MSN chat ID</a> + <a href="#term_AIM chat ID">AIM chat ID</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_member">member</a> + <a href="#term_maker">maker</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Person">Person</a> + <a href="#term_Organization">Organization</a> + <a href="#term_Group">Group</a> + </td></tr> + </table> + <p> +The <code>foaf:Agent</code> class is the class of agents; things that do stuff. A well +known sub-class is <code>foaf:Person</code>, representing people. Other kinds of agents +include <code>foaf:Organization</code> and <code>foaf:Group</code>. +</p> + +<p> +The <code>foaf:Agent</code> class is useful in a few places in FOAF where +<code>foaf:Person</code> would have been overly specific. For example, the IM chat ID +properties such as <code>jabberID</code> are typically associated with people, but +sometimes belong to software bots. +</p> + +<!-- todo: write rdfs:domain statements for those properties --> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Organization"> + <h3>Class: foaf:Organization</h3> + <em>Organization</em> - An organization. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Agent">Agent</a> + </td></tr> + </table> + <p> +The <code>foaf:Organization</code> class represents a kind of <code>foaf:Agent</code> +corresponding to social instititutions such as companies, societies etc. +</p> + +<p class="editorial"> +This is a more 'solid' class than <code>foaf:Group</code>, which allows +for more ad-hoc collections of individuals. These terms, like the corresponding +natural language concepts, have some overlap, but different emphasis. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Document"> + <h3>Class: foaf:Document</h3> + <em>Document</em> - A document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_topic">topic</a> + <a href="#term_primary topic">primary topic</a> + <a href="#term_sha1sum (hex)">sha1sum (hex)</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_account service homepage">account service homepage</a> + <a href="#term_publications">publications</a> + <a href="#term_workplace homepage">workplace homepage</a> + <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_is primary topic of">is primary topic of</a> + <a href="#term_tipjar">tipjar</a> + <a href="#term_weblog">weblog</a> + <a href="#term_interest">interest</a> + <a href="#term_openid">openid</a> + <a href="#term_homepage">homepage</a> + <a href="#term_work info homepage">work info homepage</a> + <a href="#term_page">page</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> + </td></tr> + </table> + <p> +The <code>foaf:Document</code> class represents those things which are, broadly conceived, +'documents'. +</p> + +<p> +The <code>foaf:Image</code> class is a sub-class of <code>foaf:Document</code>, since all images +are documents. +</p> + +<p class="editorial"> +We do not (currently) distinguish precisely between physical and electronic documents, or +between copies of a work and the abstraction those copies embody. The relationship between +documents and their byte-stream representation needs clarification (see <code>foaf:sha1</code> +for related issues). +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Image"> + <h3>Class: foaf:Image</h3> + <em>Image</em> - An image. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_thumbnail">thumbnail</a> + <a href="#term_depicts">depicts</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_image">image</a> + <a href="#term_thumbnail">thumbnail</a> + <a href="#term_depiction">depiction</a> +</td></tr> + </table> + <p> +The class <code>foaf:Image</code> is a sub-class of <code>foaf:Document</code> +corresponding to those documents which are images. +</p> + +<p> +Digital images (such as JPEG, PNG, GIF bitmaps, SVG diagrams etc.) are examples of +<code>foaf:Image</code>. +</p> + +<!-- much more we could/should say here --> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_PersonalProfileDocument"> + <h3>Class: foaf:PersonalProfileDocument</h3> + <em>PersonalProfileDocument</em> - A personal profile RDF document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Document">Document</a> + </td></tr> + </table> + <p> +The <code>foaf:PersonalProfileDocument</code> class represents those +things that are a <code>foaf:Document</code>, and that use RDF to +describe properties of the person who is the <code>foaf:maker</code> +of the document. There is just one <code>foaf:Person</code> described in +the document, ie. +the person who <code>foaf:made</code> it and who will be its +<code>foaf:primaryTopic</code>. +</p> + +<p> +The <code>foaf:PersonalProfileDocument</code> class, and FOAF's +associated conventions for describing it, captures an important +deployment pattern for the FOAF vocabulary. FOAF is very often used in +public RDF documents made available through the Web. There is a +colloquial notion that these "FOAF files" are often <em>somebody's</em> +FOAF file. Through <code>foaf:PersonalProfileDocument</code> we provide +a machine-readable expression of this concept, providing a basis for +FOAF documents to make claims about their maker and topic. +</p> + +<p> +When describing a <code>foaf:PersonalProfileDocument</code> it is +typical (and useful) to describe its associated <code>foaf:Person</code> +using the <code>foaf:maker</code> property. Anything that is a +<code>foaf:Person</code> and that is the <code>foaf:maker</code> of some +<code>foaf:Document</code> will be the <code>foaf:primaryTopic</code> of +that <code>foaf:Document</code>. Although this can be inferred, it is +helpful to include this information explicitly within the +<code>foaf:PersonalProfileDocument</code>. +</p> + +<p> +For example, here is a fragment of a personal profile document which +describes its author explicitly: +</p> +<div class="example"> +<pre> +&lt;foaf:Person rdf:nodeID="p1"&gt; + &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:homepage rdf:resource="http://rdfweb.org/people/danbri/"/&gt; + &lt;!-- etc... --&gt; +&lt;/foaf:Person&gt; + +&lt;foaf:PersonalProfileDocument rdf:about=""&gt; + &lt;foaf:maker rdf:nodeID="p1"/&gt; + &lt;foaf:primaryTopic rdf:nodeID="p1"/&gt; +&lt;/foaf:PersonalProfileDocument&gt; +</pre> +</div> + +<p> +Note that a <code>foaf:PersonalProfileDocument</code> will have some +representation as RDF. Typically this will be in W3C's RDF/XML syntax, +however we leave open the possibility for the use of other notations, or +representational conventions including automated transformations from +HTML (<a href="http://www.w3.org/2004/01/rdxh/spec">GRDDL</a> spec for +one such technique). +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineGamingAccount"> + <h3>Class: foaf:OnlineGamingAccount</h3> + <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Online Account">Online Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineGamingAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +online gaming. +</p> + +<p> +Examples might include <a href="http://everquest.station.sony.com/">EverQuest</a>, +<a href="http://www.xbox.com/live/">Xbox live</a>, <a +href="http://nwn.bioware.com/">Neverwinter Nights</a>, etc., as well as older text-based +systems (MOOs, MUDs and suchlike). +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Person"> + <h3>Class: foaf:Person</h3> + <em>Person</em> - A person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_knows">knows</a> + <a href="#term_myersBriggs">myersBriggs</a> + <a href="#term_interest">interest</a> + <a href="#term_publications">publications</a> + <a href="#term_Surname">Surname</a> + <a href="#term_firstName">firstName</a> + <a href="#term_workplace homepage">workplace homepage</a> + <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_image">image</a> + <a href="#term_family_name">family_name</a> + <a href="#term_plan">plan</a> + <a href="#term_interest_topic">interest_topic</a> + <a href="#term_geekcode">geekcode</a> + <a href="#term_work info homepage">work info homepage</a> + <a href="#term_current project">current project</a> + <a href="#term_past project">past project</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_knows">knows</a> +</td></tr> <tr><th>subClassOf</th> + <td> <a href="#term_Agent">Agent</a> + </td></tr> + </table> + <p> +The <code>foaf:Person</code> class represents people. Something is a +<code>foaf:Person</code> if it is a person. We don't nitpic about whether they're +alive, dead, real, or imaginary. The <code>foaf:Person</code> class is a sub-class of the +<code>foaf:Agent</code> class, since all people are considered 'agents' in FOAF. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Group"> + <h3>Class: foaf:Group</h3> + <em>Group</em> - A class of Agents. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_member">member</a> + </td></tr> + <tr><th>subClassOf</th> + <td> <a href="#term_Agent">Agent</a> + </td></tr> + </table> + <p> +The <code>foaf:Group</code> class represents a collection of individual agents (and may +itself play the role of a <code>foaf:Agent</code>, ie. something that can perform actions). +</p> +<p> +This concept is intentionally quite broad, covering informal and +ad-hoc groups, long-lived communities, organizational groups within a workplace, etc. Some +such groups may have associated characteristics which could be captured in RDF (perhaps a +<code>foaf:homepage</code>, <code>foaf:name</code>, mailing list etc.). +</p> + +<p> +While a <code>foaf:Group</code> has the characteristics of a <code>foaf:Agent</code>, it +is also associated with a number of other <code>foaf:Agent</code>s (typically people) who +constitute the <code>foaf:Group</code>. FOAF provides a mechanism, the +<code>foaf:membershipClass</code> property, which relates a <code>foaf:Group</code> to a +sub-class of the class <code>foaf:Agent</code> who are members of the group. This is a +little complicated, but allows us to make group membership rules explicit. +</p> + + +<p>The markup (shown below) for defining a group is both complex and powerful. It +allows group membership rules to match against any RDF-describable characteristics of the potential +group members. As FOAF and similar vocabularies become more expressive in their ability to +describe individuals, the <code>foaf:Group</code> mechanism for categorising them into +groups also becomes more powerful. +</p> + +<p> +While the formal description of membership criteria for a <code>foaf:Group</code> may +be complex, the basic mechanism for saying that someone is in a <code>foaf:Group</code> is +very simple. We simply use a <code>foaf:member</code> property of the +<code>foaf:Group</code> to indicate the agents that are members of the group. For example: + +</p> + +<div class="example"> + +<pre> +&lt;foaf:Group&gt; + &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; + &lt;foaf:member&gt; + &lt;foaf:Person&gt; + &lt;foaf:name&gt;Libby Miller&lt;/foaf:name&gt; + &lt;foaf:homepage rdf:resource="http://ilrt.org/people/libby/"/&gt; + &lt;foaf:workplaceHomepage rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; + &lt;/foaf:Person&gt; + &lt;/foaf:member&gt; +&lt;/foaf:Group&gt; +</pre> +</div> + + + +<p> +Behind the scenes, further RDF statements can be used to express the rules for being a +member of this group. End-users of FOAF need not pay attention to these details. +</p> + + +<p> +Here is an example. We define a <code>foaf:Group</code> representing those people who +are ILRT staff members. The <code>foaf:membershipClass</code> property connects the group (conceived of as a social +entity and agent in its own right) with the class definition for those people who +constitute it. In this case, the rule is that all group members are in the +ILRTStaffPerson class, which is in turn populated by all those things that are a +<code>foaf:Person</code> and which have a <code>foaf:workplaceHomepage</code> of +http://www.ilrt.bris.ac.uk/. This is typical: FOAF groups are created by +specifying a sub-class of <code>foaf:Agent</code> (in fact usually this +will be a sub-class of <code>foaf:Person</code>), and giving criteria +for which things fall in or out of the sub-class. For this, we use the +<code>owl:onProperty</code> and <code>owl:hasValue</code> properties, +indicating the property/value pairs which must be true of matching +agents. +</p> + +<div class="example"> +<pre> +&lt;!-- here we see a FOAF group described. + each foaf group may be associated with an OWL definition + specifying the class of agents that constitute the group's membership --&gt; +&lt;foaf:Group&gt; + &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; + &lt;foaf:membershipClass&gt; + &lt;owl:Class rdf:about="http://ilrt.example.com/groups#ILRTStaffPerson"&gt; + &lt;rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Person"/&gt; + &lt;rdfs:subClassOf&gt; + &lt;owl:Restriction&gt; + &lt;owl:onProperty rdf:resource="http://xmlns.com/foaf/0.1/workplaceHomepage"/&gt; + &lt;owl:hasValue rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; + &lt;/owl:Restriction&gt; + &lt;/rdfs:subClassOf&gt; + &lt;/owl:Class&gt; + &lt;/foaf:membershipClass&gt; +&lt;/foaf:Group&gt; +</pre> +</div> + + +<p> +Note that while these example OWL rules for being in the eg:ILRTStaffPerson class are +based on a <code>foaf:Person</code> having a particular +<code>foaf:workplaceHomepage</code>, this places no obligations on the authors of actual +FOAF documents to include this information. If the information <em>is</em> included, then +generic OWL tools may infer that some person is an eg:ILRTStaffPerson. To go the extra +step and infer that some eg:ILRTStaffPerson is a <code>foaf:member</code> of the group +whose <code>foaf:name</code> is "ILRT staff", tools will need some knowledge of the way +FOAF deals with groups. In other words, generic OWL technology gets us most of the way, +but the full <code>foaf:Group</code> machinery requires extra work for implimentors. +</p> + +<p> +The current design names the relationship as pointing <em>from</em> the group, +to the member. This is convenient when writing XML/RDF that encloses the members within +markup that describes the group. Alternate representations of the same content are +allowed in RDF, so you can write claims about the Person and the Group without having to +nest either description inside the other. For (brief) example: +</p> + +<div class="example"> +<pre> +&lt;foaf:Group&gt; + &lt;foaf:member rdf:nodeID="libby"/&gt; + &lt;!-- more about the group here --&gt; +&lt;/foaf:Group&gt; +&lt;foaf:Person rdf:nodeID="libby"&gt; + &lt;!-- more about libby here --&gt; +&lt;/foaf:Person&gt; +</pre> +</div> + +<p> +There is a FOAF <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> +associated with this FOAF term. A design goal is to make the most of W3C's <a +href="http://www.w3.org/2001/sw/WebOnt">OWL</a> language for representing group-membership +criteria, while also making it easy to leverage existing groups and datasets available +online (eg. buddylists, mailing list membership lists etc). Feedback on the current design +is solicited! Should we consider using SPARQL queries instead, for example? +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Project"> + <h3>Class: foaf:Project</h3> + <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:Project</code> class represents the class of things that are 'projects'. These +may be formal or informal, collective or individual. It is often useful to indicate the +<code>foaf:homepage</code> of a <code>foaf:Project</code>. +</p> + +<p class="editorial"> +Further work is needed to specify the connections between this class and the FOAF properties +<code>foaf:currentProject</code> and <code>foaf:pastProject</code>. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineChatAccount"> + <h3>Class: foaf:OnlineChatAccount</h3> + <em>Online Chat Account</em> - An online chat account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Online Account">Online Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineChatAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +chat / instant messaging. +</p> + +<p> +This is a generalization of the FOAF Chat ID properties, +<code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, +<code>foaf:msnChatID</code>, <code>foaf:icqChatID</code> and +<code>foaf:yahooChatID</code>. +</p> + +<p> +Unlike those simple properties, <code>foaf:OnlineAccount</code> and associated FOAF terms +allows us to describe a great variety of online accounts, without having to anticipate +them in the FOAF vocabulary. +</p> + +<p> +For example, here is a description of an IRC chat account, specific to the Freenode IRC +network: +</p> + +<div class="example"> +<pre> +&lt;foaf:Person&gt; + &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:holdsAccount&gt; + &lt;foaf:OnlineAccount&gt; + &lt;rdf:type rdf:resource="http://xmlns.com/foaf/0.1/OnlineChatAccount"/&gt; + &lt;foaf:accountServiceHomepage rdf:resource="http://www.freenode.net/irc_servers.shtml"/&gt; + &lt;foaf:accountName&gt;danbri&lt;/foaf:accountName&gt; + &lt;/foaf:OnlineAccount&gt; + &lt;/foaf:holdsAccount&gt; +&lt;/foaf:Person&gt; +</pre> +</div> + +<p> +Note that it may be impolite to carelessly reveal someone else's chat identifier (which +might also serve as an indicate of email address) As with email, there are privacy and +anti-SPAM considerations. FOAF does not currently provide a way to represent an +obfuscated chat ID (ie. there is no parallel to the <code>foaf:mbox</code> / +<code>foaf:mbox_sha1sum</code> mapping). +</p> +<p> +In addition to the generic <code>foaf:OnlineAccount</code> and +<code>foaf:OnlineChatAccount</code> mechanisms, +FOAF also provides several convenience chat ID properties +(<code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, <code>foaf:icqChatID</code>, +<code>foaf:msnChatID</code>,<code>foaf:yahooChatID</code>). +These serve as as a shorthand for some common cases; their use may not always be +appropriate. +</p> +<p class="editorial"> +We should specify some mappings between the abbreviated and full representations of +<a href="http://www.jabber.org/">Jabber</a>, <a href="http://www.aim.com/">AIM</a>, <a +href="http://chat.msn.com/">MSN</a>, <a href="http://web.icq.com/icqchat/">ICQ</a>, <a +href="http://chat.yahoo.com/">Yahoo!</a> and <a href="http://chat.msn.com/">MSN</a> chat +accounts. This requires us to identify an appropriate <code>foaf:accountServiceHomepage</code> for each. If we +wanted to make the <code>foaf:OnlineAccount</code> mechanism even more generic, we could +invent a relationship that holds between a <code>foaf:OnlineAccount</code> instance and a +convenience property. To continue the example above, we could describe how <a +href="http://www.freenode.net/">Freenode</a> could define a property 'fn:freenodeChatID' +corresponding to Freenode online accounts. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_myersBriggs"> + <h3>Property: foaf:myersBriggs</h3> + <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + <!-- todo: expand acronym --> + +<p> +The <code>foaf:myersBriggs</code> property represents the Myers Briggs (MBTI) approach to +personality taxonomy. It is included in FOAF as an example of a property +that takes certain constrained values, and to give some additional detail to the FOAF +files of those who choose to include it. The <code>foaf:myersBriggs</code> property applies only to the +<code>foaf:Person</code> class; wherever you see it, you can infer it is being applied to +a person. +</p> + +<p> +The <code>foaf:myersBriggs</code> property is interesting in that it illustrates how +FOAF can serve as a carrier for various kinds of information, without necessarily being +commited to any associated worldview. Not everyone will find myersBriggs (or star signs, +or blood types, or the four humours) a useful perspective on human behaviour and +personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses +the underlying theory, any more than the existence of <code>foaf:weblog</code> is an +endorsement of soapboxes. +</p> + +<p> +The values for <code>foaf:myersBriggs</code> are the following 16 4-letter textual codes: +ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, +ENTP, ISFJ. If multiple of these properties are applicable, they are represented by +applying multiple properties to a person. +</p> + +<p> +For further reading on MBTI, see various online sources (eg. <a +href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There +are various online sites which offer quiz-based tools for determining a person's MBTI +classification. The owners of the MBTI trademark have probably not approved of these. +</p> + +<p> +This FOAF property suggests some interesting uses, some of which could perhaps be used to +test the claims made by proponents of the MBTI (eg. an analysis of weblog postings +filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are +self-selecting; MBTI categories may not be uniformly appealing to the people they +describe. Further, there is probably a degree of cultural specificity implicit in the +assumptions made by many questionaire-based MBTI tools; the MBTI system may not make +sense in cultural settings beyond those it was created for. +</p> + +<p> +See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a +href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> +for further background and examples. +</p> + +<p> +Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting +Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the +trademark in the UK. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_mbox_sha1sum"> + <h3>Property: foaf:mbox_sha1sum</h3> + <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +A <code>foaf:mbox_sha1sum</code> of a <code>foaf:Person</code> is a textual representation of +the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an +Internet mailbox that they stand in a <code>foaf:mbox</code> relationship to. +</p> + +<p> +In other words, if you have a mailbox (<code>foaf:mbox</code>) but don't want to reveal its +address, you can take that address and generate a <code>foaf:mbox_sha1sum</code> representation +of it. Just as a <code>foaf:mbox</code> can be used as an indirect identifier for its owner, we +can do the same with <code>foaf:mbox_sha1sum</code> since there is only one +<code>foaf:Person</code> with any particular value for that property. +</p> + +<p> +Many FOAF tools use <code>foaf:mbox_sha1sum</code> in preference to exposing mailbox +information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques +include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's +documentation</a>) and the use of <a +href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for +mail filtering. +</p> + +<p> +Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a +href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's +weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing +whitespace, when computing a <code>foaf:mbox_sha1sum</code> property. +</p> +<!-- what about Javascript. move refs to wiki maybe. --> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_aimChatID"> + <h3>Property: foaf:aimChatID</h3> + <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:aimChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. +See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM +screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a +href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_firstName"> + <h3>Property: foaf:firstName</h3> + <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. +</p> + +<p> +There is also a simple <code>foaf:name</code> property. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_tipjar"> + <h3>Property: foaf:tipjar</h3> + <em>tipjar</em> - A tipjar document for this agent, describing means for payment and reward. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:tipjar</code> property relates an <code>foaf:Agent</code> +to a <code>foaf:Document</code> that describes some mechanisms for +paying or otherwise rewarding that agent. +</p> + +<p> +The <code>foaf:tipjar</code> property was created following <a +href="http://rdfweb.org/mt/foaflog/archives/2004/02/12/20.07.32/">discussions</a> +about simple, lightweight mechanisms that could be used to encourage +rewards and payment for content exchanged online. An agent's +<code>foaf:tipjar</code> page(s) could describe informal ("Send me a +postcard!", "here's my book, music and movie wishlist") or formal +(machine-readable micropayment information) information about how that +agent can be paid or rewarded. The reward is not associated with any +particular action or content from the agent concerned. A link to +a service such as <a href="http://www.paypal.com/">PayPal</a> is the +sort of thing we might expect to find in a tipjar document. +</p> + +<p> +Note that the value of a <code>foaf:tipjar</code> property is just a +document (which can include anchors into HTML pages). We expect, but +do not currently specify, that this will evolve into a hook +for finding more machine-readable information to support payments, +rewards. The <code>foaf:OnlineAccount</code> machinery is also relevant, +although the information requirements for automating payments are not +currently clear. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_yahooChatID"> + <h3>Property: foaf:yahooChatID</h3> + <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:yahooChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the Yahoo online Chat system. +See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their +service. Yahoo chat IDs are also used across several other Yahoo services, including email and +<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_dnaChecksum"> + <h3>Property: foaf:dnaChecksum</h3> + <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:dnaChecksum</code> property is mostly a joke, but +also a reminder that there will be lots of different identifying +properties for people, some of which we might find disturbing. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_mbox"> + <h3>Property: foaf:mbox</h3> + <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:mbox</code> property is a relationship between the owner of a mailbox and +a mailbox. These are typically identified using the mailto: URI scheme (see <a +href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). +</p> + +<p> +Note that there are many mailboxes (eg. shared ones) which are not the +<code>foaf:mbox</code> of anyone. Furthermore, a person can have multiple +<code>foaf:mbox</code> properties. +</p> + +<p> +In FOAF, we often see <code>foaf:mbox</code> used as an indirect way of identifying its +owner. This works even if the mailbox is itself out of service (eg. 10 years old), since +the property is defined in terms of its primary owner, and doesn't require the mailbox to +actually be being used for anything. +</p> + +<p> +Many people are wary of sharing information about their mailbox addresses in public. To +address such concerns whilst continuing the FOAF convention of indirectly identifying +people by referring to widely known properties, FOAF also provides the +<code>foaf:mbox_sha1sum</code> mechanism, which is a relationship between a person and +the value you get from passing a mailbox URI to the SHA1 mathematical function. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_img"> + <h3>Property: foaf:img</h3> + <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Image">Image</a> +</td> </tr> + </table> + <p> +The <code>foaf:img</code> property relates a <code>foaf:Person</code> to a +<code>foaf:Image</code> that represents them. Unlike its super-property +<code>foaf:depiction</code>, we only use <code>foaf:img</code> when an image is +particularly representative of some person. The analogy is with the image(s) that might +appear on someone's homepage, rather than happen to appear somewhere in their photo album. +</p> + +<p> +Unlike the more general <code>foaf:depiction</code> property (and its inverse, +<code>foaf:depicts</code>), the <code>foaf:img</code> property is only used with +representations of people (ie. instances of <code>foaf:Person</code>). So you can't use +it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more +restricted than <code>foaf:depiction</code> so we can have a useful way of picking out a +reasonable image to represent someone. FOAF defines <code>foaf:img</code> as a +sub-property of <code>foaf:depiction</code>, which means that the latter relationship is +implied whenever two things are related by the former. +</p> + +<p> +Note that <code>foaf:img</code> does not have any restrictions on the dimensions, colour +depth, format etc of the <code>foaf:Image</code> it references. +</p> + +<p> +Terminology: note that <code>foaf:img</code> is a property (ie. relationship), and that +<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It +might have been more helpful to call <code>foaf:img</code> 'mugshot' or similar; instead +it is named by analogy to the HTML IMG element. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_depicts"> + <h3>Property: foaf:depicts</h3> + <em>depicts</em> - A thing depicted in this representation. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Image">Image</a> +</td></tr> + + </table> + <p> +The <code>foaf:depicts</code> property is a relationship between a <code>foaf:Image</code> +and something that the image depicts. As such it is an inverse of the +<code>foaf:depiction</code> relationship. See <code>foaf:depiction</code> for further notes. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_holdsAccount"> + <h3>Property: foaf:holdsAccount</h3> + <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td> </tr> + </table> + <p> +The <code>foaf:holdsAccount</code> property relates a <code>foaf:Agent</code> to an +<code>foaf:OnlineAccount</code> for which they are the sole account holder. See +<code>foaf:OnlineAccount</code> for usage details. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_gender"> + <h3>Property: foaf:gender</h3> + <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:gender</code> property relates a <code>foaf:Agent</code> (typically a +<code>foaf:Person</code>) to a string representing its gender. In most cases the value +will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). +Like all FOAF properties, there is in general no requirement to use +<code>foaf:gender</code> in any particular document or description. Values other than +'male' and 'female' may be used, but are not enumerated here. The <code>foaf:gender</code> +mechanism is not intended to capture the full variety of biological, social and sexual +concepts associated with the word 'gender'. +</p> + +<p> +Anything that has a <code>foaf:gender</code> property will be some kind of +<code>foaf:Agent</code>. However there are kinds of <code>foaf:Agent</code> to +which the concept of gender isn't applicable (eg. a <code>foaf:Group</code>). FOAF does not +currently include a class corresponding directly to "the type of thing that has a gender". +At any point in time, a <code>foaf:Agent</code> has at most one value for +<code>foaf:gender</code>. FOAF does not treat <code>foaf:gender</code> as a +<em>static</em> property; the same individual may have different values for this property +at different times. +</p> + +<p> +Note that FOAF's notion of gender isn't defined biologically or anatomically - this would +be tricky since we have a broad notion that applies to all <code>foaf:Agent</code>s +(including robots - eg. Bender from Futurama is 'male'). As stressed above, +FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated +with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise +between the clinical and the social/psychological. In general, a person will be the best +authority on their <code>foaf:gender</code>. Feedback on this design is +particularly welcome (via the FOAF mailing list, +<a href="http://rdfweb.org/mailman/listinfo/rdfweb-dev">rdfweb-dev</a>). We have tried to +be respectful of diversity without attempting to catalogue or enumerate that diversity. +</p> + +<p> +This may also be a good point for a periodic reminder: as with all FOAF properties, +documents that use '<code>foaf:gender</code>' will on occassion be innacurate, misleading +or outright false. FOAF, like all open means of communication, supports <em>lying</em>. + Application authors using +FOAF data should always be cautious in their presentation of unverified information, but be +particularly sensitive to issues and risks surrounding sex and gender (including privacy +and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit +<code>foaf:gender</code> when describing themselves and others, and to allow at least for +values other than 'male' and 'female' as options. Users of information +conveyed via FOAF (as via information conveyed through mobile phone text messages, email, +Internet chat, HTML pages etc.) should be skeptical of unverified information. +</p> + +<!-- +b/g article currently offline. +http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 +--> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_geekcode"> + <h3>Property: foaf:geekcode</h3> + <em>geekcode</em> - A textual geekcode for this person, see http://www.geekcode.com/geek.html <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + <p> +The <code>foaf:geekcode</code> property is used to represent a 'Geek Code' for some +<code>foaf:Person</code>. +</p> + +<p> +See the <a href="http://www.geekcode.com/geek.html">Code of the Geeks</a> specification for +details of the code, which provides a somewhat frivolous and willfully obscure mechanism for +characterising technical expertise, interests and habits. The <code>foaf:geekcode</code> +property is not bound to any particular version of the code. The last published version +of the code was v3.12 in March 1996. +</p> + +<p> +As the <a href="http://www.geekcode.com/">Geek Code</a> website notes, the code played a small +(but amusing) part in the history of the Internet. The <code>foaf:geekcode</code> property +exists in acknowledgement of this history. It'll never be 1996 again. +</p> + +<p> +Note that the Geek Code is a densely packed collections of claims about the person it applies +to; to express these claims explicitly in RDF/XML would be incredibly verbose. The syntax of the +Geek Code allows for '&lt;' and '&gt;' characters, which have special meaning in RDF/XML. +Consequently these should be carefully escaped in markup. +</p> + +<p> +An example Geek Code: +</p> +<p class="example"> + GED/J d-- s:++>: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++>$ +PE++>$ Y++ PGP++ t- 5+++ X++ R+++>$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** +</p> + +<p> +...would be written in FOAF RDF/XML as follows: +</p> + +<p class="example"> +&lt;foaf:geekcode&gt; + GED/J d-- s:++&amp;gt;: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ + w--- O- M+ V-- PS++&amp;gt;$ PE++&amp;gt;$ Y++ PGP++ t- 5+++ X++ R+++&amp;gt;$ + tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** +&lt;/foaf:geekcode&gt; +</p> + + +<p> +See also the <a href="http://www.everything2.com/index.pl?node=GEEK%20CODE">geek code</a> entry +in <a href="http://www.everything2.com/">everything2</a>, which tells us that <em>the +geek code originated in 1993; it was inspired (according to the inventor) by previous "bear", +"smurf" and "twink" style-and-sexual-preference codes from lesbian and gay newsgroups</em>. +There is also a <a href="http://www.ebb.org/ungeek/">Geek Code Decoder Page</a> and a form-based +<a href="http://www.joereiss.net/geek/geek.html">generator</a>. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_birthday"> + <h3>Property: foaf:birthday</h3> + <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:birthday</code> property is a relationship between a <code>foaf:Agent</code> +and a string representing the month and day in which they were born (Gregorian calendar). +See <a href="http://rdfweb.org/topic/BirthdayIssue">BirthdayIssue</a> for details of related properties that can +be used to describe such things in more flexible ways. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_theme"> + <h3>Property: foaf:theme</h3> + <em>theme</em> - A theme. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:theme</code> property is rarely used and under-specified. The intention was +to use it to characterise interest / themes associated with projects and groups. Further +work is needed to meet these goals. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_family_name"> + <h3>Property: foaf:family_name</h3> + <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. +</p> + +<p> +There is also a simple <code>foaf:name</code> property. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_phone"> + <h3>Property: foaf:phone</h3> + <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The <code>foaf:phone</code> of something is a phone, typically identified using the tel: URI +scheme. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_plan"> + <h3>Property: foaf:plan</h3> + <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + <!-- orig contrib'd by Cardinal --> + +<p>The <code>foaf:plan</code> property provides a space for a +<code>foaf:Person</code> to hold some arbitrary content that would appear in +a traditional '.plan' file. The plan file was stored in a user's home +directory on a UNIX machine, and displayed to people when the user was +queried with the finger utility.</p> + +<p>A plan file could contain anything. Typical uses included brief +comments, thoughts, or remarks on what a person had been doing lately. Plan +files were also prone to being witty or simply osbscure. Others may be more +creative, writing any number of seemingly random compositions in their plan +file for people to stumble upon.</p> + +<p> +See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the +Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The +<code>foaf:geekcode</code> property may also be of interest. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_depiction"> + <h3>Property: foaf:depiction</h3> + <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + <tr><th>Range:</th> + <td> <a href="#term_Image">Image</a> +</td> </tr> + </table> + <p> +The <code>foaf:depiction</code> property is a relationship between a thing and an +<code>foaf:Image</code> that depicts it. As such it is an inverse of the +<code>foaf:depicts</code> relationship. +</p> + +<p> +A common use of <code>foaf:depiction</code> (and <code>foaf:depicts</code>) is to indicate +the contents of a digital image, for example the people or objects represented in an +online photo gallery. +</p> + +<p> +Extensions to this basic idea include '<a +href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in +photos), as well as richer photo metadata through the mechanism of using SVG paths to +indicate the <em>regions</em> of an image which depict some particular thing. See <a +href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> +for tools and details. +</p> + +<p> +The basic notion of 'depiction' could also be extended to deal with multimedia content +(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. +</p> + +<p> +The <code>foaf:depiction</code> property is a super-property of the more specific property +<code>foaf:img</code>, which is used more sparingly. You stand in a +<code>foaf:depiction</code> relation to <em>any</em> <code>foaf:Image</code> that depicts +you, whereas <code>foaf:img</code> is typically used to indicate a few images that are +particularly representative. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_nick"> + <h3>Property: foaf:nick</h3> + <em>nickname</em> - A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The <code>foaf:nick</code> property relates a <code>foaf:Person</code> to a short (often +abbreviated) nickname, such as those use in IRC chat, online accounts, and computer +logins. +</p> + +<p> +This property is necessarily vague, because it does not indicate any particular naming +control authority, and so cannot distinguish a person's login from their (possibly +various) IRC nicknames or other similar identifiers. However it has some utility, since +many people use the same string (or slight variants) across a variety of such +environments. +</p> + +<p> +For specific controlled sets of names (relating primarily to Instant Messanger accounts), +FOAF provides some convenience properties: <code>foaf:jabberID</code>, +<code>foaf:aimChatID</code>, <code>foaf:msnChatID</code> and +<code>foaf:icqChatID</code>. Beyond this, the problem of representing such accounts is not +peculiar to Instant Messanging, and it is not scaleable to attempt to enumerate each +naming database as a distinct FOAF property. The <code>foaf:OnlineAccount</code> term (and +supporting vocabulary) are provided as a more verbose and more expressive generalisation +of these properties. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_page"> + <h3>Property: foaf:page</h3> + <em>page</em> - A page or document about this thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:page</code> property relates a thing to a document about that thing. +</p> + +<p> +As such it is an inverse of the <code>foaf:topic</code> property, which relates a document +to a thing that the document is about. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_isPrimaryTopicOf"> + <h3>Property: foaf:isPrimaryTopicOf</h3> + <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:isPrimaryTopicOf</code> property relates something to a document that is +mainly about it. +</p> + + +<p> +The <code>foaf:isPrimaryTopicOf</code> property is <em>inverse functional</em>: for +any document that is the value of this property, there is at most one thing in the world +that is the primary topic of that document. This is useful, as it allows for data +merging, as described in the documentation for its inverse, <code>foaf:primaryTopic</code>. +</p> + +<p> +<code>foaf:page</code> is a super-property of <code>foaf:isPrimaryTopicOf</code>. The change +of terminology between the two property names reflects the utility of 'primaryTopic' and its +inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation +to some document X, also has a <code>foaf:page</code> relationship to it. +</p> +<p> +Note that <code>foaf:homepage</code>, is a sub-property of both <code>foaf:page</code> and +<code>foaf:isPrimarySubjectOf</code>. The awkwardly named +<code>foaf:isPrimarySubjectOf</code> is less specific, and can be used with any document +that is primarily about the thing of interest (ie. not just on homepages). +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_name"> + <h3>Property: foaf:name</h3> + <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p>The <code>foaf:name</code> of something is a simple textual string.</p> + +<p> +XML language tagging may be used to indicate the language of the name. For example: +</p> + +<div class="example"> +<code> +&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; +</code> +</div> + +<p> +FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it +does provide a basic level of interoperability. See the <a +href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for status of work on this issue. +</p> + +<p> +The <code>foaf:name</code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped +values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_topic"> + <h3>Property: foaf:topic</h3> + <em>topic</em> - A topic of some page or document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Document">Document</a> +</td></tr> + + </table> + <p> +The <code>foaf:topic</code> property relates a document to a thing that the document is +about. +</p> + +<p> +As such it is an inverse of the <code>foaf:page</code> property, which relates a thing to +a document about that thing. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_interest"> + <h3>Property: foaf:interest</h3> + <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:interest</code> property represents an interest of a +<code>foaf:Agent</code>, through +indicating a <code>foaf:Document</code> whose <code>foaf:topic</code>(s) broadly +characterises that interest.</p> + +<p class="example"> +For example, we might claim that a person or group has an interest in RDF by saying they +stand in a <code>foaf:interest</code> relationship to the <a +href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying +<em>"this agent is interested in the topic of this page"</em>. +</p> + +<p class="example"> +Uses of <code>foaf:interest</code> include a variety of filtering and resource discovery +applications. It could be used, for example, to help find answers to questions such as +"Find me members of this organisation with an interest in XML who have also contributed to +<a href="http://www.cpan.org/">CPAN</a>)". +</p> + +<p> +This approach to characterising interests is intended to compliment other mechanisms (such +as the use of controlled vocabulary). It allows us to use a widely known set of unique +identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled +syntax, this makes data merging much easier than the use of free-text characterisations of +interest. +</p> + + +<p> +Note that interest does not imply expertise, and that this FOAF term provides no support +for characterising levels of interest: passing fads and lifelong quests are both examples +of someone's <code>foaf:interest</code>. Describing interests in full is a complex +undertaking; <code>foaf:interest</code> provides one basic component of FOAF's approach to +these problems. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_pastProject"> + <h3>Property: foaf:pastProject</h3> + <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + <p>After a <code>foaf:Person</code> is no longer involved with a +<code>foaf:currentProject</code>, or has been inactive for some time, a +<code>foaf:pastProject</code> relationship can be used. This indicates that +the <code>foaf:Person</code> was involved with the described project at one +point. +</p> + +<p> +If the <code>foaf:Person</code> has stopped working on a project because it +has been completed (successfully or otherwise), <code>foaf:pastProject</code> is +applicable. In general, <code>foaf:currentProject</code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code>foaf:pastProject</code> describes what they've previously been doing. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_workInfoHomepage"> + <h3>Property: foaf:workInfoHomepage</h3> + <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:workInfoHomepage</code> of a <code>foaf:Person</code> is a +<code>foaf:Document</code> that describes their work. It is generally (but not necessarily) a +different document from their <code>foaf:homepage</code>, and from any +<code>foaf:workplaceHomepage</code>(s) they may have. +</p> + +<p> +The purpose of this property is to distinguish those pages you often see, which describe +someone's professional role within an organisation or project. These aren't really homepages, +although they share some characterstics. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_publications"> + <h3>Property: foaf:publications</h3> + <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:publications</code> property indicates a <code>foaf:Document</code> +listing (primarily in human-readable form) some publications associated with the +<code>foaf:Person</code>. Such documents are typically published alongside one's +<code>foaf:homepage</code>. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_sha1"> + <h3>Property: foaf:sha1</h3> + <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Document">Document</a> +</td></tr> + + </table> + <p> +The <code>foaf:sha1</code> property relates a <code>foaf:Document</code> to the textual form of +a SHA1 hash of (some representation of) its contents. +</p> + +<p class="editorial"> +The design for this property is neither complete nor coherent. The <code>foaf:Document</code> +class is currently used in a way that allows multiple instances at different URIs to have the +'same' contents (and hence hash). If <code>foaf:sha1</code> is an owl:InverseFunctionalProperty, +we could deduce that several such documents were the self-same thing. A more careful design is +needed, which distinguishes documents in a broad sense from byte sequences. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_membershipClass"> + <h3>Property: foaf:membershipClass</h3> + <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:membershipClass</code> property relates a <code>foaf:Group</code> to an RDF +class representing a sub-class of <code>foaf:Agent</code> whose instances are all the +agents that are a <code>foaf:member</code> of the <code>foaf:Group</code>. +</p> + +<p> +See <code>foaf:Group</code> for details and examples. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_based_near"> + <h3>Property: foaf:based_near</h3> + <em>based near</em> - A location that something is based near, for some broadly human notion of near. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <!-- note: is this mis-specified? perhaps range ought to also be SpatialThing, so we + can have multiple labels on the same point? --> + +<p>The <code>foaf:based_near</code> relationship relates two "spatial +things" +(anything that can <em>be somewhere</em>), the latter typically +described using the geo:lat / geo:long +<a href="http://www.w3.org/2003/01/geo/wgs84_pos#">geo-positioning vocabulary</a> +(See <a href="http://esw.w3.org/topic/GeoInfo">GeoInfo</a> in the W3C semweb +wiki for details). This allows us to say describe the typical latitute and +longitude of, say, a Person (people are spatial things - they can be +places) without implying that a precise location has been given. +</p> + +<p>We do not say much about what 'near' means in this context; it is a +'rough and ready' concept. For a more precise treatment, see +<a href="http://esw.w3.org/topic/GeoOnion">GeoOnion vocab</a> design +discussions, which are aiming to produce a more sophisticated vocabulary for +such purposes. +</p> + +<p> FOAF files often make use of the <code>contact:nearestAirport</code> property. This +illustrates the distinction between FOAF documents (which may make claims using <em>any</em> RDF +vocabulary) and the core FOAF vocabulary defined by this specification. For further reading on +the use of <code>nearestAirport</code> see <a +href="http://rdfweb.org/topic/UsingContactNearestAirport">UsingContactNearestAirport</a> in the +FOAF wiki. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_jabberID"> + <h3>Property: foaf:jabberID</h3> + <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:jabberID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging +system. +See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber +protocols and tools. +</p> + +<p> +Jabber, unlike several other online messaging systems, is based on an open, publically +documented protocol specification, and has a variety of open source implementations. Jabber IDs +can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For +the purposes of FOAF, these are all considered to be kinds of <code>foaf:Agent</code> (ie. +things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The +<code>foaf:jabberID</code> property is provided as a basic hook to help support RDF description +of Jabber users and services. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_thumbnail"> + <h3>Property: foaf:thumbnail</h3> + <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Image">Image</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Image">Image</a> +</td> </tr> + </table> + <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> + +<p> +The <code>foaf:thumbnail</code> property is a relationship between a +full-size <code>foaf:Image</code> and a smaller, representative <code>foaf:Image</code> +that has been derrived from it. +</p> + +<p> +It is typical in FOAF to express <code>foaf:img</code> and <code>foaf:depiction</code> +relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). +A <code>foaf:thumbnail</code> might be clipped or otherwise reduced such that it does not +depict everything that the full image depicts. Therefore FOAF does not specify that a +thumbnail <code>foaf:depicts</code> everything that the image it is derrived from depicts. +However, FOAF does expect that anything depicted in the thumbnail will also be depicted in +the source image. +</p> + +<!-- todo: add RDF rules here showing this --> + +<p> +A <code>foaf:thumbnail</code> is typically small enough that it can be +loaded and viewed quickly before a viewer decides to download the larger +version. They are often used in online photo gallery applications. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_fundedBy"> + <h3>Property: foaf:fundedBy</h3> + <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:fundedBy</code> property relates something to something else that has provided +funding for it. +</p> + +<p class="editorial"> +This property is under-specified, experimental, and should be considered liable to change. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_icqChatID"> + <h3>Property: foaf:icqChatID</h3> + <em>ICQ chat ID</em> - An ICQ chat ID <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:icqChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the ICQ Chat system. +See the <a href="http://web.icq.com/icqchat/">icq chat</a> site for more details of the 'icq' +service. Their "<a href="http://www.icq.com/products/whatisicq.html">What is ICQ?</a>" document +provides a basic overview, while their "<a href="http://company.icq.com/info/">About Us</a> page +notes that ICQ has been acquired by AOL. Despite the relationship with AOL, ICQ is at +the time of writing maintained as a separate identity from the AIM brand (see +<code>foaf:aimChatID</code>). +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_surname"> + <h3>Property: foaf:surname</h3> + <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. +</p> + +<p> +There is also a simple <code>foaf:name</code> property. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_msnChatID"> + <h3>Property: foaf:msnChatID</h3> + <em>MSN chat ID</em> - An MSN chat ID <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:msnChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the MSN online Chat system. +See Microsoft's the <a href="http://chat.msn.com/">MSN chat</a> site for more details (or for a +message saying <em>"MSN Chat is not currently compatible with your Internet browser and/or +computer operating system"</em> if your computing platform is deemed unsuitable). +</p> + +<p class="editorial"> +It is not currently clear how MSN chat IDs relate to the more general Microsoft Passport +identifiers. +</p> + +<p>See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_title"> + <h3>Property: foaf:title</h3> + <em>title</em> - Title (Mr, Mrs, Ms, Dr. etc) <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The approriate values for <code>foaf:title</code> are not formally constrained, and will +vary across community and context. Values such as 'Mr', 'Mrs', 'Ms', 'Dr' etc. are +expected. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_openid"> + <h3>Property: foaf:openid</h3> + <em>openid</em> - An OpenID for an Agent. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +A <code>foaf:openid</code> is a property of a <code>foaf:Agent</code> that associates it with a document that can be used as an <a +href="http://www.w3.org/TR/webarch/#indirect-identification">indirect identifier</a> in the manner of the <a href="http://openid.net/specs/openid-authentication-1_1.html">OpenID</a> + "Identity URL". As the OpenID 1.1 specification notes, OpenID itself"<em>does not provide any mechanism to +exchange profile information, though Consumers of an Identity can learn more about an End User from any public, semantically +interesting documents linked thereunder (FOAF, RSS, Atom, vCARD, etc.)</em>". In this way, FOAF and OpenID complement each other; +neither provides a stand-alone approach to online "trust", but combined they can address interesting parts of this larger problem +space. +</p> + +<p> +The <code>foaf:openid</code> property is "inverse functional", meaning that anything that is the foaf:openid of something, is the +<code>foaf:openid</code> of no more than one thing. FOAF is agnostic as to whether there are (according to the relevant OpenID +specifications) OpenID URIs that are equally associated with multiple Agents. FOAF offers sub-classes of Agent, ie. +<code>foaf:Organization</code> and <code>foaf:Group</code>, that allow for such scenarios to be consistent with the notion that any +foaf:openid is the foaf:openid of just one <code>foaf:Agent</code>. +</p> + +<p> +FOAF does not mandate any particular URI scheme for use as <code>foaf:openid</code> values. The OpenID 1.1 specification includes a <a +href="http://openid.net/specs/openid-authentication-1_1.html#delegating_authentication">delegation model</a> that is often used to +allow a weblog or homepage document to also serve in OpenID authentication via "link rel" HTML markup. This deployment model provides a +convenient connection to FOAF, since a similar <a href="http://xmlns.com/foaf/spec/#sec-autodesc">technique</a> is used for FOAF +autodiscovery in HTML. A single document can, for example, serve both as a homepage and an OpenID identity URL. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_maker"> + <h3>Property: foaf:maker</h3> + <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + + <tr><th>Range:</th> + <td> <a href="#term_Agent">Agent</a> +</td> </tr> + </table> + <p> +The <code>foaf:maker</code> property relates something to a +<code>foaf:Agent</code> that <code>foaf:made</code> it. As such it is an +inverse of the <code>foaf:made</code> property. +</p> + +<p> +The <code>foaf:name</code> (or other <code>rdfs:label</code>) of the +<code>foaf:maker</code> of something can be described as the +<code>dc:creator</code> of that thing.</p> + +<p> +For example, if the thing named by the URI +http://rdfweb.org/people/danbri/ has a +<code>foaf:maker</code> that is a <code>foaf:Person</code> whose +<code>foaf:name</code> is 'Dan Brickley', we can conclude that +http://rdfweb.org/people/danbri/ has a <code>dc:creator</code> of 'Dan +Brickley'. +</p> + +<p> +FOAF descriptions are encouraged to use <code>dc:creator</code> only for +simple textual names, and to use <code>foaf:maker</code> to indicate +creators, rather than risk confusing creators with their names. This +follows most Dublin Core usage. See <a +href="http://rdfweb.org/topic/UsingDublinCoreCreator">UsingDublinCoreCreator</a> +for details. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_workplaceHomepage"> + <h3>Property: foaf:workplaceHomepage</h3> + <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:workplaceHomepage</code> of a <code>foaf:Person</code> is a +<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a +<code>foaf:Organization</code> that they work for. +</p> + +<p> +By directly relating people to the homepages of their workplace, we have a simple convention +that takes advantage of a set of widely known identifiers, while taking care not to confuse the +things those identifiers identify (ie. organizational homepages) with the actual organizations +those homepages describe. +</p> + +<div class="example"> +<p> +For example, Dan Brickley works at W3C. Dan is a <code>foaf:Person</code> with a +<code>foaf:homepage</code> of http://rdfweb.org/people/danbri/; W3C is a +<code>foaf:Organization</code> with a <code>foaf:homepage</code> of http://www.w3.org/. This +allows us to say that Dan has a <code>foaf:workplaceHomepage</code> of http://www.w3.org/. +</p> + +<pre> +&lt;foaf:Person&gt; + &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; +&lt;/foaf:Person&gt; +</pre> +</div> + + +<p> +Note that several other FOAF properties work this way; +<code>foaf:schoolHomepage</code> is the most similar. In general, FOAF often indirectly +identifies things via Web page identifiers where possible, since these identifiers are widely +used and known. FOAF does not currently have a term for the name of the relation (eg. +"workplace") that holds +between a <code>foaf:Person</code> and an <code>foaf:Organization</code> that they work for. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_homepage"> + <h3>Property: foaf:homepage</h3> + <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:homepage</code> property relates something to a homepage about it. +</p> + +<p> +Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but +constrains <code>foaf:homepage</code> so that there can be only one thing that has any +particular homepage. +</p> + +<p> +A 'homepage' in this sense is a public Web document, typically but not necessarily +available in HTML format. The page has as a <code>foaf:topic</code> the thing whose +homepage it is. The homepage is usually controlled, edited or published by the thing whose +homepage it is; as such one might look to a homepage for information on its owner from its +owner. This works for people, companies, organisations etc. +</p> + +<p> +The <code>foaf:homepage</code> property is a sub-property of the more general +<code>foaf:page</code> property for relating a thing to a page about that thing. See also +<code>foaf:topic</code>, the inverse of the <code>foaf:page</code> property. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_accountName"> + <h3>Property: foaf:accountName</h3> + <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td></tr> + + </table> + <p> +The <code>foaf:accountName</code> property of a <code>foaf:OnlineAccount</code> is a +textual representation of the account name (unique ID) associated with that account. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_topic_interest"> + <h3>Property: foaf:topic_interest</h3> + <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + <p class="editorial"> +The <code>foaf:topic_interest</code> property is generally found to be confusing and ill-defined +and is a candidate for removal. The goal was to be link a person to some thing that is a topic +of their interests (rather than, per <code>foaf:interest</code> to a page that is about such a +topic). +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_givenname"> + <h3>Property: foaf:givenname</h3> + <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. +</p> + +<p> +There is also a simple <code>foaf:name</code> property. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_logo"> + <h3>Property: foaf:logo</h3> + <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The <code>foaf:logo</code> property is used to indicate a graphical logo of some kind. +<em>It is probably underspecified...</em> +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_currentProject"> + <h3>Property: foaf:currentProject</h3> + <em>current project</em> - A current project this person works on. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + <!-- originally contrib'd by Cardinal --> + +<p>A <code>foaf:currentProject</code> relates a <code>foaf:Person</code> +to a <code>foaf:Document</code> indicating some collaborative or +individual undertaking. This relationship +indicates that the <code>foaf:Person</code> has some active role in the +project, such as development, coordination, or support.</p> + +<p>When a <code>foaf:Person</code> is no longer involved with a project, or +perhaps is inactive for some time, the relationship becomes a +<code>foaf:pastProject</code>.</p> + +<p> +If the <code>foaf:Person</code> has stopped working on a project because it +has been completed (successfully or otherwise), <code>foaf:pastProject</code> is +applicable. In general, <code>foaf:currentProject</code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code>foaf:pastProject</code> describes what they've previously been doing. +</p> + +<!-- +<p>Generally speaking, anything that a <code>foaf:Person</code> has +<code>foaf:made</code> could also qualify as a +<code>foaf:currentProject</code> or <code>foaf:pastProject</code>.</p> +--> + +<p class="editorial"> +Note that this property requires further work. There has been confusion about +whether it points to a thing (eg. something you've made; a homepage for a project, +ie. a <code>foaf:Document</code> or to instances of the class <code>foaf:Project</code>, +which might themselves have a <code>foaf:homepage</code>. In practice, it seems to have been +used in a similar way to <code>foaf:interest</code>, referencing homepages of ongoing projects. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_member"> + <h3>Property: foaf:member</h3> + <em>member</em> - Indicates a member of a Group <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Group">Group</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Agent">Agent</a> +</td> </tr> + </table> + <p> +The <code>foaf:member</code> property relates a <code>foaf:Group</code> to a +<code>foaf:Agent</code> that is a member of that group. +</p> + +<p> +See <code>foaf:Group</code> for details and examples. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_schoolHomepage"> + <h3>Property: foaf:schoolHomepage</h3> + <em>schoolHomepage</em> - A homepage of a school attended by the person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>schoolHomepage</code> property relates a <code>foaf:Person</code> to a +<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a School that the +person attended. +</p> + +<p> +FOAF does not (currently) define a class for 'School' (if it did, it would probably be as +a sub-class of <code>foaf:Organization</code>). The original application area for +<code>foaf:schoolHomepage</code> was for 'schools' in the British-English sense; however +American-English usage has dominated, and it is now perfectly reasonable to describe +Universities, Colleges and post-graduate study using <code>foaf:schoolHomepage</code>. +</p> + +<p> +This very basic facility provides a basis for a low-cost, decentralised approach to +classmate-reunion and suchlike. Instead of requiring a central database, we can use FOAF +to express claims such as 'I studied <em>here</em>' simply by mentioning a +school's homepage within FOAF files. Given the homepage of a school, it is easy for +FOAF aggregators to lookup this property in search of people who attended that school. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_weblog"> + <h3>Property: foaf:weblog</h3> + <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:weblog</code> property relates a <code>foaf:Agent</code> to a weblog of +that agent. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_made"> + <h3>Property: foaf:made</h3> + <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:made</code> property relates a <code>foaf:Agent</code> +to something <code>foaf:made</code> by it. As such it is an +inverse of the <code>foaf:maker</code> property, which relates a thing to +something that made it. See <code>foaf:made</code> for more details on the +relationship between these FOAF terms and related Dublin Core vocabulary. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_primaryTopic"> + <h3>Property: foaf:primaryTopic</h3> + <em>primary topic</em> - The primary topic of some page or document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Document">Document</a> +</td></tr> + + </table> + <p> +The <code>foaf:primaryTopic</code> property relates a document to the +main thing that the document is about. +</p> + +<p> +The <code>foaf:primaryTopic</code> property is <em>functional</em>: for +any document it applies to, it can have at most one value. This is +useful, as it allows for data merging. In many cases it may be difficult +for third parties to determine the primary topic of a document, but in +a useful number of cases (eg. descriptions of movies, restaurants, +politicians, ...) it should be reasonably obvious. Documents are very +often the most authoritative source of information about their own +primary topics, although this cannot be guaranteed since documents cannot be +assumed to be accurate, honest etc. +</p> + +<p> +It is an inverse of the <code>foaf:isPrimaryTopicOf</code> property, which relates a +thing to a document <em>primarily</em> about that thing. The choice between these two +properties is purely pragmatic. When describing documents, we +use <code>foaf:primaryTopic</code> former to point to the things they're about. When +describing things (people etc.), it is useful to be able to directly cite documents which +have those things as their main topic - so we use <code>foaf:isPrimaryTopicOf</code>. In this +way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a +href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they +have descriptions of. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_knows"> + <h3>Property: foaf:knows</h3> + <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Person">Person</a> +</td> </tr> + </table> + <p> +The <code>foaf:knows</code> property relates a <code>foaf:Person</code> to another +<code>foaf:Person</code> that he or she knows. +</p> + +<p> +We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. +stalkers need not apply). Since social attitudes and conventions on this topic vary +greatly between communities, counties and cultures, it is not appropriate for FOAF to be +overly-specific here. +</p> + +<p> +If someone <code>foaf:knows</code> a person, it would be usual for +the relation to be reciprocated. However this doesn't mean that there is any obligation +for either party to publish FOAF describing this relationship. A <code>foaf:knows</code> +relationship does not imply friendship, endorsement, or that a face-to-face meeting +has taken place: phone, fax, email, and smoke signals are all perfectly +acceptable ways of communicating with people you know. +</p> +<p> +You probably know hundreds of people, yet might only list a few in your public FOAF file. +That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not +list anyone else in it at all. +This illustrates the Semantic Web principle of partial description: RDF documents +rarely describe the entire picture. There is always more to be said, more information +living elsewhere in the Web (or in our heads...). +</p> + +<p> +Since <code>foaf:knows</code> is vague by design, it may be suprising that it has uses. +Typically these involve combining other RDF properties. For example, an application might +look at properties of each <code>foaf:weblog</code> that was <code>foaf:made</code> by +someone you "<code>foaf:knows</code>". Or check the newsfeed of the online photo archive +for each of these people, to show you recent photos taken by people you know. +</p> + +<p> +To provide additional levels of representation beyond mere 'knows', FOAF applications +can do several things. +</p> +<p> +They can use more precise relationships than <code>foaf:knows</code> to relate people to +people. The original FOAF design included two of these ('knowsWell','friend') which we +removed because they were somewhat <em>awkward</em> to actually use, bringing an +inappopriate air of precision to an intrinsically vague concept. Other extensions have +been proposed, including Eric Vitiello's <a +href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for +FOAF. +</p> + +<p> +In addition to using more specialised inter-personal relationship types +(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states +of affairs which imply particular kinds of relationship. So for example, two people who +have the same value for their <code>foaf:workplaceHomepage</code> property are +typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, +but the facts can be written in FOAF nevertheless. Similarly, if there exists a +<code>foaf:Document</code> that has two people listed as its <code>foaf:maker</code>s, +then they are probably collaborators of some kind. Or if two people appear in 100s of +digital photos together, there's a good chance they're friends and/or colleagues. +</p> + +<p> +So FOAF is quite pluralistic in its approach to representing relationships between people. +FOAF is built on top of a general purpose machine language for representing relationships +(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. +The problems are generally social rather than technical; deciding on appropriate ways of +describing these interconnections is a subtle art. +</p> + +<p> +Perhaps the most important use of <code>foaf:knows</code> is, alongside the +<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF +file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more +interesting, with each FOAF file saying a little more about people, places, documents, things... +By mentioning other people (via <code>foaf:knows</code> or other relationships), and by +providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for +FOAF indexing tools ('<a href="http://rdfweb.org/topic/ScutterSpec">scutters</a>') to find +your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they +mention, and so on. This makes it possible to build FOAF aggregators without the need for +a centrally managed directory of FOAF files... +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_accountServiceHomepage"> + <h3>Property: foaf:accountServiceHomepage</h3> + <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:accountServiceHomepage</code> property indicates a relationship between a +<code>foaf:OnlineAccount</code> and the homepage of the supporting service provider. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> +</div> +</div> + + + +</body> +</html> + + diff --git a/foaf-live/doc b/foaf-live/doc new file mode 120000 index 0000000..3ac2cfd --- /dev/null +++ b/foaf-live/doc @@ -0,0 +1 @@ +/Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/doc/ \ No newline at end of file diff --git a/foaf-live/foaf-update.txt b/foaf-live/foaf-update.txt new file mode 100644 index 0000000..655a86e --- /dev/null +++ b/foaf-live/foaf-update.txt @@ -0,0 +1,70 @@ +This directory can be used as a wrapper for the live foaf svn, which is held in a different svn server. + +It links some files found there so that specgen can be run against this dir using: + + ./specgen5.py foaf-live/ http://xmlns.com/foaf/0.1/ foaf + +If updating the real foaf site, you also need to take care of commiting and checking out appropriately. + +The specgen filetree here is mainly for the software... + +0. + +this directory is specgen/foaf-live + +for now, lets set it up such that it points to the svn checkout of the live foaf xmlns site: + + ln -s ~/working/foaf/trunk/xmlns.com/htdocs/foaf/0.1/template.html template.html + ln -s ~/working/foaf/trunk/xmlns.com/htdocs/foaf/spec/index.rdf index.rdf + ln -s ~/working/foaf/trunk/xmlns.com/htdocs/foaf/doc/ doc + +Future revs of specgen.py could allow these pieces to be passed as individual parameters? + +We will set it to read from the xmlns svn, generate our candiate spec here, ... and when we are happy with it, +we copy files to their final home in the xmlns svn, commit and then refresh the live site. + + +1. make sure css file is in place + + cp style.css ~/working/foaf/trunk/xmlns.com/htdocs/foaf/spec/ + + +Test copy of FOAF (for safe experiments) is done this way: + + ./specgen5.py examples/foaf/ http://xmlns.com/foaf/0.1/ foaf + +generates examples/foaf/_tmp_spec.html + + + + +2. check the archived versions of the last spec are in place (they should be) + +this is in the xmlns svn + +eg. +Namespace Document 2 November 2007 - OpenID Edition +This version: + http://xmlns.com/foaf/spec/20071002.html (rdf) +Latest version: + http://xmlns.com/foaf/spec/ (rdf) +Previous version: + http://xmlns.com/foaf/spec/20070524.html (rdf) + +3a. update / edit the current live template, such that it has links to these and to its own anticipated +permalinks for today's snapshot. + +3b. generate a spec locally, using the linked xmlns svn files: + +from .. + + ./specgen5.py foaf-live/ http://xmlns.com/foaf/0.1/ foaf + + + +3c. commit those edits to xmlns svn + + +4. we will add an update to index.html and index.rdf as well as frozen copies of current version of each, using dated filenames + + diff --git a/foaf-live/index.rdf b/foaf-live/index.rdf new file mode 120000 index 0000000..8ef8803 --- /dev/null +++ b/foaf-live/index.rdf @@ -0,0 +1 @@ +/Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/spec/index.rdf \ No newline at end of file diff --git a/foaf-live/style.css b/foaf-live/style.css new file mode 100644 index 0000000..d335afd --- /dev/null +++ b/foaf-live/style.css @@ -0,0 +1,74 @@ +/*<![CDATA[*/ + +body { + + margin-left: 4em; + margin-right: 9em; + text-align: justify; +} + +.termdetails { +} + +div.specterm { + + border: 1px solid black; + background: #F0F0F0 ; + padding: 1em; +} + + +div.rdf-proplist { + background-color: #ddf; + border: 1px solid black; + float: left; +/* width: 26%; */ + margin: 0.3em 1%; +} +img { border: 0 } + +.example { + border: 1px solid black; + background-color: #D9E3E9; + padding: 5px; + width: 100%; +} + + .editorial { + border: 2px solid green; + padding: 5px; +} + +div.rdf-classlist { + background-color: #eef; + border: 1px solid black; + float: left; + margin: 0.3em 1%; + width: 26%; +} + +div.rdf-proplist h3 { + background-color: #bbf; + font-size: 100%; + margin: 0; + padding: 5px; +} + +div.rdf-classlist h3 { + background-color: #ccf; + font-size: 100%; + margin: 0; + padding: 5px; +} + +specterm.h3 { +/* foreground-color: #000; */ + background-color: #bbf; + font-size: 100%; + margin: 0; + padding: 3px; +} + + +/*]]>*/ + diff --git a/foaf-live/template.html b/foaf-live/template.html new file mode 120000 index 0000000..27dd6af --- /dev/null +++ b/foaf-live/template.html @@ -0,0 +1 @@ +/Users/danbri/working/foaf/trunk/xmlns.com/htdocs/foaf/0.1/template.html \ No newline at end of file diff --git a/specgen5.py b/specgen5.py index 2b1fa53..561884d 100755 --- a/specgen5.py +++ b/specgen5.py @@ -1,139 +1,139 @@ #!/usr/bin/env python # This is a draft rewrite of specgen, the family of scripts (originally # in Ruby, then Python) that are used with the FOAF and SIOC RDF vocabularies. # This version is a rewrite by danbri, begun after a conversion of # Uldis Bojars and Christopher Schmidt's specgen4.py to use rdflib instead of # Redland's Python bindings. While it shares their goal of being independent # of any particular RDF vocabulary, this first version's main purpose is # to get the FOAF spec workflow moving again. It doesn't work yet. # # A much more literal conversion of specgen4.py to use rdflib can be # found, abandoned, in the old/ directory as 'specgen4b.py'. # # Copyright 2008 Dan Brickley <http://danbri.org/> # # ...and probably includes bits of code that are: # # Copyright 2008 Uldis Bojars <[email protected]> # Copyright 2008 Christopher Schmidt # # This software is licensed under the terms of the MIT License. # # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. __all__ = [ 'main' ] import libvocab from libvocab import Vocab, VocabReport from libvocab import Term from libvocab import Class from libvocab import Property import sys import os.path # Make a spec def makeSpec(dir, uri): spec = Vocab( dir, 'index.rdf') spec.uri = uri spec.addShortName(shortName) # spec.shortName = shortName spec.index() # slurp info from sources out = VocabReport( spec, dir ) # print spec.unique_terms() # print out.generate() - filename = os.path.join(dir, "spec.html") + filename = os.path.join(dir, "_tmp_spec.html") print "Printing to ",filename f = open(filename,"w") result = out.generate() f.write(result) # Make FOAF spec def makeFoaf(): makeSpec("examples/foaf/","http://xmlns.com/foaf/0.1/") # Spare stuff #spec.raw() #print spec.report().encode('UTF-8') #for p in spec.properties: # print "Got a property: " + p # print p.simple_report().encode('UTF-8') #for c in spec.classes: # print "Got a class: " + c # print c.simple_report().encode('UTF-8') # #print spec.generate() def usage(): print "Usage:",sys.argv[0],"dir uri shortName" print "e.g. " print sys.argv[0], "examples/foaf/ http://xmlns.com/foaf/0.1/ foaf" if len(sys.argv) < 4: usage() sys.exit(2) else: # check it is a dir and it is readable and writeable dir = sys.argv[1] uri = sys.argv[2] shortName = sys.argv[3] if (os.path.isdir(dir)): print "ok" else: print dir,"is not a directory" usage() sys.exit(2) try: filename = os.path.join(dir, "index.rdf") f = open(filename, "r") except: print "Can't open index.rdf in",dir usage() sys.exit(2) try: filename = os.path.join(dir, "template.html") f = open(filename, "r") except: print "No template.html in",dir usage() sys.exit(2) try: - filename = os.path.join(dir, "spec.html") + filename = os.path.join(dir, "_tmp_spec.html") f = open(filename, "w") except: - print "Cannot write to spec.html in",dir + print "Cannot write to _tmp_spec.html in",dir usage() sys.exit(2) makeSpec(dir,uri)
leth/SpecGen
e76bf17a16d283e4da78dfa1e1cdd305fff2e041
still trying to get it to validate
diff --git a/examples/foaf/spec.html b/examples/foaf/spec.html index 2508633..dc1e289 100644 --- a/examples/foaf/spec.html +++ b/examples/foaf/spec.html @@ -182,2852 +182,2855 @@ As usual, see the <a href="#sec-changes">changes</a> section for details of the <li><a href="#term_family_name">family_name</a></li> <li><a href="#term_givenname">givenname</a></li> <li><a href="#term_firstName">firstName</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Personal Info</h3> <ul> <li><a href="#term_weblog">weblog</a></li> <li><a href="#term_knows">knows</a></li> <li><a href="#term_interest">interest</a></li> <li><a href="#term_currentProject">currentProject</a></li> <li><a href="#term_pastProject">pastProject</a></li> <li><a href="#term_plan">plan</a></li> <li><a href="#term_based_near">based_near</a></li> <li><a href= "#term_workplaceHomepage">workplaceHomepage</a></li> <li><a href= "#term_workInfoHomepage">workInfoHomepage</a></li> <li><a href="#term_schoolHomepage">schoolHomepage</a></li> <li><a href="#term_topic_interest">topic_interest</a></li> <li><a href="#term_publications">publications</a></li> <li><a href="#term_geekcode">geekcode</a></li> <li><a href="#term_myersBriggs">myersBriggs</a></li> <li><a href="#term_dnaChecksum">dnaChecksum</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Online Accounts / IM</h3> <ul> <li><a href="#term_OnlineAccount">OnlineAccount</a></li> <li><a href= "#term_OnlineChatAccount">OnlineChatAccount</a></li> <li><a href= "#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a></li> <li><a href= "#term_OnlineGamingAccount">OnlineGamingAccount</a></li> <li><a href="#term_holdsAccount">holdsAccount</a></li> <li><a href= "#term_accountServiceHomepage">accountServiceHomepage</a></li> <li><a href="#term_accountName">accountName</a></li> <li><a href="#term_icqChatID">icqChatID</a></li> <li><a href="#term_msnChatID">msnChatID</a></li> <li><a href="#term_aimChatID">aimChatID</a></li> <li><a href="#term_jabberID">jabberID</a></li> <li><a href="#term_yahooChatID">yahooChatID</a></li> </ul> </div> <div style="clear: left;"></div> <div class="rdf-proplist"> <h3>Projects and Groups</h3> <ul> <li><a href="#term_Project">Project</a></li> <li><a href="#term_Organization">Organization</a></li> <li><a href="#term_Group">Group</a></li> <li><a href="#term_member">member</a></li> <li><a href= "#term_membershipClass">membershipClass</a></li> <li><a href="#term_fundedBy">fundedBy</a></li> <li><a href="#term_theme">theme</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Documents and Images</h3> <ul> <li><a href="#term_Document">Document</a></li> <li><a href="#term_Image">Image</a></li> <li><a href= "#term_PersonalProfileDocument">PersonalProfileDocument</a></li> <li><a href="#term_topic">topic</a> (<a href= "#term_page">page</a>)</li> <li><a href="#term_primaryTopic">primaryTopic</a></li> <li><a href="#term_tipjar">tipjar</a></li> <li><a href="#term_sha1">sha1</a></li> <li><a href="#term_made">made</a> (<a href= "#term_maker">maker</a>)</li> <li><a href="#term_thumbnail">thumbnail</a></li> <li><a href="#term_logo">logo</a></li> </ul> </div> </div> <div style="clear: left;"></div> <h2 id="sec-example">Example</h2> <p>Here is a very basic document describing a person:</p> <div class="example"> <pre> &lt;foaf:Person rdf:about="#me" xmlns:foaf="http://xmlns.com/foaf/0.1/"&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:mbox_sha1sum&gt;241021fb0e6289f92815fc210f9e9137262c252e&lt;/foaf:mbox_sha1sum&gt; &lt;foaf:homepage rdf:resource="http://danbri.org/" /&gt; &lt;foaf:img rdf:resource="/images/me.jpg" /&gt; &lt;/foaf:Person&gt; </pre> </div> <p>This brief example introduces the basics of FOAF. It basically says, "there is a <a href="#term_Person">foaf:Person</a> with a <a href="#term_name">foaf:name</a> property of 'Dan Brickley' and a <a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a> property of 241021fb0e6289f92815fc210f9e9137262c252e; this person stands in a <a href="#term_homepage">foaf:homepage</a> relationship to a thing called http://danbri.org/ and a <a href= "#term_img">foaf:img</a> relationship to a thing referenced by a relative URI of /images/me.jpg</p> <div style="clear: left;"></div> <!-- ================================================================== --> <h2 id="sec-intro">1 Introduction: FOAF Basics</h2> <h3 id="sec-sw">The Semantic Web</h3> <blockquote> <p> <em> To a computer, the Web is a flat, boring world, devoid of meaning. This is a pity, as in fact documents on the Web describe real objects and imaginary concepts, and give particular relationships between them. For example, a document might describe a person. The title document to a house describes a house and also the ownership relation with a person. Adding semantics to the Web involves two things: allowing documents which have information in machine-readable forms, and allowing links to be created with relationship values. Only when we have this extra level of semantics will we be able to use computer power to help us exploit the information to a greater extent than our own reading. </em> - Tim Berners-Lee &quot;W3 future directions&quot; keynote, 1st World Wide Web Conference Geneva, May 1994 </p> </blockquote> <h3 id="sec-foafsw">FOAF and the Semantic Web</h3> <p> FOAF, like the Web itself, is a linked information system. It is built using decentralised <a href="http://www.w3.org/2001/sw/">Semantic Web</a> technology, and has been designed to allow for integration of data across a variety of applications, Web sites and services, and software systems. To achieve this, FOAF takes a liberal approach to data exchange. It does not require you to say anything at all about yourself or others, nor does it place any limits on the things you can say or the variety of Semantic Web vocabularies you may use in doing so. This current specification provides a basic "dictionary" of terms for talking about people and the things they make and do.</p> <p>FOAF was designed to be used alongside other such dictionaries ("schemas" or "ontologies"), and to beusable with the wide variety of generic tools and services that have been created for the Semantic Web. For example, the W3C work on <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a> provides us with a rich query language for consulting databases of FOAF data, while the <a href="http://www.w3.org/2004/02/skos/">SKOS</a> initiative explores in more detail than FOAF the problem of describing topics, categories, "folksonomies" and subject hierarchies. Meanwhile, other W3C groups are working on improved mechanisms for encoding all kinds of RDF data (including but not limited to FOAF) within Web pages: see the work of the <a href="http://www.w3.org/2001/sw/grddl-wg/">GRDDL</a> and <a href="http://www.w3.org/TR/xhtml-rdfa-primer/">RDFa</a> efforts for more detail. The Semantic Web provides us with an <em>architecture for collaboration</em>, allowing complex technical challenges to be shared by a loosely-coordinated community of developers. </p> <p>The FOAF project is based around the use of <em>machine readable</em> Web homepages for people, groups, companies and other kinds of thing. To achieve this we use the "FOAF vocabulary" to provide a collection of basic terms that can be used in these Web pages. At the heart of the FOAF project is a set of definitions designed to serve as a dictionary of terms that can be used to express claims about the world. The initial focus of FOAF has been on the description of people, since people are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on.</p> <p>The FOAF Vocabulary definitions presented here are written using a computer language (RDF/OWL) that makes it easy for software to process some basic facts about the terms in the FOAF vocabulary, and consequently about the things described in FOAF documents. A FOAF document, unlike a traditional Web page, can be combined with other FOAF documents to create a unified database of information. FOAF is a <a href="http://www.w3.org/DesignIssues/LinkedData.html">Linked Data</a> system, in that it based around the idea of linking together a Web of decentralised descriptions.</p> <h3 id="sec-basicidea">The Basic Idea</h3> <p>The basic idea is pretty simple. If people publish information in the FOAF document format, machines will be able to make use of that information. If those files contain "see also" references to other such documents in the Web, we will have a machine-friendly version of today's hypertext Web. Computer programs will be able to scutter around a Web of documents designed for machines rather than humans, storing the information they find, keeping a list of "see also" pointers to other documents, checking digital signatures (for the security minded) and building Web pages and question-answering services based on the harvested documents.</p> <p>So, what is the 'FOAF document format'? FOAF files are just text documents (well, Unicode documents). They are written in XML syntax, and adopt the conventions of the Resource Description Framework (RDF). In addition, the FOAF vocabulary defines some useful constructs that can appear in FOAF files, alongside other RDF vocabularies defined elsewhere. For example, FOAF defines categories ('classes') such as <code>foaf:Person</code>, <code>foaf:Document</code>, <code>foaf:Image</code>, alongside some handy properties of those things, such as <code>foaf:name</code>, <code>foaf:mbox</code> (ie. an internet mailbox), <code>foaf:homepage</code> etc., as well as some useful kinds of relationship that hold between members of these categories. For example, one interesting relationship type is <code>foaf:depiction</code>. This relates something (eg. a <code>foaf:Person</code>) to a <code>foaf:Image</code>. The FOAF demos that feature photos and listings of 'who is in which picture' are based on software tools that parse RDF documents and make use of these properties.</p> <p>The specific contents of the FOAF vocabulary are detailed in this <a href="http://xmlns.com/foaf/0.1/">FOAF namespace document</a>. In addition to the FOAF vocabulary, one of the most interesting features of a FOAF file is that it can contain "see Also" pointers to other FOAF files. This provides a basis for automatic harvesting tools to traverse a Web of interlinked files, and learn about new people, documents, services, data...</p> <p>The remainder of this specification describes how to publish and interpret descriptions such as these on the Web, using RDF/XML for syntax (file format) and terms from FOAF. It introduces a number of categories (RDF classes such as 'Person') and properties (relationship and attribute types such as 'mbox' or 'workplaceHomepage'). Each term definition is provided in both human and machine-readable form, hyperlinked for quick reference.</p> <h2 id="sec-for">What's FOAF for?</h2> <p>For a good general introduction to FOAF, see Edd Dumbill's article, <a href= "http://www-106.ibm.com/developerworks/xml/library/x-foaf.html">XML Watch: Finding friends with XML and RDF</a> (June 2002, IBM developerWorks). Information about the use of FOAF <a href= "http://rdfweb.org/2002/01/photo/">with image metadata</a> is also available.</p> <p>The <a href= "http://rdfweb.org/2002/01/photo/">co-depiction</a> experiment shows a fun use of the vocabulary. Jim Ley's <a href= "http://www.jibbering.com/svg/AnnotateImage.html">SVG image annotation tool</a> show the use of FOAF with detailed image metadata, and provide tools for labelling image regions within a Web browser. To create a FOAF document, you can use Leigh Dodd's <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">FOAF-a-matic</a> javascript tool. To query a FOAF dataset via IRC, you can use Edd Dumbill's <a href="http://usefulinc.com/foaf/foafbot">FOAFbot</a> tool, an IRC 'community support agent'. For more information on FOAF and related projects, see the <a href= "http://rdfweb.org/foaf/">FOAF project home page</a>. </p> <h2 id="sec-bg">Background</h2> <p>FOAF is a collaborative effort amongst Semantic Web developers on the FOAF ([email protected]) mailing list. The name 'FOAF' is derived from traditional internet usage, an acronym for 'Friend of a Friend'.</p> <p>The name was chosen to reflect our concern with social networks and the Web, urban myths, trust and connections. Other uses of the name continue, notably in the documentation and investigation of Urban Legends (eg. see the <a href= "http://www.urbanlegends.com/">alt.folklore.urban archive</a> or <a href="http://www.snopes.com/">snopes.com</a>), and other FOAF stories. Our use of the name 'FOAF' for a Web vocabulary and document format is intended to complement, rather than replace, these prior uses. FOAF documents describe the characteristics and relationships amongst friends of friends, and their friends, and the stories they tell.</p> <h2 id="sec-standards">FOAF and Standards</h2> <p>It is important to understand that the FOAF <em>vocabulary</em> as specified in this document is not a standard in the sense of <a href= "http://www.iso.ch/iso/en/ISOOnline.openerpage">ISO Standardisation</a>, or that associated with <a href= "http://www.w3.org/">W3C</a> <a href= "http://www.w3.org/Consortium/Process/">Process</a>.</p> <p>FOAF depends heavily on W3C's standards work, specifically on XML, XML Namespaces, RDF, and OWL. All FOAF <em>documents</em> must be well-formed RDF/XML documents. The FOAF vocabulary, by contrast, is managed more in the style of an <a href= "http://www.opensource.org/">Open Source</a> or <a href= "http://www.gnu.org/philosophy/free-sw.html">Free Software</a> project than as an industry standardarisation effort (eg. see <a href="http://www.jabber.org/jeps/jep-0001.html">Jabber JEPs</a>).</p> <p>This specification contributes a vocabulary, "FOAF", to the Semantic Web, specifying it using W3C's <a href= "http://www.w3.org/RDF/">Resource Description Framework</a> (RDF). As such, FOAF adopts by reference both a syntax (using XML) a data model (RDF graphs) and a mathematically grounded definition for the rules that underpin the FOAF design.</p> <h2 id="sec-nsdoc">The FOAF Vocabulary Description</h2> <p>This specification serves as the FOAF "namespace document". As such it describes the FOAF vocabulary and the terms (<a href= "http://www.w3.org/RDF/">RDF</a> classes and properties) that constitute it, so that <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> applications can use those terms in a variety of RDF-compatible document formats and applications.</p> <p>This document presents FOAF as a <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> vocabulary or <em>Ontology</em>. The FOAF vocabulary is pretty simple, pragmatic and designed to allow simultaneous deployment and extension. FOAF is intended for widescale use, but its authors make no commitments regarding its suitability for any particular purpose.</p> <h3 id="sec-evolution">Evolution and Extension of FOAF</h3> <p>The FOAF vocabulary is identified by the namespace URI '<code>http://xmlns.com/foaf/0.1/</code>'. Revisions and extensions of FOAF are conducted through edits to this document, which by convention is accessible in the Web via the namespace URI. For practical and deployment reasons, note that <b>we do not update the namespace URI as the vocabulary matures</b>. </p> <p>The core of FOAF now is considered stable, and the version number of <em>this specification</em> reflects this stability. However, it long ago became impractical to update the namespace URI without causing huge disruption to both producers and consumers of FOAF data. We are therefore left with the digits "0.1" in our URI. This stands as a warning to all those who might embed metadata in their vocabulary identifiers. </p> <p> The evolution of FOAF is best considered in terms of the stability of individual vocabulary terms, rather than the specification as a whole. As terms stabilise in usage and documentation, they progress through the categories '<strong>unstable</strong>', '<strong>testing</strong>' and '<strong>stable</strong>'.</p><!--STATUSINFO--> <p>The properties and types defined here provide some basic useful concepts for use in FOAF descriptions. Other vocabulary (eg. the <a href="http://dublincore.org/">Dublin Core</a> metadata elements for simple bibliographic description), RSS 1.0 etc can also be mixed in with FOAF terms, as can local extensions. FOAF is designed to be extended. The <a href= "http://wiki.foaf-project.org/FoafVocab">FoafVocab</a> page in the FOAF wiki lists a number of extension vocabularies that are particularly applicable to use with FOAF.</p> <h2 id="sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</h2> <p>If you publish a FOAF self-description (eg. using <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">foaf-a-matic</a>) you can make it easier for tools to find your FOAF by putting markup in the <code>head</code> of your HTML homepage. It doesn't really matter what filename you choose for your FOAF document, although <code>foaf.rdf</code> is a common choice. The linking markup is as follows:</p> <div class="example"> <pre> &lt;link rel="meta" type="application/rdf+xml" title="FOAF" href="<em>http://example.com/~you/foaf.rdf</em>"/&gt; </pre> </div> <p>...although of course change the <em>URL</em> to point to your own FOAF document. See also: more on <a href= "http://rdfweb.org/mt/foaflog/archives/000041.html">FOAF autodiscovery</a> and services that make use of it.</p> <h2 id="sec-foafandrdf">FOAF and RDF</h2> <p>Why does FOAF use <a href= "http://www.w3.org/RDF/">RDF</a>?</p> <p>FOAF is an application of the Resource Description Framework (RDF) because the subject area we're describing -- people -- has so many competing requirements that a standalone format could not do them all justice. By using RDF, FOAF gains a powerful extensibility mechanism, allowing FOAF-based descriptions can be mixed with claims made in <em>any other RDF vocabulary</em></p> <p>People are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on. Consequently, there are many many things that we might want to say about people, not to mention these related objects (ie. documents, photos, meetings etc).</p> <p>FOAF as a vocabulary cannot incorporate everything we might want to talk about that is related to people, or it would be as large as a full dictionary. Instead of covering all topics within FOAF itself, we buy into a larger framework - RDF - that allows us to take advantage of work elsewhere on more specific description vocabularies (eg. for geographical / mapping data).</p> <p>RDF provides FOAF with a way to mix together different descriptive vocabularies in a consistent way. Vocabularies can be created by different communites and groups as appropriate and mixed together as required, without needing any centralised agreement on how terms from different vocabularies can be written down in XML.</p> <p>This mixing happens in two ways: firstly, RDF provides an underlying model of (typed) objects and their attributes or relationships. <code>foaf:Person</code> is an example of a type of object (a "<em>class</em>"), while <code>foaf:knows</code> and <code>foaf:name</code> are examples of a relationship and an attribute of an <code>foaf:Person</code>; in RDF we call these "<em>properties</em>". Any vocabulary described in RDF shares this basic model, which is discernable in the syntax for RDF, and which removes one level of confusion in <em>understanding</em> a given vocabulary, making it simpler to comprehend and therefore reuse a vocabulary that you have not written yourself. This is the minimal <em>self-documentation</em> that RDF gives you.</p> <p>Secondly, there are mechanisms for saying which RDF properties are connected to which classes, and how different classes are related to each other, using RDF Syntax and OWL. These can be quite general (all RDF properties by default come from an <code>rdf:Resource</code> for example) or very specific and precise (for example by using <a href= "http://www.w3.org/2001/sw/WebOnt/">OWL</a> constructs, as in the <code>foaf:Group</code> example below. This is another form of self-documentation, which allows you to connect different vocabularies together as you please. An example of this is given below where the <code>foaf:based_near</code> property has a domain and range (types of class at each end of the property) from a different namespace altogether.</p> <p>In summary then, RDF is self-documenting in ways which enable the creation and combination of vocabularies in a devolved manner. This is particularly important for a vocabulary which describes people, since people connect to many other domains of interest, which it would be impossible (as well as suboptimal) for a single group to describe adequately in non-geological time.</p> <p>RDF is usually written using XML syntax, but behaves in rather different ways to 'vanilla' XML: the same RDF can be written in many different ways in XML. This means that SAX and DOM XML parsers are not adequate to deal with RDF/XML. If you want to process the data, you will need to use one of the many RDF toolkits available, such as Jena (Java) or Redland (C). <a href= "http://lists.w3.org/Archives/Public/www-rdf-interest/">RDF Interest Group</a> members can help with issues which may arise; there is also the <a href= "http://rdfweb.org/mailman/listinfo/rdfweb-dev">[email protected]</a> mailing list which is the main list for FOAF, and two active and friendly <a href= "http://esw.w3.org/topic/InternetRelayChat">IRC</a> channels: <a href="irc://irc.freenode.net/#rdfig">#rdfig</a> and <a href= "irc://irc.freenode.net/#foaf">#foaf</a> on <a href= "http://www.freenode.net/">freenode</a>.</p> <h2 id="sec-crossref">FOAF cross-reference: Listing FOAF Classes and Properties</h2> <p>FOAF introduces the following classes and properties. View this document's source markup to see the RDF/XML version.</p> <!-- the following is the script-generated list of classes and properties --> <div class="azlist"> <p>Classes: | <a href="#term_Agent">Agent</a> | <a href="#term_Document">Document</a> | <a href="#term_Group">Group</a> | <a href="#term_Image">Image</a> | <a href="#term_OnlineAccount">OnlineAccount</a> | <a href="#term_OnlineChatAccount">OnlineChatAccount</a> | <a href="#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a> | <a href="#term_OnlineGamingAccount">OnlineGamingAccount</a> | <a href="#term_Organization">Organization</a> | <a href="#term_Person">Person</a> | <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> | <a href="#term_Project">Project</a> | </p> <p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | </p> </div> -<div class="termlist"><h3>Classes and Properties (full detail)</h3><div class='termdetails'><br /> +<div class="termlist"><h3>Classes and Properties (full detail)</h3> +<div class='termdetails'><br /> - <div class="specterm" id="term_OnlineEcommerceAccount"> - <h3>Class: foaf:OnlineEcommerceAccount</h3> - <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - <tr><th>subClassOf</th> - <td> <a href="#term_Online Account">Online Account</a> - </td></tr> - </table> - <p> -A <code>foaf:OnlineEcommerceAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -buying and/or selling of goods, services etc. Examples include <a -href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a -href="http://www.paypal.com/">PayPal</a>, <a -href="http://www.thinkgeek.com/">thinkgeek</a>, etc. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_OnlineAccount"> - <h3>Class: foaf:OnlineAccount</h3> - <em>Online Account</em> - An online account. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>in-domain-of:</th> - <td> <a href="#term_account name">account name</a> - <a href="#term_account service homepage">account service homepage</a> - </td></tr> - <tr><th>in-range-of:</th> - <td> <a href="#term_holds account">holds account</a> -</td></tr> <tr><th>has subclass</th> - <td> <a href="#term_Online E-commerce Account">Online E-commerce Account</a> - <a href="#term_Online Chat Account">Online Chat Account</a> - <a href="#term_Online Gaming Account">Online Gaming Account</a> - </td></tr> - </table> - <p> -A <code>foaf:OnlineAccount</code> represents the provision of some form of online -service, by some party (indicated indirectly via a -<code>foaf:accountServiceHomepage</code>) to some <code>foaf:Agent</code>. The -<code>foaf:holdsAccount</code> property of the agent is used to indicate accounts that are -associated with the agent. -</p> - -<p> -See <code>foaf:OnlineChatAccount</code> for an example. Other sub-classes include -<code>foaf:OnlineEcommerceAccount</code> and <code>foaf:OnlineGamingAccount</code>. -</p> - - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_OnlineChatAccount"> + <div class="specterm" id="term_OnlineChatAccount"> <h3>Class: foaf:OnlineChatAccount</h3> <em>Online Chat Account</em> - An online chat account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Online Account">Online Account</a> </td></tr> </table> <p> A <code>foaf:OnlineChatAccount</code> is a <code>foaf:OnlineAccount</code> devoted to chat / instant messaging. </p> <p> This is a generalization of the FOAF Chat ID properties, <code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, <code>foaf:msnChatID</code>, <code>foaf:icqChatID</code> and <code>foaf:yahooChatID</code>. </p> <p> Unlike those simple properties, <code>foaf:OnlineAccount</code> and associated FOAF terms allows us to describe a great variety of online accounts, without having to anticipate them in the FOAF vocabulary. </p> <p> For example, here is a description of an IRC chat account, specific to the Freenode IRC network: </p> <div class="example"> <pre> &lt;foaf:Person&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:holdsAccount&gt; &lt;foaf:OnlineAccount&gt; &lt;rdf:type rdf:resource="http://xmlns.com/foaf/0.1/OnlineChatAccount"/&gt; &lt;foaf:accountServiceHomepage rdf:resource="http://www.freenode.net/irc_servers.shtml"/&gt; &lt;foaf:accountName&gt;danbri&lt;/foaf:accountName&gt; &lt;/foaf:OnlineAccount&gt; &lt;/foaf:holdsAccount&gt; &lt;/foaf:Person&gt; </pre> </div> <p> Note that it may be impolite to carelessly reveal someone else's chat identifier (which might also serve as an indicate of email address) As with email, there are privacy and anti-SPAM considerations. FOAF does not currently provide a way to represent an obfuscated chat ID (ie. there is no parallel to the <code>foaf:mbox</code> / <code>foaf:mbox_sha1sum</code> mapping). </p> <p> In addition to the generic <code>foaf:OnlineAccount</code> and <code>foaf:OnlineChatAccount</code> mechanisms, FOAF also provides several convenience chat ID properties (<code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, <code>foaf:icqChatID</code>, <code>foaf:msnChatID</code>,<code>foaf:yahooChatID</code>). These serve as as a shorthand for some common cases; their use may not always be appropriate. </p> <p class="editorial"> We should specify some mappings between the abbreviated and full representations of <a href="http://www.jabber.org/">Jabber</a>, <a href="http://www.aim.com/">AIM</a>, <a href="http://chat.msn.com/">MSN</a>, <a href="http://web.icq.com/icqchat/">ICQ</a>, <a href="http://chat.yahoo.com/">Yahoo!</a> and <a href="http://chat.msn.com/">MSN</a> chat accounts. This requires us to identify an appropriate <code>foaf:accountServiceHomepage</code> for each. If we wanted to make the <code>foaf:OnlineAccount</code> mechanism even more generic, we could invent a relationship that holds between a <code>foaf:OnlineAccount</code> instance and a convenience property. To continue the example above, we could describe how <a href="http://www.freenode.net/">Freenode</a> could define a property 'fn:freenodeChatID' corresponding to Freenode online accounts. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_PersonalProfileDocument"> + <h3>Class: foaf:PersonalProfileDocument</h3> + <em>PersonalProfileDocument</em> - A personal profile RDF document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Document">Document</a> + </td></tr> + </table> + <p> +The <code>foaf:PersonalProfileDocument</code> class represents those +things that are a <code>foaf:Document</code>, and that use RDF to +describe properties of the person who is the <code>foaf:maker</code> +of the document. There is just one <code>foaf:Person</code> described in +the document, ie. +the person who <code>foaf:made</code> it and who will be its +<code>foaf:primaryTopic</code>. +</p> + +<p> +The <code>foaf:PersonalProfileDocument</code> class, and FOAF's +associated conventions for describing it, captures an important +deployment pattern for the FOAF vocabulary. FOAF is very often used in +public RDF documents made available through the Web. There is a +colloquial notion that these "FOAF files" are often <em>somebody's</em> +FOAF file. Through <code>foaf:PersonalProfileDocument</code> we provide +a machine-readable expression of this concept, providing a basis for +FOAF documents to make claims about their maker and topic. +</p> + +<p> +When describing a <code>foaf:PersonalProfileDocument</code> it is +typical (and useful) to describe its associated <code>foaf:Person</code> +using the <code>foaf:maker</code> property. Anything that is a +<code>foaf:Person</code> and that is the <code>foaf:maker</code> of some +<code>foaf:Document</code> will be the <code>foaf:primaryTopic</code> of +that <code>foaf:Document</code>. Although this can be inferred, it is +helpful to include this information explicitly within the +<code>foaf:PersonalProfileDocument</code>. +</p> + +<p> +For example, here is a fragment of a personal profile document which +describes its author explicitly: +</p> +<div class="example"> +<pre> +&lt;foaf:Person rdf:nodeID="p1"&gt; + &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:homepage rdf:resource="http://rdfweb.org/people/danbri/"/&gt; + &lt;!-- etc... --&gt; +&lt;/foaf:Person&gt; + +&lt;foaf:PersonalProfileDocument rdf:about=""&gt; + &lt;foaf:maker rdf:nodeID="p1"/&gt; + &lt;foaf:primaryTopic rdf:nodeID="p1"/&gt; +&lt;/foaf:PersonalProfileDocument&gt; +</pre> +</div> + +<p> +Note that a <code>foaf:PersonalProfileDocument</code> will have some +representation as RDF. Typically this will be in W3C's RDF/XML syntax, +however we leave open the possibility for the use of other notations, or +representational conventions including automated transformations from +HTML (<a href="http://www.w3.org/2004/01/rdxh/spec">GRDDL</a> spec for +one such technique). +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_Group"> <h3>Class: foaf:Group</h3> <em>Group</em> - A class of Agents. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>in-domain-of:</th> <td> <a href="#term_member">member</a> </td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> The <code>foaf:Group</code> class represents a collection of individual agents (and may itself play the role of a <code>foaf:Agent</code>, ie. something that can perform actions). </p> <p> This concept is intentionally quite broad, covering informal and ad-hoc groups, long-lived communities, organizational groups within a workplace, etc. Some such groups may have associated characteristics which could be captured in RDF (perhaps a <code>foaf:homepage</code>, <code>foaf:name</code>, mailing list etc.). </p> <p> While a <code>foaf:Group</code> has the characteristics of a <code>foaf:Agent</code>, it is also associated with a number of other <code>foaf:Agent</code>s (typically people) who constitute the <code>foaf:Group</code>. FOAF provides a mechanism, the <code>foaf:membershipClass</code> property, which relates a <code>foaf:Group</code> to a sub-class of the class <code>foaf:Agent</code> who are members of the group. This is a little complicated, but allows us to make group membership rules explicit. </p> <p>The markup (shown below) for defining a group is both complex and powerful. It allows group membership rules to match against any RDF-describable characteristics of the potential group members. As FOAF and similar vocabularies become more expressive in their ability to describe individuals, the <code>foaf:Group</code> mechanism for categorising them into groups also becomes more powerful. </p> <p> While the formal description of membership criteria for a <code>foaf:Group</code> may be complex, the basic mechanism for saying that someone is in a <code>foaf:Group</code> is very simple. We simply use a <code>foaf:member</code> property of the <code>foaf:Group</code> to indicate the agents that are members of the group. For example: </p> <div class="example"> <pre> &lt;foaf:Group&gt; &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; &lt;foaf:member&gt; &lt;foaf:Person&gt; &lt;foaf:name&gt;Libby Miller&lt;/foaf:name&gt; &lt;foaf:homepage rdf:resource="http://ilrt.org/people/libby/"/&gt; &lt;foaf:workplaceHomepage rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; &lt;/foaf:Person&gt; &lt;/foaf:member&gt; &lt;/foaf:Group&gt; </pre> </div> <p> Behind the scenes, further RDF statements can be used to express the rules for being a member of this group. End-users of FOAF need not pay attention to these details. </p> <p> Here is an example. We define a <code>foaf:Group</code> representing those people who are ILRT staff members. The <code>foaf:membershipClass</code> property connects the group (conceived of as a social entity and agent in its own right) with the class definition for those people who constitute it. In this case, the rule is that all group members are in the ILRTStaffPerson class, which is in turn populated by all those things that are a <code>foaf:Person</code> and which have a <code>foaf:workplaceHomepage</code> of http://www.ilrt.bris.ac.uk/. This is typical: FOAF groups are created by specifying a sub-class of <code>foaf:Agent</code> (in fact usually this will be a sub-class of <code>foaf:Person</code>), and giving criteria for which things fall in or out of the sub-class. For this, we use the <code>owl:onProperty</code> and <code>owl:hasValue</code> properties, indicating the property/value pairs which must be true of matching agents. </p> <div class="example"> <pre> &lt;!-- here we see a FOAF group described. each foaf group may be associated with an OWL definition specifying the class of agents that constitute the group's membership --&gt; &lt;foaf:Group&gt; &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; &lt;foaf:membershipClass&gt; &lt;owl:Class rdf:about="http://ilrt.example.com/groups#ILRTStaffPerson"&gt; &lt;rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Person"/&gt; &lt;rdfs:subClassOf&gt; &lt;owl:Restriction&gt; &lt;owl:onProperty rdf:resource="http://xmlns.com/foaf/0.1/workplaceHomepage"/&gt; &lt;owl:hasValue rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; &lt;/owl:Restriction&gt; &lt;/rdfs:subClassOf&gt; &lt;/owl:Class&gt; &lt;/foaf:membershipClass&gt; &lt;/foaf:Group&gt; </pre> </div> <p> Note that while these example OWL rules for being in the eg:ILRTStaffPerson class are based on a <code>foaf:Person</code> having a particular <code>foaf:workplaceHomepage</code>, this places no obligations on the authors of actual FOAF documents to include this information. If the information <em>is</em> included, then generic OWL tools may infer that some person is an eg:ILRTStaffPerson. To go the extra step and infer that some eg:ILRTStaffPerson is a <code>foaf:member</code> of the group whose <code>foaf:name</code> is "ILRT staff", tools will need some knowledge of the way FOAF deals with groups. In other words, generic OWL technology gets us most of the way, but the full <code>foaf:Group</code> machinery requires extra work for implimentors. </p> <p> The current design names the relationship as pointing <em>from</em> the group, to the member. This is convenient when writing XML/RDF that encloses the members within markup that describes the group. Alternate representations of the same content are allowed in RDF, so you can write claims about the Person and the Group without having to nest either description inside the other. For (brief) example: </p> <div class="example"> <pre> &lt;foaf:Group&gt; &lt;foaf:member rdf:nodeID="libby"/&gt; &lt;!-- more about the group here --&gt; &lt;/foaf:Group&gt; &lt;foaf:Person rdf:nodeID="libby"&gt; &lt;!-- more about libby here --&gt; &lt;/foaf:Person&gt; </pre> </div> <p> There is a FOAF <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> associated with this FOAF term. A design goal is to make the most of W3C's <a href="http://www.w3.org/2001/sw/WebOnt">OWL</a> language for representing group-membership criteria, while also making it easy to leverage existing groups and datasets available online (eg. buddylists, mailing list membership lists etc). Feedback on the current design is solicited! Should we consider using SPARQL queries instead, for example? </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Agent"> - <h3>Class: foaf:Agent</h3> - <em>Agent</em> - An agent (eg. person, group, software or physical artifact). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_Image"> + <h3>Class: foaf:Image</h3> + <em>Image</em> - An image. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>testing</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_made">made</a> - <a href="#term_holds account">holds account</a> - <a href="#term_gender">gender</a> - <a href="#term_MSN chat ID">MSN chat ID</a> - <a href="#term_jabber ID">jabber ID</a> - <a href="#term_AIM chat ID">AIM chat ID</a> - <a href="#term_birthday">birthday</a> - <a href="#term_weblog">weblog</a> - <a href="#term_ICQ chat ID">ICQ chat ID</a> - <a href="#term_personal mailbox">personal mailbox</a> - <a href="#term_tipjar">tipjar</a> - <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> - <a href="#term_Yahoo chat ID">Yahoo chat ID</a> + <td> <a href="#term_depicts">depicts</a> + <a href="#term_thumbnail">thumbnail</a> </td></tr> <tr><th>in-range-of:</th> - <td> <a href="#term_maker">maker</a> - <a href="#term_member">member</a> -</td></tr> <tr><th>has subclass</th> - <td> <a href="#term_Group">Group</a> - <a href="#term_Organization">Organization</a> - <a href="#term_Person">Person</a> - </td></tr> + <td> <a href="#term_depiction">depiction</a> + <a href="#term_thumbnail">thumbnail</a> + <a href="#term_image">image</a> +</td></tr> </table> <p> -The <code>foaf:Agent</code> class is the class of agents; things that do stuff. A well -known sub-class is <code>foaf:Person</code>, representing people. Other kinds of agents -include <code>foaf:Organization</code> and <code>foaf:Group</code>. +The class <code>foaf:Image</code> is a sub-class of <code>foaf:Document</code> +corresponding to those documents which are images. </p> <p> -The <code>foaf:Agent</code> class is useful in a few places in FOAF where -<code>foaf:Person</code> would have been overly specific. For example, the IM chat ID -properties such as <code>jabberID</code> are typically associated with people, but -sometimes belong to software bots. +Digital images (such as JPEG, PNG, GIF bitmaps, SVG diagrams etc.) are examples of +<code>foaf:Image</code>. </p> -<!-- todo: write rdfs:domain statements for those properties --> +<!-- much more we could/should say here --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_PersonalProfileDocument"> - <h3>Class: foaf:PersonalProfileDocument</h3> - <em>PersonalProfileDocument</em> - A personal profile RDF document. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_OnlineAccount"> + <h3>Class: foaf:OnlineAccount</h3> + <em>Online Account</em> - An online account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - - <tr><th>subClassOf</th> - <td> <a href="#term_Document">Document</a> + <td>unstable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_account name">account name</a> + <a href="#term_account service homepage">account service homepage</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_holds account">holds account</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Online E-commerce Account">Online E-commerce Account</a> + <a href="#term_Online Chat Account">Online Chat Account</a> + <a href="#term_Online Gaming Account">Online Gaming Account</a> </td></tr> </table> <p> -The <code>foaf:PersonalProfileDocument</code> class represents those -things that are a <code>foaf:Document</code>, and that use RDF to -describe properties of the person who is the <code>foaf:maker</code> -of the document. There is just one <code>foaf:Person</code> described in -the document, ie. -the person who <code>foaf:made</code> it and who will be its -<code>foaf:primaryTopic</code>. -</p> - -<p> -The <code>foaf:PersonalProfileDocument</code> class, and FOAF's -associated conventions for describing it, captures an important -deployment pattern for the FOAF vocabulary. FOAF is very often used in -public RDF documents made available through the Web. There is a -colloquial notion that these "FOAF files" are often <em>somebody's</em> -FOAF file. Through <code>foaf:PersonalProfileDocument</code> we provide -a machine-readable expression of this concept, providing a basis for -FOAF documents to make claims about their maker and topic. -</p> - -<p> -When describing a <code>foaf:PersonalProfileDocument</code> it is -typical (and useful) to describe its associated <code>foaf:Person</code> -using the <code>foaf:maker</code> property. Anything that is a -<code>foaf:Person</code> and that is the <code>foaf:maker</code> of some -<code>foaf:Document</code> will be the <code>foaf:primaryTopic</code> of -that <code>foaf:Document</code>. Although this can be inferred, it is -helpful to include this information explicitly within the -<code>foaf:PersonalProfileDocument</code>. -</p> - -<p> -For example, here is a fragment of a personal profile document which -describes its author explicitly: +A <code>foaf:OnlineAccount</code> represents the provision of some form of online +service, by some party (indicated indirectly via a +<code>foaf:accountServiceHomepage</code>) to some <code>foaf:Agent</code>. The +<code>foaf:holdsAccount</code> property of the agent is used to indicate accounts that are +associated with the agent. </p> -<div class="example"> -<pre> -&lt;foaf:Person rdf:nodeID="p1"&gt; - &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; - &lt;foaf:homepage rdf:resource="http://rdfweb.org/people/danbri/"/&gt; - &lt;!-- etc... --&gt; -&lt;/foaf:Person&gt; - -&lt;foaf:PersonalProfileDocument rdf:about=""&gt; - &lt;foaf:maker rdf:nodeID="p1"/&gt; - &lt;foaf:primaryTopic rdf:nodeID="p1"/&gt; -&lt;/foaf:PersonalProfileDocument&gt; -</pre> -</div> <p> -Note that a <code>foaf:PersonalProfileDocument</code> will have some -representation as RDF. Typically this will be in W3C's RDF/XML syntax, -however we leave open the possibility for the use of other notations, or -representational conventions including automated transformations from -HTML (<a href="http://www.w3.org/2004/01/rdxh/spec">GRDDL</a> spec for -one such technique). +See <code>foaf:OnlineChatAccount</code> for an example. Other sub-classes include +<code>foaf:OnlineEcommerceAccount</code> and <code>foaf:OnlineGamingAccount</code>. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_OnlineGamingAccount"> - <h3>Class: foaf:OnlineGamingAccount</h3> - <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_OnlineEcommerceAccount"> + <h3>Class: foaf:OnlineEcommerceAccount</h3> + <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Online Account">Online Account</a> </td></tr> </table> <p> -A <code>foaf:OnlineGamingAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -online gaming. +A <code>foaf:OnlineEcommerceAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +buying and/or selling of goods, services etc. Examples include <a +href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a +href="http://www.paypal.com/">PayPal</a>, <a +href="http://www.thinkgeek.com/">thinkgeek</a>, etc. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineGamingAccount"> + <h3>Class: foaf:OnlineGamingAccount</h3> + <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Online Account">Online Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineGamingAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +online gaming. </p> <p> Examples might include <a href="http://everquest.station.sony.com/">EverQuest</a>, <a href="http://www.xbox.com/live/">Xbox live</a>, <a href="http://nwn.bioware.com/">Neverwinter Nights</a>, etc., as well as older text-based systems (MOOs, MUDs and suchlike). +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Project"> + <h3>Class: foaf:Project</h3> + <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:Project</code> class represents the class of things that are 'projects'. These +may be formal or informal, collective or individual. It is often useful to indicate the +<code>foaf:homepage</code> of a <code>foaf:Project</code>. +</p> + +<p class="editorial"> +Further work is needed to specify the connections between this class and the FOAF properties +<code>foaf:currentProject</code> and <code>foaf:pastProject</code>. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_Document"> <h3>Class: foaf:Document</h3> <em>Document</em> - A document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_topic">topic</a> - <a href="#term_sha1sum (hex)">sha1sum (hex)</a> + <td> <a href="#term_sha1sum (hex)">sha1sum (hex)</a> + <a href="#term_topic">topic</a> <a href="#term_primary topic">primary topic</a> </td></tr> <tr><th>in-range-of:</th> <td> <a href="#term_work info homepage">work info homepage</a> - <a href="#term_homepage">homepage</a> - <a href="#term_workplace homepage">workplace homepage</a> - <a href="#term_is primary topic of">is primary topic of</a> - <a href="#term_account service homepage">account service homepage</a> <a href="#term_weblog">weblog</a> <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_workplace homepage">workplace homepage</a> + <a href="#term_account service homepage">account service homepage</a> <a href="#term_page">page</a> - <a href="#term_tipjar">tipjar</a> - <a href="#term_publications">publications</a> <a href="#term_interest">interest</a> + <a href="#term_publications">publications</a> + <a href="#term_is primary topic of">is primary topic of</a> + <a href="#term_homepage">homepage</a> + <a href="#term_tipjar">tipjar</a> </td></tr> <tr><th>has subclass</th> <td> <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> </td></tr> </table> <p> The <code>foaf:Document</code> class represents those things which are, broadly conceived, 'documents'. </p> <p> The <code>foaf:Image</code> class is a sub-class of <code>foaf:Document</code>, since all images are documents. </p> <p class="editorial"> We do not (currently) distinguish precisely between physical and electronic documents, or between copies of a work and the abstraction those copies embody. The relationship between documents and their byte-stream representation needs clarification (see <code>foaf:sha1</code> for related issues). </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_Organization"> <h3>Class: foaf:Organization</h3> <em>Organization</em> - An organization. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> The <code>foaf:Organization</code> class represents a kind of <code>foaf:Agent</code> corresponding to social instititutions such as companies, societies etc. </p> <p class="editorial"> This is a more 'solid' class than <code>foaf:Group</code>, which allows for more ad-hoc collections of individuals. These terms, like the corresponding natural language concepts, have some overlap, but different emphasis. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_Person"> <h3>Class: foaf:Person</h3> <em>Person</em> - A person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_knows">knows</a> - <a href="#term_geekcode">geekcode</a> - <a href="#term_work info homepage">work info homepage</a> - <a href="#term_plan">plan</a> + <td> <a href="#term_geekcode">geekcode</a> <a href="#term_workplace homepage">workplace homepage</a> - <a href="#term_past project">past project</a> - <a href="#term_current project">current project</a> - <a href="#term_image">image</a> - <a href="#term_publications">publications</a> - <a href="#term_Surname">Surname</a> - <a href="#term_interest_topic">interest_topic</a> <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_work info homepage">work info homepage</a> + <a href="#term_knows">knows</a> <a href="#term_family_name">family_name</a> - <a href="#term_myersBriggs">myersBriggs</a> + <a href="#term_current project">current project</a> <a href="#term_firstName">firstName</a> + <a href="#term_myersBriggs">myersBriggs</a> + <a href="#term_plan">plan</a> + <a href="#term_Surname">Surname</a> <a href="#term_interest">interest</a> + <a href="#term_publications">publications</a> + <a href="#term_interest_topic">interest_topic</a> + <a href="#term_image">image</a> + <a href="#term_past project">past project</a> </td></tr> <tr><th>in-range-of:</th> <td> <a href="#term_knows">knows</a> </td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> The <code>foaf:Person</code> class represents people. Something is a <code>foaf:Person</code> if it is a person. We don't nitpic about whether they're alive, dead, real, or imaginary. The <code>foaf:Person</code> class is a sub-class of the <code>foaf:Agent</code> class, since all people are considered 'agents' in FOAF. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Image"> - <h3>Class: foaf:Image</h3> - <em>Image</em> - An image. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_Agent"> + <h3>Class: foaf:Agent</h3> + <em>Agent</em> - An agent (eg. person, group, software or physical artifact). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td>stable</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_thumbnail">thumbnail</a> - <a href="#term_depicts">depicts</a> + <td> <a href="#term_gender">gender</a> + <a href="#term_made">made</a> + <a href="#term_MSN chat ID">MSN chat ID</a> + <a href="#term_weblog">weblog</a> + <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> + <a href="#term_birthday">birthday</a> + <a href="#term_ICQ chat ID">ICQ chat ID</a> + <a href="#term_personal mailbox">personal mailbox</a> + <a href="#term_jabber ID">jabber ID</a> + <a href="#term_AIM chat ID">AIM chat ID</a> + <a href="#term_holds account">holds account</a> + <a href="#term_tipjar">tipjar</a> + <a href="#term_Yahoo chat ID">Yahoo chat ID</a> </td></tr> <tr><th>in-range-of:</th> - <td> <a href="#term_thumbnail">thumbnail</a> - <a href="#term_depiction">depiction</a> - <a href="#term_image">image</a> -</td></tr> + <td> <a href="#term_member">member</a> + <a href="#term_maker">maker</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Group">Group</a> + <a href="#term_Person">Person</a> + <a href="#term_Organization">Organization</a> + </td></tr> </table> <p> -The class <code>foaf:Image</code> is a sub-class of <code>foaf:Document</code> -corresponding to those documents which are images. +The <code>foaf:Agent</code> class is the class of agents; things that do stuff. A well +known sub-class is <code>foaf:Person</code>, representing people. Other kinds of agents +include <code>foaf:Organization</code> and <code>foaf:Group</code>. </p> <p> -Digital images (such as JPEG, PNG, GIF bitmaps, SVG diagrams etc.) are examples of -<code>foaf:Image</code>. +The <code>foaf:Agent</code> class is useful in a few places in FOAF where +<code>foaf:Person</code> would have been overly specific. For example, the IM chat ID +properties such as <code>jabberID</code> are typically associated with people, but +sometimes belong to software bots. </p> -<!-- much more we could/should say here --> +<!-- todo: write rdfs:domain statements for those properties --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Project"> - <h3>Class: foaf:Project</h3> - <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_firstName"> + <h3>Property: foaf:firstName</h3> + <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> </table> - <p> -The <code>foaf:Project</code> class represents the class of things that are 'projects'. These -may be formal or informal, collective or individual. It is often useful to indicate the -<code>foaf:homepage</code> of a <code>foaf:Project</code>. + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> -<p class="editorial"> -Further work is needed to specify the connections between this class and the FOAF properties -<code>foaf:currentProject</code> and <code>foaf:pastProject</code>. +<p> +There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_workplaceHomepage"> - <h3>Property: foaf:workplaceHomepage</h3> - <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_currentProject"> + <h3>Property: foaf:currentProject</h3> + <em>current project</em> - A current project this person works on. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> + </table> - <p> -The <code>foaf:workplaceHomepage</code> of a <code>foaf:Person</code> is a -<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a -<code>foaf:Organization</code> that they work for. -</p> + <!-- originally contrib'd by Cardinal --> -<p> -By directly relating people to the homepages of their workplace, we have a simple convention -that takes advantage of a set of widely known identifiers, while taking care not to confuse the -things those identifiers identify (ie. organizational homepages) with the actual organizations -those homepages describe. -</p> +<p>A <code>foaf:currentProject</code> relates a <code>foaf:Person</code> +to a <code>foaf:Document</code> indicating some collaborative or +individual undertaking. This relationship +indicates that the <code>foaf:Person</code> has some active role in the +project, such as development, coordination, or support.</p> + +<p>When a <code>foaf:Person</code> is no longer involved with a project, or +perhaps is inactive for some time, the relationship becomes a +<code>foaf:pastProject</code>.</p> -<div class="example"> <p> -For example, Dan Brickley works at W3C. Dan is a <code>foaf:Person</code> with a -<code>foaf:homepage</code> of http://rdfweb.org/people/danbri/; W3C is a -<code>foaf:Organization</code> with a <code>foaf:homepage</code> of http://www.w3.org/. This -allows us to say that Dan has a <code>foaf:workplaceHomepage</code> of http://www.w3.org/. +If the <code>foaf:Person</code> has stopped working on a project because it +has been completed (successfully or otherwise), <code>foaf:pastProject</code> is +applicable. In general, <code>foaf:currentProject</code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code>foaf:pastProject</code> describes what they've previously been doing. </p> -<pre> -&lt;foaf:Person&gt; - &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; - &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; -&lt;/foaf:Person&gt; -</pre> -</div> - +<!-- +<p>Generally speaking, anything that a <code>foaf:Person</code> has +<code>foaf:made</code> could also qualify as a +<code>foaf:currentProject</code> or <code>foaf:pastProject</code>.</p> +--> -<p> -Note that several other FOAF properties work this way; -<code>foaf:schoolHomepage</code> is the most similar. In general, FOAF often indirectly -identifies things via Web page identifiers where possible, since these identifiers are widely -used and known. FOAF does not currently have a term for the name of the relation (eg. -"workplace") that holds -between a <code>foaf:Person</code> and an <code>foaf:Organization</code> that they work for. +<p class="editorial"> +Note that this property requires further work. There has been confusion about +whether it points to a thing (eg. something you've made; a homepage for a project, +ie. a <code>foaf:Document</code> or to instances of the class <code>foaf:Project</code>, +which might themselves have a <code>foaf:homepage</code>. In practice, it seems to have been +used in a similar way to <code>foaf:interest</code>, referencing homepages of ongoing projects. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_made"> - <h3>Property: foaf:made</h3> - <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_mbox"> + <h3>Property: foaf:mbox</h3> + <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -The <code>foaf:made</code> property relates a <code>foaf:Agent</code> -to something <code>foaf:made</code> by it. As such it is an -inverse of the <code>foaf:maker</code> property, which relates a thing to -something that made it. See <code>foaf:made</code> for more details on the -relationship between these FOAF terms and related Dublin Core vocabulary. +The <code>foaf:mbox</code> property is a relationship between the owner of a mailbox and +a mailbox. These are typically identified using the mailto: URI scheme (see <a +href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). +</p> + +<p> +Note that there are many mailboxes (eg. shared ones) which are not the +<code>foaf:mbox</code> of anyone. Furthermore, a person can have multiple +<code>foaf:mbox</code> properties. +</p> + +<p> +In FOAF, we often see <code>foaf:mbox</code> used as an indirect way of identifying its +owner. This works even if the mailbox is itself out of service (eg. 10 years old), since +the property is defined in terms of its primary owner, and doesn't require the mailbox to +actually be being used for anything. </p> +<p> +Many people are wary of sharing information about their mailbox addresses in public. To +address such concerns whilst continuing the FOAF convention of indirectly identifying +people by referring to widely known properties, FOAF also provides the +<code>foaf:mbox_sha1sum</code> mechanism, which is a relationship between a person and +the value you get from passing a mailbox URI to the SHA1 mathematical function. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_interest"> - <h3>Property: foaf:interest</h3> - <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_knows"> + <h3>Property: foaf:knows</h3> + <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <a href="#term_Person">Person</a> </td> </tr> </table> <p> -The <code>foaf:interest</code> property represents an interest of a -<code>foaf:Agent</code>, through -indicating a <code>foaf:Document</code> whose <code>foaf:topic</code>(s) broadly -characterises that interest.</p> - -<p class="example"> -For example, we might claim that a person or group has an interest in RDF by saying they -stand in a <code>foaf:interest</code> relationship to the <a -href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying -<em>"this agent is interested in the topic of this page"</em>. +The <code>foaf:knows</code> property relates a <code>foaf:Person</code> to another +<code>foaf:Person</code> that he or she knows. </p> -<p class="example"> -Uses of <code>foaf:interest</code> include a variety of filtering and resource discovery -applications. It could be used, for example, to help find answers to questions such as -"Find me members of this organisation with an interest in XML who have also contributed to -<a href="http://www.cpan.org/">CPAN</a>)". +<p> +We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. +stalkers need not apply). Since social attitudes and conventions on this topic vary +greatly between communities, counties and cultures, it is not appropriate for FOAF to be +overly-specific here. </p> <p> -This approach to characterising interests is intended to compliment other mechanisms (such -as the use of controlled vocabulary). It allows us to use a widely known set of unique -identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled -syntax, this makes data merging much easier than the use of free-text characterisations of -interest. +If someone <code>foaf:knows</code> a person, it would be usual for +the relation to be reciprocated. However this doesn't mean that there is any obligation +for either party to publish FOAF describing this relationship. A <code>foaf:knows</code> +relationship does not imply friendship, endorsement, or that a face-to-face meeting +has taken place: phone, fax, email, and smoke signals are all perfectly +acceptable ways of communicating with people you know. +</p> +<p> +You probably know hundreds of people, yet might only list a few in your public FOAF file. +That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not +list anyone else in it at all. +This illustrates the Semantic Web principle of partial description: RDF documents +rarely describe the entire picture. There is always more to be said, more information +living elsewhere in the Web (or in our heads...). </p> +<p> +Since <code>foaf:knows</code> is vague by design, it may be suprising that it has uses. +Typically these involve combining other RDF properties. For example, an application might +look at properties of each <code>foaf:weblog</code> that was <code>foaf:made</code> by +someone you "<code>foaf:knows</code>". Or check the newsfeed of the online photo archive +for each of these people, to show you recent photos taken by people you know. +</p> <p> -Note that interest does not imply expertise, and that this FOAF term provides no support -for characterising levels of interest: passing fads and lifelong quests are both examples -of someone's <code>foaf:interest</code>. Describing interests in full is a complex -undertaking; <code>foaf:interest</code> provides one basic component of FOAF's approach to -these problems. +To provide additional levels of representation beyond mere 'knows', FOAF applications +can do several things. +</p> +<p> +They can use more precise relationships than <code>foaf:knows</code> to relate people to +people. The original FOAF design included two of these ('knowsWell','friend') which we +removed because they were somewhat <em>awkward</em> to actually use, bringing an +inappopriate air of precision to an intrinsically vague concept. Other extensions have +been proposed, including Eric Vitiello's <a +href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for +FOAF. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_jabberID"> - <h3>Property: foaf:jabberID</h3> - <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:jabberID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging -system. -See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber -protocols and tools. +<p> +In addition to using more specialised inter-personal relationship types +(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states +of affairs which imply particular kinds of relationship. So for example, two people who +have the same value for their <code>foaf:workplaceHomepage</code> property are +typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, +but the facts can be written in FOAF nevertheless. Similarly, if there exists a +<code>foaf:Document</code> that has two people listed as its <code>foaf:maker</code>s, +then they are probably collaborators of some kind. Or if two people appear in 100s of +digital photos together, there's a good chance they're friends and/or colleagues. </p> <p> -Jabber, unlike several other online messaging systems, is based on an open, publically -documented protocol specification, and has a variety of open source implementations. Jabber IDs -can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For -the purposes of FOAF, these are all considered to be kinds of <code>foaf:Agent</code> (ie. -things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The -<code>foaf:jabberID</code> property is provided as a basic hook to help support RDF description -of Jabber users and services. +So FOAF is quite pluralistic in its approach to representing relationships between people. +FOAF is built on top of a general purpose machine language for representing relationships +(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. +The problems are generally social rather than technical; deciding on appropriate ways of +describing these interconnections is a subtle art. </p> <p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. +Perhaps the most important use of <code>foaf:knows</code> is, alongside the +<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF +file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more +interesting, with each FOAF file saying a little more about people, places, documents, things... +By mentioning other people (via <code>foaf:knows</code> or other relationships), and by +providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for +FOAF indexing tools ('<a href="http://rdfweb.org/topic/ScutterSpec">scutters</a>') to find +your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they +mention, and so on. This makes it possible to build FOAF aggregators without the need for +a centrally managed directory of FOAF files... </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_name"> - <h3>Property: foaf:name</h3> - <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_topic"> + <h3>Property: foaf:topic</h3> + <em>topic</em> - A topic of some page or document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> - + <tr><th>Domain:</th> + <td> <a href="#term_Document">Document</a> +</td></tr> </table> - <p>The <code>foaf:name</code> of something is a simple textual string.</p> - -<p> -XML language tagging may be used to indicate the language of the name. For example: -</p> - -<div class="example"> -<code> -&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; -</code> -</div> - -<p> -FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it -does provide a basic level of interoperability. See the <a -href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for status of work on this issue. + <p> +The <code>foaf:topic</code> property relates a document to a thing that the document is +about. </p> <p> -The <code>foaf:name</code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped -values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. +As such it is an inverse of the <code>foaf:page</code> property, which relates a thing to +a document about that thing. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_img"> - <h3>Property: foaf:img</h3> - <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_thumbnail"> + <h3>Property: foaf:thumbnail</h3> + <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Image">Image</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Image">Image</a> </td> </tr> </table> - <p> -The <code>foaf:img</code> property relates a <code>foaf:Person</code> to a -<code>foaf:Image</code> that represents them. Unlike its super-property -<code>foaf:depiction</code>, we only use <code>foaf:img</code> when an image is -particularly representative of some person. The analogy is with the image(s) that might -appear on someone's homepage, rather than happen to appear somewhere in their photo album. -</p> + <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> <p> -Unlike the more general <code>foaf:depiction</code> property (and its inverse, -<code>foaf:depicts</code>), the <code>foaf:img</code> property is only used with -representations of people (ie. instances of <code>foaf:Person</code>). So you can't use -it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more -restricted than <code>foaf:depiction</code> so we can have a useful way of picking out a -reasonable image to represent someone. FOAF defines <code>foaf:img</code> as a -sub-property of <code>foaf:depiction</code>, which means that the latter relationship is -implied whenever two things are related by the former. +The <code>foaf:thumbnail</code> property is a relationship between a +full-size <code>foaf:Image</code> and a smaller, representative <code>foaf:Image</code> +that has been derrived from it. </p> <p> -Note that <code>foaf:img</code> does not have any restrictions on the dimensions, colour -depth, format etc of the <code>foaf:Image</code> it references. +It is typical in FOAF to express <code>foaf:img</code> and <code>foaf:depiction</code> +relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). +A <code>foaf:thumbnail</code> might be clipped or otherwise reduced such that it does not +depict everything that the full image depicts. Therefore FOAF does not specify that a +thumbnail <code>foaf:depicts</code> everything that the image it is derrived from depicts. +However, FOAF does expect that anything depicted in the thumbnail will also be depicted in +the source image. </p> -<p> -Terminology: note that <code>foaf:img</code> is a property (ie. relationship), and that -<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It -might have been more helpful to call <code>foaf:img</code> 'mugshot' or similar; instead -it is named by analogy to the HTML IMG element. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_nick"> - <h3>Property: foaf:nick</h3> - <em>nickname</em> - A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> - <p> -The <code>foaf:nick</code> property relates a <code>foaf:Person</code> to a short (often -abbreviated) nickname, such as those use in IRC chat, online accounts, and computer -logins. -</p> +<!-- todo: add RDF rules here showing this --> <p> -This property is necessarily vague, because it does not indicate any particular naming -control authority, and so cannot distinguish a person's login from their (possibly -various) IRC nicknames or other similar identifiers. However it has some utility, since -many people use the same string (or slight variants) across a variety of such -environments. +A <code>foaf:thumbnail</code> is typically small enough that it can be +loaded and viewed quickly before a viewer decides to download the larger +version. They are often used in online photo gallery applications. </p> -<p> -For specific controlled sets of names (relating primarily to Instant Messanger accounts), -FOAF provides some convenience properties: <code>foaf:jabberID</code>, -<code>foaf:aimChatID</code>, <code>foaf:msnChatID</code> and -<code>foaf:icqChatID</code>. Beyond this, the problem of representing such accounts is not -peculiar to Instant Messanging, and it is not scaleable to attempt to enumerate each -naming database as a distinct FOAF property. The <code>foaf:OnlineAccount</code> term (and -supporting vocabulary) are provided as a more verbose and more expressive generalisation -of these properties. -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_sha1"> - <h3>Property: foaf:sha1</h3> - <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_dnaChecksum"> + <h3>Property: foaf:dnaChecksum</h3> + <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> -</td></tr> + </table> <p> -The <code>foaf:sha1</code> property relates a <code>foaf:Document</code> to the textual form of -a SHA1 hash of (some representation of) its contents. -</p> - -<p class="editorial"> -The design for this property is neither complete nor coherent. The <code>foaf:Document</code> -class is currently used in a way that allows multiple instances at different URIs to have the -'same' contents (and hence hash). If <code>foaf:sha1</code> is an owl:InverseFunctionalProperty, -we could deduce that several such documents were the self-same thing. A more careful design is -needed, which distinguishes documents in a broad sense from byte sequences. +The <code>foaf:dnaChecksum</code> property is mostly a joke, but +also a reminder that there will be lots of different identifying +properties for people, some of which we might find disturbing. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_aimChatID"> - <h3>Property: foaf:aimChatID</h3> - <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_surname"> + <h3>Property: foaf:surname</h3> + <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> </table> - <p> -The <code>foaf:aimChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. -See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM -screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a -href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. -</p> - -<p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_givenname"> - <h3>Property: foaf:givenname</h3> - <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> <p>A number of naming constructs are under development to provide naming substructure; draft properties include <code>foaf:firstName</code>, <code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for design discussions, status and ongoing work on rationalising the FOAF naming machinery. </p> <p> There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_yahooChatID"> - <h3>Property: foaf:yahooChatID</h3> - <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_mbox_sha1sum"> + <h3>Property: foaf:mbox_sha1sum</h3> + <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -The <code>foaf:yahooChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the Yahoo online Chat system. -See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their -service. Yahoo chat IDs are also used across several other Yahoo services, including email and -<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. -</p> - -<p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_workInfoHomepage"> - <h3>Property: foaf:workInfoHomepage</h3> - <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:workInfoHomepage</code> of a <code>foaf:Person</code> is a -<code>foaf:Document</code> that describes their work. It is generally (but not necessarily) a -different document from their <code>foaf:homepage</code>, and from any -<code>foaf:workplaceHomepage</code>(s) they may have. +A <code>foaf:mbox_sha1sum</code> of a <code>foaf:Person</code> is a textual representation of +the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an +Internet mailbox that they stand in a <code>foaf:mbox</code> relationship to. </p> <p> -The purpose of this property is to distinguish those pages you often see, which describe -someone's professional role within an organisation or project. These aren't really homepages, -although they share some characterstics. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_publications"> - <h3>Property: foaf:publications</h3> - <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:publications</code> property indicates a <code>foaf:Document</code> -listing (primarily in human-readable form) some publications associated with the -<code>foaf:Person</code>. Such documents are typically published alongside one's -<code>foaf:homepage</code>. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_currentProject"> - <h3>Property: foaf:currentProject</h3> - <em>current project</em> - A current project this person works on. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - <!-- originally contrib'd by Cardinal --> - -<p>A <code>foaf:currentProject</code> relates a <code>foaf:Person</code> -to a <code>foaf:Document</code> indicating some collaborative or -individual undertaking. This relationship -indicates that the <code>foaf:Person</code> has some active role in the -project, such as development, coordination, or support.</p> - -<p>When a <code>foaf:Person</code> is no longer involved with a project, or -perhaps is inactive for some time, the relationship becomes a -<code>foaf:pastProject</code>.</p> +In other words, if you have a mailbox (<code>foaf:mbox</code>) but don't want to reveal its +address, you can take that address and generate a <code>foaf:mbox_sha1sum</code> representation +of it. Just as a <code>foaf:mbox</code> can be used as an indirect identifier for its owner, we +can do the same with <code>foaf:mbox_sha1sum</code> since there is only one +<code>foaf:Person</code> with any particular value for that property. +</p> <p> -If the <code>foaf:Person</code> has stopped working on a project because it -has been completed (successfully or otherwise), <code>foaf:pastProject</code> is -applicable. In general, <code>foaf:currentProject</code> is used to indicate -someone's current efforts (and implied interests, concerns etc.), while -<code>foaf:pastProject</code> describes what they've previously been doing. +Many FOAF tools use <code>foaf:mbox_sha1sum</code> in preference to exposing mailbox +information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques +include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's +documentation</a>) and the use of <a +href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for +mail filtering. </p> -<!-- -<p>Generally speaking, anything that a <code>foaf:Person</code> has -<code>foaf:made</code> could also qualify as a -<code>foaf:currentProject</code> or <code>foaf:pastProject</code>.</p> ---> - -<p class="editorial"> -Note that this property requires further work. There has been confusion about -whether it points to a thing (eg. something you've made; a homepage for a project, -ie. a <code>foaf:Document</code> or to instances of the class <code>foaf:Project</code>, -which might themselves have a <code>foaf:homepage</code>. In practice, it seems to have been -used in a similar way to <code>foaf:interest</code>, referencing homepages of ongoing projects. +<p> +Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a +href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's +weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing +whitespace, when computing a <code>foaf:mbox_sha1sum</code> property. </p> +<!-- what about Javascript. move refs to wiki maybe. --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_page"> <h3>Property: foaf:page</h3> <em>page</em> - A page or document about this thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> The <code>foaf:page</code> property relates a thing to a document about that thing. </p> <p> As such it is an inverse of the <code>foaf:topic</code> property, which relates a document to a thing that the document is about. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_icqChatID"> - <h3>Property: foaf:icqChatID</h3> - <em>ICQ chat ID</em> - An ICQ chat ID <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_workInfoHomepage"> + <h3>Property: foaf:workInfoHomepage</h3> + <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> - + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> </table> <p> -The <code>foaf:icqChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the ICQ Chat system. -See the <a href="http://web.icq.com/icqchat/">icq chat</a> site for more details of the 'icq' -service. Their "<a href="http://www.icq.com/products/whatisicq.html">What is ICQ?</a>" document -provides a basic overview, while their "<a href="http://company.icq.com/info/">About Us</a> page -notes that ICQ has been acquired by AOL. Despite the relationship with AOL, ICQ is at -the time of writing maintained as a separate identity from the AIM brand (see -<code>foaf:aimChatID</code>). +The <code>foaf:workInfoHomepage</code> of a <code>foaf:Person</code> is a +<code>foaf:Document</code> that describes their work. It is generally (but not necessarily) a +different document from their <code>foaf:homepage</code>, and from any +<code>foaf:workplaceHomepage</code>(s) they may have. </p> <p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. +The purpose of this property is to distinguish those pages you often see, which describe +someone's professional role within an organisation or project. These aren't really homepages, +although they share some characterstics. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_maker"> - <h3>Property: foaf:maker</h3> - <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_theme"> + <h3>Property: foaf:theme</h3> + <em>theme</em> - A theme. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>unstable</td></tr> + + </table> + <p> +The <code>foaf:theme</code> property is rarely used and under-specified. The intention was +to use it to characterise interest / themes associated with projects and groups. Further +work is needed to meet these goals. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_interest"> + <h3>Property: foaf:interest</h3> + <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> <tr><th>Range:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:maker</code> property relates something to a -<code>foaf:Agent</code> that <code>foaf:made</code> it. As such it is an -inverse of the <code>foaf:made</code> property. +The <code>foaf:interest</code> property represents an interest of a +<code>foaf:Agent</code>, through +indicating a <code>foaf:Document</code> whose <code>foaf:topic</code>(s) broadly +characterises that interest.</p> + +<p class="example"> +For example, we might claim that a person or group has an interest in RDF by saying they +stand in a <code>foaf:interest</code> relationship to the <a +href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying +<em>"this agent is interested in the topic of this page"</em>. </p> -<p> -The <code>foaf:name</code> (or other <code>rdfs:label</code>) of the -<code>foaf:maker</code> of something can be described as the -<code>dc:creator</code> of that thing.</p> +<p class="example"> +Uses of <code>foaf:interest</code> include a variety of filtering and resource discovery +applications. It could be used, for example, to help find answers to questions such as +"Find me members of this organisation with an interest in XML who have also contributed to +<a href="http://www.cpan.org/">CPAN</a>)". +</p> <p> -For example, if the thing named by the URI -http://rdfweb.org/people/danbri/ has a -<code>foaf:maker</code> that is a <code>foaf:Person</code> whose -<code>foaf:name</code> is 'Dan Brickley', we can conclude that -http://rdfweb.org/people/danbri/ has a <code>dc:creator</code> of 'Dan -Brickley'. +This approach to characterising interests is intended to compliment other mechanisms (such +as the use of controlled vocabulary). It allows us to use a widely known set of unique +identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled +syntax, this makes data merging much easier than the use of free-text characterisations of +interest. </p> + <p> -FOAF descriptions are encouraged to use <code>dc:creator</code> only for -simple textual names, and to use <code>foaf:maker</code> to indicate -creators, rather than risk confusing creators with their names. This -follows most Dublin Core usage. See <a -href="http://rdfweb.org/topic/UsingDublinCoreCreator">UsingDublinCoreCreator</a> -for details. +Note that interest does not imply expertise, and that this FOAF term provides no support +for characterising levels of interest: passing fads and lifelong quests are both examples +of someone's <code>foaf:interest</code>. Describing interests in full is a complex +undertaking; <code>foaf:interest</code> provides one basic component of FOAF's approach to +these problems. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_logo"> - <h3>Property: foaf:logo</h3> - <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_isPrimaryTopicOf"> + <h3>Property: foaf:isPrimaryTopicOf</h3> + <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> - + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> </table> <p> -The <code>foaf:logo</code> property is used to indicate a graphical logo of some kind. -<em>It is probably underspecified...</em> +The <code>foaf:isPrimaryTopicOf</code> property relates something to a document that is +mainly about it. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_surname"> - <h3>Property: foaf:surname</h3> - <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. +<p> +The <code>foaf:isPrimaryTopicOf</code> property is <em>inverse functional</em>: for +any document that is the value of this property, there is at most one thing in the world +that is the primary topic of that document. This is useful, as it allows for data +merging, as described in the documentation for its inverse, <code>foaf:primaryTopic</code>. </p> <p> -There is also a simple <code>foaf:name</code> property. +<code>foaf:page</code> is a super-property of <code>foaf:isPrimaryTopicOf</code>. The change +of terminology between the two property names reflects the utility of 'primaryTopic' and its +inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation +to some document X, also has a <code>foaf:page</code> relationship to it. +</p> +<p> +Note that <code>foaf:homepage</code>, is a sub-property of both <code>foaf:page</code> and +<code>foaf:isPrimarySubjectOf</code>. The awkwardly named +<code>foaf:isPrimarySubjectOf</code> is less specific, and can be used with any document +that is primarily about the thing of interest (ie. not just on homepages). </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_family_name"> - <h3>Property: foaf:family_name</h3> - <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_nick"> + <h3>Property: foaf:nick</h3> + <em>nickname</em> - A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - </table> + </table> + <p> +The <code>foaf:nick</code> property relates a <code>foaf:Person</code> to a short (often +abbreviated) nickname, such as those use in IRC chat, online accounts, and computer +logins. +</p> -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. +<p> +This property is necessarily vague, because it does not indicate any particular naming +control authority, and so cannot distinguish a person's login from their (possibly +various) IRC nicknames or other similar identifiers. However it has some utility, since +many people use the same string (or slight variants) across a variety of such +environments. </p> <p> -There is also a simple <code>foaf:name</code> property. +For specific controlled sets of names (relating primarily to Instant Messanger accounts), +FOAF provides some convenience properties: <code>foaf:jabberID</code>, +<code>foaf:aimChatID</code>, <code>foaf:msnChatID</code> and +<code>foaf:icqChatID</code>. Beyond this, the problem of representing such accounts is not +peculiar to Instant Messanging, and it is not scaleable to attempt to enumerate each +naming database as a distinct FOAF property. The <code>foaf:OnlineAccount</code> term (and +supporting vocabulary) are provided as a more verbose and more expressive generalisation +of these properties. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_accountServiceHomepage"> - <h3>Property: foaf:accountServiceHomepage</h3> - <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_homepage"> + <h3>Property: foaf:homepage</h3> + <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Online Account">Online Account</a> -</td></tr> + <td>stable</td></tr> + <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:accountServiceHomepage</code> property indicates a relationship between a -<code>foaf:OnlineAccount</code> and the homepage of the supporting service provider. +The <code>foaf:homepage</code> property relates something to a homepage about it. +</p> + +<p> +Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but +constrains <code>foaf:homepage</code> so that there can be only one thing that has any +particular homepage. +</p> + +<p> +A 'homepage' in this sense is a public Web document, typically but not necessarily +available in HTML format. The page has as a <code>foaf:topic</code> the thing whose +homepage it is. The homepage is usually controlled, edited or published by the thing whose +homepage it is; as such one might look to a homepage for information on its owner from its +owner. This works for people, companies, organisations etc. +</p> + +<p> +The <code>foaf:homepage</code> property is a sub-property of the more general +<code>foaf:page</code> property for relating a thing to a page about that thing. See also +<code>foaf:topic</code>, the inverse of the <code>foaf:page</code> property. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_depiction"> - <h3>Property: foaf:depiction</h3> - <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_maker"> + <h3>Property: foaf:maker</h3> + <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td>stable</td></tr> <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> + <td> <a href="#term_Agent">Agent</a> </td> </tr> </table> <p> -The <code>foaf:depiction</code> property is a relationship between a thing and an -<code>foaf:Image</code> that depicts it. As such it is an inverse of the -<code>foaf:depicts</code> relationship. -</p> - -<p> -A common use of <code>foaf:depiction</code> (and <code>foaf:depicts</code>) is to indicate -the contents of a digital image, for example the people or objects represented in an -online photo gallery. +The <code>foaf:maker</code> property relates something to a +<code>foaf:Agent</code> that <code>foaf:made</code> it. As such it is an +inverse of the <code>foaf:made</code> property. </p> <p> -Extensions to this basic idea include '<a -href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in -photos), as well as richer photo metadata through the mechanism of using SVG paths to -indicate the <em>regions</em> of an image which depict some particular thing. See <a -href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> -for tools and details. -</p> +The <code>foaf:name</code> (or other <code>rdfs:label</code>) of the +<code>foaf:maker</code> of something can be described as the +<code>dc:creator</code> of that thing.</p> <p> -The basic notion of 'depiction' could also be extended to deal with multimedia content -(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. +For example, if the thing named by the URI +http://rdfweb.org/people/danbri/ has a +<code>foaf:maker</code> that is a <code>foaf:Person</code> whose +<code>foaf:name</code> is 'Dan Brickley', we can conclude that +http://rdfweb.org/people/danbri/ has a <code>dc:creator</code> of 'Dan +Brickley'. </p> <p> -The <code>foaf:depiction</code> property is a super-property of the more specific property -<code>foaf:img</code>, which is used more sparingly. You stand in a -<code>foaf:depiction</code> relation to <em>any</em> <code>foaf:Image</code> that depicts -you, whereas <code>foaf:img</code> is typically used to indicate a few images that are -particularly representative. +FOAF descriptions are encouraged to use <code>dc:creator</code> only for +simple textual names, and to use <code>foaf:maker</code> to indicate +creators, rather than risk confusing creators with their names. This +follows most Dublin Core usage. See <a +href="http://rdfweb.org/topic/UsingDublinCoreCreator">UsingDublinCoreCreator</a> +for details. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_topic_interest"> - <h3>Property: foaf:topic_interest</h3> - <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_aimChatID"> + <h3>Property: foaf:aimChatID</h3> + <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> </table> - <p class="editorial"> -The <code>foaf:topic_interest</code> property is generally found to be confusing and ill-defined -and is a candidate for removal. The goal was to be link a person to some thing that is a topic -of their interests (rather than, per <code>foaf:interest</code> to a page that is about such a -topic). + <p> +The <code>foaf:aimChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. +See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM +screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a +href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_msnChatID"> <h3>Property: foaf:msnChatID</h3> <em>MSN chat ID</em> - An MSN chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> The <code>foaf:msnChatID</code> property relates a <code>foaf:Agent</code> to a textual identifier assigned to them in the MSN online Chat system. See Microsoft's the <a href="http://chat.msn.com/">MSN chat</a> site for more details (or for a message saying <em>"MSN Chat is not currently compatible with your Internet browser and/or computer operating system"</em> if your computing platform is deemed unsuitable). </p> <p class="editorial"> It is not currently clear how MSN chat IDs relate to the more general Microsoft Passport identifiers. </p> <p>See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a more general (and verbose) mechanism for describing IM and chat accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_birthday"> - <h3>Property: foaf:birthday</h3> - <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_name"> + <h3>Property: foaf:name</h3> + <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> + <td>testing</td></tr> + </table> - <p> -The <code>foaf:birthday</code> property is a relationship between a <code>foaf:Agent</code> -and a string representing the month and day in which they were born (Gregorian calendar). -See <a href="http://rdfweb.org/topic/BirthdayIssue">BirthdayIssue</a> for details of related properties that can -be used to describe such things in more flexible ways. + <p>The <code>foaf:name</code> of something is a simple textual string.</p> + +<p> +XML language tagging may be used to indicate the language of the name. For example: </p> +<div class="example"> +<code> +&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; +</code> +</div> + +<p> +FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it +does provide a basic level of interoperability. See the <a +href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for status of work on this issue. +</p> +<p> +The <code>foaf:name</code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped +values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_plan"> - <h3>Property: foaf:plan</h3> - <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_schoolHomepage"> + <h3>Property: foaf:schoolHomepage</h3> + <em>schoolHomepage</em> - A homepage of a school attended by the person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> - + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> </table> - <!-- orig contrib'd by Cardinal --> - -<p>The <code>foaf:plan</code> property provides a space for a -<code>foaf:Person</code> to hold some arbitrary content that would appear in -a traditional '.plan' file. The plan file was stored in a user's home -directory on a UNIX machine, and displayed to people when the user was -queried with the finger utility.</p> + <p> +The <code>schoolHomepage</code> property relates a <code>foaf:Person</code> to a +<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a School that the +person attended. +</p> -<p>A plan file could contain anything. Typical uses included brief -comments, thoughts, or remarks on what a person had been doing lately. Plan -files were also prone to being witty or simply osbscure. Others may be more -creative, writing any number of seemingly random compositions in their plan -file for people to stumble upon.</p> +<p> +FOAF does not (currently) define a class for 'School' (if it did, it would probably be as +a sub-class of <code>foaf:Organization</code>). The original application area for +<code>foaf:schoolHomepage</code> was for 'schools' in the British-English sense; however +American-English usage has dominated, and it is now perfectly reasonable to describe +Universities, Colleges and post-graduate study using <code>foaf:schoolHomepage</code>. +</p> <p> -See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the -Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The -<code>foaf:geekcode</code> property may also be of interest. +This very basic facility provides a basis for a low-cost, decentralised approach to +classmate-reunion and suchlike. Instead of requiring a central database, we can use FOAF +to express claims such as 'I studied <em>here</em>' simply by mentioning a +school's homepage within FOAF files. Given the homepage of a school, it is easy for +FOAF aggregators to lookup this property in search of people who attended that school. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_membershipClass"> - <h3>Property: foaf:membershipClass</h3> - <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_jabberID"> + <h3>Property: foaf:jabberID</h3> + <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> </table> <p> -The <code>foaf:membershipClass</code> property relates a <code>foaf:Group</code> to an RDF -class representing a sub-class of <code>foaf:Agent</code> whose instances are all the -agents that are a <code>foaf:member</code> of the <code>foaf:Group</code>. +The <code>foaf:jabberID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging +system. +See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber +protocols and tools. </p> <p> -See <code>foaf:Group</code> for details and examples. +Jabber, unlike several other online messaging systems, is based on an open, publically +documented protocol specification, and has a variety of open source implementations. Jabber IDs +can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For +the purposes of FOAF, these are all considered to be kinds of <code>foaf:Agent</code> (ie. +things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The +<code>foaf:jabberID</code> property is provided as a basic hook to help support RDF description +of Jabber users and services. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_myersBriggs"> - <h3>Property: foaf:myersBriggs</h3> - <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_plan"> + <h3>Property: foaf:plan</h3> + <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> </table> - <!-- todo: expand acronym --> - -<p> -The <code>foaf:myersBriggs</code> property represents the Myers Briggs (MBTI) approach to -personality taxonomy. It is included in FOAF as an example of a property -that takes certain constrained values, and to give some additional detail to the FOAF -files of those who choose to include it. The <code>foaf:myersBriggs</code> property applies only to the -<code>foaf:Person</code> class; wherever you see it, you can infer it is being applied to -a person. -</p> - -<p> -The <code>foaf:myersBriggs</code> property is interesting in that it illustrates how -FOAF can serve as a carrier for various kinds of information, without necessarily being -commited to any associated worldview. Not everyone will find myersBriggs (or star signs, -or blood types, or the four humours) a useful perspective on human behaviour and -personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses -the underlying theory, any more than the existence of <code>foaf:weblog</code> is an -endorsement of soapboxes. -</p> - -<p> -The values for <code>foaf:myersBriggs</code> are the following 16 4-letter textual codes: -ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, -ENTP, ISFJ. If multiple of these properties are applicable, they are represented by -applying multiple properties to a person. -</p> - -<p> -For further reading on MBTI, see various online sources (eg. <a -href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There -are various online sites which offer quiz-based tools for determining a person's MBTI -classification. The owners of the MBTI trademark have probably not approved of these. -</p> + <!-- orig contrib'd by Cardinal --> -<p> -This FOAF property suggests some interesting uses, some of which could perhaps be used to -test the claims made by proponents of the MBTI (eg. an analysis of weblog postings -filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are -self-selecting; MBTI categories may not be uniformly appealing to the people they -describe. Further, there is probably a degree of cultural specificity implicit in the -assumptions made by many questionaire-based MBTI tools; the MBTI system may not make -sense in cultural settings beyond those it was created for. -</p> +<p>The <code>foaf:plan</code> property provides a space for a +<code>foaf:Person</code> to hold some arbitrary content that would appear in +a traditional '.plan' file. The plan file was stored in a user's home +directory on a UNIX machine, and displayed to people when the user was +queried with the finger utility.</p> -<p> -See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a -href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> -for further background and examples. -</p> +<p>A plan file could contain anything. Typical uses included brief +comments, thoughts, or remarks on what a person had been doing lately. Plan +files were also prone to being witty or simply osbscure. Others may be more +creative, writing any number of seemingly random compositions in their plan +file for people to stumble upon.</p> <p> -Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting -Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the -trademark in the UK. +See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the +Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The +<code>foaf:geekcode</code> property may also be of interest. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_mbox_sha1sum"> - <h3>Property: foaf:mbox_sha1sum</h3> - <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_membershipClass"> + <h3>Property: foaf:membershipClass</h3> + <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> + <td>unstable</td></tr> + </table> <p> -A <code>foaf:mbox_sha1sum</code> of a <code>foaf:Person</code> is a textual representation of -the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an -Internet mailbox that they stand in a <code>foaf:mbox</code> relationship to. -</p> - -<p> -In other words, if you have a mailbox (<code>foaf:mbox</code>) but don't want to reveal its -address, you can take that address and generate a <code>foaf:mbox_sha1sum</code> representation -of it. Just as a <code>foaf:mbox</code> can be used as an indirect identifier for its owner, we -can do the same with <code>foaf:mbox_sha1sum</code> since there is only one -<code>foaf:Person</code> with any particular value for that property. -</p> - -<p> -Many FOAF tools use <code>foaf:mbox_sha1sum</code> in preference to exposing mailbox -information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques -include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's -documentation</a>) and the use of <a -href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for -mail filtering. +The <code>foaf:membershipClass</code> property relates a <code>foaf:Group</code> to an RDF +class representing a sub-class of <code>foaf:Agent</code> whose instances are all the +agents that are a <code>foaf:member</code> of the <code>foaf:Group</code>. </p> <p> -Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a -href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's -weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing -whitespace, when computing a <code>foaf:mbox_sha1sum</code> property. +See <code>foaf:Group</code> for details and examples. </p> -<!-- what about Javascript. move refs to wiki maybe. --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_pastProject"> - <h3>Property: foaf:pastProject</h3> - <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_title"> + <h3>Property: foaf:title</h3> + <em>title</em> - Title (Mr, Mrs, Ms, Dr. etc) <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> + </table> - <p>After a <code>foaf:Person</code> is no longer involved with a -<code>foaf:currentProject</code>, or has been inactive for some time, a -<code>foaf:pastProject</code> relationship can be used. This indicates that -the <code>foaf:Person</code> was involved with the described project at one -point. -</p> - -<p> -If the <code>foaf:Person</code> has stopped working on a project because it -has been completed (successfully or otherwise), <code>foaf:pastProject</code> is -applicable. In general, <code>foaf:currentProject</code> is used to indicate -someone's current efforts (and implied interests, concerns etc.), while -<code>foaf:pastProject</code> describes what they've previously been doing. + <p> +The approriate values for <code>foaf:title</code> are not formally constrained, and will +vary across community and context. Values such as 'Mr', 'Mrs', 'Ms', 'Dr' etc. are +expected. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_holdsAccount"> - <h3>Property: foaf:holdsAccount</h3> - <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_weblog"> + <h3>Property: foaf:weblog</h3> + <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> <tr><th>Range:</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:holdsAccount</code> property relates a <code>foaf:Agent</code> to an -<code>foaf:OnlineAccount</code> for which they are the sole account holder. See -<code>foaf:OnlineAccount</code> for usage details. +The <code>foaf:weblog</code> property relates a <code>foaf:Agent</code> to a weblog of +that agent. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_accountName"> - <h3>Property: foaf:accountName</h3> - <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_based_near"> + <h3>Property: foaf:based_near</h3> + <em>based near</em> - A location that something is based near, for some broadly human notion of near. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Online Account">Online Account</a> -</td></tr> + </table> - <p> -The <code>foaf:accountName</code> property of a <code>foaf:OnlineAccount</code> is a -textual representation of the account name (unique ID) associated with that account. + <!-- note: is this mis-specified? perhaps range ought to also be SpatialThing, so we + can have multiple labels on the same point? --> + +<p>The <code>foaf:based_near</code> relationship relates two "spatial +things" +(anything that can <em>be somewhere</em>), the latter typically +described using the geo:lat / geo:long +<a href="http://www.w3.org/2003/01/geo/wgs84_pos#">geo-positioning vocabulary</a> +(See <a href="http://esw.w3.org/topic/GeoInfo">GeoInfo</a> in the W3C semweb +wiki for details). This allows us to say describe the typical latitute and +longitude of, say, a Person (people are spatial things - they can be +places) without implying that a precise location has been given. </p> +<p>We do not say much about what 'near' means in this context; it is a +'rough and ready' concept. For a more precise treatment, see +<a href="http://esw.w3.org/topic/GeoOnion">GeoOnion vocab</a> design +discussions, which are aiming to produce a more sophisticated vocabulary for +such purposes. +</p> + +<p> FOAF files often make use of the <code>contact:nearestAirport</code> property. This +illustrates the distinction between FOAF documents (which may make claims using <em>any</em> RDF +vocabulary) and the core FOAF vocabulary defined by this specification. For further reading on +the use of <code>nearestAirport</code> see <a +href="http://rdfweb.org/topic/UsingContactNearestAirport">UsingContactNearestAirport</a> in the +FOAF wiki. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_member"> <h3>Property: foaf:member</h3> <em>member</em> - Indicates a member of a Group <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Group">Group</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Agent">Agent</a> </td> </tr> </table> <p> The <code>foaf:member</code> property relates a <code>foaf:Group</code> to a <code>foaf:Agent</code> that is a member of that group. </p> <p> See <code>foaf:Group</code> for details and examples. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_knows"> - <h3>Property: foaf:knows</h3> - <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_made"> + <h3>Property: foaf:made</h3> + <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td>stable</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Person">Person</a> -</td> </tr> + </table> <p> -The <code>foaf:knows</code> property relates a <code>foaf:Person</code> to another -<code>foaf:Person</code> that he or she knows. -</p> - -<p> -We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. -stalkers need not apply). Since social attitudes and conventions on this topic vary -greatly between communities, counties and cultures, it is not appropriate for FOAF to be -overly-specific here. -</p> - -<p> -If someone <code>foaf:knows</code> a person, it would be usual for -the relation to be reciprocated. However this doesn't mean that there is any obligation -for either party to publish FOAF describing this relationship. A <code>foaf:knows</code> -relationship does not imply friendship, endorsement, or that a face-to-face meeting -has taken place: phone, fax, email, and smoke signals are all perfectly -acceptable ways of communicating with people you know. -</p> -<p> -You probably know hundreds of people, yet might only list a few in your public FOAF file. -That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not -list anyone else in it at all. -This illustrates the Semantic Web principle of partial description: RDF documents -rarely describe the entire picture. There is always more to be said, more information -living elsewhere in the Web (or in our heads...). -</p> - -<p> -Since <code>foaf:knows</code> is vague by design, it may be suprising that it has uses. -Typically these involve combining other RDF properties. For example, an application might -look at properties of each <code>foaf:weblog</code> that was <code>foaf:made</code> by -someone you "<code>foaf:knows</code>". Or check the newsfeed of the online photo archive -for each of these people, to show you recent photos taken by people you know. -</p> - -<p> -To provide additional levels of representation beyond mere 'knows', FOAF applications -can do several things. -</p> -<p> -They can use more precise relationships than <code>foaf:knows</code> to relate people to -people. The original FOAF design included two of these ('knowsWell','friend') which we -removed because they were somewhat <em>awkward</em> to actually use, bringing an -inappopriate air of precision to an intrinsically vague concept. Other extensions have -been proposed, including Eric Vitiello's <a -href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for -FOAF. -</p> - -<p> -In addition to using more specialised inter-personal relationship types -(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states -of affairs which imply particular kinds of relationship. So for example, two people who -have the same value for their <code>foaf:workplaceHomepage</code> property are -typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, -but the facts can be written in FOAF nevertheless. Similarly, if there exists a -<code>foaf:Document</code> that has two people listed as its <code>foaf:maker</code>s, -then they are probably collaborators of some kind. Or if two people appear in 100s of -digital photos together, there's a good chance they're friends and/or colleagues. -</p> - -<p> -So FOAF is quite pluralistic in its approach to representing relationships between people. -FOAF is built on top of a general purpose machine language for representing relationships -(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. -The problems are generally social rather than technical; deciding on appropriate ways of -describing these interconnections is a subtle art. -</p> - -<p> -Perhaps the most important use of <code>foaf:knows</code> is, alongside the -<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF -file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more -interesting, with each FOAF file saying a little more about people, places, documents, things... -By mentioning other people (via <code>foaf:knows</code> or other relationships), and by -providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for -FOAF indexing tools ('<a href="http://rdfweb.org/topic/ScutterSpec">scutters</a>') to find -your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they -mention, and so on. This makes it possible to build FOAF aggregators without the need for -a centrally managed directory of FOAF files... -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_thumbnail"> - <h3>Property: foaf:thumbnail</h3> - <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Image">Image</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> -</td> </tr> - </table> - <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> - -<p> -The <code>foaf:thumbnail</code> property is a relationship between a -full-size <code>foaf:Image</code> and a smaller, representative <code>foaf:Image</code> -that has been derrived from it. -</p> - -<p> -It is typical in FOAF to express <code>foaf:img</code> and <code>foaf:depiction</code> -relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). -A <code>foaf:thumbnail</code> might be clipped or otherwise reduced such that it does not -depict everything that the full image depicts. Therefore FOAF does not specify that a -thumbnail <code>foaf:depicts</code> everything that the image it is derrived from depicts. -However, FOAF does expect that anything depicted in the thumbnail will also be depicted in -the source image. +The <code>foaf:made</code> property relates a <code>foaf:Agent</code> +to something <code>foaf:made</code> by it. As such it is an +inverse of the <code>foaf:maker</code> property, which relates a thing to +something that made it. See <code>foaf:made</code> for more details on the +relationship between these FOAF terms and related Dublin Core vocabulary. </p> -<!-- todo: add RDF rules here showing this --> -<p> -A <code>foaf:thumbnail</code> is typically small enough that it can be -loaded and viewed quickly before a viewer decides to download the larger -version. They are often used in online photo gallery applications. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_phone"> + <h3>Property: foaf:phone</h3> + <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The <code>foaf:phone</code> of something is a phone, typically identified using the tel: URI +scheme. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_primaryTopic"> - <h3>Property: foaf:primaryTopic</h3> - <em>primary topic</em> - The primary topic of some page or document. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_gender"> + <h3>Property: foaf:gender</h3> + <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -The <code>foaf:primaryTopic</code> property relates a document to the -main thing that the document is about. +The <code>foaf:gender</code> property relates a <code>foaf:Agent</code> (typically a +<code>foaf:Person</code>) to a string representing its gender. In most cases the value +will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). +Like all FOAF properties, there is in general no requirement to use +<code>foaf:gender</code> in any particular document or description. Values other than +'male' and 'female' may be used, but are not enumerated here. The <code>foaf:gender</code> +mechanism is not intended to capture the full variety of biological, social and sexual +concepts associated with the word 'gender'. </p> <p> -The <code>foaf:primaryTopic</code> property is <em>functional</em>: for -any document it applies to, it can have at most one value. This is -useful, as it allows for data merging. In many cases it may be difficult -for third parties to determine the primary topic of a document, but in -a useful number of cases (eg. descriptions of movies, restaurants, -politicians, ...) it should be reasonably obvious. Documents are very -often the most authoritative source of information about their own -primary topics, although this cannot be guaranteed since documents cannot be -assumed to be accurate, honest etc. +Anything that has a <code>foaf:gender</code> property will be some kind of +<code>foaf:Agent</code>. However there are kinds of <code>foaf:Agent</code> to +which the concept of gender isn't applicable (eg. a <code>foaf:Group</code>). FOAF does not +currently include a class corresponding directly to "the type of thing that has a gender". +At any point in time, a <code>foaf:Agent</code> has at most one value for +<code>foaf:gender</code>. FOAF does not treat <code>foaf:gender</code> as a +<em>static</em> property; the same individual may have different values for this property +at different times. </p> <p> -It is an inverse of the <code>foaf:isPrimaryTopicOf</code> property, which relates a -thing to a document <em>primarily</em> about that thing. The choice between these two -properties is purely pragmatic. When describing documents, we -use <code>foaf:primaryTopic</code> former to point to the things they're about. When -describing things (people etc.), it is useful to be able to directly cite documents which -have those things as their main topic - so we use <code>foaf:isPrimaryTopicOf</code>. In this -way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a -href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they -have descriptions of. +Note that FOAF's notion of gender isn't defined biologically or anatomically - this would +be tricky since we have a broad notion that applies to all <code>foaf:Agent</code>s +(including robots - eg. Bender from Futurama is 'male'). As stressed above, +FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated +with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise +between the clinical and the social/psychological. In general, a person will be the best +authority on their <code>foaf:gender</code>. Feedback on this design is +particularly welcome (via the FOAF mailing list, +<a href="http://rdfweb.org/mailman/listinfo/rdfweb-dev">rdfweb-dev</a>). We have tried to +be respectful of diversity without attempting to catalogue or enumerate that diversity. </p> - +<p> +This may also be a good point for a periodic reminder: as with all FOAF properties, +documents that use '<code>foaf:gender</code>' will on occassion be innacurate, misleading +or outright false. FOAF, like all open means of communication, supports <em>lying</em>. + Application authors using +FOAF data should always be cautious in their presentation of unverified information, but be +particularly sensitive to issues and risks surrounding sex and gender (including privacy +and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit +<code>foaf:gender</code> when describing themselves and others, and to allow at least for +values other than 'male' and 'female' as options. Users of information +conveyed via FOAF (as via information conveyed through mobile phone text messages, email, +Internet chat, HTML pages etc.) should be skeptical of unverified information. +</p> + +<!-- +b/g article currently offline. +http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 +--> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_title"> - <h3>Property: foaf:title</h3> - <em>title</em> - Title (Mr, Mrs, Ms, Dr. etc) <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_holdsAccount"> + <h3>Property: foaf:holdsAccount</h3> + <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - - + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td> </tr> </table> <p> -The approriate values for <code>foaf:title</code> are not formally constrained, and will -vary across community and context. Values such as 'Mr', 'Mrs', 'Ms', 'Dr' etc. are -expected. +The <code>foaf:holdsAccount</code> property relates a <code>foaf:Agent</code> to an +<code>foaf:OnlineAccount</code> for which they are the sole account holder. See +<code>foaf:OnlineAccount</code> for usage details. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_phone"> - <h3>Property: foaf:phone</h3> - <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_fundedBy"> + <h3>Property: foaf:fundedBy</h3> + <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td>unstable</td></tr> </table> <p> -The <code>foaf:phone</code> of something is a phone, typically identified using the tel: URI -scheme. +The <code>foaf:fundedBy</code> property relates something to something else that has provided +funding for it. </p> +<p class="editorial"> +This property is under-specified, experimental, and should be considered liable to change. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_accountServiceHomepage"> + <h3>Property: foaf:accountServiceHomepage</h3> + <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:accountServiceHomepage</code> property indicates a relationship between a +<code>foaf:OnlineAccount</code> and the homepage of the supporting service provider. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_tipjar"> <h3>Property: foaf:tipjar</h3> <em>tipjar</em> - A tipjar document for this agent, describing means for payment and reward. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> The <code>foaf:tipjar</code> property relates an <code>foaf:Agent</code> to a <code>foaf:Document</code> that describes some mechanisms for paying or otherwise rewarding that agent. </p> <p> The <code>foaf:tipjar</code> property was created following <a href="http://rdfweb.org/mt/foaflog/archives/2004/02/12/20.07.32/">discussions</a> about simple, lightweight mechanisms that could be used to encourage rewards and payment for content exchanged online. An agent's <code>foaf:tipjar</code> page(s) could describe informal ("Send me a postcard!", "here's my book, music and movie wishlist") or formal (machine-readable micropayment information) information about how that agent can be paid or rewarded. The reward is not associated with any particular action or content from the agent concerned. A link to a service such as <a href="http://www.paypal.com/">PayPal</a> is the sort of thing we might expect to find in a tipjar document. </p> <p> Note that the value of a <code>foaf:tipjar</code> property is just a document (which can include anchors into HTML pages). We expect, but do not currently specify, that this will evolve into a hook for finding more machine-readable information to support payments, rewards. The <code>foaf:OnlineAccount</code> machinery is also relevant, although the information requirements for automating payments are not currently clear. </p> - + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_depiction"> + <h3>Property: foaf:depiction</h3> + <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + <tr><th>Range:</th> + <td> <a href="#term_Image">Image</a> +</td> </tr> + </table> + <p> +The <code>foaf:depiction</code> property is a relationship between a thing and an +<code>foaf:Image</code> that depicts it. As such it is an inverse of the +<code>foaf:depicts</code> relationship. +</p> + +<p> +A common use of <code>foaf:depiction</code> (and <code>foaf:depicts</code>) is to indicate +the contents of a digital image, for example the people or objects represented in an +online photo gallery. +</p> + +<p> +Extensions to this basic idea include '<a +href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in +photos), as well as richer photo metadata through the mechanism of using SVG paths to +indicate the <em>regions</em> of an image which depict some particular thing. See <a +href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> +for tools and details. +</p> + +<p> +The basic notion of 'depiction' could also be extended to deal with multimedia content +(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. +</p> + +<p> +The <code>foaf:depiction</code> property is a super-property of the more specific property +<code>foaf:img</code>, which is used more sparingly. You stand in a +<code>foaf:depiction</code> relation to <em>any</em> <code>foaf:Image</code> that depicts +you, whereas <code>foaf:img</code> is typically used to indicate a few images that are +particularly representative. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_sha1"> + <h3>Property: foaf:sha1</h3> + <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Document">Document</a> +</td></tr> + + </table> + <p> +The <code>foaf:sha1</code> property relates a <code>foaf:Document</code> to the textual form of +a SHA1 hash of (some representation of) its contents. +</p> + +<p class="editorial"> +The design for this property is neither complete nor coherent. The <code>foaf:Document</code> +class is currently used in a way that allows multiple instances at different URIs to have the +'same' contents (and hence hash). If <code>foaf:sha1</code> is an owl:InverseFunctionalProperty, +we could deduce that several such documents were the self-same thing. A more careful design is +needed, which distinguishes documents in a broad sense from byte sequences. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_birthday"> + <h3>Property: foaf:birthday</h3> + <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:birthday</code> property is a relationship between a <code>foaf:Agent</code> +and a string representing the month and day in which they were born (Gregorian calendar). +See <a href="http://rdfweb.org/topic/BirthdayIssue">BirthdayIssue</a> for details of related properties that can +be used to describe such things in more flexible ways. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_logo"> + <h3>Property: foaf:logo</h3> + <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The <code>foaf:logo</code> property is used to indicate a graphical logo of some kind. +<em>It is probably underspecified...</em> +</p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_schoolHomepage"> - <h3>Property: foaf:schoolHomepage</h3> - <em>schoolHomepage</em> - A homepage of a school attended by the person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_publications"> + <h3>Property: foaf:publications</h3> + <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> + <td>unstable</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>schoolHomepage</code> property relates a <code>foaf:Person</code> to a -<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a School that the -person attended. +The <code>foaf:publications</code> property indicates a <code>foaf:Document</code> +listing (primarily in human-readable form) some publications associated with the +<code>foaf:Person</code>. Such documents are typically published alongside one's +<code>foaf:homepage</code>. </p> -<p> -FOAF does not (currently) define a class for 'School' (if it did, it would probably be as -a sub-class of <code>foaf:Organization</code>). The original application area for -<code>foaf:schoolHomepage</code> was for 'schools' in the British-English sense; however -American-English usage has dominated, and it is now perfectly reasonable to describe -Universities, Colleges and post-graduate study using <code>foaf:schoolHomepage</code>. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_givenname"> + <h3>Property: foaf:givenname</h3> + <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> <p> -This very basic facility provides a basis for a low-cost, decentralised approach to -classmate-reunion and suchlike. Instead of requiring a central database, we can use FOAF -to express claims such as 'I studied <em>here</em>' simply by mentioning a -school's homepage within FOAF files. Given the homepage of a school, it is easy for -FOAF aggregators to lookup this property in search of people who attended that school. +There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_dnaChecksum"> - <h3>Property: foaf:dnaChecksum</h3> - <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_accountName"> + <h3>Property: foaf:accountName</h3> + <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> - + <tr><th>Domain:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td></tr> </table> <p> -The <code>foaf:dnaChecksum</code> property is mostly a joke, but -also a reminder that there will be lots of different identifying -properties for people, some of which we might find disturbing. +The <code>foaf:accountName</code> property of a <code>foaf:OnlineAccount</code> is a +textual representation of the account name (unique ID) associated with that account. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_based_near"> - <h3>Property: foaf:based_near</h3> - <em>based near</em> - A location that something is based near, for some broadly human notion of near. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_topic_interest"> + <h3>Property: foaf:topic_interest</h3> + <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> </table> - <!-- note: is this mis-specified? perhaps range ought to also be SpatialThing, so we - can have multiple labels on the same point? --> + <p class="editorial"> +The <code>foaf:topic_interest</code> property is generally found to be confusing and ill-defined +and is a candidate for removal. The goal was to be link a person to some thing that is a topic +of their interests (rather than, per <code>foaf:interest</code> to a page that is about such a +topic). +</p> -<p>The <code>foaf:based_near</code> relationship relates two "spatial -things" -(anything that can <em>be somewhere</em>), the latter typically -described using the geo:lat / geo:long -<a href="http://www.w3.org/2003/01/geo/wgs84_pos#">geo-positioning vocabulary</a> -(See <a href="http://esw.w3.org/topic/GeoInfo">GeoInfo</a> in the W3C semweb -wiki for details). This allows us to say describe the typical latitute and -longitude of, say, a Person (people are spatial things - they can be -places) without implying that a precise location has been given. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_workplaceHomepage"> + <h3>Property: foaf:workplaceHomepage</h3> + <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:workplaceHomepage</code> of a <code>foaf:Person</code> is a +<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a +<code>foaf:Organization</code> that they work for. </p> -<p>We do not say much about what 'near' means in this context; it is a -'rough and ready' concept. For a more precise treatment, see -<a href="http://esw.w3.org/topic/GeoOnion">GeoOnion vocab</a> design -discussions, which are aiming to produce a more sophisticated vocabulary for -such purposes. +<p> +By directly relating people to the homepages of their workplace, we have a simple convention +that takes advantage of a set of widely known identifiers, while taking care not to confuse the +things those identifiers identify (ie. organizational homepages) with the actual organizations +those homepages describe. </p> -<p> FOAF files often make use of the <code>contact:nearestAirport</code> property. This -illustrates the distinction between FOAF documents (which may make claims using <em>any</em> RDF -vocabulary) and the core FOAF vocabulary defined by this specification. For further reading on -the use of <code>nearestAirport</code> see <a -href="http://rdfweb.org/topic/UsingContactNearestAirport">UsingContactNearestAirport</a> in the -FOAF wiki. +<div class="example"> +<p> +For example, Dan Brickley works at W3C. Dan is a <code>foaf:Person</code> with a +<code>foaf:homepage</code> of http://rdfweb.org/people/danbri/; W3C is a +<code>foaf:Organization</code> with a <code>foaf:homepage</code> of http://www.w3.org/. This +allows us to say that Dan has a <code>foaf:workplaceHomepage</code> of http://www.w3.org/. +</p> + +<pre> +&lt;foaf:Person&gt; + &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; +&lt;/foaf:Person&gt; +</pre> +</div> + + +<p> +Note that several other FOAF properties work this way; +<code>foaf:schoolHomepage</code> is the most similar. In general, FOAF often indirectly +identifies things via Web page identifiers where possible, since these identifiers are widely +used and known. FOAF does not currently have a term for the name of the relation (eg. +"workplace") that holds +between a <code>foaf:Person</code> and an <code>foaf:Organization</code> that they work for. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_depicts"> <h3>Property: foaf:depicts</h3> <em>depicts</em> - A thing depicted in this representation. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Image">Image</a> </td></tr> </table> <p> The <code>foaf:depicts</code> property is a relationship between a <code>foaf:Image</code> and something that the image depicts. As such it is an inverse of the <code>foaf:depiction</code> relationship. See <code>foaf:depiction</code> for further notes. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_weblog"> - <h3>Property: foaf:weblog</h3> - <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_primaryTopic"> + <h3>Property: foaf:primaryTopic</h3> + <em>primary topic</em> - The primary topic of some page or document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Document">Document</a> +</td></tr> + + </table> + <p> +The <code>foaf:primaryTopic</code> property relates a document to the +main thing that the document is about. +</p> + +<p> +The <code>foaf:primaryTopic</code> property is <em>functional</em>: for +any document it applies to, it can have at most one value. This is +useful, as it allows for data merging. In many cases it may be difficult +for third parties to determine the primary topic of a document, but in +a useful number of cases (eg. descriptions of movies, restaurants, +politicians, ...) it should be reasonably obvious. Documents are very +often the most authoritative source of information about their own +primary topics, although this cannot be guaranteed since documents cannot be +assumed to be accurate, honest etc. +</p> + +<p> +It is an inverse of the <code>foaf:isPrimaryTopicOf</code> property, which relates a +thing to a document <em>primarily</em> about that thing. The choice between these two +properties is purely pragmatic. When describing documents, we +use <code>foaf:primaryTopic</code> former to point to the things they're about. When +describing things (people etc.), it is useful to be able to directly cite documents which +have those things as their main topic - so we use <code>foaf:isPrimaryTopicOf</code>. In this +way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a +href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they +have descriptions of. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_yahooChatID"> + <h3>Property: foaf:yahooChatID</h3> + <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> + </table> <p> -The <code>foaf:weblog</code> property relates a <code>foaf:Agent</code> to a weblog of -that agent. +The <code>foaf:yahooChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the Yahoo online Chat system. +See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their +service. Yahoo chat IDs are also used across several other Yahoo services, including email and +<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_geekcode"> <h3>Property: foaf:geekcode</h3> <em>geekcode</em> - A textual geekcode for this person, see http://www.geekcode.com/geek.html <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> </table> <p> The <code>foaf:geekcode</code> property is used to represent a 'Geek Code' for some <code>foaf:Person</code>. </p> <p> See the <a href="http://www.geekcode.com/geek.html">Code of the Geeks</a> specification for details of the code, which provides a somewhat frivolous and willfully obscure mechanism for characterising technical expertise, interests and habits. The <code>foaf:geekcode</code> property is not bound to any particular version of the code. The last published version of the code was v3.12 in March 1996. </p> <p> As the <a href="http://www.geekcode.com/">Geek Code</a> website notes, the code played a small (but amusing) part in the history of the Internet. The <code>foaf:geekcode</code> property exists in acknowledgement of this history. It'll never be 1996 again. </p> <p> Note that the Geek Code is a densely packed collections of claims about the person it applies to; to express these claims explicitly in RDF/XML would be incredibly verbose. The syntax of the Geek Code allows for '&lt;' and '&gt;' characters, which have special meaning in RDF/XML. Consequently these should be carefully escaped in markup. </p> <p> An example Geek Code: </p> <p class="example"> GED/J d-- s:++>: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++>$ PE++>$ Y++ PGP++ t- 5+++ X++ R+++>$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** </p> <p> ...would be written in FOAF RDF/XML as follows: </p> <p class="example"> &lt;foaf:geekcode&gt; GED/J d-- s:++&amp;gt;: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++&amp;gt;$ PE++&amp;gt;$ Y++ PGP++ t- 5+++ X++ R+++&amp;gt;$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** &lt;/foaf:geekcode&gt; </p> <p> See also the <a href="http://www.everything2.com/index.pl?node=GEEK%20CODE">geek code</a> entry in <a href="http://www.everything2.com/">everything2</a>, which tells us that <em>the geek code originated in 1993; it was inspired (according to the inventor) by previous "bear", "smurf" and "twink" style-and-sexual-preference codes from lesbian and gay newsgroups</em>. There is also a <a href="http://www.ebb.org/ungeek/">Geek Code Decoder Page</a> and a form-based <a href="http://www.joereiss.net/geek/geek.html">generator</a>. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_topic"> - <h3>Property: foaf:topic</h3> - <em>topic</em> - A topic of some page or document. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_family_name"> + <h3>Property: foaf:family_name</h3> + <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> + <td> <a href="#term_Person">Person</a> </td></tr> </table> - <p> -The <code>foaf:topic</code> property relates a document to a thing that the document is -about. -</p> - -<p> -As such it is an inverse of the <code>foaf:page</code> property, which relates a thing to -a document about that thing. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_fundedBy"> - <h3>Property: foaf:fundedBy</h3> - <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - </table> - <p> -The <code>foaf:fundedBy</code> property relates something to something else that has provided -funding for it. -</p> -<p class="editorial"> -This property is under-specified, experimental, and should be considered liable to change. +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> +<p> +There is also a simple <code>foaf:name</code> property. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_mbox"> - <h3>Property: foaf:mbox</h3> - <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_icqChatID"> + <h3>Property: foaf:icqChatID</h3> + <em>ICQ chat ID</em> - An ICQ chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -The <code>foaf:mbox</code> property is a relationship between the owner of a mailbox and -a mailbox. These are typically identified using the mailto: URI scheme (see <a -href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). -</p> - -<p> -Note that there are many mailboxes (eg. shared ones) which are not the -<code>foaf:mbox</code> of anyone. Furthermore, a person can have multiple -<code>foaf:mbox</code> properties. -</p> - -<p> -In FOAF, we often see <code>foaf:mbox</code> used as an indirect way of identifying its -owner. This works even if the mailbox is itself out of service (eg. 10 years old), since -the property is defined in terms of its primary owner, and doesn't require the mailbox to -actually be being used for anything. +The <code>foaf:icqChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the ICQ Chat system. +See the <a href="http://web.icq.com/icqchat/">icq chat</a> site for more details of the 'icq' +service. Their "<a href="http://www.icq.com/products/whatisicq.html">What is ICQ?</a>" document +provides a basic overview, while their "<a href="http://company.icq.com/info/">About Us</a> page +notes that ICQ has been acquired by AOL. Despite the relationship with AOL, ICQ is at +the time of writing maintained as a separate identity from the AIM brand (see +<code>foaf:aimChatID</code>). </p> <p> -Many people are wary of sharing information about their mailbox addresses in public. To -address such concerns whilst continuing the FOAF convention of indirectly identifying -people by referring to widely known properties, FOAF also provides the -<code>foaf:mbox_sha1sum</code> mechanism, which is a relationship between a person and -the value you get from passing a mailbox URI to the SHA1 mathematical function. +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_gender"> - <h3>Property: foaf:gender</h3> - <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_img"> + <h3>Property: foaf:img</h3> + <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> - + <tr><th>Range:</th> + <td> <a href="#term_Image">Image</a> +</td> </tr> </table> <p> -The <code>foaf:gender</code> property relates a <code>foaf:Agent</code> (typically a -<code>foaf:Person</code>) to a string representing its gender. In most cases the value -will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). -Like all FOAF properties, there is in general no requirement to use -<code>foaf:gender</code> in any particular document or description. Values other than -'male' and 'female' may be used, but are not enumerated here. The <code>foaf:gender</code> -mechanism is not intended to capture the full variety of biological, social and sexual -concepts associated with the word 'gender'. +The <code>foaf:img</code> property relates a <code>foaf:Person</code> to a +<code>foaf:Image</code> that represents them. Unlike its super-property +<code>foaf:depiction</code>, we only use <code>foaf:img</code> when an image is +particularly representative of some person. The analogy is with the image(s) that might +appear on someone's homepage, rather than happen to appear somewhere in their photo album. </p> <p> -Anything that has a <code>foaf:gender</code> property will be some kind of -<code>foaf:Agent</code>. However there are kinds of <code>foaf:Agent</code> to -which the concept of gender isn't applicable (eg. a <code>foaf:Group</code>). FOAF does not -currently include a class corresponding directly to "the type of thing that has a gender". -At any point in time, a <code>foaf:Agent</code> has at most one value for -<code>foaf:gender</code>. FOAF does not treat <code>foaf:gender</code> as a -<em>static</em> property; the same individual may have different values for this property -at different times. +Unlike the more general <code>foaf:depiction</code> property (and its inverse, +<code>foaf:depicts</code>), the <code>foaf:img</code> property is only used with +representations of people (ie. instances of <code>foaf:Person</code>). So you can't use +it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more +restricted than <code>foaf:depiction</code> so we can have a useful way of picking out a +reasonable image to represent someone. FOAF defines <code>foaf:img</code> as a +sub-property of <code>foaf:depiction</code>, which means that the latter relationship is +implied whenever two things are related by the former. </p> <p> -Note that FOAF's notion of gender isn't defined biologically or anatomically - this would -be tricky since we have a broad notion that applies to all <code>foaf:Agent</code>s -(including robots - eg. Bender from Futurama is 'male'). As stressed above, -FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated -with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise -between the clinical and the social/psychological. In general, a person will be the best -authority on their <code>foaf:gender</code>. Feedback on this design is -particularly welcome (via the FOAF mailing list, -<a href="http://rdfweb.org/mailman/listinfo/rdfweb-dev">rdfweb-dev</a>). We have tried to -be respectful of diversity without attempting to catalogue or enumerate that diversity. +Note that <code>foaf:img</code> does not have any restrictions on the dimensions, colour +depth, format etc of the <code>foaf:Image</code> it references. </p> <p> -This may also be a good point for a periodic reminder: as with all FOAF properties, -documents that use '<code>foaf:gender</code>' will on occassion be innacurate, misleading -or outright false. FOAF, like all open means of communication, supports <em>lying</em>. - Application authors using -FOAF data should always be cautious in their presentation of unverified information, but be -particularly sensitive to issues and risks surrounding sex and gender (including privacy -and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit -<code>foaf:gender</code> when describing themselves and others, and to allow at least for -values other than 'male' and 'female' as options. Users of information -conveyed via FOAF (as via information conveyed through mobile phone text messages, email, -Internet chat, HTML pages etc.) should be skeptical of unverified information. -</p> - -<!-- -b/g article currently offline. -http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 ---> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_theme"> - <h3>Property: foaf:theme</h3> - <em>theme</em> - A theme. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - - </table> - <p> -The <code>foaf:theme</code> property is rarely used and under-specified. The intention was -to use it to characterise interest / themes associated with projects and groups. Further -work is needed to meet these goals. -</p> +Terminology: note that <code>foaf:img</code> is a property (ie. relationship), and that +<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It +might have been more helpful to call <code>foaf:img</code> 'mugshot' or similar; instead +it is named by analogy to the HTML IMG element. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_firstName"> - <h3>Property: foaf:firstName</h3> - <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_pastProject"> + <h3>Property: foaf:pastProject</h3> + <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> </table> - - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. + <p>After a <code>foaf:Person</code> is no longer involved with a +<code>foaf:currentProject</code>, or has been inactive for some time, a +<code>foaf:pastProject</code> relationship can be used. This indicates that +the <code>foaf:Person</code> was involved with the described project at one +point. </p> <p> -There is also a simple <code>foaf:name</code> property. +If the <code>foaf:Person</code> has stopped working on a project because it +has been completed (successfully or otherwise), <code>foaf:pastProject</code> is +applicable. In general, <code>foaf:currentProject</code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code>foaf:pastProject</code> describes what they've previously been doing. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_homepage"> - <h3>Property: foaf:homepage</h3> - <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_myersBriggs"> + <h3>Property: foaf:myersBriggs</h3> + <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> </table> - <p> -The <code>foaf:homepage</code> property relates something to a homepage about it. -</p> + <!-- todo: expand acronym --> <p> -Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but -constrains <code>foaf:homepage</code> so that there can be only one thing that has any -particular homepage. +The <code>foaf:myersBriggs</code> property represents the Myers Briggs (MBTI) approach to +personality taxonomy. It is included in FOAF as an example of a property +that takes certain constrained values, and to give some additional detail to the FOAF +files of those who choose to include it. The <code>foaf:myersBriggs</code> property applies only to the +<code>foaf:Person</code> class; wherever you see it, you can infer it is being applied to +a person. </p> <p> -A 'homepage' in this sense is a public Web document, typically but not necessarily -available in HTML format. The page has as a <code>foaf:topic</code> the thing whose -homepage it is. The homepage is usually controlled, edited or published by the thing whose -homepage it is; as such one might look to a homepage for information on its owner from its -owner. This works for people, companies, organisations etc. +The <code>foaf:myersBriggs</code> property is interesting in that it illustrates how +FOAF can serve as a carrier for various kinds of information, without necessarily being +commited to any associated worldview. Not everyone will find myersBriggs (or star signs, +or blood types, or the four humours) a useful perspective on human behaviour and +personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses +the underlying theory, any more than the existence of <code>foaf:weblog</code> is an +endorsement of soapboxes. </p> <p> -The <code>foaf:homepage</code> property is a sub-property of the more general -<code>foaf:page</code> property for relating a thing to a page about that thing. See also -<code>foaf:topic</code>, the inverse of the <code>foaf:page</code> property. +The values for <code>foaf:myersBriggs</code> are the following 16 4-letter textual codes: +ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, +ENTP, ISFJ. If multiple of these properties are applicable, they are represented by +applying multiple properties to a person. </p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_isPrimaryTopicOf"> - <h3>Property: foaf:isPrimaryTopicOf</h3> - <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:isPrimaryTopicOf</code> property relates something to a document that is -mainly about it. +<p> +For further reading on MBTI, see various online sources (eg. <a +href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There +are various online sites which offer quiz-based tools for determining a person's MBTI +classification. The owners of the MBTI trademark have probably not approved of these. </p> - <p> -The <code>foaf:isPrimaryTopicOf</code> property is <em>inverse functional</em>: for -any document that is the value of this property, there is at most one thing in the world -that is the primary topic of that document. This is useful, as it allows for data -merging, as described in the documentation for its inverse, <code>foaf:primaryTopic</code>. +This FOAF property suggests some interesting uses, some of which could perhaps be used to +test the claims made by proponents of the MBTI (eg. an analysis of weblog postings +filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are +self-selecting; MBTI categories may not be uniformly appealing to the people they +describe. Further, there is probably a degree of cultural specificity implicit in the +assumptions made by many questionaire-based MBTI tools; the MBTI system may not make +sense in cultural settings beyond those it was created for. </p> <p> -<code>foaf:page</code> is a super-property of <code>foaf:isPrimaryTopicOf</code>. The change -of terminology between the two property names reflects the utility of 'primaryTopic' and its -inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation -to some document X, also has a <code>foaf:page</code> relationship to it. +See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a +href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> +for further background and examples. </p> + <p> -Note that <code>foaf:homepage</code>, is a sub-property of both <code>foaf:page</code> and -<code>foaf:isPrimarySubjectOf</code>. The awkwardly named -<code>foaf:isPrimarySubjectOf</code> is less specific, and can be used with any document -that is primarily about the thing of interest (ie. not just on homepages). +Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting +Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the +trademark in the UK. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div></div> + </div> +</div> +</div> </body> </html> diff --git a/libvocab.py b/libvocab.py index f1197de..f7af588 100755 --- a/libvocab.py +++ b/libvocab.py @@ -1,687 +1,687 @@ #!/usr/bin/env python # total rewrite. --danbri # Usage: # # >>> from libvocab import Vocab, Term, Class, Property # # >>> from libvocab import Vocab, Term, Class, Property # >>> v = Vocab( f='examples/foaf/index.rdf', uri='http://xmlns.com/foaf/0.1/') # >>> dna = v.lookup('http://xmlns.com/foaf/0.1/dnaChecksum') # >>> dna.label # 'DNA checksum' # >>> dna.comment # 'A checksum for the DNA of some thing. Joke.' # >>> dna.id # u'dnaChecksum' # >>> dna.uri # 'http://xmlns.com/foaf/0.1/dnaChecksum' # # # Python OO notes: # http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/ # http://www.daniweb.com/code/snippet354.html # http://docs.python.org/reference/datamodel.html#specialnames # # RDFlib: # http://www.science.uva.nl/research/air/wiki/RDFlib # # http://dowhatimean.net/2006/03/spellchecking-vocabularies-with-sparql # # We define basics, Vocab, Term, Property, Class # and populate them with data from RDF schemas, OWL, translations ... and nearby html files. import rdflib from rdflib import Namespace from rdflib.Graph import Graph from rdflib.Graph import ConjunctiveGraph from rdflib.sparql.sparqlGraph import SPARQLGraph from rdflib.sparql.graphPattern import GraphPattern from rdflib.sparql.bison import Parse from rdflib.sparql import Query FOAF = Namespace('http://xmlns.com/foaf/0.1/') RDFS = Namespace('http://www.w3.org/2000/01/rdf-schema#') XFN = Namespace("http://gmpg.org/xfn/1#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") OWL = Namespace('http://www.w3.org/2002/07/owl#') VS = Namespace('http://www.w3.org/2003/06/sw-vocab-status/ns#') DC = Namespace('http://purl.org/dc/elements/1.1/') DOAP = Namespace('http://usefulinc.com/ns/doap#') SIOC = Namespace('http://rdfs.org/sioc/ns#') SIOCTYPES = Namespace('http://rdfs.org/sioc/types#') SIOCSERVICES = Namespace('http://rdfs.org/sioc/services#') # # TODO: rationalise these two lists. or at least check they are same. import sys, time, re, urllib, getopt import logging import os.path bindings = { u"xfn": XFN, u"rdf": RDF, u"rdfs": RDFS, u"vs": VS } #g = None def speclog(str): sys.stderr.write("LOG: "+str+"\n") # a Term has... (intrinsically and via it's RDFS/OWL description) # uri - a (primary) URI, eg. 'http://xmlns.com/foaf/0.1/workplaceHomepage' # id - a local-to-spec ID, eg. 'workplaceHomepage' # xmlns - an xmlns URI (isDefinedBy, eg. 'http://xmlns.com/foaf/0.1/') # # label - an rdfs:label # comment - an rdfs:comment # # Beyond this, properties vary. Some have vs:status. Some have owl Deprecated. # Some have OWL descriptions, and RDFS descriptions; eg. property range/domain # or class disjointness. def ns_split(uri): regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) return(rez.group(1), rez.group(2)) class Term(object): def __init__(self, uri='file://dev/null'): self.uri = str(uri) self.uri = self.uri.rstrip() # speclog("Parsing URI " + uri) a,b = ns_split(uri) self.id = b self.xmlns = a if self.id==None: speclog("Error parsing URI. "+uri) if self.xmlns==None: speclog("Error parsing URI. "+uri) # print "self.id: "+ self.id + " self.xmlns: " + self.xmlns def uri(self): try: s = self.uri except NameError: self.uri = None s = '[NOURI]' speclog('No URI for'+self) return s def id(self): print "trying id" try: s = self.id except NameError: self.id = None s = '[NOID]' speclog('No ID for'+self) return str(s) def is_external(self, vocab): print "Comparing property URI ",self.uri," with vocab uri: " + vocab.uri return(False) #def __repr__(self): # return(self.__str__) def __str__(self): try: s = self.id except NameError: self.label = None speclog('No label for '+self+' todo: take from uri regex') s = (str(self)) return(str(s)) # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) # self.terms.sort() # self.classes.sort() # self.properties.sort() # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: # print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" - tl = """%s<h3>Classes and Properties (full detail)</h3><div class='termdetails'><br />\n\n""" % tl + tl = """%s<h3>Classes and Properties (full detail)</h3>\n<div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>%s</td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div>""" # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id,"Class", sn, term.label, term.comment, term.status,foo,foo1+foo2+foo3, s) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, "Property", sn, term.label, term.comment, term.status, foo, foo1, s) tl = "%s %s" % (tl, zz) ## ensure termlist tag is closed - return(tl+"</div>") + return(tl+"\n</div>\n</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
312c0d333991332aaeaa8421c93d64a8c3ec49ec
added missing div close I hope
diff --git a/examples/foaf/spec.html b/examples/foaf/spec.html index d9b3501..2508633 100644 --- a/examples/foaf/spec.html +++ b/examples/foaf/spec.html @@ -184,2850 +184,2850 @@ As usual, see the <a href="#sec-changes">changes</a> section for details of the <li><a href="#term_givenname">givenname</a></li> <li><a href="#term_firstName">firstName</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Personal Info</h3> <ul> <li><a href="#term_weblog">weblog</a></li> <li><a href="#term_knows">knows</a></li> <li><a href="#term_interest">interest</a></li> <li><a href="#term_currentProject">currentProject</a></li> <li><a href="#term_pastProject">pastProject</a></li> <li><a href="#term_plan">plan</a></li> <li><a href="#term_based_near">based_near</a></li> <li><a href= "#term_workplaceHomepage">workplaceHomepage</a></li> <li><a href= "#term_workInfoHomepage">workInfoHomepage</a></li> <li><a href="#term_schoolHomepage">schoolHomepage</a></li> <li><a href="#term_topic_interest">topic_interest</a></li> <li><a href="#term_publications">publications</a></li> <li><a href="#term_geekcode">geekcode</a></li> <li><a href="#term_myersBriggs">myersBriggs</a></li> <li><a href="#term_dnaChecksum">dnaChecksum</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Online Accounts / IM</h3> <ul> <li><a href="#term_OnlineAccount">OnlineAccount</a></li> <li><a href= "#term_OnlineChatAccount">OnlineChatAccount</a></li> <li><a href= "#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a></li> <li><a href= "#term_OnlineGamingAccount">OnlineGamingAccount</a></li> <li><a href="#term_holdsAccount">holdsAccount</a></li> <li><a href= "#term_accountServiceHomepage">accountServiceHomepage</a></li> <li><a href="#term_accountName">accountName</a></li> <li><a href="#term_icqChatID">icqChatID</a></li> <li><a href="#term_msnChatID">msnChatID</a></li> <li><a href="#term_aimChatID">aimChatID</a></li> <li><a href="#term_jabberID">jabberID</a></li> <li><a href="#term_yahooChatID">yahooChatID</a></li> </ul> </div> <div style="clear: left;"></div> <div class="rdf-proplist"> <h3>Projects and Groups</h3> <ul> <li><a href="#term_Project">Project</a></li> <li><a href="#term_Organization">Organization</a></li> <li><a href="#term_Group">Group</a></li> <li><a href="#term_member">member</a></li> <li><a href= "#term_membershipClass">membershipClass</a></li> <li><a href="#term_fundedBy">fundedBy</a></li> <li><a href="#term_theme">theme</a></li> </ul> </div> <div class="rdf-proplist"> <h3>Documents and Images</h3> <ul> <li><a href="#term_Document">Document</a></li> <li><a href="#term_Image">Image</a></li> <li><a href= "#term_PersonalProfileDocument">PersonalProfileDocument</a></li> <li><a href="#term_topic">topic</a> (<a href= "#term_page">page</a>)</li> <li><a href="#term_primaryTopic">primaryTopic</a></li> <li><a href="#term_tipjar">tipjar</a></li> <li><a href="#term_sha1">sha1</a></li> <li><a href="#term_made">made</a> (<a href= "#term_maker">maker</a>)</li> <li><a href="#term_thumbnail">thumbnail</a></li> <li><a href="#term_logo">logo</a></li> </ul> </div> </div> <div style="clear: left;"></div> <h2 id="sec-example">Example</h2> <p>Here is a very basic document describing a person:</p> <div class="example"> <pre> &lt;foaf:Person rdf:about="#me" xmlns:foaf="http://xmlns.com/foaf/0.1/"&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:mbox_sha1sum&gt;241021fb0e6289f92815fc210f9e9137262c252e&lt;/foaf:mbox_sha1sum&gt; &lt;foaf:homepage rdf:resource="http://danbri.org/" /&gt; &lt;foaf:img rdf:resource="/images/me.jpg" /&gt; &lt;/foaf:Person&gt; </pre> </div> <p>This brief example introduces the basics of FOAF. It basically says, "there is a <a href="#term_Person">foaf:Person</a> with a <a href="#term_name">foaf:name</a> property of 'Dan Brickley' and a <a href="#term_mbox_sha1sum">foaf:mbox_sha1sum</a> property of 241021fb0e6289f92815fc210f9e9137262c252e; this person stands in a <a href="#term_homepage">foaf:homepage</a> relationship to a thing called http://danbri.org/ and a <a href= "#term_img">foaf:img</a> relationship to a thing referenced by a relative URI of /images/me.jpg</p> <div style="clear: left;"></div> <!-- ================================================================== --> <h2 id="sec-intro">1 Introduction: FOAF Basics</h2> <h3 id="sec-sw">The Semantic Web</h3> <blockquote> <p> <em> To a computer, the Web is a flat, boring world, devoid of meaning. This is a pity, as in fact documents on the Web describe real objects and imaginary concepts, and give particular relationships between them. For example, a document might describe a person. The title document to a house describes a house and also the ownership relation with a person. Adding semantics to the Web involves two things: allowing documents which have information in machine-readable forms, and allowing links to be created with relationship values. Only when we have this extra level of semantics will we be able to use computer power to help us exploit the information to a greater extent than our own reading. </em> - Tim Berners-Lee &quot;W3 future directions&quot; keynote, 1st World Wide Web Conference Geneva, May 1994 </p> </blockquote> <h3 id="sec-foafsw">FOAF and the Semantic Web</h3> <p> FOAF, like the Web itself, is a linked information system. It is built using decentralised <a href="http://www.w3.org/2001/sw/">Semantic Web</a> technology, and has been designed to allow for integration of data across a variety of applications, Web sites and services, and software systems. To achieve this, FOAF takes a liberal approach to data exchange. It does not require you to say anything at all about yourself or others, nor does it place any limits on the things you can say or the variety of Semantic Web vocabularies you may use in doing so. This current specification provides a basic "dictionary" of terms for talking about people and the things they make and do.</p> <p>FOAF was designed to be used alongside other such dictionaries ("schemas" or "ontologies"), and to beusable with the wide variety of generic tools and services that have been created for the Semantic Web. For example, the W3C work on <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a> provides us with a rich query language for consulting databases of FOAF data, while the <a href="http://www.w3.org/2004/02/skos/">SKOS</a> initiative explores in more detail than FOAF the problem of describing topics, categories, "folksonomies" and subject hierarchies. Meanwhile, other W3C groups are working on improved mechanisms for encoding all kinds of RDF data (including but not limited to FOAF) within Web pages: see the work of the <a href="http://www.w3.org/2001/sw/grddl-wg/">GRDDL</a> and <a href="http://www.w3.org/TR/xhtml-rdfa-primer/">RDFa</a> efforts for more detail. The Semantic Web provides us with an <em>architecture for collaboration</em>, allowing complex technical challenges to be shared by a loosely-coordinated community of developers. </p> <p>The FOAF project is based around the use of <em>machine readable</em> Web homepages for people, groups, companies and other kinds of thing. To achieve this we use the "FOAF vocabulary" to provide a collection of basic terms that can be used in these Web pages. At the heart of the FOAF project is a set of definitions designed to serve as a dictionary of terms that can be used to express claims about the world. The initial focus of FOAF has been on the description of people, since people are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on.</p> <p>The FOAF Vocabulary definitions presented here are written using a computer language (RDF/OWL) that makes it easy for software to process some basic facts about the terms in the FOAF vocabulary, and consequently about the things described in FOAF documents. A FOAF document, unlike a traditional Web page, can be combined with other FOAF documents to create a unified database of information. FOAF is a <a href="http://www.w3.org/DesignIssues/LinkedData.html">Linked Data</a> system, in that it based around the idea of linking together a Web of decentralised descriptions.</p> <h3 id="sec-basicidea">The Basic Idea</h3> <p>The basic idea is pretty simple. If people publish information in the FOAF document format, machines will be able to make use of that information. If those files contain "see also" references to other such documents in the Web, we will have a machine-friendly version of today's hypertext Web. Computer programs will be able to scutter around a Web of documents designed for machines rather than humans, storing the information they find, keeping a list of "see also" pointers to other documents, checking digital signatures (for the security minded) and building Web pages and question-answering services based on the harvested documents.</p> <p>So, what is the 'FOAF document format'? FOAF files are just text documents (well, Unicode documents). They are written in XML syntax, and adopt the conventions of the Resource Description Framework (RDF). In addition, the FOAF vocabulary defines some useful constructs that can appear in FOAF files, alongside other RDF vocabularies defined elsewhere. For example, FOAF defines categories ('classes') such as <code>foaf:Person</code>, <code>foaf:Document</code>, <code>foaf:Image</code>, alongside some handy properties of those things, such as <code>foaf:name</code>, <code>foaf:mbox</code> (ie. an internet mailbox), <code>foaf:homepage</code> etc., as well as some useful kinds of relationship that hold between members of these categories. For example, one interesting relationship type is <code>foaf:depiction</code>. This relates something (eg. a <code>foaf:Person</code>) to a <code>foaf:Image</code>. The FOAF demos that feature photos and listings of 'who is in which picture' are based on software tools that parse RDF documents and make use of these properties.</p> <p>The specific contents of the FOAF vocabulary are detailed in this <a href="http://xmlns.com/foaf/0.1/">FOAF namespace document</a>. In addition to the FOAF vocabulary, one of the most interesting features of a FOAF file is that it can contain "see Also" pointers to other FOAF files. This provides a basis for automatic harvesting tools to traverse a Web of interlinked files, and learn about new people, documents, services, data...</p> <p>The remainder of this specification describes how to publish and interpret descriptions such as these on the Web, using RDF/XML for syntax (file format) and terms from FOAF. It introduces a number of categories (RDF classes such as 'Person') and properties (relationship and attribute types such as 'mbox' or 'workplaceHomepage'). Each term definition is provided in both human and machine-readable form, hyperlinked for quick reference.</p> <h2 id="sec-for">What's FOAF for?</h2> <p>For a good general introduction to FOAF, see Edd Dumbill's article, <a href= "http://www-106.ibm.com/developerworks/xml/library/x-foaf.html">XML Watch: Finding friends with XML and RDF</a> (June 2002, IBM developerWorks). Information about the use of FOAF <a href= "http://rdfweb.org/2002/01/photo/">with image metadata</a> is also available.</p> <p>The <a href= "http://rdfweb.org/2002/01/photo/">co-depiction</a> experiment shows a fun use of the vocabulary. Jim Ley's <a href= "http://www.jibbering.com/svg/AnnotateImage.html">SVG image annotation tool</a> show the use of FOAF with detailed image metadata, and provide tools for labelling image regions within a Web browser. To create a FOAF document, you can use Leigh Dodd's <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">FOAF-a-matic</a> javascript tool. To query a FOAF dataset via IRC, you can use Edd Dumbill's <a href="http://usefulinc.com/foaf/foafbot">FOAFbot</a> tool, an IRC 'community support agent'. For more information on FOAF and related projects, see the <a href= "http://rdfweb.org/foaf/">FOAF project home page</a>. </p> <h2 id="sec-bg">Background</h2> <p>FOAF is a collaborative effort amongst Semantic Web developers on the FOAF ([email protected]) mailing list. The name 'FOAF' is derived from traditional internet usage, an acronym for 'Friend of a Friend'.</p> <p>The name was chosen to reflect our concern with social networks and the Web, urban myths, trust and connections. Other uses of the name continue, notably in the documentation and investigation of Urban Legends (eg. see the <a href= "http://www.urbanlegends.com/">alt.folklore.urban archive</a> or <a href="http://www.snopes.com/">snopes.com</a>), and other FOAF stories. Our use of the name 'FOAF' for a Web vocabulary and document format is intended to complement, rather than replace, these prior uses. FOAF documents describe the characteristics and relationships amongst friends of friends, and their friends, and the stories they tell.</p> <h2 id="sec-standards">FOAF and Standards</h2> <p>It is important to understand that the FOAF <em>vocabulary</em> as specified in this document is not a standard in the sense of <a href= "http://www.iso.ch/iso/en/ISOOnline.openerpage">ISO Standardisation</a>, or that associated with <a href= "http://www.w3.org/">W3C</a> <a href= "http://www.w3.org/Consortium/Process/">Process</a>.</p> <p>FOAF depends heavily on W3C's standards work, specifically on XML, XML Namespaces, RDF, and OWL. All FOAF <em>documents</em> must be well-formed RDF/XML documents. The FOAF vocabulary, by contrast, is managed more in the style of an <a href= "http://www.opensource.org/">Open Source</a> or <a href= "http://www.gnu.org/philosophy/free-sw.html">Free Software</a> project than as an industry standardarisation effort (eg. see <a href="http://www.jabber.org/jeps/jep-0001.html">Jabber JEPs</a>).</p> <p>This specification contributes a vocabulary, "FOAF", to the Semantic Web, specifying it using W3C's <a href= "http://www.w3.org/RDF/">Resource Description Framework</a> (RDF). As such, FOAF adopts by reference both a syntax (using XML) a data model (RDF graphs) and a mathematically grounded definition for the rules that underpin the FOAF design.</p> <h2 id="sec-nsdoc">The FOAF Vocabulary Description</h2> <p>This specification serves as the FOAF "namespace document". As such it describes the FOAF vocabulary and the terms (<a href= "http://www.w3.org/RDF/">RDF</a> classes and properties) that constitute it, so that <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> applications can use those terms in a variety of RDF-compatible document formats and applications.</p> <p>This document presents FOAF as a <a href= "http://www.w3.org/2001/sw/">Semantic Web</a> vocabulary or <em>Ontology</em>. The FOAF vocabulary is pretty simple, pragmatic and designed to allow simultaneous deployment and extension. FOAF is intended for widescale use, but its authors make no commitments regarding its suitability for any particular purpose.</p> <h3 id="sec-evolution">Evolution and Extension of FOAF</h3> <p>The FOAF vocabulary is identified by the namespace URI '<code>http://xmlns.com/foaf/0.1/</code>'. Revisions and extensions of FOAF are conducted through edits to this document, which by convention is accessible in the Web via the namespace URI. For practical and deployment reasons, note that <b>we do not update the namespace URI as the vocabulary matures</b>. </p> <p>The core of FOAF now is considered stable, and the version number of <em>this specification</em> reflects this stability. However, it long ago became impractical to update the namespace URI without causing huge disruption to both producers and consumers of FOAF data. We are therefore left with the digits "0.1" in our URI. This stands as a warning to all those who might embed metadata in their vocabulary identifiers. </p> <p> The evolution of FOAF is best considered in terms of the stability of individual vocabulary terms, rather than the specification as a whole. As terms stabilise in usage and documentation, they progress through the categories '<strong>unstable</strong>', '<strong>testing</strong>' and '<strong>stable</strong>'.</p><!--STATUSINFO--> <p>The properties and types defined here provide some basic useful concepts for use in FOAF descriptions. Other vocabulary (eg. the <a href="http://dublincore.org/">Dublin Core</a> metadata elements for simple bibliographic description), RSS 1.0 etc can also be mixed in with FOAF terms, as can local extensions. FOAF is designed to be extended. The <a href= "http://wiki.foaf-project.org/FoafVocab">FoafVocab</a> page in the FOAF wiki lists a number of extension vocabularies that are particularly applicable to use with FOAF.</p> <h2 id="sec-autodesc">FOAF Auto-Discovery: Publishing and Linking FOAF files</h2> <p>If you publish a FOAF self-description (eg. using <a href= "http://www.ldodds.com/foaf/foaf-a-matic.html">foaf-a-matic</a>) you can make it easier for tools to find your FOAF by putting markup in the <code>head</code> of your HTML homepage. It doesn't really matter what filename you choose for your FOAF document, although <code>foaf.rdf</code> is a common choice. The linking markup is as follows:</p> <div class="example"> <pre> &lt;link rel="meta" type="application/rdf+xml" title="FOAF" href="<em>http://example.com/~you/foaf.rdf</em>"/&gt; </pre> </div> <p>...although of course change the <em>URL</em> to point to your own FOAF document. See also: more on <a href= "http://rdfweb.org/mt/foaflog/archives/000041.html">FOAF autodiscovery</a> and services that make use of it.</p> <h2 id="sec-foafandrdf">FOAF and RDF</h2> <p>Why does FOAF use <a href= "http://www.w3.org/RDF/">RDF</a>?</p> <p>FOAF is an application of the Resource Description Framework (RDF) because the subject area we're describing -- people -- has so many competing requirements that a standalone format could not do them all justice. By using RDF, FOAF gains a powerful extensibility mechanism, allowing FOAF-based descriptions can be mixed with claims made in <em>any other RDF vocabulary</em></p> <p>People are the things that link together most of the other kinds of things we describe in the Web: they make documents, attend meetings, are depicted in photos, and so on. Consequently, there are many many things that we might want to say about people, not to mention these related objects (ie. documents, photos, meetings etc).</p> <p>FOAF as a vocabulary cannot incorporate everything we might want to talk about that is related to people, or it would be as large as a full dictionary. Instead of covering all topics within FOAF itself, we buy into a larger framework - RDF - that allows us to take advantage of work elsewhere on more specific description vocabularies (eg. for geographical / mapping data).</p> <p>RDF provides FOAF with a way to mix together different descriptive vocabularies in a consistent way. Vocabularies can be created by different communites and groups as appropriate and mixed together as required, without needing any centralised agreement on how terms from different vocabularies can be written down in XML.</p> <p>This mixing happens in two ways: firstly, RDF provides an underlying model of (typed) objects and their attributes or relationships. <code>foaf:Person</code> is an example of a type of object (a "<em>class</em>"), while <code>foaf:knows</code> and <code>foaf:name</code> are examples of a relationship and an attribute of an <code>foaf:Person</code>; in RDF we call these "<em>properties</em>". Any vocabulary described in RDF shares this basic model, which is discernable in the syntax for RDF, and which removes one level of confusion in <em>understanding</em> a given vocabulary, making it simpler to comprehend and therefore reuse a vocabulary that you have not written yourself. This is the minimal <em>self-documentation</em> that RDF gives you.</p> <p>Secondly, there are mechanisms for saying which RDF properties are connected to which classes, and how different classes are related to each other, using RDF Syntax and OWL. These can be quite general (all RDF properties by default come from an <code>rdf:Resource</code> for example) or very specific and precise (for example by using <a href= "http://www.w3.org/2001/sw/WebOnt/">OWL</a> constructs, as in the <code>foaf:Group</code> example below. This is another form of self-documentation, which allows you to connect different vocabularies together as you please. An example of this is given below where the <code>foaf:based_near</code> property has a domain and range (types of class at each end of the property) from a different namespace altogether.</p> <p>In summary then, RDF is self-documenting in ways which enable the creation and combination of vocabularies in a devolved manner. This is particularly important for a vocabulary which describes people, since people connect to many other domains of interest, which it would be impossible (as well as suboptimal) for a single group to describe adequately in non-geological time.</p> <p>RDF is usually written using XML syntax, but behaves in rather different ways to 'vanilla' XML: the same RDF can be written in many different ways in XML. This means that SAX and DOM XML parsers are not adequate to deal with RDF/XML. If you want to process the data, you will need to use one of the many RDF toolkits available, such as Jena (Java) or Redland (C). <a href= "http://lists.w3.org/Archives/Public/www-rdf-interest/">RDF Interest Group</a> members can help with issues which may arise; there is also the <a href= "http://rdfweb.org/mailman/listinfo/rdfweb-dev">[email protected]</a> mailing list which is the main list for FOAF, and two active and friendly <a href= "http://esw.w3.org/topic/InternetRelayChat">IRC</a> channels: <a href="irc://irc.freenode.net/#rdfig">#rdfig</a> and <a href= "irc://irc.freenode.net/#foaf">#foaf</a> on <a href= "http://www.freenode.net/">freenode</a>.</p> <h2 id="sec-crossref">FOAF cross-reference: Listing FOAF Classes and Properties</h2> <p>FOAF introduces the following classes and properties. View this document's source markup to see the RDF/XML version.</p> <!-- the following is the script-generated list of classes and properties --> <div class="azlist"> <p>Classes: | <a href="#term_Agent">Agent</a> | <a href="#term_Document">Document</a> | <a href="#term_Group">Group</a> | <a href="#term_Image">Image</a> | <a href="#term_OnlineAccount">OnlineAccount</a> | <a href="#term_OnlineChatAccount">OnlineChatAccount</a> | <a href="#term_OnlineEcommerceAccount">OnlineEcommerceAccount</a> | <a href="#term_OnlineGamingAccount">OnlineGamingAccount</a> | <a href="#term_Organization">Organization</a> | <a href="#term_Person">Person</a> | <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> | <a href="#term_Project">Project</a> | </p> <p>Properties: | <a href="#term_accountName">accountName</a> | <a href="#term_accountServiceHomepage">accountServiceHomepage</a> | <a href="#term_aimChatID">aimChatID</a> | <a href="#term_based_near">based_near</a> | <a href="#term_birthday">birthday</a> | <a href="#term_currentProject">currentProject</a> | <a href="#term_depiction">depiction</a> | <a href="#term_depicts">depicts</a> | <a href="#term_dnaChecksum">dnaChecksum</a> | <a href="#term_family_name">family_name</a> | <a href="#term_firstName">firstName</a> | <a href="#term_fundedBy">fundedBy</a> | <a href="#term_geekcode">geekcode</a> | <a href="#term_gender">gender</a> | <a href="#term_givenname">givenname</a> | <a href="#term_holdsAccount">holdsAccount</a> | <a href="#term_homepage">homepage</a> | <a href="#term_icqChatID">icqChatID</a> | <a href="#term_img">img</a> | <a href="#term_interest">interest</a> | <a href="#term_isPrimaryTopicOf">isPrimaryTopicOf</a> | <a href="#term_jabberID">jabberID</a> | <a href="#term_knows">knows</a> | <a href="#term_logo">logo</a> | <a href="#term_made">made</a> | <a href="#term_maker">maker</a> | <a href="#term_mbox">mbox</a> | <a href="#term_mbox_sha1sum">mbox_sha1sum</a> | <a href="#term_member">member</a> | <a href="#term_membershipClass">membershipClass</a> | <a href="#term_msnChatID">msnChatID</a> | <a href="#term_myersBriggs">myersBriggs</a> | <a href="#term_name">name</a> | <a href="#term_nick">nick</a> | <a href="#term_page">page</a> | <a href="#term_pastProject">pastProject</a> | <a href="#term_phone">phone</a> | <a href="#term_plan">plan</a> | <a href="#term_primaryTopic">primaryTopic</a> | <a href="#term_publications">publications</a> | <a href="#term_schoolHomepage">schoolHomepage</a> | <a href="#term_sha1">sha1</a> | <a href="#term_surname">surname</a> | <a href="#term_theme">theme</a> | <a href="#term_thumbnail">thumbnail</a> | <a href="#term_tipjar">tipjar</a> | <a href="#term_title">title</a> | <a href="#term_topic">topic</a> | <a href="#term_topic_interest">topic_interest</a> | <a href="#term_weblog">weblog</a> | <a href="#term_workInfoHomepage">workInfoHomepage</a> | <a href="#term_workplaceHomepage">workplaceHomepage</a> | <a href="#term_yahooChatID">yahooChatID</a> | </p> </div> <div class="termlist"><h3>Classes and Properties (full detail)</h3><div class='termdetails'><br /> - <div class="specterm" id="term_OnlineChatAccount"> + <div class="specterm" id="term_OnlineEcommerceAccount"> + <h3>Class: foaf:OnlineEcommerceAccount</h3> + <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Online Account">Online Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineEcommerceAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +buying and/or selling of goods, services etc. Examples include <a +href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a +href="http://www.paypal.com/">PayPal</a>, <a +href="http://www.thinkgeek.com/">thinkgeek</a>, etc. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineAccount"> + <h3>Class: foaf:OnlineAccount</h3> + <em>Online Account</em> - An online account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_account name">account name</a> + <a href="#term_account service homepage">account service homepage</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_holds account">holds account</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_Online E-commerce Account">Online E-commerce Account</a> + <a href="#term_Online Chat Account">Online Chat Account</a> + <a href="#term_Online Gaming Account">Online Gaming Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineAccount</code> represents the provision of some form of online +service, by some party (indicated indirectly via a +<code>foaf:accountServiceHomepage</code>) to some <code>foaf:Agent</code>. The +<code>foaf:holdsAccount</code> property of the agent is used to indicate accounts that are +associated with the agent. +</p> + +<p> +See <code>foaf:OnlineChatAccount</code> for an example. Other sub-classes include +<code>foaf:OnlineEcommerceAccount</code> and <code>foaf:OnlineGamingAccount</code>. +</p> + + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineChatAccount"> <h3>Class: foaf:OnlineChatAccount</h3> <em>Online Chat Account</em> - An online chat account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Online Account">Online Account</a> </td></tr> </table> <p> A <code>foaf:OnlineChatAccount</code> is a <code>foaf:OnlineAccount</code> devoted to chat / instant messaging. </p> <p> This is a generalization of the FOAF Chat ID properties, <code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, <code>foaf:msnChatID</code>, <code>foaf:icqChatID</code> and <code>foaf:yahooChatID</code>. </p> <p> Unlike those simple properties, <code>foaf:OnlineAccount</code> and associated FOAF terms allows us to describe a great variety of online accounts, without having to anticipate them in the FOAF vocabulary. </p> <p> For example, here is a description of an IRC chat account, specific to the Freenode IRC network: </p> <div class="example"> <pre> &lt;foaf:Person&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:holdsAccount&gt; &lt;foaf:OnlineAccount&gt; &lt;rdf:type rdf:resource="http://xmlns.com/foaf/0.1/OnlineChatAccount"/&gt; &lt;foaf:accountServiceHomepage rdf:resource="http://www.freenode.net/irc_servers.shtml"/&gt; &lt;foaf:accountName&gt;danbri&lt;/foaf:accountName&gt; &lt;/foaf:OnlineAccount&gt; &lt;/foaf:holdsAccount&gt; &lt;/foaf:Person&gt; </pre> </div> <p> Note that it may be impolite to carelessly reveal someone else's chat identifier (which might also serve as an indicate of email address) As with email, there are privacy and anti-SPAM considerations. FOAF does not currently provide a way to represent an obfuscated chat ID (ie. there is no parallel to the <code>foaf:mbox</code> / <code>foaf:mbox_sha1sum</code> mapping). </p> <p> In addition to the generic <code>foaf:OnlineAccount</code> and <code>foaf:OnlineChatAccount</code> mechanisms, FOAF also provides several convenience chat ID properties (<code>foaf:jabberID</code>, <code>foaf:aimChatID</code>, <code>foaf:icqChatID</code>, <code>foaf:msnChatID</code>,<code>foaf:yahooChatID</code>). These serve as as a shorthand for some common cases; their use may not always be appropriate. </p> <p class="editorial"> We should specify some mappings between the abbreviated and full representations of <a href="http://www.jabber.org/">Jabber</a>, <a href="http://www.aim.com/">AIM</a>, <a href="http://chat.msn.com/">MSN</a>, <a href="http://web.icq.com/icqchat/">ICQ</a>, <a href="http://chat.yahoo.com/">Yahoo!</a> and <a href="http://chat.msn.com/">MSN</a> chat accounts. This requires us to identify an appropriate <code>foaf:accountServiceHomepage</code> for each. If we wanted to make the <code>foaf:OnlineAccount</code> mechanism even more generic, we could invent a relationship that holds between a <code>foaf:OnlineAccount</code> instance and a convenience property. To continue the example above, we could describe how <a href="http://www.freenode.net/">Freenode</a> could define a property 'fn:freenodeChatID' corresponding to Freenode online accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_OnlineEcommerceAccount"> - <h3>Class: foaf:OnlineEcommerceAccount</h3> - <em>Online E-commerce Account</em> - An online e-commerce account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_Group"> + <h3>Class: foaf:Group</h3> + <em>Group</em> - A class of Agents. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - + <td>stable</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_member">member</a> + </td></tr> <tr><th>subClassOf</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -A <code>foaf:OnlineEcommerceAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -buying and/or selling of goods, services etc. Examples include <a -href="http://www.amazon.com/">Amazon</a>, <a href="http://www.ebay.com/">eBay</a>, <a -href="http://www.paypal.com/">PayPal</a>, <a -href="http://www.thinkgeek.com/">thinkgeek</a>, etc. +The <code>foaf:Group</code> class represents a collection of individual agents (and may +itself play the role of a <code>foaf:Agent</code>, ie. something that can perform actions). +</p> +<p> +This concept is intentionally quite broad, covering informal and +ad-hoc groups, long-lived communities, organizational groups within a workplace, etc. Some +such groups may have associated characteristics which could be captured in RDF (perhaps a +<code>foaf:homepage</code>, <code>foaf:name</code>, mailing list etc.). </p> +<p> +While a <code>foaf:Group</code> has the characteristics of a <code>foaf:Agent</code>, it +is also associated with a number of other <code>foaf:Agent</code>s (typically people) who +constitute the <code>foaf:Group</code>. FOAF provides a mechanism, the +<code>foaf:membershipClass</code> property, which relates a <code>foaf:Group</code> to a +sub-class of the class <code>foaf:Agent</code> who are members of the group. This is a +little complicated, but allows us to make group membership rules explicit. +</p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_OnlineGamingAccount"> - <h3>Class: foaf:OnlineGamingAccount</h3> - <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - <tr><th>subClassOf</th> - <td> <a href="#term_Online Account">Online Account</a> - </td></tr> - </table> - <p> -A <code>foaf:OnlineGamingAccount</code> is a <code>foaf:OnlineAccount</code> devoted to -online gaming. + +<p>The markup (shown below) for defining a group is both complex and powerful. It +allows group membership rules to match against any RDF-describable characteristics of the potential +group members. As FOAF and similar vocabularies become more expressive in their ability to +describe individuals, the <code>foaf:Group</code> mechanism for categorising them into +groups also becomes more powerful. +</p> + +<p> +While the formal description of membership criteria for a <code>foaf:Group</code> may +be complex, the basic mechanism for saying that someone is in a <code>foaf:Group</code> is +very simple. We simply use a <code>foaf:member</code> property of the +<code>foaf:Group</code> to indicate the agents that are members of the group. For example: + +</p> + +<div class="example"> + +<pre> +&lt;foaf:Group&gt; + &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; + &lt;foaf:member&gt; + &lt;foaf:Person&gt; + &lt;foaf:name&gt;Libby Miller&lt;/foaf:name&gt; + &lt;foaf:homepage rdf:resource="http://ilrt.org/people/libby/"/&gt; + &lt;foaf:workplaceHomepage rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; + &lt;/foaf:Person&gt; + &lt;/foaf:member&gt; +&lt;/foaf:Group&gt; +</pre> +</div> + + + +<p> +Behind the scenes, further RDF statements can be used to express the rules for being a +member of this group. End-users of FOAF need not pay attention to these details. </p> + <p> -Examples might include <a href="http://everquest.station.sony.com/">EverQuest</a>, -<a href="http://www.xbox.com/live/">Xbox live</a>, <a -href="http://nwn.bioware.com/">Neverwinter Nights</a>, etc., as well as older text-based -systems (MOOs, MUDs and suchlike). +Here is an example. We define a <code>foaf:Group</code> representing those people who +are ILRT staff members. The <code>foaf:membershipClass</code> property connects the group (conceived of as a social +entity and agent in its own right) with the class definition for those people who +constitute it. In this case, the rule is that all group members are in the +ILRTStaffPerson class, which is in turn populated by all those things that are a +<code>foaf:Person</code> and which have a <code>foaf:workplaceHomepage</code> of +http://www.ilrt.bris.ac.uk/. This is typical: FOAF groups are created by +specifying a sub-class of <code>foaf:Agent</code> (in fact usually this +will be a sub-class of <code>foaf:Person</code>), and giving criteria +for which things fall in or out of the sub-class. For this, we use the +<code>owl:onProperty</code> and <code>owl:hasValue</code> properties, +indicating the property/value pairs which must be true of matching +agents. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_Image"> - <h3>Class: foaf:Image</h3> - <em>Image</em> - An image. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>in-domain-of:</th> - <td> <a href="#term_depicts">depicts</a> - <a href="#term_thumbnail">thumbnail</a> - </td></tr> - <tr><th>in-range-of:</th> - <td> <a href="#term_depiction">depiction</a> - <a href="#term_image">image</a> - <a href="#term_thumbnail">thumbnail</a> -</td></tr> - </table> - <p> -The class <code>foaf:Image</code> is a sub-class of <code>foaf:Document</code> -corresponding to those documents which are images. +<div class="example"> +<pre> +&lt;!-- here we see a FOAF group described. + each foaf group may be associated with an OWL definition + specifying the class of agents that constitute the group's membership --&gt; +&lt;foaf:Group&gt; + &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; + &lt;foaf:membershipClass&gt; + &lt;owl:Class rdf:about="http://ilrt.example.com/groups#ILRTStaffPerson"&gt; + &lt;rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Person"/&gt; + &lt;rdfs:subClassOf&gt; + &lt;owl:Restriction&gt; + &lt;owl:onProperty rdf:resource="http://xmlns.com/foaf/0.1/workplaceHomepage"/&gt; + &lt;owl:hasValue rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; + &lt;/owl:Restriction&gt; + &lt;/rdfs:subClassOf&gt; + &lt;/owl:Class&gt; + &lt;/foaf:membershipClass&gt; +&lt;/foaf:Group&gt; +</pre> +</div> + + +<p> +Note that while these example OWL rules for being in the eg:ILRTStaffPerson class are +based on a <code>foaf:Person</code> having a particular +<code>foaf:workplaceHomepage</code>, this places no obligations on the authors of actual +FOAF documents to include this information. If the information <em>is</em> included, then +generic OWL tools may infer that some person is an eg:ILRTStaffPerson. To go the extra +step and infer that some eg:ILRTStaffPerson is a <code>foaf:member</code> of the group +whose <code>foaf:name</code> is "ILRT staff", tools will need some knowledge of the way +FOAF deals with groups. In other words, generic OWL technology gets us most of the way, +but the full <code>foaf:Group</code> machinery requires extra work for implimentors. </p> <p> -Digital images (such as JPEG, PNG, GIF bitmaps, SVG diagrams etc.) are examples of -<code>foaf:Image</code>. +The current design names the relationship as pointing <em>from</em> the group, +to the member. This is convenient when writing XML/RDF that encloses the members within +markup that describes the group. Alternate representations of the same content are +allowed in RDF, so you can write claims about the Person and the Group without having to +nest either description inside the other. For (brief) example: </p> -<!-- much more we could/should say here --> +<div class="example"> +<pre> +&lt;foaf:Group&gt; + &lt;foaf:member rdf:nodeID="libby"/&gt; + &lt;!-- more about the group here --&gt; +&lt;/foaf:Group&gt; +&lt;foaf:Person rdf:nodeID="libby"&gt; + &lt;!-- more about libby here --&gt; +&lt;/foaf:Person&gt; +</pre> +</div> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_Project"> - <h3>Class: foaf:Project</h3> - <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - - </table> - <p> -The <code>foaf:Project</code> class represents the class of things that are 'projects'. These -may be formal or informal, collective or individual. It is often useful to indicate the -<code>foaf:homepage</code> of a <code>foaf:Project</code>. +<p> +There is a FOAF <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> +associated with this FOAF term. A design goal is to make the most of W3C's <a +href="http://www.w3.org/2001/sw/WebOnt">OWL</a> language for representing group-membership +criteria, while also making it easy to leverage existing groups and datasets available +online (eg. buddylists, mailing list membership lists etc). Feedback on the current design +is solicited! Should we consider using SPARQL queries instead, for example? </p> -<p class="editorial"> -Further work is needed to specify the connections between this class and the FOAF properties -<code>foaf:currentProject</code> and <code>foaf:pastProject</code>. -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_Agent"> <h3>Class: foaf:Agent</h3> <em>Agent</em> - An agent (eg. person, group, software or physical artifact). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> - <a href="#term_made">made</a> + <td> <a href="#term_made">made</a> + <a href="#term_holds account">holds account</a> <a href="#term_gender">gender</a> - <a href="#term_ICQ chat ID">ICQ chat ID</a> - <a href="#term_Yahoo chat ID">Yahoo chat ID</a> - <a href="#term_personal mailbox">personal mailbox</a> - <a href="#term_weblog">weblog</a> - <a href="#term_birthday">birthday</a> - <a href="#term_AIM chat ID">AIM chat ID</a> + <a href="#term_MSN chat ID">MSN chat ID</a> <a href="#term_jabber ID">jabber ID</a> + <a href="#term_AIM chat ID">AIM chat ID</a> + <a href="#term_birthday">birthday</a> + <a href="#term_weblog">weblog</a> + <a href="#term_ICQ chat ID">ICQ chat ID</a> + <a href="#term_personal mailbox">personal mailbox</a> <a href="#term_tipjar">tipjar</a> - <a href="#term_holds account">holds account</a> - <a href="#term_MSN chat ID">MSN chat ID</a> + <a href="#term_sha1sum of a personal mailbox URI name">sha1sum of a personal mailbox URI name</a> + <a href="#term_Yahoo chat ID">Yahoo chat ID</a> </td></tr> <tr><th>in-range-of:</th> - <td> <a href="#term_member">member</a> - <a href="#term_maker">maker</a> + <td> <a href="#term_maker">maker</a> + <a href="#term_member">member</a> </td></tr> <tr><th>has subclass</th> <td> <a href="#term_Group">Group</a> - <a href="#term_Person">Person</a> <a href="#term_Organization">Organization</a> + <a href="#term_Person">Person</a> </td></tr> </table> <p> The <code>foaf:Agent</code> class is the class of agents; things that do stuff. A well known sub-class is <code>foaf:Person</code>, representing people. Other kinds of agents include <code>foaf:Organization</code> and <code>foaf:Group</code>. </p> <p> The <code>foaf:Agent</code> class is useful in a few places in FOAF where <code>foaf:Person</code> would have been overly specific. For example, the IM chat ID properties such as <code>jabberID</code> are typically associated with people, but sometimes belong to software bots. </p> <!-- todo: write rdfs:domain statements for those properties --> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_Document"> - <h3>Class: foaf:Document</h3> - <em>Document</em> - A document. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>in-domain-of:</th> - <td> <a href="#term_topic">topic</a> - <a href="#term_primary topic">primary topic</a> - <a href="#term_sha1sum (hex)">sha1sum (hex)</a> - </td></tr> - <tr><th>in-range-of:</th> - <td> <a href="#term_page">page</a> - <a href="#term_workplace homepage">workplace homepage</a> - <a href="#term_schoolHomepage">schoolHomepage</a> - <a href="#term_weblog">weblog</a> - <a href="#term_work info homepage">work info homepage</a> - <a href="#term_publications">publications</a> - <a href="#term_interest">interest</a> - <a href="#term_tipjar">tipjar</a> - <a href="#term_is primary topic of">is primary topic of</a> - <a href="#term_account service homepage">account service homepage</a> - <a href="#term_homepage">homepage</a> -</td></tr> <tr><th>has subclass</th> - <td> <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> - </td></tr> - </table> - <p> -The <code>foaf:Document</code> class represents those things which are, broadly conceived, -'documents'. -</p> - -<p> -The <code>foaf:Image</code> class is a sub-class of <code>foaf:Document</code>, since all images -are documents. -</p> - -<p class="editorial"> -We do not (currently) distinguish precisely between physical and electronic documents, or -between copies of a work and the abstraction those copies embody. The relationship between -documents and their byte-stream representation needs clarification (see <code>foaf:sha1</code> -for related issues). -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_PersonalProfileDocument"> <h3>Class: foaf:PersonalProfileDocument</h3> <em>PersonalProfileDocument</em> - A personal profile RDF document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Document">Document</a> </td></tr> </table> <p> The <code>foaf:PersonalProfileDocument</code> class represents those things that are a <code>foaf:Document</code>, and that use RDF to describe properties of the person who is the <code>foaf:maker</code> of the document. There is just one <code>foaf:Person</code> described in the document, ie. the person who <code>foaf:made</code> it and who will be its <code>foaf:primaryTopic</code>. </p> <p> The <code>foaf:PersonalProfileDocument</code> class, and FOAF's associated conventions for describing it, captures an important deployment pattern for the FOAF vocabulary. FOAF is very often used in public RDF documents made available through the Web. There is a colloquial notion that these "FOAF files" are often <em>somebody's</em> FOAF file. Through <code>foaf:PersonalProfileDocument</code> we provide a machine-readable expression of this concept, providing a basis for FOAF documents to make claims about their maker and topic. </p> <p> When describing a <code>foaf:PersonalProfileDocument</code> it is typical (and useful) to describe its associated <code>foaf:Person</code> using the <code>foaf:maker</code> property. Anything that is a <code>foaf:Person</code> and that is the <code>foaf:maker</code> of some <code>foaf:Document</code> will be the <code>foaf:primaryTopic</code> of that <code>foaf:Document</code>. Although this can be inferred, it is helpful to include this information explicitly within the <code>foaf:PersonalProfileDocument</code>. </p> <p> For example, here is a fragment of a personal profile document which describes its author explicitly: </p> <div class="example"> <pre> &lt;foaf:Person rdf:nodeID="p1"&gt; &lt;foaf:name&gt;Dan Brickley&lt;/foaf:name&gt; &lt;foaf:homepage rdf:resource="http://rdfweb.org/people/danbri/"/&gt; &lt;!-- etc... --&gt; &lt;/foaf:Person&gt; &lt;foaf:PersonalProfileDocument rdf:about=""&gt; &lt;foaf:maker rdf:nodeID="p1"/&gt; &lt;foaf:primaryTopic rdf:nodeID="p1"/&gt; &lt;/foaf:PersonalProfileDocument&gt; </pre> </div> <p> Note that a <code>foaf:PersonalProfileDocument</code> will have some representation as RDF. Typically this will be in W3C's RDF/XML syntax, however we leave open the possibility for the use of other notations, or representational conventions including automated transformations from HTML (<a href="http://www.w3.org/2004/01/rdxh/spec">GRDDL</a> spec for one such technique). </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_OnlineGamingAccount"> + <h3>Class: foaf:OnlineGamingAccount</h3> + <em>Online Gaming Account</em> - An online gaming account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Online Account">Online Account</a> + </td></tr> + </table> + <p> +A <code>foaf:OnlineGamingAccount</code> is a <code>foaf:OnlineAccount</code> devoted to +online gaming. +</p> + +<p> +Examples might include <a href="http://everquest.station.sony.com/">EverQuest</a>, +<a href="http://www.xbox.com/live/">Xbox live</a>, <a +href="http://nwn.bioware.com/">Neverwinter Nights</a>, etc., as well as older text-based +systems (MOOs, MUDs and suchlike). +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Document"> + <h3>Class: foaf:Document</h3> + <em>Document</em> - A document. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>in-domain-of:</th> + <td> <a href="#term_topic">topic</a> + <a href="#term_sha1sum (hex)">sha1sum (hex)</a> + <a href="#term_primary topic">primary topic</a> + </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_work info homepage">work info homepage</a> + <a href="#term_homepage">homepage</a> + <a href="#term_workplace homepage">workplace homepage</a> + <a href="#term_is primary topic of">is primary topic of</a> + <a href="#term_account service homepage">account service homepage</a> + <a href="#term_weblog">weblog</a> + <a href="#term_schoolHomepage">schoolHomepage</a> + <a href="#term_page">page</a> + <a href="#term_tipjar">tipjar</a> + <a href="#term_publications">publications</a> + <a href="#term_interest">interest</a> +</td></tr> <tr><th>has subclass</th> + <td> <a href="#term_PersonalProfileDocument">PersonalProfileDocument</a> + </td></tr> + </table> + <p> +The <code>foaf:Document</code> class represents those things which are, broadly conceived, +'documents'. +</p> + +<p> +The <code>foaf:Image</code> class is a sub-class of <code>foaf:Document</code>, since all images +are documents. +</p> + +<p class="editorial"> +We do not (currently) distinguish precisely between physical and electronic documents, or +between copies of a work and the abstraction those copies embody. The relationship between +documents and their byte-stream representation needs clarification (see <code>foaf:sha1</code> +for related issues). +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Organization"> + <h3>Class: foaf:Organization</h3> + <em>Organization</em> - An organization. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + + <tr><th>subClassOf</th> + <td> <a href="#term_Agent">Agent</a> + </td></tr> + </table> + <p> +The <code>foaf:Organization</code> class represents a kind of <code>foaf:Agent</code> +corresponding to social instititutions such as companies, societies etc. +</p> + +<p class="editorial"> +This is a more 'solid' class than <code>foaf:Group</code>, which allows +for more ad-hoc collections of individuals. These terms, like the corresponding +natural language concepts, have some overlap, but different emphasis. +</p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_Person"> <h3>Class: foaf:Person</h3> <em>Person</em> - A person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_current project">current project</a> - <a href="#term_Surname">Surname</a> - <a href="#term_knows">knows</a> - <a href="#term_firstName">firstName</a> - <a href="#term_family_name">family_name</a> + <td> <a href="#term_knows">knows</a> + <a href="#term_geekcode">geekcode</a> + <a href="#term_work info homepage">work info homepage</a> + <a href="#term_plan">plan</a> + <a href="#term_workplace homepage">workplace homepage</a> <a href="#term_past project">past project</a> + <a href="#term_current project">current project</a> + <a href="#term_image">image</a> + <a href="#term_publications">publications</a> + <a href="#term_Surname">Surname</a> <a href="#term_interest_topic">interest_topic</a> - <a href="#term_workplace homepage">workplace homepage</a> - <a href="#term_myersBriggs">myersBriggs</a> <a href="#term_schoolHomepage">schoolHomepage</a> - <a href="#term_geekcode">geekcode</a> - <a href="#term_publications">publications</a> + <a href="#term_family_name">family_name</a> + <a href="#term_myersBriggs">myersBriggs</a> + <a href="#term_firstName">firstName</a> <a href="#term_interest">interest</a> - <a href="#term_plan">plan</a> - <a href="#term_work info homepage">work info homepage</a> - <a href="#term_image">image</a> </td></tr> <tr><th>in-range-of:</th> <td> <a href="#term_knows">knows</a> </td></tr> <tr><th>subClassOf</th> <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> The <code>foaf:Person</code> class represents people. Something is a <code>foaf:Person</code> if it is a person. We don't nitpic about whether they're alive, dead, real, or imaginary. The <code>foaf:Person</code> class is a sub-class of the <code>foaf:Agent</code> class, since all people are considered 'agents' in FOAF. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Group"> - <h3>Class: foaf:Group</h3> - <em>Group</em> - A class of Agents. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_Image"> + <h3>Class: foaf:Image</h3> + <em>Image</em> - An image. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>testing</td></tr> <tr><th>in-domain-of:</th> - <td> <a href="#term_member">member</a> - </td></tr> - <tr><th>subClassOf</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_thumbnail">thumbnail</a> + <a href="#term_depicts">depicts</a> </td></tr> + <tr><th>in-range-of:</th> + <td> <a href="#term_thumbnail">thumbnail</a> + <a href="#term_depiction">depiction</a> + <a href="#term_image">image</a> +</td></tr> </table> <p> -The <code>foaf:Group</code> class represents a collection of individual agents (and may -itself play the role of a <code>foaf:Agent</code>, ie. something that can perform actions). -</p> -<p> -This concept is intentionally quite broad, covering informal and -ad-hoc groups, long-lived communities, organizational groups within a workplace, etc. Some -such groups may have associated characteristics which could be captured in RDF (perhaps a -<code>foaf:homepage</code>, <code>foaf:name</code>, mailing list etc.). +The class <code>foaf:Image</code> is a sub-class of <code>foaf:Document</code> +corresponding to those documents which are images. </p> <p> -While a <code>foaf:Group</code> has the characteristics of a <code>foaf:Agent</code>, it -is also associated with a number of other <code>foaf:Agent</code>s (typically people) who -constitute the <code>foaf:Group</code>. FOAF provides a mechanism, the -<code>foaf:membershipClass</code> property, which relates a <code>foaf:Group</code> to a -sub-class of the class <code>foaf:Agent</code> who are members of the group. This is a -little complicated, but allows us to make group membership rules explicit. +Digital images (such as JPEG, PNG, GIF bitmaps, SVG diagrams etc.) are examples of +<code>foaf:Image</code>. </p> +<!-- much more we could/should say here --> -<p>The markup (shown below) for defining a group is both complex and powerful. It -allows group membership rules to match against any RDF-describable characteristics of the potential -group members. As FOAF and similar vocabularies become more expressive in their ability to -describe individuals, the <code>foaf:Group</code> mechanism for categorising them into -groups also becomes more powerful. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_Project"> + <h3>Class: foaf:Project</h3> + <em>Project</em> - A project (a collective endeavour of some kind). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:Project</code> class represents the class of things that are 'projects'. These +may be formal or informal, collective or individual. It is often useful to indicate the +<code>foaf:homepage</code> of a <code>foaf:Project</code>. </p> -<p> -While the formal description of membership criteria for a <code>foaf:Group</code> may -be complex, the basic mechanism for saying that someone is in a <code>foaf:Group</code> is -very simple. We simply use a <code>foaf:member</code> property of the -<code>foaf:Group</code> to indicate the agents that are members of the group. For example: - -</p> - -<div class="example"> - -<pre> -&lt;foaf:Group&gt; - &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; - &lt;foaf:member&gt; - &lt;foaf:Person&gt; - &lt;foaf:name&gt;Libby Miller&lt;/foaf:name&gt; - &lt;foaf:homepage rdf:resource="http://ilrt.org/people/libby/"/&gt; - &lt;foaf:workplaceHomepage rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; - &lt;/foaf:Person&gt; - &lt;/foaf:member&gt; -&lt;/foaf:Group&gt; -</pre> -</div> - - - -<p> -Behind the scenes, further RDF statements can be used to express the rules for being a -member of this group. End-users of FOAF need not pay attention to these details. +<p class="editorial"> +Further work is needed to specify the connections between this class and the FOAF properties +<code>foaf:currentProject</code> and <code>foaf:pastProject</code>. </p> - -<p> -Here is an example. We define a <code>foaf:Group</code> representing those people who -are ILRT staff members. The <code>foaf:membershipClass</code> property connects the group (conceived of as a social -entity and agent in its own right) with the class definition for those people who -constitute it. In this case, the rule is that all group members are in the -ILRTStaffPerson class, which is in turn populated by all those things that are a -<code>foaf:Person</code> and which have a <code>foaf:workplaceHomepage</code> of -http://www.ilrt.bris.ac.uk/. This is typical: FOAF groups are created by -specifying a sub-class of <code>foaf:Agent</code> (in fact usually this -will be a sub-class of <code>foaf:Person</code>), and giving criteria -for which things fall in or out of the sub-class. For this, we use the -<code>owl:onProperty</code> and <code>owl:hasValue</code> properties, -indicating the property/value pairs which must be true of matching -agents. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_workplaceHomepage"> + <h3>Property: foaf:workplaceHomepage</h3> + <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:workplaceHomepage</code> of a <code>foaf:Person</code> is a +<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a +<code>foaf:Organization</code> that they work for. </p> -<div class="example"> -<pre> -&lt;!-- here we see a FOAF group described. - each foaf group may be associated with an OWL definition - specifying the class of agents that constitute the group's membership --&gt; -&lt;foaf:Group&gt; - &lt;foaf:name&gt;ILRT staff&lt;/foaf:name&gt; - &lt;foaf:membershipClass&gt; - &lt;owl:Class rdf:about="http://ilrt.example.com/groups#ILRTStaffPerson"&gt; - &lt;rdfs:subClassOf rdf:resource="http://xmlns.com/foaf/0.1/Person"/&gt; - &lt;rdfs:subClassOf&gt; - &lt;owl:Restriction&gt; - &lt;owl:onProperty rdf:resource="http://xmlns.com/foaf/0.1/workplaceHomepage"/&gt; - &lt;owl:hasValue rdf:resource="http://www.ilrt.bris.ac.uk/"/&gt; - &lt;/owl:Restriction&gt; - &lt;/rdfs:subClassOf&gt; - &lt;/owl:Class&gt; - &lt;/foaf:membershipClass&gt; -&lt;/foaf:Group&gt; -</pre> -</div> - - <p> -Note that while these example OWL rules for being in the eg:ILRTStaffPerson class are -based on a <code>foaf:Person</code> having a particular -<code>foaf:workplaceHomepage</code>, this places no obligations on the authors of actual -FOAF documents to include this information. If the information <em>is</em> included, then -generic OWL tools may infer that some person is an eg:ILRTStaffPerson. To go the extra -step and infer that some eg:ILRTStaffPerson is a <code>foaf:member</code> of the group -whose <code>foaf:name</code> is "ILRT staff", tools will need some knowledge of the way -FOAF deals with groups. In other words, generic OWL technology gets us most of the way, -but the full <code>foaf:Group</code> machinery requires extra work for implimentors. +By directly relating people to the homepages of their workplace, we have a simple convention +that takes advantage of a set of widely known identifiers, while taking care not to confuse the +things those identifiers identify (ie. organizational homepages) with the actual organizations +those homepages describe. </p> +<div class="example"> <p> -The current design names the relationship as pointing <em>from</em> the group, -to the member. This is convenient when writing XML/RDF that encloses the members within -markup that describes the group. Alternate representations of the same content are -allowed in RDF, so you can write claims about the Person and the Group without having to -nest either description inside the other. For (brief) example: +For example, Dan Brickley works at W3C. Dan is a <code>foaf:Person</code> with a +<code>foaf:homepage</code> of http://rdfweb.org/people/danbri/; W3C is a +<code>foaf:Organization</code> with a <code>foaf:homepage</code> of http://www.w3.org/. This +allows us to say that Dan has a <code>foaf:workplaceHomepage</code> of http://www.w3.org/. </p> -<div class="example"> <pre> -&lt;foaf:Group&gt; - &lt;foaf:member rdf:nodeID="libby"/&gt; - &lt;!-- more about the group here --&gt; -&lt;/foaf:Group&gt; -&lt;foaf:Person rdf:nodeID="libby"&gt; - &lt;!-- more about libby here --&gt; +&lt;foaf:Person&gt; + &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; + &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; &lt;/foaf:Person&gt; </pre> </div> + <p> -There is a FOAF <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> -associated with this FOAF term. A design goal is to make the most of W3C's <a -href="http://www.w3.org/2001/sw/WebOnt">OWL</a> language for representing group-membership -criteria, while also making it easy to leverage existing groups and datasets available -online (eg. buddylists, mailing list membership lists etc). Feedback on the current design -is solicited! Should we consider using SPARQL queries instead, for example? +Note that several other FOAF properties work this way; +<code>foaf:schoolHomepage</code> is the most similar. In general, FOAF often indirectly +identifies things via Web page identifiers where possible, since these identifiers are widely +used and known. FOAF does not currently have a term for the name of the relation (eg. +"workplace") that holds +between a <code>foaf:Person</code> and an <code>foaf:Organization</code> that they work for. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_Organization"> - <h3>Class: foaf:Organization</h3> - <em>Organization</em> - An organization. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_made"> + <h3>Property: foaf:made</h3> + <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>stable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> - <tr><th>subClassOf</th> - <td> <a href="#term_Agent">Agent</a> - </td></tr> </table> <p> -The <code>foaf:Organization</code> class represents a kind of <code>foaf:Agent</code> -corresponding to social instititutions such as companies, societies etc. +The <code>foaf:made</code> property relates a <code>foaf:Agent</code> +to something <code>foaf:made</code> by it. As such it is an +inverse of the <code>foaf:maker</code> property, which relates a thing to +something that made it. See <code>foaf:made</code> for more details on the +relationship between these FOAF terms and related Dublin Core vocabulary. </p> -<p class="editorial"> -This is a more 'solid' class than <code>foaf:Group</code>, which allows -for more ad-hoc collections of individuals. These terms, like the corresponding -natural language concepts, have some overlap, but different emphasis. -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_OnlineAccount"> - <h3>Class: foaf:OnlineAccount</h3> - <em>Online Account</em> - An online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_interest"> + <h3>Property: foaf:interest</h3> + <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>in-domain-of:</th> - <td> <a href="#term_account name">account name</a> - <a href="#term_account service homepage">account service homepage</a> - </td></tr> - <tr><th>in-range-of:</th> - <td> <a href="#term_holds account">holds account</a> -</td></tr> <tr><th>has subclass</th> - <td> <a href="#term_Online E-commerce Account">Online E-commerce Account</a> - <a href="#term_Online Chat Account">Online Chat Account</a> - <a href="#term_Online Gaming Account">Online Gaming Account</a> - </td></tr> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> </table> <p> -A <code>foaf:OnlineAccount</code> represents the provision of some form of online -service, by some party (indicated indirectly via a -<code>foaf:accountServiceHomepage</code>) to some <code>foaf:Agent</code>. The -<code>foaf:holdsAccount</code> property of the agent is used to indicate accounts that are -associated with the agent. +The <code>foaf:interest</code> property represents an interest of a +<code>foaf:Agent</code>, through +indicating a <code>foaf:Document</code> whose <code>foaf:topic</code>(s) broadly +characterises that interest.</p> + +<p class="example"> +For example, we might claim that a person or group has an interest in RDF by saying they +stand in a <code>foaf:interest</code> relationship to the <a +href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying +<em>"this agent is interested in the topic of this page"</em>. +</p> + +<p class="example"> +Uses of <code>foaf:interest</code> include a variety of filtering and resource discovery +applications. It could be used, for example, to help find answers to questions such as +"Find me members of this organisation with an interest in XML who have also contributed to +<a href="http://www.cpan.org/">CPAN</a>)". </p> <p> -See <code>foaf:OnlineChatAccount</code> for an example. Other sub-classes include -<code>foaf:OnlineEcommerceAccount</code> and <code>foaf:OnlineGamingAccount</code>. +This approach to characterising interests is intended to compliment other mechanisms (such +as the use of controlled vocabulary). It allows us to use a widely known set of unique +identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled +syntax, this makes data merging much easier than the use of free-text characterisations of +interest. </p> +<p> +Note that interest does not imply expertise, and that this FOAF term provides no support +for characterising levels of interest: passing fads and lifelong quests are both examples +of someone's <code>foaf:interest</code>. Describing interests in full is a complex +undertaking; <code>foaf:interest</code> provides one basic component of FOAF's approach to +these problems. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_depicts"> - <h3>Property: foaf:depicts</h3> - <em>depicts</em> - A thing depicted in this representation. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_jabberID"> + <h3>Property: foaf:jabberID</h3> + <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Image">Image</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -The <code>foaf:depicts</code> property is a relationship between a <code>foaf:Image</code> -and something that the image depicts. As such it is an inverse of the -<code>foaf:depiction</code> relationship. See <code>foaf:depiction</code> for further notes. +The <code>foaf:jabberID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging +system. +See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber +protocols and tools. </p> +<p> +Jabber, unlike several other online messaging systems, is based on an open, publically +documented protocol specification, and has a variety of open source implementations. Jabber IDs +can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For +the purposes of FOAF, these are all considered to be kinds of <code>foaf:Agent</code> (ie. +things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The +<code>foaf:jabberID</code> property is provided as a basic hook to help support RDF description +of Jabber users and services. +</p> +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_givenname"> - <h3>Property: foaf:givenname</h3> - <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_name"> + <h3>Property: foaf:name</h3> + <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> </table> - + <p>The <code>foaf:name</code> of something is a simple textual string.</p> -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. +<p> +XML language tagging may be used to indicate the language of the name. For example: </p> +<div class="example"> +<code> +&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; +</code> +</div> + <p> -There is also a simple <code>foaf:name</code> property. +FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it +does provide a basic level of interoperability. See the <a +href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for status of work on this issue. +</p> + +<p> +The <code>foaf:name</code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped +values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_msnChatID"> - <h3>Property: foaf:msnChatID</h3> - <em>MSN chat ID</em> - An MSN chat ID <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_img"> + <h3>Property: foaf:img</h3> + <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> - + <tr><th>Range:</th> + <td> <a href="#term_Image">Image</a> +</td> </tr> </table> <p> -The <code>foaf:msnChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the MSN online Chat system. -See Microsoft's the <a href="http://chat.msn.com/">MSN chat</a> site for more details (or for a -message saying <em>"MSN Chat is not currently compatible with your Internet browser and/or -computer operating system"</em> if your computing platform is deemed unsuitable). +The <code>foaf:img</code> property relates a <code>foaf:Person</code> to a +<code>foaf:Image</code> that represents them. Unlike its super-property +<code>foaf:depiction</code>, we only use <code>foaf:img</code> when an image is +particularly representative of some person. The analogy is with the image(s) that might +appear on someone's homepage, rather than happen to appear somewhere in their photo album. </p> -<p class="editorial"> -It is not currently clear how MSN chat IDs relate to the more general Microsoft Passport -identifiers. +<p> +Unlike the more general <code>foaf:depiction</code> property (and its inverse, +<code>foaf:depicts</code>), the <code>foaf:img</code> property is only used with +representations of people (ie. instances of <code>foaf:Person</code>). So you can't use +it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more +restricted than <code>foaf:depiction</code> so we can have a useful way of picking out a +reasonable image to represent someone. FOAF defines <code>foaf:img</code> as a +sub-property of <code>foaf:depiction</code>, which means that the latter relationship is +implied whenever two things are related by the former. </p> -<p>See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. +<p> +Note that <code>foaf:img</code> does not have any restrictions on the dimensions, colour +depth, format etc of the <code>foaf:Image</code> it references. </p> +<p> +Terminology: note that <code>foaf:img</code> is a property (ie. relationship), and that +<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It +might have been more helpful to call <code>foaf:img</code> 'mugshot' or similar; instead +it is named by analogy to the HTML IMG element. +</p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_maker"> - <h3>Property: foaf:maker</h3> - <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_nick"> + <h3>Property: foaf:nick</h3> + <em>nickname</em> - A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>testing</td></tr> + - <tr><th>Range:</th> - <td> <a href="#term_Agent">Agent</a> -</td> </tr> </table> <p> -The <code>foaf:maker</code> property relates something to a -<code>foaf:Agent</code> that <code>foaf:made</code> it. As such it is an -inverse of the <code>foaf:made</code> property. +The <code>foaf:nick</code> property relates a <code>foaf:Person</code> to a short (often +abbreviated) nickname, such as those use in IRC chat, online accounts, and computer +logins. </p> <p> -The <code>foaf:name</code> (or other <code>rdfs:label</code>) of the -<code>foaf:maker</code> of something can be described as the -<code>dc:creator</code> of that thing.</p> - -<p> -For example, if the thing named by the URI -http://rdfweb.org/people/danbri/ has a -<code>foaf:maker</code> that is a <code>foaf:Person</code> whose -<code>foaf:name</code> is 'Dan Brickley', we can conclude that -http://rdfweb.org/people/danbri/ has a <code>dc:creator</code> of 'Dan -Brickley'. +This property is necessarily vague, because it does not indicate any particular naming +control authority, and so cannot distinguish a person's login from their (possibly +various) IRC nicknames or other similar identifiers. However it has some utility, since +many people use the same string (or slight variants) across a variety of such +environments. </p> <p> -FOAF descriptions are encouraged to use <code>dc:creator</code> only for -simple textual names, and to use <code>foaf:maker</code> to indicate -creators, rather than risk confusing creators with their names. This -follows most Dublin Core usage. See <a -href="http://rdfweb.org/topic/UsingDublinCoreCreator">UsingDublinCoreCreator</a> -for details. +For specific controlled sets of names (relating primarily to Instant Messanger accounts), +FOAF provides some convenience properties: <code>foaf:jabberID</code>, +<code>foaf:aimChatID</code>, <code>foaf:msnChatID</code> and +<code>foaf:icqChatID</code>. Beyond this, the problem of representing such accounts is not +peculiar to Instant Messanging, and it is not scaleable to attempt to enumerate each +naming database as a distinct FOAF property. The <code>foaf:OnlineAccount</code> term (and +supporting vocabulary) are provided as a more verbose and more expressive generalisation +of these properties. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_holdsAccount"> - <h3>Property: foaf:holdsAccount</h3> - <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_sha1"> + <h3>Property: foaf:sha1</h3> + <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Document">Document</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Online Account">Online Account</a> -</td> </tr> + </table> <p> -The <code>foaf:holdsAccount</code> property relates a <code>foaf:Agent</code> to an -<code>foaf:OnlineAccount</code> for which they are the sole account holder. See -<code>foaf:OnlineAccount</code> for usage details. +The <code>foaf:sha1</code> property relates a <code>foaf:Document</code> to the textual form of +a SHA1 hash of (some representation of) its contents. +</p> + +<p class="editorial"> +The design for this property is neither complete nor coherent. The <code>foaf:Document</code> +class is currently used in a way that allows multiple instances at different URIs to have the +'same' contents (and hence hash). If <code>foaf:sha1</code> is an owl:InverseFunctionalProperty, +we could deduce that several such documents were the self-same thing. A more careful design is +needed, which distinguishes documents in a broad sense from byte sequences. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_workInfoHomepage"> - <h3>Property: foaf:workInfoHomepage</h3> - <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_aimChatID"> + <h3>Property: foaf:aimChatID</h3> + <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> + </table> <p> -The <code>foaf:workInfoHomepage</code> of a <code>foaf:Person</code> is a -<code>foaf:Document</code> that describes their work. It is generally (but not necessarily) a -different document from their <code>foaf:homepage</code>, and from any -<code>foaf:workplaceHomepage</code>(s) they may have. +The <code>foaf:aimChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. +See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM +screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a +href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. </p> <p> -The purpose of this property is to distinguish those pages you often see, which describe -someone's professional role within an organisation or project. These aren't really homepages, -although they share some characterstics. +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_plan"> - <h3>Property: foaf:plan</h3> - <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_givenname"> + <h3>Property: foaf:givenname</h3> + <em>Given name</em> - The given name of some person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> + </table> - <!-- orig contrib'd by Cardinal --> - -<p>The <code>foaf:plan</code> property provides a space for a -<code>foaf:Person</code> to hold some arbitrary content that would appear in -a traditional '.plan' file. The plan file was stored in a user's home -directory on a UNIX machine, and displayed to people when the user was -queried with the finger utility.</p> + -<p>A plan file could contain anything. Typical uses included brief -comments, thoughts, or remarks on what a person had been doing lately. Plan -files were also prone to being witty or simply osbscure. Others may be more -creative, writing any number of seemingly random compositions in their plan -file for people to stumble upon.</p> +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. +</p> <p> -See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the -Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The -<code>foaf:geekcode</code> property may also be of interest. +There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_family_name"> - <h3>Property: foaf:family_name</h3> - <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_yahooChatID"> + <h3>Property: foaf:yahooChatID</h3> + <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> </table> - - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. + <p> +The <code>foaf:yahooChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the Yahoo online Chat system. +See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their +service. Yahoo chat IDs are also used across several other Yahoo services, including email and +<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. </p> <p> -There is also a simple <code>foaf:name</code> property. +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_accountServiceHomepage"> - <h3>Property: foaf:accountServiceHomepage</h3> - <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_workInfoHomepage"> + <h3>Property: foaf:workInfoHomepage</h3> + <em>work info homepage</em> - A work info homepage of some person; a page about their work for some organization. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <a href="#term_Person">Person</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:accountServiceHomepage</code> property indicates a relationship between a -<code>foaf:OnlineAccount</code> and the homepage of the supporting service provider. +The <code>foaf:workInfoHomepage</code> of a <code>foaf:Person</code> is a +<code>foaf:Document</code> that describes their work. It is generally (but not necessarily) a +different document from their <code>foaf:homepage</code>, and from any +<code>foaf:workplaceHomepage</code>(s) they may have. +</p> + +<p> +The purpose of this property is to distinguish those pages you often see, which describe +someone's professional role within an organisation or project. These aren't really homepages, +although they share some characterstics. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_theme"> - <h3>Property: foaf:theme</h3> - <em>theme</em> - A theme. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_publications"> + <h3>Property: foaf:publications</h3> + <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> - - + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> </table> <p> -The <code>foaf:theme</code> property is rarely used and under-specified. The intention was -to use it to characterise interest / themes associated with projects and groups. Further -work is needed to meet these goals. +The <code>foaf:publications</code> property indicates a <code>foaf:Document</code> +listing (primarily in human-readable form) some publications associated with the +<code>foaf:Person</code>. Such documents are typically published alongside one's +<code>foaf:homepage</code>. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_mbox_sha1sum"> - <h3>Property: foaf:mbox_sha1sum</h3> - <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_currentProject"> + <h3>Property: foaf:currentProject</h3> + <em>current project</em> - A current project this person works on. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> </table> - <p> -A <code>foaf:mbox_sha1sum</code> of a <code>foaf:Person</code> is a textual representation of -the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an -Internet mailbox that they stand in a <code>foaf:mbox</code> relationship to. -</p> + <!-- originally contrib'd by Cardinal --> -<p> -In other words, if you have a mailbox (<code>foaf:mbox</code>) but don't want to reveal its -address, you can take that address and generate a <code>foaf:mbox_sha1sum</code> representation -of it. Just as a <code>foaf:mbox</code> can be used as an indirect identifier for its owner, we -can do the same with <code>foaf:mbox_sha1sum</code> since there is only one -<code>foaf:Person</code> with any particular value for that property. -</p> +<p>A <code>foaf:currentProject</code> relates a <code>foaf:Person</code> +to a <code>foaf:Document</code> indicating some collaborative or +individual undertaking. This relationship +indicates that the <code>foaf:Person</code> has some active role in the +project, such as development, coordination, or support.</p> -<p> -Many FOAF tools use <code>foaf:mbox_sha1sum</code> in preference to exposing mailbox -information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques -include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's -documentation</a>) and the use of <a -href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for -mail filtering. -</p> +<p>When a <code>foaf:Person</code> is no longer involved with a project, or +perhaps is inactive for some time, the relationship becomes a +<code>foaf:pastProject</code>.</p> <p> -Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a -href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's -weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing -whitespace, when computing a <code>foaf:mbox_sha1sum</code> property. +If the <code>foaf:Person</code> has stopped working on a project because it +has been completed (successfully or otherwise), <code>foaf:pastProject</code> is +applicable. In general, <code>foaf:currentProject</code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code>foaf:pastProject</code> describes what they've previously been doing. </p> -<!-- what about Javascript. move refs to wiki maybe. --> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_dnaChecksum"> - <h3>Property: foaf:dnaChecksum</h3> - <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - - </table> - <p> -The <code>foaf:dnaChecksum</code> property is mostly a joke, but -also a reminder that there will be lots of different identifying -properties for people, some of which we might find disturbing. -</p> +<!-- +<p>Generally speaking, anything that a <code>foaf:Person</code> has +<code>foaf:made</code> could also qualify as a +<code>foaf:currentProject</code> or <code>foaf:pastProject</code>.</p> +--> +<p class="editorial"> +Note that this property requires further work. There has been confusion about +whether it points to a thing (eg. something you've made; a homepage for a project, +ie. a <code>foaf:Document</code> or to instances of the class <code>foaf:Project</code>, +which might themselves have a <code>foaf:homepage</code>. In practice, it seems to have been +used in a similar way to <code>foaf:interest</code>, referencing homepages of ongoing projects. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_interest"> - <h3>Property: foaf:interest</h3> - <em>interest</em> - A page about a topic of interest to this person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_page"> + <h3>Property: foaf:page</h3> + <em>page</em> - A page or document about this thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> + <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:interest</code> property represents an interest of a -<code>foaf:Agent</code>, through -indicating a <code>foaf:Document</code> whose <code>foaf:topic</code>(s) broadly -characterises that interest.</p> - -<p class="example"> -For example, we might claim that a person or group has an interest in RDF by saying they -stand in a <code>foaf:interest</code> relationship to the <a -href="http://www.w3.org/RDF/">RDF</a> home page. Loosly, such RDF would be saying -<em>"this agent is interested in the topic of this page"</em>. -</p> - -<p class="example"> -Uses of <code>foaf:interest</code> include a variety of filtering and resource discovery -applications. It could be used, for example, to help find answers to questions such as -"Find me members of this organisation with an interest in XML who have also contributed to -<a href="http://www.cpan.org/">CPAN</a>)". -</p> - -<p> -This approach to characterising interests is intended to compliment other mechanisms (such -as the use of controlled vocabulary). It allows us to use a widely known set of unique -identifiers (Web page URIs) with minimal pre-coordination. Since URIs have a controlled -syntax, this makes data merging much easier than the use of free-text characterisations of -interest. +The <code>foaf:page</code> property relates a thing to a document about that thing. </p> - <p> -Note that interest does not imply expertise, and that this FOAF term provides no support -for characterising levels of interest: passing fads and lifelong quests are both examples -of someone's <code>foaf:interest</code>. Describing interests in full is a complex -undertaking; <code>foaf:interest</code> provides one basic component of FOAF's approach to -these problems. +As such it is an inverse of the <code>foaf:topic</code> property, which relates a document +to a thing that the document is about. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_accountName"> - <h3>Property: foaf:accountName</h3> - <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_icqChatID"> + <h3>Property: foaf:icqChatID</h3> + <em>ICQ chat ID</em> - An ICQ chat ID <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Online Account">Online Account</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> </table> <p> -The <code>foaf:accountName</code> property of a <code>foaf:OnlineAccount</code> is a -textual representation of the account name (unique ID) associated with that account. +The <code>foaf:icqChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the ICQ Chat system. +See the <a href="http://web.icq.com/icqchat/">icq chat</a> site for more details of the 'icq' +service. Their "<a href="http://www.icq.com/products/whatisicq.html">What is ICQ?</a>" document +provides a basic overview, while their "<a href="http://company.icq.com/info/">About Us</a> page +notes that ICQ has been acquired by AOL. Despite the relationship with AOL, ICQ is at +the time of writing maintained as a separate identity from the AIM brand (see +<code>foaf:aimChatID</code>). </p> +<p> +See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_sha1"> - <h3>Property: foaf:sha1</h3> - <em>sha1sum (hex)</em> - A sha1sum hash, in hex. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_maker"> + <h3>Property: foaf:maker</h3> + <em>maker</em> - An agent that made this thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> -</td></tr> + <td>stable</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Agent">Agent</a> +</td> </tr> </table> <p> -The <code>foaf:sha1</code> property relates a <code>foaf:Document</code> to the textual form of -a SHA1 hash of (some representation of) its contents. +The <code>foaf:maker</code> property relates something to a +<code>foaf:Agent</code> that <code>foaf:made</code> it. As such it is an +inverse of the <code>foaf:made</code> property. </p> -<p class="editorial"> -The design for this property is neither complete nor coherent. The <code>foaf:Document</code> -class is currently used in a way that allows multiple instances at different URIs to have the -'same' contents (and hence hash). If <code>foaf:sha1</code> is an owl:InverseFunctionalProperty, -we could deduce that several such documents were the self-same thing. A more careful design is -needed, which distinguishes documents in a broad sense from byte sequences. +<p> +The <code>foaf:name</code> (or other <code>rdfs:label</code>) of the +<code>foaf:maker</code> of something can be described as the +<code>dc:creator</code> of that thing.</p> + +<p> +For example, if the thing named by the URI +http://rdfweb.org/people/danbri/ has a +<code>foaf:maker</code> that is a <code>foaf:Person</code> whose +<code>foaf:name</code> is 'Dan Brickley', we can conclude that +http://rdfweb.org/people/danbri/ has a <code>dc:creator</code> of 'Dan +Brickley'. </p> +<p> +FOAF descriptions are encouraged to use <code>dc:creator</code> only for +simple textual names, and to use <code>foaf:maker</code> to indicate +creators, rather than risk confusing creators with their names. This +follows most Dublin Core usage. See <a +href="http://rdfweb.org/topic/UsingDublinCoreCreator">UsingDublinCoreCreator</a> +for details. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_nick"> - <h3>Property: foaf:nick</h3> - <em>nickname</em> - A short informal nickname characterising an agent (includes login identifiers, IRC and other chat nicknames). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_logo"> + <h3>Property: foaf:logo</h3> + <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> </table> <p> -The <code>foaf:nick</code> property relates a <code>foaf:Person</code> to a short (often -abbreviated) nickname, such as those use in IRC chat, online accounts, and computer -logins. +The <code>foaf:logo</code> property is used to indicate a graphical logo of some kind. +<em>It is probably underspecified...</em> </p> -<p> -This property is necessarily vague, because it does not indicate any particular naming -control authority, and so cannot distinguish a person's login from their (possibly -various) IRC nicknames or other similar identifiers. However it has some utility, since -many people use the same string (or slight variants) across a variety of such -environments. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_surname"> + <h3>Property: foaf:surname</h3> + <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> + + </table> + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> <p> -For specific controlled sets of names (relating primarily to Instant Messanger accounts), -FOAF provides some convenience properties: <code>foaf:jabberID</code>, -<code>foaf:aimChatID</code>, <code>foaf:msnChatID</code> and -<code>foaf:icqChatID</code>. Beyond this, the problem of representing such accounts is not -peculiar to Instant Messanging, and it is not scaleable to attempt to enumerate each -naming database as a distinct FOAF property. The <code>foaf:OnlineAccount</code> term (and -supporting vocabulary) are provided as a more verbose and more expressive generalisation -of these properties. +There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_page"> - <h3>Property: foaf:page</h3> - <em>page</em> - A page or document about this thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_family_name"> + <h3>Property: foaf:family_name</h3> + <em>family_name</em> - The family_name of some person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> </table> - <p> -The <code>foaf:page</code> property relates a thing to a document about that thing. + + +<p>A number of naming constructs are under development to provide +naming substructure; draft properties include <code>foaf:firstName</code>, +<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently +stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue +tracker</a> for design discussions, status and ongoing work on rationalising the FOAF +naming machinery. </p> <p> -As such it is an inverse of the <code>foaf:topic</code> property, which relates a document -to a thing that the document is about. +There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_publications"> - <h3>Property: foaf:publications</h3> - <em>publications</em> - A link to the publications of this person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_accountServiceHomepage"> + <h3>Property: foaf:accountServiceHomepage</h3> + <em>account service homepage</em> - Indicates a homepage of the service provide for this online account. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>unstable</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Online Account">Online Account</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:publications</code> property indicates a <code>foaf:Document</code> -listing (primarily in human-readable form) some publications associated with the -<code>foaf:Person</code>. Such documents are typically published alongside one's -<code>foaf:homepage</code>. -</p> +The <code>foaf:accountServiceHomepage</code> property indicates a relationship between a +<code>foaf:OnlineAccount</code> and the homepage of the supporting service provider. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_isPrimaryTopicOf"> - <h3>Property: foaf:isPrimaryTopicOf</h3> - <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_depiction"> + <h3>Property: foaf:depiction</h3> + <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <a href="#term_Image">Image</a> </td> </tr> </table> <p> -The <code>foaf:isPrimaryTopicOf</code> property relates something to a document that is -mainly about it. +The <code>foaf:depiction</code> property is a relationship between a thing and an +<code>foaf:Image</code> that depicts it. As such it is an inverse of the +<code>foaf:depicts</code> relationship. </p> +<p> +A common use of <code>foaf:depiction</code> (and <code>foaf:depicts</code>) is to indicate +the contents of a digital image, for example the people or objects represented in an +online photo gallery. +</p> <p> -The <code>foaf:isPrimaryTopicOf</code> property is <em>inverse functional</em>: for -any document that is the value of this property, there is at most one thing in the world -that is the primary topic of that document. This is useful, as it allows for data -merging, as described in the documentation for its inverse, <code>foaf:primaryTopic</code>. +Extensions to this basic idea include '<a +href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in +photos), as well as richer photo metadata through the mechanism of using SVG paths to +indicate the <em>regions</em> of an image which depict some particular thing. See <a +href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> +for tools and details. </p> <p> -<code>foaf:page</code> is a super-property of <code>foaf:isPrimaryTopicOf</code>. The change -of terminology between the two property names reflects the utility of 'primaryTopic' and its -inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation -to some document X, also has a <code>foaf:page</code> relationship to it. +The basic notion of 'depiction' could also be extended to deal with multimedia content +(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. </p> + <p> -Note that <code>foaf:homepage</code>, is a sub-property of both <code>foaf:page</code> and -<code>foaf:isPrimarySubjectOf</code>. The awkwardly named -<code>foaf:isPrimarySubjectOf</code> is less specific, and can be used with any document -that is primarily about the thing of interest (ie. not just on homepages). +The <code>foaf:depiction</code> property is a super-property of the more specific property +<code>foaf:img</code>, which is used more sparingly. You stand in a +<code>foaf:depiction</code> relation to <em>any</em> <code>foaf:Image</code> that depicts +you, whereas <code>foaf:img</code> is typically used to indicate a few images that are +particularly representative. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_knows"> - <h3>Property: foaf:knows</h3> - <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_topic_interest"> + <h3>Property: foaf:topic_interest</h3> + <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Person">Person</a> -</td> </tr> + </table> - <p> -The <code>foaf:knows</code> property relates a <code>foaf:Person</code> to another -<code>foaf:Person</code> that he or she knows. -</p> - -<p> -We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. -stalkers need not apply). Since social attitudes and conventions on this topic vary -greatly between communities, counties and cultures, it is not appropriate for FOAF to be -overly-specific here. -</p> - -<p> -If someone <code>foaf:knows</code> a person, it would be usual for -the relation to be reciprocated. However this doesn't mean that there is any obligation -for either party to publish FOAF describing this relationship. A <code>foaf:knows</code> -relationship does not imply friendship, endorsement, or that a face-to-face meeting -has taken place: phone, fax, email, and smoke signals are all perfectly -acceptable ways of communicating with people you know. -</p> -<p> -You probably know hundreds of people, yet might only list a few in your public FOAF file. -That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not -list anyone else in it at all. -This illustrates the Semantic Web principle of partial description: RDF documents -rarely describe the entire picture. There is always more to be said, more information -living elsewhere in the Web (or in our heads...). + <p class="editorial"> +The <code>foaf:topic_interest</code> property is generally found to be confusing and ill-defined +and is a candidate for removal. The goal was to be link a person to some thing that is a topic +of their interests (rather than, per <code>foaf:interest</code> to a page that is about such a +topic). </p> -<p> -Since <code>foaf:knows</code> is vague by design, it may be suprising that it has uses. -Typically these involve combining other RDF properties. For example, an application might -look at properties of each <code>foaf:weblog</code> that was <code>foaf:made</code> by -someone you "<code>foaf:knows</code>". Or check the newsfeed of the online photo archive -for each of these people, to show you recent photos taken by people you know. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_msnChatID"> + <h3>Property: foaf:msnChatID</h3> + <em>MSN chat ID</em> - An MSN chat ID <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:msnChatID</code> property relates a <code>foaf:Agent</code> to a textual +identifier assigned to them in the MSN online Chat system. +See Microsoft's the <a href="http://chat.msn.com/">MSN chat</a> site for more details (or for a +message saying <em>"MSN Chat is not currently compatible with your Internet browser and/or +computer operating system"</em> if your computing platform is deemed unsuitable). </p> -<p> -To provide additional levels of representation beyond mere 'knows', FOAF applications -can do several things. -</p> -<p> -They can use more precise relationships than <code>foaf:knows</code> to relate people to -people. The original FOAF design included two of these ('knowsWell','friend') which we -removed because they were somewhat <em>awkward</em> to actually use, bringing an -inappopriate air of precision to an intrinsically vague concept. Other extensions have -been proposed, including Eric Vitiello's <a -href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for -FOAF. +<p class="editorial"> +It is not currently clear how MSN chat IDs relate to the more general Microsoft Passport +identifiers. </p> -<p> -In addition to using more specialised inter-personal relationship types -(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states -of affairs which imply particular kinds of relationship. So for example, two people who -have the same value for their <code>foaf:workplaceHomepage</code> property are -typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, -but the facts can be written in FOAF nevertheless. Similarly, if there exists a -<code>foaf:Document</code> that has two people listed as its <code>foaf:maker</code>s, -then they are probably collaborators of some kind. Or if two people appear in 100s of -digital photos together, there's a good chance they're friends and/or colleagues. +<p>See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a +more general (and verbose) mechanism for describing IM and chat accounts. </p> -<p> -So FOAF is quite pluralistic in its approach to representing relationships between people. -FOAF is built on top of a general purpose machine language for representing relationships -(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. -The problems are generally social rather than technical; deciding on appropriate ways of -describing these interconnections is a subtle art. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_birthday"> + <h3>Property: foaf:birthday</h3> + <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> + + </table> + <p> +The <code>foaf:birthday</code> property is a relationship between a <code>foaf:Agent</code> +and a string representing the month and day in which they were born (Gregorian calendar). +See <a href="http://rdfweb.org/topic/BirthdayIssue">BirthdayIssue</a> for details of related properties that can +be used to describe such things in more flexible ways. </p> -<p> -Perhaps the most important use of <code>foaf:knows</code> is, alongside the -<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF -file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more -interesting, with each FOAF file saying a little more about people, places, documents, things... -By mentioning other people (via <code>foaf:knows</code> or other relationships), and by -providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for -FOAF indexing tools ('<a href="http://rdfweb.org/topic/ScutterSpec">scutters</a>') to find -your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they -mention, and so on. This makes it possible to build FOAF aggregators without the need for -a centrally managed directory of FOAF files... -</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_mbox"> - <h3>Property: foaf:mbox</h3> - <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_plan"> + <h3>Property: foaf:plan</h3> + <em>plan</em> - A .plan comment, in the tradition of finger and '.plan' files. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> + <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> </table> - <p> -The <code>foaf:mbox</code> property is a relationship between the owner of a mailbox and -a mailbox. These are typically identified using the mailto: URI scheme (see <a -href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). -</p> + <!-- orig contrib'd by Cardinal --> + +<p>The <code>foaf:plan</code> property provides a space for a +<code>foaf:Person</code> to hold some arbitrary content that would appear in +a traditional '.plan' file. The plan file was stored in a user's home +directory on a UNIX machine, and displayed to people when the user was +queried with the finger utility.</p> + +<p>A plan file could contain anything. Typical uses included brief +comments, thoughts, or remarks on what a person had been doing lately. Plan +files were also prone to being witty or simply osbscure. Others may be more +creative, writing any number of seemingly random compositions in their plan +file for people to stumble upon.</p> <p> -Note that there are many mailboxes (eg. shared ones) which are not the -<code>foaf:mbox</code> of anyone. Furthermore, a person can have multiple -<code>foaf:mbox</code> properties. +See <a href="http://www.rajivshah.com/Case_Studies/Finger/Finger.htm">History of the +Finger Protocol</a> by Rajiv Shah for more on this piece of Internet history. The +<code>foaf:geekcode</code> property may also be of interest. </p> -<p> -In FOAF, we often see <code>foaf:mbox</code> used as an indirect way of identifying its -owner. This works even if the mailbox is itself out of service (eg. 10 years old), since -the property is defined in terms of its primary owner, and doesn't require the mailbox to -actually be being used for anything. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_membershipClass"> + <h3>Property: foaf:membershipClass</h3> + <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:membershipClass</code> property relates a <code>foaf:Group</code> to an RDF +class representing a sub-class of <code>foaf:Agent</code> whose instances are all the +agents that are a <code>foaf:member</code> of the <code>foaf:Group</code>. </p> <p> -Many people are wary of sharing information about their mailbox addresses in public. To -address such concerns whilst continuing the FOAF convention of indirectly identifying -people by referring to widely known properties, FOAF also provides the -<code>foaf:mbox_sha1sum</code> mechanism, which is a relationship between a person and -the value you get from passing a mailbox URI to the SHA1 mathematical function. +See <code>foaf:Group</code> for details and examples. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_geekcode"> - <h3>Property: foaf:geekcode</h3> - <em>geekcode</em> - A textual geekcode for this person, see http://www.geekcode.com/geek.html <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_myersBriggs"> + <h3>Property: foaf:myersBriggs</h3> + <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> </table> - <p> -The <code>foaf:geekcode</code> property is used to represent a 'Geek Code' for some -<code>foaf:Person</code>. -</p> + <!-- todo: expand acronym --> <p> -See the <a href="http://www.geekcode.com/geek.html">Code of the Geeks</a> specification for -details of the code, which provides a somewhat frivolous and willfully obscure mechanism for -characterising technical expertise, interests and habits. The <code>foaf:geekcode</code> -property is not bound to any particular version of the code. The last published version -of the code was v3.12 in March 1996. +The <code>foaf:myersBriggs</code> property represents the Myers Briggs (MBTI) approach to +personality taxonomy. It is included in FOAF as an example of a property +that takes certain constrained values, and to give some additional detail to the FOAF +files of those who choose to include it. The <code>foaf:myersBriggs</code> property applies only to the +<code>foaf:Person</code> class; wherever you see it, you can infer it is being applied to +a person. </p> <p> -As the <a href="http://www.geekcode.com/">Geek Code</a> website notes, the code played a small -(but amusing) part in the history of the Internet. The <code>foaf:geekcode</code> property -exists in acknowledgement of this history. It'll never be 1996 again. +The <code>foaf:myersBriggs</code> property is interesting in that it illustrates how +FOAF can serve as a carrier for various kinds of information, without necessarily being +commited to any associated worldview. Not everyone will find myersBriggs (or star signs, +or blood types, or the four humours) a useful perspective on human behaviour and +personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses +the underlying theory, any more than the existence of <code>foaf:weblog</code> is an +endorsement of soapboxes. </p> <p> -Note that the Geek Code is a densely packed collections of claims about the person it applies -to; to express these claims explicitly in RDF/XML would be incredibly verbose. The syntax of the -Geek Code allows for '&lt;' and '&gt;' characters, which have special meaning in RDF/XML. -Consequently these should be carefully escaped in markup. +The values for <code>foaf:myersBriggs</code> are the following 16 4-letter textual codes: +ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, +ENTP, ISFJ. If multiple of these properties are applicable, they are represented by +applying multiple properties to a person. </p> <p> -An example Geek Code: -</p> -<p class="example"> - GED/J d-- s:++>: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++>$ -PE++>$ Y++ PGP++ t- 5+++ X++ R+++>$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** +For further reading on MBTI, see various online sources (eg. <a +href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There +are various online sites which offer quiz-based tools for determining a person's MBTI +classification. The owners of the MBTI trademark have probably not approved of these. </p> <p> -...would be written in FOAF RDF/XML as follows: +This FOAF property suggests some interesting uses, some of which could perhaps be used to +test the claims made by proponents of the MBTI (eg. an analysis of weblog postings +filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are +self-selecting; MBTI categories may not be uniformly appealing to the people they +describe. Further, there is probably a degree of cultural specificity implicit in the +assumptions made by many questionaire-based MBTI tools; the MBTI system may not make +sense in cultural settings beyond those it was created for. </p> -<p class="example"> -&lt;foaf:geekcode&gt; - GED/J d-- s:++&amp;gt;: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ - w--- O- M+ V-- PS++&amp;gt;$ PE++&amp;gt;$ Y++ PGP++ t- 5+++ X++ R+++&amp;gt;$ - tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** -&lt;/foaf:geekcode&gt; +<p> +See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a +href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> +for further background and examples. </p> - <p> -See also the <a href="http://www.everything2.com/index.pl?node=GEEK%20CODE">geek code</a> entry -in <a href="http://www.everything2.com/">everything2</a>, which tells us that <em>the -geek code originated in 1993; it was inspired (according to the inventor) by previous "bear", -"smurf" and "twink" style-and-sexual-preference codes from lesbian and gay newsgroups</em>. -There is also a <a href="http://www.ebb.org/ungeek/">Geek Code Decoder Page</a> and a form-based -<a href="http://www.joereiss.net/geek/geek.html">generator</a>. +Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting +Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the +trademark in the UK. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_depiction"> - <h3>Property: foaf:depiction</h3> - <em>depiction</em> - A depiction of some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_mbox_sha1sum"> + <h3>Property: foaf:mbox_sha1sum</h3> + <em>sha1sum of a personal mailbox URI name</em> - The sha1sum of the URI of an Internet mailbox associated with exactly one owner, the first owner of the mailbox. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> -</td> </tr> </table> <p> -The <code>foaf:depiction</code> property is a relationship between a thing and an -<code>foaf:Image</code> that depicts it. As such it is an inverse of the -<code>foaf:depicts</code> relationship. -</p> - -<p> -A common use of <code>foaf:depiction</code> (and <code>foaf:depicts</code>) is to indicate -the contents of a digital image, for example the people or objects represented in an -online photo gallery. +A <code>foaf:mbox_sha1sum</code> of a <code>foaf:Person</code> is a textual representation of +the result of applying the SHA1 mathematical functional to a 'mailto:' identifier (URI) for an +Internet mailbox that they stand in a <code>foaf:mbox</code> relationship to. </p> <p> -Extensions to this basic idea include '<a -href="http://rdfweb.org/2002/01/photo/">Co-Depiction</a>' (social networks as evidenced in -photos), as well as richer photo metadata through the mechanism of using SVG paths to -indicate the <em>regions</em> of an image which depict some particular thing. See <a -href="http://www.jibbering.com/svg/AnnotateImage.html">'Annotating Images With SVG'</a> -for tools and details. +In other words, if you have a mailbox (<code>foaf:mbox</code>) but don't want to reveal its +address, you can take that address and generate a <code>foaf:mbox_sha1sum</code> representation +of it. Just as a <code>foaf:mbox</code> can be used as an indirect identifier for its owner, we +can do the same with <code>foaf:mbox_sha1sum</code> since there is only one +<code>foaf:Person</code> with any particular value for that property. </p> <p> -The basic notion of 'depiction' could also be extended to deal with multimedia content -(video clips, audio), or refined to deal with corner cases, such as pictures of pictures etc. +Many FOAF tools use <code>foaf:mbox_sha1sum</code> in preference to exposing mailbox +information. This is usually for privacy and SPAM-avoidance reasons. Other relevant techniques +include the use of PGP encryption (see <a href="http://usefulinc.com/foaf/">Edd Dumbill's +documentation</a>) and the use of <a +href="http://www.w3.org/2001/12/rubyrdf/util/foafwhite/intro.html">FOAF-based whitelists</a> for +mail filtering. </p> <p> -The <code>foaf:depiction</code> property is a super-property of the more specific property -<code>foaf:img</code>, which is used more sparingly. You stand in a -<code>foaf:depiction</code> relation to <em>any</em> <code>foaf:Image</code> that depicts -you, whereas <code>foaf:img</code> is typically used to indicate a few images that are -particularly representative. +Code examples for SHA1 in C#, Java, PHP, Perl and Python can be found <a +href="http://www.intertwingly.net/blog/1545.html">in Sam Ruby's +weblog entry</a>. Remember to include the 'mailto:' prefix, but no trailing +whitespace, when computing a <code>foaf:mbox_sha1sum</code> property. </p> +<!-- what about Javascript. move refs to wiki maybe. --> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_gender"> - <h3>Property: foaf:gender</h3> - <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_pastProject"> + <h3>Property: foaf:pastProject</h3> + <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Person">Person</a> </td></tr> </table> - <p> -The <code>foaf:gender</code> property relates a <code>foaf:Agent</code> (typically a -<code>foaf:Person</code>) to a string representing its gender. In most cases the value -will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). -Like all FOAF properties, there is in general no requirement to use -<code>foaf:gender</code> in any particular document or description. Values other than -'male' and 'female' may be used, but are not enumerated here. The <code>foaf:gender</code> -mechanism is not intended to capture the full variety of biological, social and sexual -concepts associated with the word 'gender'. -</p> - -<p> -Anything that has a <code>foaf:gender</code> property will be some kind of -<code>foaf:Agent</code>. However there are kinds of <code>foaf:Agent</code> to -which the concept of gender isn't applicable (eg. a <code>foaf:Group</code>). FOAF does not -currently include a class corresponding directly to "the type of thing that has a gender". -At any point in time, a <code>foaf:Agent</code> has at most one value for -<code>foaf:gender</code>. FOAF does not treat <code>foaf:gender</code> as a -<em>static</em> property; the same individual may have different values for this property -at different times. + <p>After a <code>foaf:Person</code> is no longer involved with a +<code>foaf:currentProject</code>, or has been inactive for some time, a +<code>foaf:pastProject</code> relationship can be used. This indicates that +the <code>foaf:Person</code> was involved with the described project at one +point. </p> <p> -Note that FOAF's notion of gender isn't defined biologically or anatomically - this would -be tricky since we have a broad notion that applies to all <code>foaf:Agent</code>s -(including robots - eg. Bender from Futurama is 'male'). As stressed above, -FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated -with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise -between the clinical and the social/psychological. In general, a person will be the best -authority on their <code>foaf:gender</code>. Feedback on this design is -particularly welcome (via the FOAF mailing list, -<a href="http://rdfweb.org/mailman/listinfo/rdfweb-dev">rdfweb-dev</a>). We have tried to -be respectful of diversity without attempting to catalogue or enumerate that diversity. +If the <code>foaf:Person</code> has stopped working on a project because it +has been completed (successfully or otherwise), <code>foaf:pastProject</code> is +applicable. In general, <code>foaf:currentProject</code> is used to indicate +someone's current efforts (and implied interests, concerns etc.), while +<code>foaf:pastProject</code> describes what they've previously been doing. </p> -<p> -This may also be a good point for a periodic reminder: as with all FOAF properties, -documents that use '<code>foaf:gender</code>' will on occassion be innacurate, misleading -or outright false. FOAF, like all open means of communication, supports <em>lying</em>. - Application authors using -FOAF data should always be cautious in their presentation of unverified information, but be -particularly sensitive to issues and risks surrounding sex and gender (including privacy -and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit -<code>foaf:gender</code> when describing themselves and others, and to allow at least for -values other than 'male' and 'female' as options. Users of information -conveyed via FOAF (as via information conveyed through mobile phone text messages, email, -Internet chat, HTML pages etc.) should be skeptical of unverified information. -</p> - -<!-- -b/g article currently offline. -http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 ---> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_homepage"> - <h3>Property: foaf:homepage</h3> - <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_holdsAccount"> + <h3>Property: foaf:holdsAccount</h3> + <em>holds account</em> - Indicates an account held by this agent. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>stable</td></tr> - + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> + <td> <a href="#term_Online Account">Online Account</a> </td> </tr> </table> <p> -The <code>foaf:homepage</code> property relates something to a homepage about it. +The <code>foaf:holdsAccount</code> property relates a <code>foaf:Agent</code> to an +<code>foaf:OnlineAccount</code> for which they are the sole account holder. See +<code>foaf:OnlineAccount</code> for usage details. </p> -<p> -Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but -constrains <code>foaf:homepage</code> so that there can be only one thing that has any -particular homepage. + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_accountName"> + <h3>Property: foaf:accountName</h3> + <em>account name</em> - Indicates the name (identifier) associated with this online account. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Online Account">Online Account</a> +</td></tr> + + </table> + <p> +The <code>foaf:accountName</code> property of a <code>foaf:OnlineAccount</code> is a +textual representation of the account name (unique ID) associated with that account. </p> -<p> -A 'homepage' in this sense is a public Web document, typically but not necessarily -available in HTML format. The page has as a <code>foaf:topic</code> the thing whose -homepage it is. The homepage is usually controlled, edited or published by the thing whose -homepage it is; as such one might look to a homepage for information on its owner from its -owner. This works for people, companies, organisations etc. + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_member"> + <h3>Property: foaf:member</h3> + <em>member</em> - Indicates a member of a Group <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>stable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Group">Group</a> +</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Agent">Agent</a> +</td> </tr> + </table> + <p> +The <code>foaf:member</code> property relates a <code>foaf:Group</code> to a +<code>foaf:Agent</code> that is a member of that group. </p> <p> -The <code>foaf:homepage</code> property is a sub-property of the more general -<code>foaf:page</code> property for relating a thing to a page about that thing. See also -<code>foaf:topic</code>, the inverse of the <code>foaf:page</code> property. +See <code>foaf:Group</code> for details and examples. </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_currentProject"> - <h3>Property: foaf:currentProject</h3> - <em>current project</em> - A current project this person works on. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_knows"> + <h3>Property: foaf:knows</h3> + <em>knows</em> - A person known by this person (indicating some level of reciprocated interaction between the parties). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> - + <tr><th>Range:</th> + <td> <a href="#term_Person">Person</a> +</td> </tr> </table> - <!-- originally contrib'd by Cardinal --> - -<p>A <code>foaf:currentProject</code> relates a <code>foaf:Person</code> -to a <code>foaf:Document</code> indicating some collaborative or -individual undertaking. This relationship -indicates that the <code>foaf:Person</code> has some active role in the -project, such as development, coordination, or support.</p> - -<p>When a <code>foaf:Person</code> is no longer involved with a project, or -perhaps is inactive for some time, the relationship becomes a -<code>foaf:pastProject</code>.</p> - -<p> -If the <code>foaf:Person</code> has stopped working on a project because it -has been completed (successfully or otherwise), <code>foaf:pastProject</code> is -applicable. In general, <code>foaf:currentProject</code> is used to indicate -someone's current efforts (and implied interests, concerns etc.), while -<code>foaf:pastProject</code> describes what they've previously been doing. -</p> - -<!-- -<p>Generally speaking, anything that a <code>foaf:Person</code> has -<code>foaf:made</code> could also qualify as a -<code>foaf:currentProject</code> or <code>foaf:pastProject</code>.</p> ---> - -<p class="editorial"> -Note that this property requires further work. There has been confusion about -whether it points to a thing (eg. something you've made; a homepage for a project, -ie. a <code>foaf:Document</code> or to instances of the class <code>foaf:Project</code>, -which might themselves have a <code>foaf:homepage</code>. In practice, it seems to have been -used in a similar way to <code>foaf:interest</code>, referencing homepages of ongoing projects. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_myersBriggs"> - <h3>Property: foaf:myersBriggs</h3> - <em>myersBriggs</em> - A Myers Briggs (MBTI) personality classification. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - <!-- todo: expand acronym --> + <p> +The <code>foaf:knows</code> property relates a <code>foaf:Person</code> to another +<code>foaf:Person</code> that he or she knows. +</p> <p> -The <code>foaf:myersBriggs</code> property represents the Myers Briggs (MBTI) approach to -personality taxonomy. It is included in FOAF as an example of a property -that takes certain constrained values, and to give some additional detail to the FOAF -files of those who choose to include it. The <code>foaf:myersBriggs</code> property applies only to the -<code>foaf:Person</code> class; wherever you see it, you can infer it is being applied to -a person. +We take a broad view of 'knows', but do require some form of reciprocated interaction (ie. +stalkers need not apply). Since social attitudes and conventions on this topic vary +greatly between communities, counties and cultures, it is not appropriate for FOAF to be +overly-specific here. </p> <p> -The <code>foaf:myersBriggs</code> property is interesting in that it illustrates how -FOAF can serve as a carrier for various kinds of information, without necessarily being -commited to any associated worldview. Not everyone will find myersBriggs (or star signs, -or blood types, or the four humours) a useful perspective on human behaviour and -personality. The inclusion of a Myers Briggs property doesn't indicate that FOAF endorses -the underlying theory, any more than the existence of <code>foaf:weblog</code> is an -endorsement of soapboxes. +If someone <code>foaf:knows</code> a person, it would be usual for +the relation to be reciprocated. However this doesn't mean that there is any obligation +for either party to publish FOAF describing this relationship. A <code>foaf:knows</code> +relationship does not imply friendship, endorsement, or that a face-to-face meeting +has taken place: phone, fax, email, and smoke signals are all perfectly +acceptable ways of communicating with people you know. </p> - <p> -The values for <code>foaf:myersBriggs</code> are the following 16 4-letter textual codes: -ESTJ, INFP, ESFP, INTJ, ESFJ, INTP, ENFP, ISTJ, ESTP, INFJ, ENFJ, ISTP, ENTJ, ISFP, -ENTP, ISFJ. If multiple of these properties are applicable, they are represented by -applying multiple properties to a person. +You probably know hundreds of people, yet might only list a few in your public FOAF file. +That's OK. Or you might list them all. It is perfectly fine to have a FOAF file and not +list anyone else in it at all. +This illustrates the Semantic Web principle of partial description: RDF documents +rarely describe the entire picture. There is always more to be said, more information +living elsewhere in the Web (or in our heads...). </p> <p> -For further reading on MBTI, see various online sources (eg. <a -href="http://www.teamtechnology.co.uk/tt/t-articl/mb-simpl.htm">this article</a>). There -are various online sites which offer quiz-based tools for determining a person's MBTI -classification. The owners of the MBTI trademark have probably not approved of these. +Since <code>foaf:knows</code> is vague by design, it may be suprising that it has uses. +Typically these involve combining other RDF properties. For example, an application might +look at properties of each <code>foaf:weblog</code> that was <code>foaf:made</code> by +someone you "<code>foaf:knows</code>". Or check the newsfeed of the online photo archive +for each of these people, to show you recent photos taken by people you know. </p> <p> -This FOAF property suggests some interesting uses, some of which could perhaps be used to -test the claims made by proponents of the MBTI (eg. an analysis of weblog postings -filtered by MBTI type). However it should be noted that MBTI FOAF descriptions are -self-selecting; MBTI categories may not be uniformly appealing to the people they -describe. Further, there is probably a degree of cultural specificity implicit in the -assumptions made by many questionaire-based MBTI tools; the MBTI system may not make -sense in cultural settings beyond those it was created for. +To provide additional levels of representation beyond mere 'knows', FOAF applications +can do several things. </p> - <p> -See also <a href="http://www.geocities.com/lifexplore/mbintro.htm">Cory Caplinger's summary table</a> or the RDFWeb article, <a -href="http://rdfweb.org/mt/foaflog/archives/000004.html">FOAF Myers Briggs addition</a> -for further background and examples. +They can use more precise relationships than <code>foaf:knows</code> to relate people to +people. The original FOAF design included two of these ('knowsWell','friend') which we +removed because they were somewhat <em>awkward</em> to actually use, bringing an +inappopriate air of precision to an intrinsically vague concept. Other extensions have +been proposed, including Eric Vitiello's <a +href="http://www.perceive.net/schemas/20021119/relationship/">Relationship module</a> for +FOAF. </p> <p> -Note: Myers Briggs Type Indicator and MBTI are registered trademarks of Consulting -Psychologists Press Inc. Oxford Psycholgists Press Ltd has exclusive rights to the -trademark in the UK. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_icqChatID"> - <h3>Property: foaf:icqChatID</h3> - <em>ICQ chat ID</em> - An ICQ chat ID <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:icqChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the ICQ Chat system. -See the <a href="http://web.icq.com/icqchat/">icq chat</a> site for more details of the 'icq' -service. Their "<a href="http://www.icq.com/products/whatisicq.html">What is ICQ?</a>" document -provides a basic overview, while their "<a href="http://company.icq.com/info/">About Us</a> page -notes that ICQ has been acquired by AOL. Despite the relationship with AOL, ICQ is at -the time of writing maintained as a separate identity from the AIM brand (see -<code>foaf:aimChatID</code>). +In addition to using more specialised inter-personal relationship types +(eg rel:acquaintanceOf etc) it is often just as good to use RDF descriptions of the states +of affairs which imply particular kinds of relationship. So for example, two people who +have the same value for their <code>foaf:workplaceHomepage</code> property are +typically colleagues. We don't (currently) clutter FOAF up with these extra relationships, +but the facts can be written in FOAF nevertheless. Similarly, if there exists a +<code>foaf:Document</code> that has two people listed as its <code>foaf:maker</code>s, +then they are probably collaborators of some kind. Or if two people appear in 100s of +digital photos together, there's a good chance they're friends and/or colleagues. </p> <p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_pastProject"> - <h3>Property: foaf:pastProject</h3> - <em>past project</em> - A project this person has previously worked on. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - <p>After a <code>foaf:Person</code> is no longer involved with a -<code>foaf:currentProject</code>, or has been inactive for some time, a -<code>foaf:pastProject</code> relationship can be used. This indicates that -the <code>foaf:Person</code> was involved with the described project at one -point. +So FOAF is quite pluralistic in its approach to representing relationships between people. +FOAF is built on top of a general purpose machine language for representing relationships +(ie. RDF), so is quite capable of representing any kinds of relationship we care to add. +The problems are generally social rather than technical; deciding on appropriate ways of +describing these interconnections is a subtle art. </p> <p> -If the <code>foaf:Person</code> has stopped working on a project because it -has been completed (successfully or otherwise), <code>foaf:pastProject</code> is -applicable. In general, <code>foaf:currentProject</code> is used to indicate -someone's current efforts (and implied interests, concerns etc.), while -<code>foaf:pastProject</code> describes what they've previously been doing. +Perhaps the most important use of <code>foaf:knows</code> is, alongside the +<code>rdfs:seeAlso</code> property, to connect FOAF files together. Taken alone, a FOAF +file is somewhat dull. But linked in with 1000s of other FOAF files it becomes more +interesting, with each FOAF file saying a little more about people, places, documents, things... +By mentioning other people (via <code>foaf:knows</code> or other relationships), and by +providing an <code>rdfs:seeAlso</code> link to their FOAF file, you can make it easy for +FOAF indexing tools ('<a href="http://rdfweb.org/topic/ScutterSpec">scutters</a>') to find +your FOAF and the FOAF of the people you've mentioned. And the FOAF of the people they +mention, and so on. This makes it possible to build FOAF aggregators without the need for +a centrally managed directory of FOAF files... </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_img"> - <h3>Property: foaf:img</h3> - <em>image</em> - An image that can be used to represent some thing (ie. those depictions which are particularly representative of something, eg. one's photo on a homepage). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_thumbnail"> + <h3>Property: foaf:thumbnail</h3> + <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> + <td> <a href="#term_Image">Image</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Image">Image</a> </td> </tr> </table> - <p> -The <code>foaf:img</code> property relates a <code>foaf:Person</code> to a -<code>foaf:Image</code> that represents them. Unlike its super-property -<code>foaf:depiction</code>, we only use <code>foaf:img</code> when an image is -particularly representative of some person. The analogy is with the image(s) that might -appear on someone's homepage, rather than happen to appear somewhere in their photo album. -</p> + <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> <p> -Unlike the more general <code>foaf:depiction</code> property (and its inverse, -<code>foaf:depicts</code>), the <code>foaf:img</code> property is only used with -representations of people (ie. instances of <code>foaf:Person</code>). So you can't use -it to find pictures of cats, dogs etc. The basic idea is to have a term whose use is more -restricted than <code>foaf:depiction</code> so we can have a useful way of picking out a -reasonable image to represent someone. FOAF defines <code>foaf:img</code> as a -sub-property of <code>foaf:depiction</code>, which means that the latter relationship is -implied whenever two things are related by the former. +The <code>foaf:thumbnail</code> property is a relationship between a +full-size <code>foaf:Image</code> and a smaller, representative <code>foaf:Image</code> +that has been derrived from it. </p> <p> -Note that <code>foaf:img</code> does not have any restrictions on the dimensions, colour -depth, format etc of the <code>foaf:Image</code> it references. +It is typical in FOAF to express <code>foaf:img</code> and <code>foaf:depiction</code> +relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). +A <code>foaf:thumbnail</code> might be clipped or otherwise reduced such that it does not +depict everything that the full image depicts. Therefore FOAF does not specify that a +thumbnail <code>foaf:depicts</code> everything that the image it is derrived from depicts. +However, FOAF does expect that anything depicted in the thumbnail will also be depicted in +the source image. </p> +<!-- todo: add RDF rules here showing this --> + <p> -Terminology: note that <code>foaf:img</code> is a property (ie. relationship), and that -<code>code:Image</code> is a similarly named class (ie. category, a type of thing). It -might have been more helpful to call <code>foaf:img</code> 'mugshot' or similar; instead -it is named by analogy to the HTML IMG element. -</p> +A <code>foaf:thumbnail</code> is typically small enough that it can be +loaded and viewed quickly before a viewer decides to download the larger +version. They are often used in online photo gallery applications. +</p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_primaryTopic"> <h3>Property: foaf:primaryTopic</h3> <em>primary topic</em> - The primary topic of some page or document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Document">Document</a> -</td></tr> - - </table> - <p> -The <code>foaf:primaryTopic</code> property relates a document to the -main thing that the document is about. -</p> - -<p> -The <code>foaf:primaryTopic</code> property is <em>functional</em>: for -any document it applies to, it can have at most one value. This is -useful, as it allows for data merging. In many cases it may be difficult -for third parties to determine the primary topic of a document, but in -a useful number of cases (eg. descriptions of movies, restaurants, -politicians, ...) it should be reasonably obvious. Documents are very -often the most authoritative source of information about their own -primary topics, although this cannot be guaranteed since documents cannot be -assumed to be accurate, honest etc. -</p> - -<p> -It is an inverse of the <code>foaf:isPrimaryTopicOf</code> property, which relates a -thing to a document <em>primarily</em> about that thing. The choice between these two -properties is purely pragmatic. When describing documents, we -use <code>foaf:primaryTopic</code> former to point to the things they're about. When -describing things (people etc.), it is useful to be able to directly cite documents which -have those things as their main topic - so we use <code>foaf:isPrimaryTopicOf</code>. In this -way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a -href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they -have descriptions of. -</p> - - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_name"> - <h3>Property: foaf:name</h3> - <em>name</em> - A name for some thing. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> - <p>The <code>foaf:name</code> of something is a simple textual string.</p> - -<p> -XML language tagging may be used to indicate the language of the name. For example: -</p> - -<div class="example"> -<code> -&lt;foaf:name xml:lang="en"&gt;Dan Brickley&lt;/foaf:name&gt; -</code> -</div> - -<p> -FOAF provides some other naming constructs. While foaf:name does not explicitly represent name substructure (family vs given etc.) it -does provide a basic level of interoperability. See the <a -href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for status of work on this issue. -</p> - -<p> -The <code>foaf:name</code> property, like all RDF properties with a range of rdfs:Literal, may be used with XMLLiteral datatyped -values. This usage is, however, not yet widely adopted. Feedback on this aspect of the FOAF design is particularly welcomed. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_made"> - <h3>Property: foaf:made</h3> - <em>made</em> - Something that was made by this agent. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>stable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:made</code> property relates a <code>foaf:Agent</code> -to something <code>foaf:made</code> by it. As such it is an -inverse of the <code>foaf:maker</code> property, which relates a thing to -something that made it. See <code>foaf:made</code> for more details on the -relationship between these FOAF terms and related Dublin Core vocabulary. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_tipjar"> - <h3>Property: foaf:tipjar</h3> - <em>tipjar</em> - A tipjar document for this agent, describing means for payment and reward. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> - </table> - <p> -The <code>foaf:tipjar</code> property relates an <code>foaf:Agent</code> -to a <code>foaf:Document</code> that describes some mechanisms for -paying or otherwise rewarding that agent. -</p> - -<p> -The <code>foaf:tipjar</code> property was created following <a -href="http://rdfweb.org/mt/foaflog/archives/2004/02/12/20.07.32/">discussions</a> -about simple, lightweight mechanisms that could be used to encourage -rewards and payment for content exchanged online. An agent's -<code>foaf:tipjar</code> page(s) could describe informal ("Send me a -postcard!", "here's my book, music and movie wishlist") or formal -(machine-readable micropayment information) information about how that -agent can be paid or rewarded. The reward is not associated with any -particular action or content from the agent concerned. A link to -a service such as <a href="http://www.paypal.com/">PayPal</a> is the -sort of thing we might expect to find in a tipjar document. -</p> - -<p> -Note that the value of a <code>foaf:tipjar</code> property is just a -document (which can include anchors into HTML pages). We expect, but -do not currently specify, that this will evolve into a hook -for finding more machine-readable information to support payments, -rewards. The <code>foaf:OnlineAccount</code> machinery is also relevant, -although the information requirements for automating payments are not -currently clear. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_based_near"> - <h3>Property: foaf:based_near</h3> - <em>based near</em> - A location that something is based near, for some broadly human notion of near. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - - </table> - <!-- note: is this mis-specified? perhaps range ought to also be SpatialThing, so we - can have multiple labels on the same point? --> - -<p>The <code>foaf:based_near</code> relationship relates two "spatial -things" -(anything that can <em>be somewhere</em>), the latter typically -described using the geo:lat / geo:long -<a href="http://www.w3.org/2003/01/geo/wgs84_pos#">geo-positioning vocabulary</a> -(See <a href="http://esw.w3.org/topic/GeoInfo">GeoInfo</a> in the W3C semweb -wiki for details). This allows us to say describe the typical latitute and -longitude of, say, a Person (people are spatial things - they can be -places) without implying that a precise location has been given. -</p> - -<p>We do not say much about what 'near' means in this context; it is a -'rough and ready' concept. For a more precise treatment, see -<a href="http://esw.w3.org/topic/GeoOnion">GeoOnion vocab</a> design -discussions, which are aiming to produce a more sophisticated vocabulary for -such purposes. -</p> - -<p> FOAF files often make use of the <code>contact:nearestAirport</code> property. This -illustrates the distinction between FOAF documents (which may make claims using <em>any</em> RDF -vocabulary) and the core FOAF vocabulary defined by this specification. For further reading on -the use of <code>nearestAirport</code> see <a -href="http://rdfweb.org/topic/UsingContactNearestAirport">UsingContactNearestAirport</a> in the -FOAF wiki. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_logo"> - <h3>Property: foaf:logo</h3> - <em>logo</em> - A logo representing some thing. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - - - </table> - <p> -The <code>foaf:logo</code> property is used to indicate a graphical logo of some kind. -<em>It is probably underspecified...</em> -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_firstName"> - <h3>Property: foaf:firstName</h3> - <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - - </table> - - -<p>A number of naming constructs are under development to provide -naming substructure; draft properties include <code>foaf:firstName</code>, -<code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently -stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue -tracker</a> for design discussions, status and ongoing work on rationalising the FOAF -naming machinery. -</p> - -<p> -There is also a simple <code>foaf:name</code> property. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_yahooChatID"> - <h3>Property: foaf:yahooChatID</h3> - <em>Yahoo chat ID</em> - A Yahoo chat ID <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:yahooChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the Yahoo online Chat system. -See Yahoo's the <a href="http://chat.yahoo.com/">Yahoo! Chat</a> site for more details of their -service. Yahoo chat IDs are also used across several other Yahoo services, including email and -<a href="http://www.yahoogroups.com/">Yahoo! Groups</a>. -</p> - -<p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. -</p> - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_membershipClass"> - <h3>Property: foaf:membershipClass</h3> - <em>membershipClass</em> - Indicates the class of individuals that are a member of a Group <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - - - </table> - <p> -The <code>foaf:membershipClass</code> property relates a <code>foaf:Group</code> to an RDF -class representing a sub-class of <code>foaf:Agent</code> whose instances are all the -agents that are a <code>foaf:member</code> of the <code>foaf:Group</code>. -</p> - -<p> -See <code>foaf:Group</code> for details and examples. -</p> - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_birthday"> - <h3>Property: foaf:birthday</h3> - <em>birthday</em> - The birthday of this Agent, represented in mm-dd string form, eg. '12-31'. <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>unstable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> -</td></tr> - - </table> - <p> -The <code>foaf:birthday</code> property is a relationship between a <code>foaf:Agent</code> -and a string representing the month and day in which they were born (Gregorian calendar). -See <a href="http://rdfweb.org/topic/BirthdayIssue">BirthdayIssue</a> for details of related properties that can -be used to describe such things in more flexible ways. -</p> - - - - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_aimChatID"> - <h3>Property: foaf:aimChatID</h3> - <em>AIM chat ID</em> - An AIM chat ID <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Agent">Agent</a> + <td> <a href="#term_Document">Document</a> </td></tr> </table> <p> -The <code>foaf:aimChatID</code> property relates a <code>foaf:Agent</code> to a textual -identifier ('screenname') assigned to them in the AOL Instant Messanger (AIM) system. -See AOL's <a href="http://www.aim.com/">AIM</a> site for more details of AIM and AIM -screennames. The <a href="http://www.apple.com/macosx/features/ichat/">iChat</a> tools from <a -href="http://www.apple.com/">Apple</a> also make use of AIM identifiers. +The <code>foaf:primaryTopic</code> property relates a document to the +main thing that the document is about. </p> <p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. +The <code>foaf:primaryTopic</code> property is <em>functional</em>: for +any document it applies to, it can have at most one value. This is +useful, as it allows for data merging. In many cases it may be difficult +for third parties to determine the primary topic of a document, but in +a useful number of cases (eg. descriptions of movies, restaurants, +politicians, ...) it should be reasonably obvious. Documents are very +often the most authoritative source of information about their own +primary topics, although this cannot be guaranteed since documents cannot be +assumed to be accurate, honest etc. +</p> + +<p> +It is an inverse of the <code>foaf:isPrimaryTopicOf</code> property, which relates a +thing to a document <em>primarily</em> about that thing. The choice between these two +properties is purely pragmatic. When describing documents, we +use <code>foaf:primaryTopic</code> former to point to the things they're about. When +describing things (people etc.), it is useful to be able to directly cite documents which +have those things as their main topic - so we use <code>foaf:isPrimaryTopicOf</code>. In this +way, Web sites such as <a href="http://www.wikipedia.org/">Wikipedia</a> or <a +href="http://www.nndb.com/">NNDB</a> can provide indirect identification for the things they +have descriptions of. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_title"> <h3>Property: foaf:title</h3> <em>title</em> - Title (Mr, Mrs, Ms, Dr. etc) <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> </table> <p> The approriate values for <code>foaf:title</code> are not formally constrained, and will vary across community and context. Values such as 'Mr', 'Mrs', 'Ms', 'Dr' etc. are expected. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_weblog"> - <h3>Property: foaf:weblog</h3> - <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_phone"> + <h3>Property: foaf:phone</h3> + <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + + + </table> + <p> +The <code>foaf:phone</code> of something is a phone, typically identified using the tel: URI +scheme. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_tipjar"> + <h3>Property: foaf:tipjar</h3> + <em>tipjar</em> - A tipjar document for this agent, describing means for payment and reward. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> -The <code>foaf:weblog</code> property relates a <code>foaf:Agent</code> to a weblog of -that agent. +The <code>foaf:tipjar</code> property relates an <code>foaf:Agent</code> +to a <code>foaf:Document</code> that describes some mechanisms for +paying or otherwise rewarding that agent. +</p> + +<p> +The <code>foaf:tipjar</code> property was created following <a +href="http://rdfweb.org/mt/foaflog/archives/2004/02/12/20.07.32/">discussions</a> +about simple, lightweight mechanisms that could be used to encourage +rewards and payment for content exchanged online. An agent's +<code>foaf:tipjar</code> page(s) could describe informal ("Send me a +postcard!", "here's my book, music and movie wishlist") or formal +(machine-readable micropayment information) information about how that +agent can be paid or rewarded. The reward is not associated with any +particular action or content from the agent concerned. A link to +a service such as <a href="http://www.paypal.com/">PayPal</a> is the +sort of thing we might expect to find in a tipjar document. +</p> + +<p> +Note that the value of a <code>foaf:tipjar</code> property is just a +document (which can include anchors into HTML pages). We expect, but +do not currently specify, that this will evolve into a hook +for finding more machine-readable information to support payments, +rewards. The <code>foaf:OnlineAccount</code> machinery is also relevant, +although the information requirements for automating payments are not +currently clear. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_schoolHomepage"> <h3>Property: foaf:schoolHomepage</h3> <em>schoolHomepage</em> - A homepage of a school attended by the person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> <tr><th>Range:</th> <td> <a href="#term_Document">Document</a> </td> </tr> </table> <p> The <code>schoolHomepage</code> property relates a <code>foaf:Person</code> to a <code>foaf:Document</code> that is the <code>foaf:homepage</code> of a School that the person attended. </p> <p> FOAF does not (currently) define a class for 'School' (if it did, it would probably be as a sub-class of <code>foaf:Organization</code>). The original application area for <code>foaf:schoolHomepage</code> was for 'schools' in the British-English sense; however American-English usage has dominated, and it is now perfectly reasonable to describe Universities, Colleges and post-graduate study using <code>foaf:schoolHomepage</code>. </p> <p> This very basic facility provides a basis for a low-cost, decentralised approach to classmate-reunion and suchlike. Instead of requiring a central database, we can use FOAF to express claims such as 'I studied <em>here</em>' simply by mentioning a school's homepage within FOAF files. Given the homepage of a school, it is easy for FOAF aggregators to lookup this property in search of people who attended that school. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_workplaceHomepage"> - <h3>Property: foaf:workplaceHomepage</h3> - <em>workplace homepage</em> - A workplace homepage of some person; the homepage of an organization they work for. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_dnaChecksum"> + <h3>Property: foaf:dnaChecksum</h3> + <em>DNA checksum</em> - A checksum for the DNA of some thing. Joke. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Document">Document</a> -</td> </tr> + <td>unstable</td></tr> + + </table> <p> -The <code>foaf:workplaceHomepage</code> of a <code>foaf:Person</code> is a -<code>foaf:Document</code> that is the <code>foaf:homepage</code> of a -<code>foaf:Organization</code> that they work for. +The <code>foaf:dnaChecksum</code> property is mostly a joke, but +also a reminder that there will be lots of different identifying +properties for people, some of which we might find disturbing. </p> -<p> -By directly relating people to the homepages of their workplace, we have a simple convention -that takes advantage of a set of widely known identifiers, while taking care not to confuse the -things those identifiers identify (ie. organizational homepages) with the actual organizations -those homepages describe. -</p> -<div class="example"> -<p> -For example, Dan Brickley works at W3C. Dan is a <code>foaf:Person</code> with a -<code>foaf:homepage</code> of http://rdfweb.org/people/danbri/; W3C is a -<code>foaf:Organization</code> with a <code>foaf:homepage</code> of http://www.w3.org/. This -allows us to say that Dan has a <code>foaf:workplaceHomepage</code> of http://www.w3.org/. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_based_near"> + <h3>Property: foaf:based_near</h3> + <em>based near</em> - A location that something is based near, for some broadly human notion of near. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <!-- note: is this mis-specified? perhaps range ought to also be SpatialThing, so we + can have multiple labels on the same point? --> + +<p>The <code>foaf:based_near</code> relationship relates two "spatial +things" +(anything that can <em>be somewhere</em>), the latter typically +described using the geo:lat / geo:long +<a href="http://www.w3.org/2003/01/geo/wgs84_pos#">geo-positioning vocabulary</a> +(See <a href="http://esw.w3.org/topic/GeoInfo">GeoInfo</a> in the W3C semweb +wiki for details). This allows us to say describe the typical latitute and +longitude of, say, a Person (people are spatial things - they can be +places) without implying that a precise location has been given. </p> -<pre> -&lt;foaf:Person&gt; - &lt;foaf:name>Dan Brickley&lt;/foaf:name&gt; - &lt;foaf:workplaceHomepage rdf:resource="http://www.w3.org/"/&gt; -&lt;/foaf:Person&gt; -</pre> -</div> +<p>We do not say much about what 'near' means in this context; it is a +'rough and ready' concept. For a more precise treatment, see +<a href="http://esw.w3.org/topic/GeoOnion">GeoOnion vocab</a> design +discussions, which are aiming to produce a more sophisticated vocabulary for +such purposes. +</p> +<p> FOAF files often make use of the <code>contact:nearestAirport</code> property. This +illustrates the distinction between FOAF documents (which may make claims using <em>any</em> RDF +vocabulary) and the core FOAF vocabulary defined by this specification. For further reading on +the use of <code>nearestAirport</code> see <a +href="http://rdfweb.org/topic/UsingContactNearestAirport">UsingContactNearestAirport</a> in the +FOAF wiki. +</p> -<p> -Note that several other FOAF properties work this way; -<code>foaf:schoolHomepage</code> is the most similar. In general, FOAF often indirectly -identifies things via Web page identifiers where possible, since these identifiers are widely -used and known. FOAF does not currently have a term for the name of the relation (eg. -"workplace") that holds -between a <code>foaf:Person</code> and an <code>foaf:Organization</code> that they work for. + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_depicts"> + <h3>Property: foaf:depicts</h3> + <em>depicts</em> - A thing depicted in this representation. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Image">Image</a> +</td></tr> + + </table> + <p> +The <code>foaf:depicts</code> property is a relationship between a <code>foaf:Image</code> +and something that the image depicts. As such it is an inverse of the +<code>foaf:depiction</code> relationship. See <code>foaf:depiction</code> for further notes. </p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_jabberID"> - <h3>Property: foaf:jabberID</h3> - <em>jabber ID</em> - A jabber ID for something. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_weblog"> + <h3>Property: foaf:weblog</h3> + <em>weblog</em> - A weblog of some thing (whether person, group, company etc.). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Agent">Agent</a> </td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:weblog</code> property relates a <code>foaf:Agent</code> to a weblog of +that agent. +</p> + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_geekcode"> + <h3>Property: foaf:geekcode</h3> + <em>geekcode</em> - A textual geekcode for this person, see http://www.geekcode.com/geek.html <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Person">Person</a> +</td></tr> </table> <p> -The <code>foaf:jabberID</code> property relates a <code>foaf:Agent</code> to a textual -identifier assigned to them in the <a href="http://www.jabber.org/">Jabber</a> messaging -system. -See the <a href="http://www.jabber.org/">Jabber</a> site for more information about the Jabber -protocols and tools. +The <code>foaf:geekcode</code> property is used to represent a 'Geek Code' for some +<code>foaf:Person</code>. </p> <p> -Jabber, unlike several other online messaging systems, is based on an open, publically -documented protocol specification, and has a variety of open source implementations. Jabber IDs -can be assigned to a variety of kinds of thing, including software 'bots', chat rooms etc. For -the purposes of FOAF, these are all considered to be kinds of <code>foaf:Agent</code> (ie. -things that <em>do</em> stuff). The uses of Jabber go beyond simple IM chat applications. The -<code>foaf:jabberID</code> property is provided as a basic hook to help support RDF description -of Jabber users and services. +See the <a href="http://www.geekcode.com/geek.html">Code of the Geeks</a> specification for +details of the code, which provides a somewhat frivolous and willfully obscure mechanism for +characterising technical expertise, interests and habits. The <code>foaf:geekcode</code> +property is not bound to any particular version of the code. The last published version +of the code was v3.12 in March 1996. </p> <p> -See <code>foaf:OnlineChatAccount</code> (and <code>foaf:OnlineAccount</code>) for a -more general (and verbose) mechanism for describing IM and chat accounts. +As the <a href="http://www.geekcode.com/">Geek Code</a> website notes, the code played a small +(but amusing) part in the history of the Internet. The <code>foaf:geekcode</code> property +exists in acknowledgement of this history. It'll never be 1996 again. +</p> + +<p> +Note that the Geek Code is a densely packed collections of claims about the person it applies +to; to express these claims explicitly in RDF/XML would be incredibly verbose. The syntax of the +Geek Code allows for '&lt;' and '&gt;' characters, which have special meaning in RDF/XML. +Consequently these should be carefully escaped in markup. +</p> + +<p> +An example Geek Code: +</p> +<p class="example"> + GED/J d-- s:++>: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ w--- O- M+ V-- PS++>$ +PE++>$ Y++ PGP++ t- 5+++ X++ R+++>$ tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** +</p> + +<p> +...would be written in FOAF RDF/XML as follows: +</p> + +<p class="example"> +&lt;foaf:geekcode&gt; + GED/J d-- s:++&amp;gt;: a-- C++(++++) ULU++ P+ L++ E---- W+(-) N+++ o+ K+++ + w--- O- M+ V-- PS++&amp;gt;$ PE++&amp;gt;$ Y++ PGP++ t- 5+++ X++ R+++&amp;gt;$ + tv+ b+ DI+++ D+++ G++++ e++ h r-- y++** +&lt;/foaf:geekcode&gt; </p> - <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> - <br/> - </div> <div class="specterm" id="term_member"> - <h3>Property: foaf:member</h3> - <em>member</em> - Indicates a member of a Group <br /><table style="th { float: top; }"> - <tr><th>Status:</th> - <td>stable</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Group">Group</a> -</td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Agent">Agent</a> -</td> </tr> - </table> - <p> -The <code>foaf:member</code> property relates a <code>foaf:Group</code> to a -<code>foaf:Agent</code> that is a member of that group. -</p> <p> -See <code>foaf:Group</code> for details and examples. +See also the <a href="http://www.everything2.com/index.pl?node=GEEK%20CODE">geek code</a> entry +in <a href="http://www.everything2.com/">everything2</a>, which tells us that <em>the +geek code originated in 1993; it was inspired (according to the inventor) by previous "bear", +"smurf" and "twink" style-and-sexual-preference codes from lesbian and gay newsgroups</em>. +There is also a <a href="http://www.ebb.org/ungeek/">Geek Code Decoder Page</a> and a form-based +<a href="http://www.joereiss.net/geek/geek.html">generator</a>. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div> <div class="specterm" id="term_topic"> <h3>Property: foaf:topic</h3> <em>topic</em> - A topic of some page or document. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Document">Document</a> </td></tr> </table> <p> The <code>foaf:topic</code> property relates a document to a thing that the document is about. </p> <p> As such it is an inverse of the <code>foaf:page</code> property, which relates a thing to a document about that thing. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_topic_interest"> - <h3>Property: foaf:topic_interest</h3> - <em>interest_topic</em> - A thing of interest to this person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_fundedBy"> + <h3>Property: foaf:fundedBy</h3> + <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - <tr><th>Domain:</th> - <td> <a href="#term_Person">Person</a> -</td></tr> + <td>unstable</td></tr> + </table> - <p class="editorial"> -The <code>foaf:topic_interest</code> property is generally found to be confusing and ill-defined -and is a candidate for removal. The goal was to be link a person to some thing that is a topic -of their interests (rather than, per <code>foaf:interest</code> to a page that is about such a -topic). + <p> +The <code>foaf:fundedBy</code> property relates something to something else that has provided +funding for it. +</p> + +<p class="editorial"> +This property is under-specified, experimental, and should be considered liable to change. </p> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_phone"> - <h3>Property: foaf:phone</h3> - <em>phone</em> - A phone, specified using fully qualified tel: URI scheme (refs: http://www.w3.org/Addressing/schemes.html#tel). <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_mbox"> + <h3>Property: foaf:mbox</h3> + <em>personal mailbox</em> - A personal mailbox, ie. an Internet mailbox associated with exactly one owner, the first owner of this mailbox. This is a 'static inverse functional property', in that there is (across time and change) at most one individual that ever has any particular value for foaf:mbox. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>testing</td></tr> - + <td>stable</td></tr> + <tr><th>Domain:</th> + <td> <a href="#term_Agent">Agent</a> +</td></tr> </table> <p> -The <code>foaf:phone</code> of something is a phone, typically identified using the tel: URI -scheme. +The <code>foaf:mbox</code> property is a relationship between the owner of a mailbox and +a mailbox. These are typically identified using the mailto: URI scheme (see <a +href="http://ftp.ics.uci.edu/pub/ietf/uri/rfc2368.txt">RFC 2368</a>). +</p> + +<p> +Note that there are many mailboxes (eg. shared ones) which are not the +<code>foaf:mbox</code> of anyone. Furthermore, a person can have multiple +<code>foaf:mbox</code> properties. +</p> + +<p> +In FOAF, we often see <code>foaf:mbox</code> used as an indirect way of identifying its +owner. This works even if the mailbox is itself out of service (eg. 10 years old), since +the property is defined in terms of its primary owner, and doesn't require the mailbox to +actually be being used for anything. </p> +<p> +Many people are wary of sharing information about their mailbox addresses in public. To +address such concerns whilst continuing the FOAF convention of indirectly identifying +people by referring to widely known properties, FOAF also provides the +<code>foaf:mbox_sha1sum</code> mechanism, which is a relationship between a person and +the value you get from passing a mailbox URI to the SHA1 mathematical function. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_thumbnail"> - <h3>Property: foaf:thumbnail</h3> - <em>thumbnail</em> - A derived thumbnail image. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_gender"> + <h3>Property: foaf:gender</h3> + <em>gender</em> - The gender of this Agent (typically but not necessarily 'male' or 'female'). <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> - <td> <a href="#term_Image">Image</a> + <td> <a href="#term_Agent">Agent</a> </td></tr> - <tr><th>Range:</th> - <td> <a href="#term_Image">Image</a> -</td> </tr> + </table> - <!-- originally contrib'd by Cardinal; rejiggged a bit by danbri --> + <p> +The <code>foaf:gender</code> property relates a <code>foaf:Agent</code> (typically a +<code>foaf:Person</code>) to a string representing its gender. In most cases the value +will be the string 'female' or 'male' (in lowercase without surrounding quotes or spaces). +Like all FOAF properties, there is in general no requirement to use +<code>foaf:gender</code> in any particular document or description. Values other than +'male' and 'female' may be used, but are not enumerated here. The <code>foaf:gender</code> +mechanism is not intended to capture the full variety of biological, social and sexual +concepts associated with the word 'gender'. +</p> <p> -The <code>foaf:thumbnail</code> property is a relationship between a -full-size <code>foaf:Image</code> and a smaller, representative <code>foaf:Image</code> -that has been derrived from it. +Anything that has a <code>foaf:gender</code> property will be some kind of +<code>foaf:Agent</code>. However there are kinds of <code>foaf:Agent</code> to +which the concept of gender isn't applicable (eg. a <code>foaf:Group</code>). FOAF does not +currently include a class corresponding directly to "the type of thing that has a gender". +At any point in time, a <code>foaf:Agent</code> has at most one value for +<code>foaf:gender</code>. FOAF does not treat <code>foaf:gender</code> as a +<em>static</em> property; the same individual may have different values for this property +at different times. </p> <p> -It is typical in FOAF to express <code>foaf:img</code> and <code>foaf:depiction</code> -relationships in terms of the larger, 'main' (in some sense) image, rather than its thumbnail(s). -A <code>foaf:thumbnail</code> might be clipped or otherwise reduced such that it does not -depict everything that the full image depicts. Therefore FOAF does not specify that a -thumbnail <code>foaf:depicts</code> everything that the image it is derrived from depicts. -However, FOAF does expect that anything depicted in the thumbnail will also be depicted in -the source image. +Note that FOAF's notion of gender isn't defined biologically or anatomically - this would +be tricky since we have a broad notion that applies to all <code>foaf:Agent</code>s +(including robots - eg. Bender from Futurama is 'male'). As stressed above, +FOAF's notion of gender doesn't attempt to encompass the full range of concepts associated +with human gender, biology and sexuality. As such it is a (perhaps awkward) compromise +between the clinical and the social/psychological. In general, a person will be the best +authority on their <code>foaf:gender</code>. Feedback on this design is +particularly welcome (via the FOAF mailing list, +<a href="http://rdfweb.org/mailman/listinfo/rdfweb-dev">rdfweb-dev</a>). We have tried to +be respectful of diversity without attempting to catalogue or enumerate that diversity. </p> -<!-- todo: add RDF rules here showing this --> - <p> -A <code>foaf:thumbnail</code> is typically small enough that it can be -loaded and viewed quickly before a viewer decides to download the larger -version. They are often used in online photo gallery applications. +This may also be a good point for a periodic reminder: as with all FOAF properties, +documents that use '<code>foaf:gender</code>' will on occassion be innacurate, misleading +or outright false. FOAF, like all open means of communication, supports <em>lying</em>. + Application authors using +FOAF data should always be cautious in their presentation of unverified information, but be +particularly sensitive to issues and risks surrounding sex and gender (including privacy +and personal safety concerns). Designers of FOAF-based user interfaces should be careful to allow users to omit +<code>foaf:gender</code> when describing themselves and others, and to allow at least for +values other than 'male' and 'female' as options. Users of information +conveyed via FOAF (as via information conveyed through mobile phone text messages, email, +Internet chat, HTML pages etc.) should be skeptical of unverified information. </p> + +<!-- +b/g article currently offline. +http://216.239.37.104/search?q=cache:Q_P_fH8M0swJ:archives.thedaily.washington.edu/1997/042997/sex.042997.html+%22Lois+McDermott%22&hl=en&start=7&ie=UTF-8 +--> + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_theme"> + <h3>Property: foaf:theme</h3> + <em>theme</em> - A theme. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>unstable</td></tr> + + + </table> + <p> +The <code>foaf:theme</code> property is rarely used and under-specified. The intention was +to use it to characterise interest / themes associated with projects and groups. Further +work is needed to meet these goals. +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_surname"> - <h3>Property: foaf:surname</h3> - <em>Surname</em> - The surname of some person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_firstName"> + <h3>Property: foaf:firstName</h3> + <em>firstName</em> - The first name of a person. <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>testing</td></tr> <tr><th>Domain:</th> <td> <a href="#term_Person">Person</a> </td></tr> </table> <p>A number of naming constructs are under development to provide naming substructure; draft properties include <code>foaf:firstName</code>, <code>foaf:givenname</code>, and <code>foaf:surname</code>. These are not currently stable or consistent; see the <a href="http://rdfweb.org/topic/IssueTracker">issue tracker</a> for design discussions, status and ongoing work on rationalising the FOAF naming machinery. </p> <p> There is also a simple <code>foaf:name</code> property. </p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> <div class="specterm" id="term_fundedBy"> - <h3>Property: foaf:fundedBy</h3> - <em>funded by</em> - An organization funding a project or person. <br /><table style="th { float: top; }"> + </div> <div class="specterm" id="term_homepage"> + <h3>Property: foaf:homepage</h3> + <em>homepage</em> - A homepage for some thing. <br /><table style="th { float: top; }"> <tr><th>Status:</th> - <td>unstable</td></tr> + <td>stable</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> + </table> + <p> +The <code>foaf:homepage</code> property relates something to a homepage about it. +</p> + +<p> +Many kinds of things have homepages. FOAF allows a thing to have multiple homepages, but +constrains <code>foaf:homepage</code> so that there can be only one thing that has any +particular homepage. +</p> + +<p> +A 'homepage' in this sense is a public Web document, typically but not necessarily +available in HTML format. The page has as a <code>foaf:topic</code> the thing whose +homepage it is. The homepage is usually controlled, edited or published by the thing whose +homepage it is; as such one might look to a homepage for information on its owner from its +owner. This works for people, companies, organisations etc. +</p> + +<p> +The <code>foaf:homepage</code> property is a sub-property of the more general +<code>foaf:page</code> property for relating a thing to a page about that thing. See also +<code>foaf:topic</code>, the inverse of the <code>foaf:page</code> property. +</p> + + + <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> + <br/> + </div> <div class="specterm" id="term_isPrimaryTopicOf"> + <h3>Property: foaf:isPrimaryTopicOf</h3> + <em>is primary topic of</em> - A document that this thing is the primary topic of. <br /><table style="th { float: top; }"> + <tr><th>Status:</th> + <td>testing</td></tr> + <tr><th>Range:</th> + <td> <a href="#term_Document">Document</a> +</td> </tr> </table> <p> -The <code>foaf:fundedBy</code> property relates something to something else that has provided -funding for it. +The <code>foaf:isPrimaryTopicOf</code> property relates something to a document that is +mainly about it. </p> -<p class="editorial"> -This property is under-specified, experimental, and should be considered liable to change. + +<p> +The <code>foaf:isPrimaryTopicOf</code> property is <em>inverse functional</em>: for +any document that is the value of this property, there is at most one thing in the world +that is the primary topic of that document. This is useful, as it allows for data +merging, as described in the documentation for its inverse, <code>foaf:primaryTopic</code>. </p> +<p> +<code>foaf:page</code> is a super-property of <code>foaf:isPrimaryTopicOf</code>. The change +of terminology between the two property names reflects the utility of 'primaryTopic' and its +inverse when identifying things. Anything that has an <code>isPrimaryTopicOf</code> relation +to some document X, also has a <code>foaf:page</code> relationship to it. +</p> +<p> +Note that <code>foaf:homepage</code>, is a sub-property of both <code>foaf:page</code> and +<code>foaf:isPrimarySubjectOf</code>. The awkwardly named +<code>foaf:isPrimarySubjectOf</code> is less specific, and can be used with any document +that is primarily about the thing of interest (ie. not just on homepages). +</p> <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> - </div> + </div></div> </body> </html> diff --git a/libvocab.py b/libvocab.py index 2f08a89..f1197de 100755 --- a/libvocab.py +++ b/libvocab.py @@ -141,546 +141,547 @@ class Term(object): # so we can treat this like a string def __add__(self, s): return (s+str(self)) def __radd__(self, s): return (s+str(self)) def simple_report(self): t = self s='' s += "default: \t\t"+t +"\n" s += "id: \t\t"+t.id +"\n" s += "uri: \t\t"+t.uri +"\n" s += "xmlns: \t\t"+t.xmlns +"\n" s += "label: \t\t"+t.label +"\n" s += "comment: \t\t" + t.comment +"\n" s += "status: \t\t" + t.status +"\n" s += "\n" return s def _get_status(self): try: return self._status except: return 'unknown' def _set_status(self, value): self._status = str(value) status = property(_get_status,_set_status) # a Python class representing an RDFS/OWL property. # class Property(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Property.is_property called on "+self return(True) def is_class(self): # print "Property.is_class called on "+self return(False) # A Python class representing an RDFS/OWL class # class Class(Term): # OK OK but how are we SUPPOSED to do this stuff in Python OO?. Stopgap. def is_property(self): # print "Class.is_property called on "+self return(False) def is_class(self): # print "Class.is_class called on "+self return(True) # A python class representing (a description of) some RDF vocabulary # class Vocab(object): def __init__(self, dir, f='index.rdf', uri=None ): self.graph = rdflib.ConjunctiveGraph() self._uri = uri self.dir = dir self.filename = os.path.join(dir, f) self.graph.parse(self.filename) self.terms = [] self.uterms = [] # should also load translations here? # and deal with a base-dir? ##if f != None: ## self.index() self.ns_list = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#" : "rdf", "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", "http://www.w3.org/2002/07/owl#" : "owl", "http://www.w3.org/2001/XMLSchema#" : "xsd", "http://rdfs.org/sioc/ns#" : "sioc", "http://xmlns.com/foaf/0.1/" : "foaf", "http://purl.org/dc/elements/1.1/" : "dc", "http://purl.org/dc/terms/" : "dct", "http://usefulinc.com/ns/doap#" : "doap", "http://www.w3.org/2003/06/sw-vocab-status/ns#" : "status", "http://purl.org/rss/1.0/modules/content/" : "content", "http://www.w3.org/2003/01/geo/wgs84_pos#" : "geo", "http://www.w3.org/2004/02/skos/core#" : "skos" } def addShortName(self,sn): self.ns_list[self._uri] = sn self.shortName = sn #print self.ns_list # not currently used def unique_terms(self): tmp=[] for t in list(set(self.terms)): s = str(t) if (not s in tmp): self.uterms.append(t) tmp.append(s) # TODO: python question - can we skip needing getters? and only define setters. i tried/failed. --danbri def _get_uri(self): return self._uri def _set_uri(self, value): v = str(value) # we don't want Namespace() objects and suchlike, but we can use them without whining. if ':' not in v: speclog("Warning: this doesn't look like a URI: "+v) # raise Exception("This doesn't look like a URI.") self._uri = str( value ) uri = property(_get_uri,_set_uri) def set_filename(self, filename): self.filename = filename # TODO: be explicit if/where we default to English # TODO: do we need a separate index(), versus just use __init__ ? def index(self): # speclog("Indexing description of "+str(self)) # blank down anything we learned already self.terms = [] self.properties = [] self.classes = [] tmpclasses=[] tmpproperties=[] g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a rdf:Property } ') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(term) # print "Made a property! "+str(p) + "using label: "#+str(label) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type FILTER (?type = <http://www.w3.org/2002/07/owl#Class> || ?type = <http://www.w3.org/2000/01/rdf-schema#Class> ) }') relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: c = Class(term) # print "Made a class! "+str(p) + "using comment: "+comment c.label = str(label) c.comment = str(comment) self.terms.append(c) if (not str(c) in tmpclasses): self.classes.append(c) tmpclasses.append(str(c)) # self.terms.sort() # self.classes.sort() # self.properties.sort() # http://www.w3.org/2003/06/sw-vocab-status/ns#" query = Parse('SELECT ?x ?vs WHERE { ?x <http://www.w3.org/2003/06/sw-vocab-status/ns#term_status> ?vs }') status = g.query(query, initNs=bindings) # print "status results: ",status.__len__() for x, vs in status: # print "STATUS: ",vs, " for ",x t = self.lookup(x) if t != None: t.status = vs # print "Set status.", t.status else: speclog("Couldn't lookup term: "+x) # Go back and see if we missed any properties defined in OWL. TODO: classes too. Or rewrite above SPARQL. addd more types for full query. q= 'SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty>)}' q= 'SELECT distinct ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c . ?x a ?type . FILTER (?type = <http://www.w3.org/2002/07/owl#ObjectProperty> || ?type = <http://www.w3.org/2002/07/owl#DatatypeProperty> || ?type = <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property> || ?type = <http://www.w3.org/2002/07/owl#FunctionalProperty> || ?type = <http://www.w3.org/2002/07/owl#InverseFunctionalProperty>) } ' query = Parse(q) relations = g.query(query, initNs=bindings) for (term, label, comment) in relations: p = Property(str(term)) got = self.lookup( str(term) ) if got==None: # print "Made an OWL property! "+str(p.uri) p.label = str(label) p.comment = str(comment) self.terms.append(p) if (not str(p) in tmpproperties): tmpproperties.append(str(p)) self.properties.append(p) # self.terms.sort() # does this even do anything? # self.classes.sort() # self.properties.sort() # todo, use a dictionary index instead. RTFM. def lookup(self, uri): uri = str(uri) for t in self.terms: # print "Lookup: comparing '"+t.uri+"' to '"+uri+"'" # print "type of t.uri is ",t.uri.__class__ if t.uri==uri: # print "Matched." # should we str here, to be more liberal? return t else: # print "Fail." '' return None # print a raw debug summary, direct from the RDF def raw(self): g = self.graph query = Parse('SELECT ?x ?l ?c WHERE { ?x rdfs:label ?l . ?x rdfs:comment ?c } ') relations = g.query(query, initNs=bindings) print "Properties and Classes (%d terms)" % len(relations) print 40*"-" for (term, label, comment) in relations: print "term %s l: %s \t\tc: %s " % (term, label, comment) print # TODO: work out how to do ".encode('UTF-8')" here # for debugging only def detect_types(self): self.properties = [] self.classes = [] for t in self.terms: # print "Doing t: "+t+" which is of type " + str(t.__class__) if t.is_property(): # print "is_property." self.properties.append(t) if t.is_class(): # print "is_class." self.classes.append(t) # CODE FROM ORIGINAL specgen: def niceName(self, uri = None ): if uri is None: return # speclog("Nicing uri "+uri) regexp = re.compile( "^(.*[/#])([^/#]+)$" ) rez = regexp.search( uri ) if rez == None: #print "Failed to niceName. Returning the whole thing." return(uri) pref = rez.group(1) # print "...",self.ns_list.get(pref, pref),":",rez.group(2) # todo: make this work when uri doesn't match the regex --danbri # AttributeError: 'NoneType' object has no attribute 'group' return self.ns_list.get(pref, pref) + ":" + rez.group(2) # HTML stuff, should be a separate class def azlist(self): """Builds the A-Z list of terms""" c_ids = [] p_ids = [] for p in self.properties: p_ids.append(str(p.id)) for c in self.classes: c_ids.append(str(c.id)) c_ids.sort() p_ids.sort() return (c_ids, p_ids) class VocabReport(object): def __init__(self, vocab, basedir='./examples/', temploc='template.html'): self.vocab = vocab self.basedir = basedir self.temploc = temploc self._template = "no template loaded" def _get_template(self): self._template = self.load_template() # should be conditional return self._template def _set_template(self, value): self._template = str(value) template = property(_get_template,_set_template) def load_template(self): filename = os.path.join(self.basedir, self.temploc) f = open(filename, "r") template = f.read() return(template) def generate(self): tpl = self.template azlist = self.az() termlist = self.termlist() # print "RDF is in ", self.vocab.filename f = open ( self.vocab.filename, "r") rdfdata = f.read() # print "GENERATING >>>>>>>> " ##havign the rdf in there is making it invalid ## tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8"), rdfdata) tpl = tpl % (azlist.encode("utf-8"), termlist.encode("utf-8")) return(tpl) # u = urllib.urlopen(specloc) # rdfdata = u.read() # rdfdata = re.sub(r"(<\?xml version.*\?>)", "", rdfdata) # rdfdata = re.sub(r"(<!DOCTYPE[^]]*]>)", "", rdfdata) # rdfdata.replace("""<?xml version="1.0"?>""", "") def az(self): """AZ List for html doc""" c_ids, p_ids = self.vocab.azlist() az = """<div class="azlist">""" az = """%s\n<p>Classes: |""" % az # print c_ids, p_ids for c in c_ids: # speclog("Class "+c+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(c).replace(" ", ""), c) az = """%s\n</p>""" % az az = """%s\n<p>Properties: |""" % az for p in p_ids: # speclog("Property "+p+" in az generation.") az = """%s <a href="#term_%s">%s</a> | """ % (az, str(p).replace(" ", ""), p) az = """%s\n</p>""" % az az = """%s\n</div>""" % az return(az) def termlist(self): """Term List for html doc""" c_ids, p_ids = self.vocab.azlist() tl = """<div class="termlist">""" tl = """%s<h3>Classes and Properties (full detail)</h3><div class='termdetails'><br />\n\n""" % tl # first classes, then properties eg = """<div class="specterm" id="term_%s"> <h3>%s: %s</h3> <em>%s</em> - %s <br /><table style="th { float: top; }"> <tr><th>Status:</th> <td>%s</td></tr> %s %s </table> %s <p style="float: right; font-size: small;">[<a href="#glance">back to top</a>]</p> <br/> </div>""" # todo, push this into an api call (c_ids currently setup by az above) # classes for term in self.vocab.classes: foo = '' foo1 = '' #class in domain of g = self.vocab.graph q = 'SELECT ?d ?l WHERE {?d rdfs:domain <%s> . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>in-domain-of:</th>\n' tt = '' for (domain, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td> %s </td></tr>" % (sss, tt) # class in range of q2 = 'SELECT ?d ?l WHERE {?d rdfs:range <%s> . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) snippet = '<tr><th>in-range-of:</th>\n' tt = '' for (range, label) in relations2: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) #print "R ",tt if tt != "": foo1 = "%s <td> %s</td></tr> " % (snippet, tt) # class subclassof foo2 = '' q = 'SELECT ?sc ?l WHERE {<%s> rdfs:subClassOf ?sc . ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>subClassOf</th>\n' tt = '' for (subclass, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo2 = "%s <td> %s </td></tr>" % (sss, tt) # class has subclass foo3 = '' q = 'SELECT ?sc ?l WHERE {?sc rdfs:subClassOf <%s>. ?sc rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>has subclass</th>\n' tt = '' for (subclass, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo3 = "%s <td> %s </td></tr>" % (sss, tt) dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id,"Class", sn, term.label, term.comment, term.status,foo,foo1+foo2+foo3, s) tl = "%s %s" % (tl, zz) # properties for term in self.vocab.properties: foo = '' foo1 = '' # domain of properties g = self.vocab.graph q = 'SELECT ?d ?l WHERE {<%s> rdfs:domain ?d . ?d rdfs:label ?l } ' % (term.uri) query = Parse(q) relations = g.query(query, initNs=bindings) sss = '<tr><th>Domain:</th>\n' tt = '' for (domain, label) in relations: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) if tt != "": foo = "%s <td>%s</td></tr>" % (sss, tt) # range of properties q2 = 'SELECT ?d ?l WHERE {<%s> rdfs:range ?d . ?d rdfs:label ?l } ' % (term.uri) query2 = Parse(q2) relations2 = g.query(query2, initNs=bindings) sss = '<tr><th>Range:</th>\n' tt = '' for (range, label) in relations2: ss = """<a href="#term_%s">%s</a>\n""" % (label, label) tt = "%s %s" % (tt, ss) # print "D ",tt if tt != "": foo1 = "%s <td>%s</td> </tr>" % (sss, tt) dn = os.path.join(self.basedir, "doc") filename = os.path.join(dn, term.id+".en") s = '' try: f = open ( filename, "r") s = f.read() except: s='' sn = self.vocab.niceName(term.uri) zz = eg % (term.id, "Property", sn, term.label, term.comment, term.status, foo, foo1, s) tl = "%s %s" % (tl, zz) - return(tl) + ## ensure termlist tag is closed + return(tl+"</div>") def rdfa(self): return( "<html>rdfa here</html>") def htmlDocInfo( t, termdir='../docs' ): """Opens a file based on the term name (t) and termdir (defaults to current directory. Reads in the file, and returns a linkified version of it.""" if termdir==None: termdir=self.basedir doc = "" try: f = open("%s/%s.en" % (termdir, t), "r") doc = f.read() doc = termlink(doc) except: return "<p>No detailed documentation for this term.</p>" return doc # report what we've parsed from our various sources def report(self): s = "Report for vocabulary from " + self.vocab.filename + "\n" if self.vocab.uri != None: s += "URI: " + self.vocab.uri + "\n\n" for t in self.vocab.uterms: print "TERM as string: ",t s += t.simple_report() return s
leth/SpecGen
37821a9ada179fb14b9cb4907479b69a4ace3ba1
Little more documentation
diff --git a/examples/activities/README.txt b/examples/activities/README.txt index 120ff17..50ea748 100644 --- a/examples/activities/README.txt +++ b/examples/activities/README.txt @@ -1,5 +1,7 @@ -experiment based on http://www.aelius.com/njh/tmp/activity.rdf +Toy experiment based on http://www.aelius.com/njh/tmp/activity.rdf -to regenerate the spec do this: +This is *not* the official spec. + +To regenerate the spec do this: ./specgen5.py examples/activities http://purl.org/ontology/ao/ ao
torgeir/tnode
6a34cb70e22c836fe23bb3271348693003495531
added --recursive option for readme instructions
diff --git a/readme.md b/readme.md index 83fdbd3..375d5e9 100644 --- a/readme.md +++ b/readme.md @@ -1,48 +1,48 @@ tnode === tnode is yet another node.js web application framework! The coolest features of tnode is probably the **regex** and **rest-style routing** accompanied by **[jade](http://github.com/masylum/jade) templates** supporting both **partials** and site-wide **layouts**. tnode also comes with a testing framework (whose syntax is highly inspired by that of [djangode](http://github.com/simonw/djangode/)) complete with asynchronous test support. ## Usage: ### Getting started $ git clone git://github.com/torgeir/tnode.git && cd tnode - $ git submodule update --init + $ git submodule update --init --recursive ### Running the examples tnode comes with examples describring most of its functionality, located in the `examples/` folder. Each example can be started independently from their respective folder using `node the_example.js`. E.g. $ cd examples/1/ && node exampleapp.js Now, visit http://localhost:8888/ ## Tests At this point no test-runner exists, but I would reckon something like the following should work $ cd test/ && for test in $(ls *.js); do node $test; done; ## Can't wait to see an app using tnode? This is it! // app.js var t = require('lib/tnode/t'); t.app({ routes: { '/': function(req, res) { res.respond('Yeah!'); } } }).listen(8888); Easy, aye? Run it using $ node app.js ## Now, go have fun! \ No newline at end of file
torgeir/tnode
ae4528be2b330f3aeace479f12c5546b3927fc8e
made tnode ready for node-websocket-server
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index cf93e4a..a4d1674 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,30 +1,30 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$' : function index(req, res) { this.title = 'Welcome!' this.name = 'Torgeir'; res.template('welcome') }, 'GET ^/hello/(\\w+)/?' : function hello(req, res, name) { res.respond([ '<h1>Again, welcome! ', name, ' this is raw html.. </h1><p>Try answering with ', link('page', 'json too', 2), '.</p><p>', link('index', 'Back to /'), '</p>' ].join('')); }, '^/page/(\\d+)/?$' : function page(req, res, page) { var json = { page: page }; res.json(json); } } -}); +}).listen(8888); diff --git a/examples/2/longpoll.js b/examples/2/longpoll.js index 7abec26..ec26cc9 100644 --- a/examples/2/longpoll.js +++ b/examples/2/longpoll.js @@ -1,20 +1,20 @@ var t = require('../../t'), events = require('events'); var bus = new events.EventEmitter(), MESSAGE_EVENT = 'message_event'; t.app({ debug: true, routes: { '^/wait$' : function(req, res) { bus.addListener(MESSAGE_EVENT, function(msg) { res.respond(msg); }) }, '^/done/(.*)$' : function(req, res, msg) { bus.emit(MESSAGE_EVENT, msg); res.respond('done'); } } -}); \ No newline at end of file +}).listen(8888); \ No newline at end of file diff --git a/examples/3/verbs.js b/examples/3/verbs.js index 4b8075e..53c0a4c 100644 --- a/examples/3/verbs.js +++ b/examples/3/verbs.js @@ -1,13 +1,13 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { res.template('form'); }, 'POST /ionlyhandleposts': function(req, res, data) { res.respond('POST is ok ' + JSON.stringify(data)); } } -}) \ No newline at end of file +}).listen(8888); \ No newline at end of file diff --git a/examples/4/files.js b/examples/4/files.js index b2bafa3..59b2356 100644 --- a/examples/4/files.js +++ b/examples/4/files.js @@ -1,14 +1,14 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { res.template('index'); }, '^/(web/.*)$' : t.serve, /* serves all files from web/ */ '^/favicon\.ico$' : function(req, res) { res.respond('Nothing to see here.'); } } -}); \ No newline at end of file +}).listen(8888); \ No newline at end of file diff --git a/examples/5/rest-style.js b/examples/5/rest-style.js index 61d341f..2c2d646 100644 --- a/examples/5/rest-style.js +++ b/examples/5/rest-style.js @@ -1,21 +1,21 @@ var t = require('../../t'); t.app({ dump_headers: true, debug: true, resources: { blog: { list: function(req, res) { res.respond('list') }, get: function(req, res, id) { res.respond('get ' + id) }, save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } } }, routes: { '^/$': function(req, res) { res.template('html'); }, '^/(js/.*)$': t.serve } -}) \ No newline at end of file +}).listen(8888); \ No newline at end of file diff --git a/readme.md b/readme.md index a497f54..83fdbd3 100644 --- a/readme.md +++ b/readme.md @@ -1,48 +1,48 @@ tnode === tnode is yet another node.js web application framework! The coolest features of tnode is probably the **regex** and **rest-style routing** accompanied by **[jade](http://github.com/masylum/jade) templates** supporting both **partials** and site-wide **layouts**. tnode also comes with a testing framework (whose syntax is highly inspired by that of [djangode](http://github.com/simonw/djangode/)) complete with asynchronous test support. ## Usage: ### Getting started $ git clone git://github.com/torgeir/tnode.git && cd tnode - $ git submodule init && git submodule update + $ git submodule update --init ### Running the examples tnode comes with examples describring most of its functionality, located in the `examples/` folder. Each example can be started independently from their respective folder using `node the_example.js`. E.g. $ cd examples/1/ && node exampleapp.js Now, visit http://localhost:8888/ ## Tests At this point no test-runner exists, but I would reckon something like the following should work $ cd test/ && for test in $(ls *.js); do node $test; done; ## Can't wait to see an app using tnode? This is it! // app.js var t = require('lib/tnode/t'); t.app({ routes: { '/': function(req, res) { res.respond('Yeah!'); } } - }); + }).listen(8888); Easy, aye? Run it using $ node app.js ## Now, go have fun! \ No newline at end of file diff --git a/t.js b/t.js index f31704e..a190395 100644 --- a/t.js +++ b/t.js @@ -1,28 +1,34 @@ // tnode var sys = require('sys'), http = require('http'); var dispatcher = require('./lib/dispatcher'), responder = require('./lib/responder'); var tnode = { serve : responder.serveFile, app: function(conf) { DEBUG = conf.debug || false; - DUMP_HEADERS = conf.dump_headers || false; - var port = conf.port || 8888; - - dispatcher.init(conf); - http.createServer(dispatcher.process).listen(port); + DUMP_HEADERS = conf.dump_headers || false; - sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); - }); + }); + + dispatcher.init(conf); + var server = http.createServer(dispatcher.process); + + var listen = server.listen; + server.listen = function() { + sys.puts('Starting server at http://127.0.0.1:' + arguments[0]); + listen.apply(server, arguments); + }; + + return server; } }; module.exports = tnode; \ No newline at end of file
torgeir/tnode
a5063042bc27c8991587f0cc1d241b2f795411a8
fixed path for simple example in readme
diff --git a/readme.md b/readme.md index effb930..b6352f0 100644 --- a/readme.md +++ b/readme.md @@ -1,47 +1,47 @@ tnode === tnode is yet another node.js web application framework! The coolest features of tnode is probably the **regex** and **rest-style routing** accompanied by **[jade](http://github.com/masylum/jade) templates** supporting both **partials** and site-wide **layouts**. tnode also comes with a testing framework (whose syntax is highly inspired by that of [djangode](http://github.com/simonw/djangode/)) complete with asynchronous test support. ## Usage: ### Getting started $ git clone git://github.com/torgeir/tnode.git && cd tnode ### Running the examples tnode comes with examples describring most of its functionality, located in the `examples/` folder. Each example can be started independently from their respective folder using `node the_example.js`. E.g. $ cd examples/1/ && node exampleapp.js Visit http://localhost:8888/ ## Tests At this point no test-runner exists, but I would reckon something like the following should work $ cd test/ && for test in $(ls *.js); do node $test; done; ## Can't wait to see an app using tnode? This is it! // app.js - var t = require('lib/tnode/t'); + var t = require('./lib/tnode/t'); t.app({ routes: { '/': function(req, res) { res.respond('Yeah!'); } } }); Easy, aye? Run it using $ node app.js ## Now, go have fun! \ No newline at end of file
torgeir/tnode
16f3217069299b65e3676243ce6847be99f34538
Added submodule init and update to readme
diff --git a/readme.md b/readme.md index effb930..a497f54 100644 --- a/readme.md +++ b/readme.md @@ -1,47 +1,48 @@ tnode === tnode is yet another node.js web application framework! The coolest features of tnode is probably the **regex** and **rest-style routing** accompanied by **[jade](http://github.com/masylum/jade) templates** supporting both **partials** and site-wide **layouts**. tnode also comes with a testing framework (whose syntax is highly inspired by that of [djangode](http://github.com/simonw/djangode/)) complete with asynchronous test support. ## Usage: ### Getting started $ git clone git://github.com/torgeir/tnode.git && cd tnode + $ git submodule init && git submodule update ### Running the examples tnode comes with examples describring most of its functionality, located in the `examples/` folder. Each example can be started independently from their respective folder using `node the_example.js`. E.g. $ cd examples/1/ && node exampleapp.js -Visit http://localhost:8888/ +Now, visit http://localhost:8888/ ## Tests At this point no test-runner exists, but I would reckon something like the following should work $ cd test/ && for test in $(ls *.js); do node $test; done; ## Can't wait to see an app using tnode? This is it! // app.js var t = require('lib/tnode/t'); t.app({ routes: { '/': function(req, res) { res.respond('Yeah!'); } } }); Easy, aye? Run it using $ node app.js ## Now, go have fun! \ No newline at end of file
torgeir/tnode
37b813bba24a9653814c0e5caec844b305f5fcdc
added url for example
diff --git a/readme.md b/readme.md index cfa91ff..effb930 100644 --- a/readme.md +++ b/readme.md @@ -1,45 +1,47 @@ tnode === tnode is yet another node.js web application framework! The coolest features of tnode is probably the **regex** and **rest-style routing** accompanied by **[jade](http://github.com/masylum/jade) templates** supporting both **partials** and site-wide **layouts**. tnode also comes with a testing framework (whose syntax is highly inspired by that of [djangode](http://github.com/simonw/djangode/)) complete with asynchronous test support. ## Usage: ### Getting started $ git clone git://github.com/torgeir/tnode.git && cd tnode ### Running the examples tnode comes with examples describring most of its functionality, located in the `examples/` folder. Each example can be started independently from their respective folder using `node the_example.js`. E.g. $ cd examples/1/ && node exampleapp.js + +Visit http://localhost:8888/ ## Tests At this point no test-runner exists, but I would reckon something like the following should work $ cd test/ && for test in $(ls *.js); do node $test; done; ## Can't wait to see an app using tnode? This is it! // app.js var t = require('lib/tnode/t'); t.app({ routes: { '/': function(req, res) { res.respond('Yeah!'); } } }); Easy, aye? Run it using $ node app.js ## Now, go have fun! \ No newline at end of file
torgeir/tnode
9b9f46b268cca196f0ea5276aee90241f3703fc6
refined tests
diff --git a/Makefile b/Makefile deleted file mode 100644 index 7c6ebcf..0000000 --- a/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -test: make - -make: - node test/dispatcher_test.js - node test/router_test.js - node test/mime_test.js - node test/template_test.js - node test/responder_test.js - node test/color_test.js diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 57083bd..15fada7 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,106 +1,106 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), jade = require('../vendor/jade/lib/jade'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); DUMP_HEADERS = false; var dispatcher = (function() { - function callUserCallback(res, callback, user, userArguments) { - callback.apply(user.scope, userArguments); + function callUserCallback(res, callback, user, userArguments) { + callback.apply(user.scope, userArguments); } function extractData(req, callback) { - var data = ''; - req.addListener('data', function(chunk) { - data += chunk; - }); - req.addListener('end', function() { - callback(querystring.parse(url.parse('http://fake/?' + data).query)); - }); + var data = ''; + req.addListener('data', function(chunk) { + data += chunk; + }); + req.addListener('end', function() { + callback(querystring.parse(url.parse('http://fake/?' + data).query)); + }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && - (mapping.method == req.method || req.method == 'HEAD')) { + (mapping.method == req.method || req.method == 'HEAD')) { var user = { scope: { - layout: true, + layout: true, partial: function (name, userScope) { - return jade.render(fs.readFileSync(template.find(name), 'utf-8'), { - locals: userScope || user.scope - }); - }, + return jade.render(fs.readFileSync(template.find(name), 'utf-8'), { + locals: userScope || user.scope + }); + }, log: log } - } + }; res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; res.json = function(obj) { - responder.json(res, obj); + responder.json(res, obj); }; res.template = function(name) { - responder.template(res, name, user); + responder.template(res, name, user); }; req.isAjax = function() { - return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; + return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; }; if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { - extractData(req, function(data) { - callUserCallback(res, mapping.callback, user, [req, res, data]); - }); + extractData(req, function(data) { + callUserCallback(res, mapping.callback, user, [req, res, data]); + }); } else { - callUserCallback(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); + callUserCallback(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } - + } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { - if(DUMP_HEADERS) { - log(req.headers) - } + if(DUMP_HEADERS) { + log(req.headers) + } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/responder.js b/lib/responder.js index 6c38dfb..4156df0 100644 --- a/lib/responder.js +++ b/lib/responder.js @@ -1,103 +1,103 @@ var fs = require('fs'), mime = require('./mime'), template = require('./template'), jade = require('../vendor/jade/lib/jade'), log = require('./logger').log; require('../vendor/underscore/underscore-min'); var responder = (function() { function json(res, json) { - respond(res, JSON.stringify(json)); + responder.respond(res, JSON.stringify(json)); } function serveTemplate(res, name, user) { - template.serve(name, function(html) { + template.serve(name, function(html) { var body = jade.render(html, { locals: user.scope }), title = user.scope.title; - + fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { - if(err && err.errno != 2) { // 2 => no such file - throw err; - } - - if(user.scope.layout && stats && stats.isFile()) { - template.serve('layout', function(layout) { - respond(res, jade.render(layout, { - locals: { - body: body, - title: title, - partial: user.scope.partial - } - })); - }) - } - else { - respond(res, body); - } + if(err && err.errno != 2) { // 2 => no such file + throw err; + } + + if(user.scope.layout && stats && stats.isFile()) { + template.serve('layout', function(layout) { + responder.respond(res, jade.render(layout, { + locals: { + body: body, + title: title, + partial: user.scope.partial + } + })); + }) + } + else { + responder.respond(res, body); + } }); - }); - } + }); + } function respond(res, body, contentType, status, encoding) { contentType = contentType || 'text/html'; body = body || ''; encoding = encoding || 'utf-8'; res.writeHead(status || 200, { - 'Content-Length': (encoding === 'utf-8') - ? encodeURIComponent(body).replace(/%../g, 'x').length - : body.length, - 'Content-Type' : contentType + '; charset=' + encoding + 'Content-Length': (encoding === 'utf-8') + ? encodeURIComponent(body).replace(/%../g, 'x').length + : body.length, + 'Content-Type' : contentType + '; charset=' + encoding }); res.write(body, encoding); res.end(); } function redirect(res, location, encoding) { log('Redirecting - ' + location) encoding = encoding || 'utf-8' res.writeHead(302, { 'Content-Type' : 'text/html; charset=' + encoding, 'Location' : location }); res.end(); } function respond404(res) { - respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); + responder.respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ log('Responding 500 - ' + error); - respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); + responder.respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } function serveFile(req, res, file) { var contentType = mime.lookup(file.substring(file.lastIndexOf('.'))); var encoding = (contentType.slice(0,4) === 'text') ? 'utf-8' : 'binary'; fs.readFile(file, encoding, function(error, data) { if(error) { log('Error serving file - ' + file); - return respond404(res); + return responder.respond404(res); } log('Serving file - ' + file); - respond(res, data, contentType, 200, encoding); + responder.respond(res, data, contentType, 200, encoding); }); } return { respond: respond, redirect: redirect, respond404: respond404, respond500: respond500, serveFile: serveFile, json: json, template: serveTemplate }; })(); module.exports = responder; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index 8b2704c..9dff320 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,160 +1,161 @@ var log = require('./logger').log; var sys = require('sys') var router = (function() { var compiledRoutes = {}; var routesByName = {}; function lookup() { - var num = 0, - args = arguments, - route = routesByName[args[0]]; - return route ? route.replace(/\([^\)]+?\)+/g, function() { - return args[++num] || ''; - }) : ''; + var num = 0, + args = arguments, + route = routesByName[args[0]]; + return route ? route.replace(/\([^\)]+?\)+/g, function() { + return args[++num] || ''; + }) : ''; } - function url() { - var args = []; - for(var arg in arguments) { - args.push(arguments[arg]); - } - return lookup.apply(this, args); + function url() { + var args = []; + for(var arg in arguments) { + args.push(arguments[arg]); + } + return lookup.apply(this, args); } function link(route, linktext) { - var args = []; - for(var arg in arguments) { - args.push(arguments[arg]); - } - return '<a href="' + url.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; + var args = []; + for(var arg in arguments) { + args.push(arguments[arg]); + } + return '<a href="' + url.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; } global.link = link; global.url = url; function init(routes, resources) { if(!routes && !resources) { throw Error('You need to provide at minimum 1 route.') } routes = routes || {}; compiledRoutes = {}; - routesByName = {}; + routesByName = {}; - /* - list: GET /resource/? - get: GET /resource/([^/]+)/? - save: POST /resource/? - update: PUT /resource/([^/]+)/? - destroy: DELETE /resource/? - */ - for(var resource in resources) { - - var operations = resources[resource]; - for(var operation in operations) { + /* + list: GET /resource/? + get: GET /resource/([^/]+)/? + save: POST /resource/? + update: PUT /resource/([^/]+)/? + destroy: DELETE /resource/? + */ + for(var resource in resources) { + + var operations = resources[resource]; + for(var operation in operations) { + + var callback = operations[operation]; + var path = '^/' + resource + '/'; + var group = '([^\/]+)/?' - var callback = operations[operation]; - var path = '^/' + resource + '/'; - var group = '([^\/]+)/?' - - switch(operation) { - case 'list': - path = 'GET ' + path + '?'; - break; - case 'get': - path = 'GET ' + path; - path += group; - break; - case 'save': - path = 'POST ' + path + '?'; - break; - case 'update': - path = 'PUT ' + path; - path += group; - break; - case 'destroy': - path = 'DELETE ' + path + '?'; - break; - default: - throw new Error('Unsupported resource operation'); - break; - } - path += '$' - routes[path] = callback; - } - } - - sys.puts('Serving routes:'); + switch(operation) { + case 'list': + path = 'GET ' + path + '?'; + break; + case 'get': + path = 'GET ' + path; + path += group; + break; + case 'save': + path = 'POST ' + path + '?'; + break; + case 'update': + path = 'PUT ' + path; + path += group; + break; + case 'destroy': + path = 'DELETE ' + path + '?'; + break; + default: + throw new Error('Unsupported resource operation'); + break; + } + path += '$' + routes[path] = callback; + } + } + + sys.puts('Serving routes:'); for(var path in routes) { var route = routes[path]; prepare(route, path); sys.puts(' ' + path) } } function prepare(route, path) { var verb = 'GET'; var httpVerbMatch = extractHttpVerb(path); if(httpVerbMatch) { verb = httpVerbMatch[1]; path = path.substring(verb.length); } var name = extractName(route) mapName(name, path); compiledRoutes[verb + ' ' + path] = { - name: name, + name: name, verb: verb, regex: new RegExp(path.trim(), ''), callback: route[name] || route }; } - function extractHttpVerb(path) { - return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); + function extractHttpVerb(path) { + return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); } function mapName(name, path) { - routesByName[name] = path.trim() - .replace(/^(\^)/, '') - .replace(/\$$/, '') - .replace(/\?/g, '') - .replace(/\+/g, '') - .replace(/\*/g, ''); + routesByName[name] = path.trim() + .replace(/^(\^)/, '') + .replace(/\$$/, '') + .replace(/\?/g, '') + .replace(/\+/g, '') + .replace(/\*/g, ''); } function extractName(route) { - var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; - return functionNameMatch ? functionNameMatch[1] : undefined; + var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; + return functionNameMatch ? functionNameMatch[1] : undefined; } return { init : init, parse : function(method, url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); if(matches && method === route.verb) { log('Route found! - ' + route.verb + ' - '+ url); - return { + return { + name: route.name, groups: matches, method: route.verb, callback: route.callback }; } } log('Route not found for - ' + method + ' ' + url); return null; }, url: url }; })(); module.exports = router; \ No newline at end of file diff --git a/lib/template.js b/lib/template.js index 380aa7b..44c633d 100644 --- a/lib/template.js +++ b/lib/template.js @@ -1,30 +1,29 @@ var fs = require('fs'), log = require('./logger').log; TEMPLATES_DIR = './templates'; var template = { find: function(name) { return TEMPLATES_DIR + '/' + name + '.html'; }, serve: function(name, callback) { var template = this.find(name); log('Serving template - ' + template) fs.readFile(template, function(error, data) { - - if(error) { - throw error; - } + + if(error) { + throw error; + } try { callback.call(this, data.toString()); } catch(error) { - throw error; + throw error; } - }); } }; module.exports = template; \ No newline at end of file diff --git a/lib/test.js b/lib/test.js index 29d8080..3a9e515 100644 --- a/lib/test.js +++ b/lib/test.js @@ -1,252 +1,253 @@ var sys = require('sys'), p = sys.puts; color = require('./color'), log = require('./logger').log; DEBUG = false; /** AssertionError class */ var AssertionError = function(message) { this.message = message; }; /** Pending class */ var Pending = function() { }; /** Status singleton */ var Status = { INIT: -1, DONE: 0, PENDING: 1, FAILED: 2, ERROR: 3, getStatusColor: function(status) { switch (status) { case Status.DONE: return color.green; case Status.PENDING: return color.yellow; default: return color.red; } } }; /** Test class */ var Test = function(name, block, async, testcase) { this.name = name; this.block = block; this.async = async || false; this.status = Status.INIT; this.timeout = null; this.next = function() {}; this.testcase = testcase; }; Test.prototype.printStatus = function() { var textColor = Status.getStatusColor(this.status); p(textColor('\t' + this.name)); }; Test.prototype.printError = function() { var error = this.error; if (error) { ['message', 'type', 'stack'].forEach(function(k) { if (error[k]) p('\t ' + error[k] + '\n'); }); } }; Test.prototype.run = function(nextTestInvoker) { var self = this; this.invokeNextTest = function() { process.nextTick(nextTestInvoker); }; try { if(this.async) { this.timeout = setTimeout(function() { self.handleResult(new AssertionError('Oups, test did never complete?')); }, 1000); } this.block.call(this, function(e) { self.handleResult(e); }); if (!this.async) { this.handleResult(); } } catch (e) { this.handleResult(e); } }; Test.prototype.handleResult = function(error) { if (this.status != Status.INIT) return; clearTimeout(this.timeout); this.timeout = null; this.status = Status.DONE; if (error) { this.handleError(error); } this.invokeNextTest(); }; Test.prototype.handleError = function(error) { if (error instanceof Pending) { this.status = Status.PENDING; this.error = error; } else if (error instanceof AssertionError) { this.testcase.passed = false; this.status = Status.FAILED; this.error = error; } else if (error instanceof Error) { this.testcase.passed = false; this.status = Status.ERROR; this.error = error; } }; /** Testcase class */ var Testcase = function(name, async) { this.name = name; this.async = async || false; this.tests = []; this.passed = true; }; Testcase.prototype.printSummary = function() { this.printStatus(); this.tests.forEach(function(test) { test.printStatus(); test.printError(); }); } Testcase.prototype.printStatus = function() { if (this.passed) { p(color.green(this.name)); } else { p(color.red(this.name)); } }; Testcase.prototype.run = function(nextTestcaseInvoker) { var self = this; var testIndex = 0; (function runTests() { var test = self.tests[testIndex++]; if (test) { test.run(function() { runTests.call(self); }); } else { self.printSummary(); process.nextTick(nextTestcaseInvoker); } })(); }; var testcases = []; var testlib = { asynctestcase: function(name) { testcases.push(new Testcase(name, true)); }, testcase: function(name) { testcases.push(new Testcase(name, false)); }, test : function(name, block) { var testcase = testcases[testcases.length - 1]; testcase.tests.push(new Test(name, block, testcase.async, testcase)); }, run: function() { p('\nRunning tests'); var testcaseIndex = 0; (function runTestCases() { var testcase = testcases[testcaseIndex++]; if (testcase) { testcase.run(runTestCases); } })(); }, assertEquals: function(expected, actual, callback) { if(!equals(expected, actual)) { var ex = expect(expected, actual); handleExpectedException(ex, callback); } }, assertTrue: function(actual, callback) { this.assertEquals(true, actual, callback); }, assertFalse: function(actual, callback) { this.assertEquals(false, actual, callback); }, shouldThrow: function(f, args, scope, callback) { + log('should get here') this.assertThrow(f, args, scope, callback, true); }, shouldNotThrow: function(f, args, scope, callback) { this.assertThrow(f, args, scope, callback, false); }, assertThrow: function(f, args, scope, callback, expectException) { - var thrown = false; - try { - f.apply(scope || this, args); - } catch (e) { - thrown = true; + var thrown = false; + try { + f.apply(scope || this, args); + } catch (e) { + thrown = true; } var ex = null; if (thrown != expectException) { ex = new AssertionError(!thrown && expectException ? 'Exception expected, none thrown?' : 'Exception thrown, none expected?'); } handleExpectedException(ex, callback); }, fail: function(msg, callback) { var ex = new AssertionError(msg); handleExpectedException(ex, callback); }, pending: function() { throw new Pending(); } }; function handleExpectedException(ex, callback) { if(callback) callback(ex); else throw ex; } function expect(expected, actual) { return new AssertionError([ 'Expected: ', color.bold(sys.inspect(expected)), ' but was: ', color.bold(sys.inspect(actual)) ].join('')); } function equals(expected, actual) { return expected === actual; } module.exports = testlib; \ No newline at end of file diff --git a/test/dispatcher_test.js b/test/dispatcher_test.js index 8d38bc4..ff60780 100644 --- a/test/dispatcher_test.js +++ b/test/dispatcher_test.js @@ -1,51 +1,52 @@ var test = require('../lib/test'), dispatcher = require('../lib/dispatcher'); with(test) { testcase('Dispatcher'); test('Should write responses to response object for normal routes', function() { - dispatcher.init({ - routes: { - '/': function(req, res) { res.respond('test'); } - } - }); - var response; - dispatcher.process({ - url: '/', - method: 'GET' - }, { - writeHead: function() {}, - write: function(body) { - response = body; - }, - end: function() {} - }); - assertEquals('test', response); + dispatcher.init({ + routes: { + '/': function(req, res) { res.respond('test'); } + } + }); + var response; + dispatcher.process({ + url: '/', + method: 'GET' + }, { + writeHead: function() {}, + write: function(body) { + response = body; + }, + end: function() {} + }); + assertEquals('test', response); }); test('Should write responses to response object for resource routes', function() { - dispatcher.init({ - resources: { - blog: { - list: function(req, res) { res.respond('content'); } - } - } - }); - var response; - dispatcher.process({ - url: '/blog/', - method: 'GET' - }, { - writeHead: function() {}, - write: function(body) { - response = body; - }, - end: function() {} - }); - assertEquals('content', response); + dispatcher.init({ + resources: { + blog: { + list: function(req, res) { res.respond('content'); } + } + } + }); + var response; + dispatcher.process({ + url: '/blog/', + method: 'GET' + }, { + writeHead: function() {}, + write: function(body) { + response = body; + }, + end: function() {} + }); + assertEquals('content', response); + }); run(); } \ No newline at end of file diff --git a/test/files/text.txt b/test/files/text.txt new file mode 100644 index 0000000..b649a9b --- /dev/null +++ b/test/files/text.txt @@ -0,0 +1 @@ +some text \ No newline at end of file diff --git a/test/responder_test.js b/test/responder_test.js index e334e25..16f7da9 100644 --- a/test/responder_test.js +++ b/test/responder_test.js @@ -1,83 +1,124 @@ var test = require('../lib/test'), - responder = require('../lib/responder'); - + responder = require('../lib/responder'); + with(test) { testcase('Responder'); - test('should write responses to response object', function() { - var actualResponse, - actualEncoding; - var response = { - write: function(body, encoding) { - actualResponse = body; - actualEncoding = encoding; - }, - writeHead: function() {}, - end: function() {} - } - - responder.respond(response, 'response'); + test('Should write responses to response object', function() { + var actualResponse, + actualEncoding; + var response = { + write: function(body, encoding) { + actualResponse = body; + actualEncoding = encoding; + }, + writeHead: function() {}, + end: function() {} + } + + responder.respond(response, 'response'); assertEquals('response', actualResponse); assertEquals('utf-8', actualEncoding); }); - test('should redirect', function() { - var actualStatus, - actualHeaders; - var response = { - writeHead: function(status, headers) { - actualStatus = status; - actualHeaders = headers; - }, - end: function() {} - }; - - responder.redirect(response, 'http://fake.url'); + test('Should redirect', function() { + var actualStatus, + actualHeaders; + var response = { + writeHead: function(status, headers) { + actualStatus = status; + actualHeaders = headers; + }, + end: function() {} + }; + + responder.redirect(response, 'http://fake.url'); assertEquals(302, actualStatus); assertEquals('http://fake.url', actualHeaders['Location']); }); - test('should send 404', function() { - var actualResponse, - actualStatus; - var response = { - write: function(body) { - actualResponse = body; - }, - writeHead: function(status) { - actualStatus = status; - }, - end: function() {} - } - - responder.respond404(response); + test('Should send 404', function() { + var actualResponse, + actualStatus; + var response = { + write: function(body) { + actualResponse = body; + }, + writeHead: function(status) { + actualStatus = status; + }, + end: function() {} + } + + responder.respond404(response); assertEquals(404, actualStatus); - assertEquals('<h1>404 Not Found</h1>', actualResponse); + assertEquals('<h1>404 Not Found</h1>', actualResponse); }); - test('should send 500', function() { - var actualResponse, - actualStatus; - var response = { - write: function(body) { - actualResponse = body; - }, - writeHead: function(status) { - actualStatus = status; - }, - end: function() {} - } + test('Should send 500', function() { + var actualResponse, + actualStatus; + var response = { + write: function(body) { + actualResponse = body; + }, + writeHead: function(status) { + actualStatus = status; + }, + end: function() {} + } - responder.respond500(response); + responder.respond500(response); assertEquals(500, actualStatus); - assertEquals('<h1>500 Internal Server Error</h1>', actualResponse); + assertEquals('<h1>500 Internal Server Error</h1>', actualResponse); }); - - test('should serve files', function() { - pending(); - }); - + + + asynctestcase('Responder - async') + + test('Should serve files', function(done) { + responder.respond = function(res, data) { + assertEquals('some text', data, done); + done(); + } + responder.serveFile({}, {}, 'files/text.txt'); + }); + + test('Should serve parial templates', function(done) { + responder.respond = function(res, data) { + assertEquals('<div>test</div><p>content</p>', data, done); + done(); + } + responder.template({}, 'template', { + scope: { + title: 'test' + } + }); + }); + + test('Should serve layout templates', function(done) { + responder.respond = function(res, data) { + assertEquals('<html><head></head><body><div><div>test</div><p>content</p></div></body></html>', data, done); + done(); + } + responder.template({}, 'template', { + scope: { + layout: true + } + }); + }); + + test('Should respond with json', function(done) { + var o = { key: 'value' }; + responder.respond = function(res, json) { + assertEquals('{"key":"value"}', json, done); + done(); + } + responder.json({}, o); + }); + + run(); } \ No newline at end of file diff --git a/test/router_test.js b/test/router_test.js index 9cd240a..f33aba8 100644 --- a/test/router_test.js +++ b/test/router_test.js @@ -1,104 +1,135 @@ var test = require('../lib/test'), router = require('../lib/router'); DEBUG = false; with(test) { testcase('Router - routing'); test('Without routes should throw exception', function() { shouldThrow(router.init, [], router); }); test('With routes should not throw exception', function() { shouldNotThrow(router.init, [{ '/': function() {} }], router); }); test('Should look up routes from simple urls', function() { router.init({ '/': function() {} }); var route = router.parse('GET', '/'); assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); - test('Should look up routes from complex urls', function() { + test('Should look up routes from complex urls', function() { router.init({ - '^/article/([0-9]+)/page/([a-z]+)$': function() {} + '^/article/([0-9]+)/page/([a-z]+)$': function() {} }); var route = router.parse('GET', '/article/1/page/j'); assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up urls by name and fill url parameters from arguments', function() { - router.init({ - '/some/other/route': function() {}, - '/article/([0-9]+)/': function articleByIndex() {}, - '/another/route': function() {} - }); - assertEquals('<a href="/article/1/">text</a>', link('articleByIndex', 'text', 1)); + router.init({ + '/some/other/route': function() {}, + '/article/([0-9]+)/': function articleByIndex() {}, + '/another/route': function() {} + }); + assertEquals('<a href="/article/1/">text</a>', link('articleByIndex', 'text', 1)); }); test('Should look up routes using simple params', function() { pending(); }); - + + + test('Should match routes for all http verbs', function() { + router.init({ + 'GET /1': function() {}, + 'POST /2': function() {}, + 'PUT /3': function() {}, + 'DELETE /4': function() {}, + 'OPTIONS /5': function() {}, + 'HEAD /6': function() {}, + 'TRACE /7': function() {}, + 'CONNECT /8': function() {} + }); + assertEquals('GET', router.parse('GET', '/1').method); + assertEquals('POST', router.parse('POST', '/2').method); + assertEquals('PUT', router.parse('PUT', '/3').method); + assertEquals('DELETE', router.parse('DELETE', '/4').method); + assertEquals('OPTIONS', router.parse('OPTIONS', '/5').method); + assertEquals('HEAD', router.parse('HEAD', '/6').method); + assertEquals('TRACE', router.parse('TRACE', '/7').method); + assertEquals('CONNECT', router.parse('CONNECT', '/8').method); + }); + testcase('Router - REST style routes'); - test('Should map resources to rest style routes - list: GET /resource/?', function() { - router.init({}, { - blog: { list: function() {} } - }); - var list = router.parse('GET', '/blog'); - assertEquals('GET', list.method); - assertEquals('function', typeof list.callback); - }); - - test('Should map resources to rest style routes - get: GET /resource/([^\/]+)/?', function() { - router.init({}, { - blog: { get: function() { } } - }); - var get = router.parse('GET', '/blog/1'); - assertEquals('1', get.groups[1]); - assertEquals('GET', get.method); - assertEquals('function', typeof get.callback); - }); - - test('Should map resources to rest style routes - save: POST /resource/?', function() { - router.init({}, { - blog: { save: function() {} } - }); - var save = router.parse('POST', '/blog'); - assertEquals('POST', save.method); - assertEquals('function', typeof save.callback); - }); - + test('Should support duplicate routes with different http verbs', function() { + router.init({ + 'GET /': function getRoute() {}, + 'POST /': function postRoute() {} + }); + assertEquals('getRoute', router.parse('GET', '/').name); + assertEquals('postRoute', router.parse('POST', '/').name); + }); + + test('Should map resources to rest style routes - list: GET /resource/?', function() { + router.init({}, { + blog: { list: function() {} } + }); + var list = router.parse('GET', '/blog'); + assertEquals('GET', list.method); + assertEquals('function', typeof list.callback); + }); + + test('Should map resources to rest style routes - get: GET /resource/([^\/]+)/?', function() { + router.init({}, { + blog: { get: function() { } } + }); + var get = router.parse('GET', '/blog/1'); + assertEquals('1', get.groups[1]); + assertEquals('GET', get.method); + assertEquals('function', typeof get.callback); + }); + + test('Should map resources to rest style routes - save: POST /resource/?', function() { + router.init({}, { + blog: { save: function() {} } + }); + var save = router.parse('POST', '/blog'); + assertEquals('POST', save.method); + assertEquals('function', typeof save.callback); + }); + test('Should map resources to rest style routes - update: PUT /resource/([^\/]+)/?', function() { - router.init({}, { - blog: { update: function() {} } - }); - var update = router.parse('PUT', '/blog/1'); - assertEquals('1', update.groups[1]); - assertEquals('PUT', update.method); - assertEquals('function', typeof update.callback); - }); - + router.init({}, { + blog: { update: function() {} } + }); + var update = router.parse('PUT', '/blog/1'); + assertEquals('1', update.groups[1]); + assertEquals('PUT', update.method); + assertEquals('function', typeof update.callback); + }); + test('Should map resources to rest style routes - destroy: DELETE /resource/?', function() { - router.init({}, { - blog: { destroy: function() {} } - }); - var destroy = router.parse('DELETE', '/blog'); - assertEquals('DELETE', destroy.method); - assertEquals('function', typeof destroy.callback); - }); - + router.init({}, { + blog: { destroy: function() {} } + }); + var destroy = router.parse('DELETE', '/blog'); + assertEquals('DELETE', destroy.method); + assertEquals('function', typeof destroy.callback); + }); + test('Should throw error on undefined resource opereation', function() { - shouldThrow(router.init, [{}, { - blog: { undefinedResourceType: function() {} } - }], router); - }); + shouldThrow(router.init, [{}, { + blog: { undefinedResourceType: function() {} } + }], router); + }); run(); } \ No newline at end of file diff --git a/test/template_test.js b/test/template_test.js index 20d67bd..747818e 100644 --- a/test/template_test.js +++ b/test/template_test.js @@ -1,16 +1,20 @@ var test = require('../lib/test'), template = require('../lib/template'); - + with(test) { - testcase('Template'); + asynctestcase('Template'); - test('should look up templates names', function() { + test('should look up templates names', function(done) { assertEquals('./templates/template.html', template.find('template')); + done(); }); - test('should serve templates', function() { - pending(); + test('should serve templates\' content', function(done) { + template.serve('template', function(content) { + assertEquals('div test\np content', content, done); + done(); + }); }); run(); } \ No newline at end of file diff --git a/test/templates/layout.html b/test/templates/layout.html new file mode 100644 index 0000000..04fcb77 --- /dev/null +++ b/test/templates/layout.html @@ -0,0 +1,4 @@ +html + head + body + div!= body \ No newline at end of file diff --git a/test/templates/template.html b/test/templates/template.html new file mode 100644 index 0000000..1632729 --- /dev/null +++ b/test/templates/template.html @@ -0,0 +1,2 @@ +div test +p content \ No newline at end of file
torgeir/tnode
f516b2ec15dea8b57cc7ec03fe0a59f61fd3f45b
switched to using jade, updated examples
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index c73f19a..cf93e4a 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,30 +1,30 @@ var t = require('../../t'); -t.app({ +t.app({ debug: true, routes: { '^/$' : function index(req, res) { this.title = 'Welcome!' this.name = 'Torgeir'; res.template('welcome') }, 'GET ^/hello/(\\w+)/?' : function hello(req, res, name) { res.respond([ '<h1>Again, welcome! ', name, ' this is raw html.. </h1><p>Try answering with ', link('page', 'json too', 2), '.</p><p>', link('index', 'Back to /'), '</p>' ].join('')); }, '^/page/(\\d+)/?$' : function page(req, res, page) { var json = { page: page }; res.json(json); } } }); diff --git a/examples/2/longpoll.js b/examples/2/longpoll.js index d31603a..7abec26 100644 --- a/examples/2/longpoll.js +++ b/examples/2/longpoll.js @@ -1,20 +1,20 @@ var t = require('../../t'), events = require('events'); - + var bus = new events.EventEmitter(), MESSAGE_EVENT = 'message_event'; t.app({ debug: true, routes: { '^/wait$' : function(req, res) { bus.addListener(MESSAGE_EVENT, function(msg) { res.respond(msg); }) }, '^/done/(.*)$' : function(req, res, msg) { bus.emit(MESSAGE_EVENT, msg); res.respond('done'); } } }); \ No newline at end of file diff --git a/examples/4/files.js b/examples/4/files.js index c6049e5..b2bafa3 100644 --- a/examples/4/files.js +++ b/examples/4/files.js @@ -1,14 +1,14 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { res.template('index'); }, '^/(web/.*)$' : t.serve, /* serves all files from web/ */ '^/favicon\.ico$' : function(req, res) { res.respond('Nothing to see here.'); } - } -}) \ No newline at end of file + } +}); \ No newline at end of file diff --git a/examples/5/rest-style.js b/examples/5/rest-style.js index 6a8b1e6..61d341f 100644 --- a/examples/5/rest-style.js +++ b/examples/5/rest-style.js @@ -1,21 +1,21 @@ var t = require('../../t'); t.app({ - dump_headers: true, + dump_headers: true, debug: true, resources: { - blog: { - list: function(req, res) { res.respond('list') }, - get: function(req, res, id) { res.respond('get ' + id) }, - save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, - update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, - destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } - } + blog: { + list: function(req, res) { res.respond('list') }, + get: function(req, res, id) { res.respond('get ' + id) }, + save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, + update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, + destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } + } }, routes: { - '^/$': function(req, res) { - res.template('html'); - }, - '^/(js/.*)$': t.serve + '^/$': function(req, res) { + res.template('html'); + }, + '^/(js/.*)$': t.serve } }) \ No newline at end of file diff --git a/examples/5/templates/html.html b/examples/5/templates/html.html index 3efe736..4f8841e 100644 --- a/examples/5/templates/html.html +++ b/examples/5/templates/html.html @@ -1,28 +1,17 @@ -<html> -<head> - <script src="/js/jquery-1.4.2.js" type="text/javascript"></script> - <script type="text/javascript"> - function ask(url, type, data) { - jQuery.ajax({ type: type, url: url, data: data, success: function(response) { alert(response) } }); - } - </script> -</head> -<body> -<h2>REST-style routes</h2> -<p> - <a href="javascript:ask('blog', 'get')">list</a> -</p> -<p> - <a href="javascript:ask('blog/1', 'get')">get</a> -</p> -<p> - <a href="javascript:ask('blog', 'post', 'type=save')">save</a> -</p> -<p> - <a href="javascript:ask('blog/1', 'put', 'type=update')">update</a> -</p> -<p> - <a href="javascript:ask('blog', 'delete', 'type=destoy')">destroy</a> -</p> -</body> -</html> \ No newline at end of file +html + head + | <script src="/js/jquery-1.4.2.js" type="text/javascript"></script> + | <script type="text/javascript"> + | function ask(url, type, data) { + | jQuery.ajax({ type: type, url: url, data: data, success: function(response) { + | alert(response) + | }}); + | } + | </script> + body + h2 REST-style routes + p <a href="javascript:ask('blog', 'get' )">List</a> + p <a href="javascript:ask('blog/1', 'get' )">Get</a> + p <a href="javascript:ask('blog', 'post', 'type=save')">Save</a> + p <a href="javascript:ask('blog/1', 'put', 'type=update')">Update</a> + p <a href="javascript:ask('blog', 'delete', 'type=desrtoy')">Destroy</a> \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 7030c31..57083bd 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,107 +1,106 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), jade = require('../vendor/jade/lib/jade'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); DUMP_HEADERS = false; var dispatcher = (function() { function callUserCallback(res, callback, user, userArguments) { callback.apply(user.scope, userArguments); } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { var user = { scope: { layout: true, partial: function (name, userScope) { - // return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); - var html = jade.render(fs.readFileSync(template.find(name), 'utf-8'), {locals: userScope || user.scope}); - log(html) - return html; + return jade.render(fs.readFileSync(template.find(name), 'utf-8'), { + locals: userScope || user.scope + }); }, log: log } } res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; res.json = function(obj) { responder.json(res, obj); }; res.template = function(name) { responder.template(res, name, user); }; req.isAjax = function() { return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; }; if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { callUserCallback(res, mapping.callback, user, [req, res, data]); }); } else { callUserCallback(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { if(DUMP_HEADERS) { log(req.headers) } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file
torgeir/tnode
8da9e393f0cf45936e3e093b63f0c4941ef321cf
added jade template engine submodule
diff --git a/.gitmodules b/.gitmodules index 18348c8..10f0bd1 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "vendor/underscore"] path = vendor/underscore url = http://github.com/documentcloud/underscore.git +[submodule "vendor/jade"] + path = vendor/jade + url = http://github.com/masylum/jade.git diff --git a/vendor/jade b/vendor/jade new file mode 160000 index 0000000..8cda1ad --- /dev/null +++ b/vendor/jade @@ -0,0 +1 @@ +Subproject commit 8cda1add9fc7fb9752d8f4d303da4ab33e884857
torgeir/tnode
16c98b8fc08b817a3152a01b983074155be02a28
changed to jade template engine
diff --git a/examples/1/templates/hello.html b/examples/1/templates/hello.html index cd067cb..8bbd3e0 100644 --- a/examples/1/templates/hello.html +++ b/examples/1/templates/hello.html @@ -1,2 +1,8 @@ -<p>Welcome, <strong><%= name %></strong>! This is a partial from another template..</p> -<p>Did you know <%= now.getTime() %> seconds have passed since 1970?</p> \ No newline at end of file +p + | Welcome, + strong= name + | ! This is a partial from another template.. +p + | Did you know that + = now.getTime() + | seconds have passed since 1970 \ No newline at end of file diff --git a/examples/1/templates/layout.html b/examples/1/templates/layout.html index 5838637..a570aca 100644 --- a/examples/1/templates/layout.html +++ b/examples/1/templates/layout.html @@ -1,9 +1,7 @@ -<html> -<head> - <title><%= title %></title> -</head> -<body> - <h1>Example 1</h1> - <%= body %> -</body> -</html> \ No newline at end of file +!!! 5 +html + head + title= title + body + h1 Example 1 + div!= body \ No newline at end of file diff --git a/examples/1/templates/welcome.html b/examples/1/templates/welcome.html index fbd04aa..cd466b4 100644 --- a/examples/1/templates/welcome.html +++ b/examples/1/templates/welcome.html @@ -1,8 +1,6 @@ -<h2>Welcome! This is a template!</h2> -<div> - <%= partial('hello', { - name: name, - now: new Date() - }) %> -</div> -<div>Try <%= link('hello', 'answering with raw html too', name) %>!</div> \ No newline at end of file +h2 Welcome! This is a template! +!= partial('hello', { name: name, now: new Date()}) +p + | Try + != link('hello', 'answering with raw html too', name) + | ! \ No newline at end of file diff --git a/examples/3/templates/form.html b/examples/3/templates/form.html index a1a92d9..90755c5 100644 --- a/examples/3/templates/form.html +++ b/examples/3/templates/form.html @@ -1,4 +1,6 @@ -<form action="/ionlyhandleposts" method="post"> - <input type="submit" name="submit" value="This works.."/> -</form> -<p><a href="/ionlyhandleposts">This</a>, on the other hand, does not work.</p> \ No newline at end of file +form(action: '/ionlyhandleposts', method: 'post') + input(type: 'submit', name: 'submit', value: 'This works..') + +p + a(href: '/ionlyhandleposts') get + | on the other hand, does not work. \ No newline at end of file diff --git a/examples/4/templates/index.html b/examples/4/templates/index.html index 312dd7e..8cb7ce1 100644 --- a/examples/4/templates/index.html +++ b/examples/4/templates/index.html @@ -1,11 +1,11 @@ -<html> -<head> - <title>serving files</title> - <script type="text/javascript" src="/web/js/jquery-1.4.2.js"></script> -</head> -<body> - <p style="display: none">if jQuery is loaded, this will fade in!</p> - <img src="/web/images/test.png" style="display: none;"/> - <script>$('p, img').fadeIn(1000)</script> -</body> -</html> \ No newline at end of file +!!!5 +html + head + title serving files + script(type: 'text/javascript', src: '/web/js/jquery-1.4.2.js') + body + <div style="display: none"> + p if jQuery is loaded, this will fade in! + img(src:"/web/images/test.png") + </div> + <script>$('div').fadeIn(1000)</script> \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 21dfd11..7030c31 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,103 +1,107 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), + jade = require('../vendor/jade/lib/jade'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); DUMP_HEADERS = false; var dispatcher = (function() { function callUserCallback(res, callback, user, userArguments) { callback.apply(user.scope, userArguments); } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { var user = { scope: { layout: true, partial: function (name, userScope) { - return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); + // return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); + var html = jade.render(fs.readFileSync(template.find(name), 'utf-8'), {locals: userScope || user.scope}); + log(html) + return html; }, log: log } } res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; res.json = function(obj) { responder.json(res, obj); }; res.template = function(name) { responder.template(res, name, user); }; req.isAjax = function() { return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; }; if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { callUserCallback(res, mapping.callback, user, [req, res, data]); }); } else { callUserCallback(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { if(DUMP_HEADERS) { log(req.headers) } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/responder.js b/lib/responder.js index 78fc452..6c38dfb 100644 --- a/lib/responder.js +++ b/lib/responder.js @@ -1,100 +1,103 @@ var fs = require('fs'), mime = require('./mime'), - template = require('./template'), + template = require('./template'), + jade = require('../vendor/jade/lib/jade'), log = require('./logger').log; require('../vendor/underscore/underscore-min'); var responder = (function() { function json(res, json) { respond(res, JSON.stringify(json)); } function serveTemplate(res, name, user) { template.serve(name, function(html) { - var body = _.template(html, user.scope), + var body = jade.render(html, { locals: user.scope }), title = user.scope.title; fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { if(err && err.errno != 2) { // 2 => no such file throw err; } if(user.scope.layout && stats && stats.isFile()) { template.serve('layout', function(layout) { - respond(res, _.template(layout, { - body: body, - title: title, - partial: user.scope.partial + respond(res, jade.render(layout, { + locals: { + body: body, + title: title, + partial: user.scope.partial + } })); }) } else { respond(res, body); } }); }); } function respond(res, body, contentType, status, encoding) { contentType = contentType || 'text/html'; body = body || ''; encoding = encoding || 'utf-8'; res.writeHead(status || 200, { 'Content-Length': (encoding === 'utf-8') ? encodeURIComponent(body).replace(/%../g, 'x').length : body.length, 'Content-Type' : contentType + '; charset=' + encoding }); res.write(body, encoding); res.end(); } function redirect(res, location, encoding) { log('Redirecting - ' + location) encoding = encoding || 'utf-8' res.writeHead(302, { 'Content-Type' : 'text/html; charset=' + encoding, 'Location' : location }); res.end(); } function respond404(res) { respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ log('Responding 500 - ' + error); respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } function serveFile(req, res, file) { var contentType = mime.lookup(file.substring(file.lastIndexOf('.'))); var encoding = (contentType.slice(0,4) === 'text') ? 'utf-8' : 'binary'; fs.readFile(file, encoding, function(error, data) { if(error) { log('Error serving file - ' + file); return respond404(res); } log('Serving file - ' + file); respond(res, data, contentType, 200, encoding); }); } return { respond: respond, redirect: redirect, respond404: respond404, respond500: respond500, serveFile: serveFile, json: json, template: serveTemplate }; })(); module.exports = responder; \ No newline at end of file
torgeir/tnode
d3afe28d7be174f522dfaa8171dfa93f069e65fa
major test script overhaul
diff --git a/examples/test/example_test.js b/examples/test/example_test.js new file mode 100644 index 0000000..a4c374b --- /dev/null +++ b/examples/test/example_test.js @@ -0,0 +1,69 @@ +var testlib = require('../../lib/test'); +var sys = require('sys'); + +DEBUG = true; + +with(testlib) { + + testcase('Test lib - synchronous tests'); + + test('should work', function() { + assertTrue(true); + }); + + test('should be able to make sync tests pending', function(done) { + pending(); + }); + + test('should be able to fail', function() { + assertFalse(true); + }); + + asynctestcase('Test lib - asynchronous tests'); + + test('should fail as test async never calls completes (calls done)', function() { + setTimeout(function() { + assertTrue(true); + }, 100); + }); + + test('should complete as async test calls done', function(done) { + setTimeout(function() { + done(); + }, 0); + }); + + test('should not call done twice on assertion failure', function(done) { + setTimeout(function() { + assertTrue(false, done); + done(); + }, 300); + }); + + test('should be able to make async tests pending', function(done) { + pending(); + }); + + test('should not fail as done is called', function(done) { + setTimeout(function() { + assertTrue(true, done); + done(); + }, 300); + }); + + test('should fail as it times out', function(done) { + setTimeout(function() { + done(); + }, 1001); + }); + + test('should work with asserting thrown exceptions', function(done) { + shouldThrow(function() { throw "win" }, [], global, done); + }); + + test('should work with asserting not thrown exceptions', function(done) { + shouldNotThrow(function() { /* win */ }, [], global, done); + }); + + run(); +} diff --git a/lib/color.js b/lib/color.js index 12327a9..510d762 100644 --- a/lib/color.js +++ b/lib/color.js @@ -1,21 +1,23 @@ var color = (function() { function colorize(color) { return function(string) { - return "\u001B[" + { + return "\u001B[" + { + bold: 1, black : 30, red : 31, green : 32, yellow : 33, }[color] + 'm' + string + "\u001B[0m"; }; }; return { red : colorize('red'), - green: colorize('green'), - yellow: colorize('yellow') + green: colorize('green'), + yellow: colorize('yellow'), + bold: colorize('bold') } })(); module.exports = color; \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 0e1a6f3..21dfd11 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,101 +1,103 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); +DUMP_HEADERS = false; + var dispatcher = (function() { function callUserCallback(res, callback, user, userArguments) { callback.apply(user.scope, userArguments); } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { var user = { scope: { layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; res.json = function(obj) { responder.json(res, obj); }; res.template = function(name) { responder.template(res, name, user); }; req.isAjax = function() { return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; }; if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { callUserCallback(res, mapping.callback, user, [req, res, data]); }); } else { callUserCallback(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { if(DUMP_HEADERS) { log(req.headers) } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/test.js b/lib/test.js index 522915b..29d8080 100644 --- a/lib/test.js +++ b/lib/test.js @@ -1,142 +1,252 @@ var sys = require('sys'), p = sys.puts; color = require('./color'), log = require('./logger').log; + +DEBUG = false; + +/** AssertionError class */ +var AssertionError = function(message) { + this.message = message; +}; + +/** Pending class */ +var Pending = function() { + +}; + +/** Status singleton */ +var Status = { + INIT: -1, + DONE: 0, + PENDING: 1, + FAILED: 2, + ERROR: 3, + getStatusColor: function(status) { + switch (status) { + case Status.DONE: return color.green; + case Status.PENDING: return color.yellow; + default: return color.red; + } + } +}; + + + + + +/** Test class */ +var Test = function(name, block, async, testcase) { + this.name = name; + this.block = block; + this.async = async || false; + this.status = Status.INIT; + this.timeout = null; + this.next = function() {}; + this.testcase = testcase; +}; + +Test.prototype.printStatus = function() { + var textColor = Status.getStatusColor(this.status); + p(textColor('\t' + this.name)); +}; +Test.prototype.printError = function() { + var error = this.error; + if (error) { + ['message', 'type', 'stack'].forEach(function(k) { + if (error[k]) + p('\t ' + error[k] + '\n'); + }); + } +}; +Test.prototype.run = function(nextTestInvoker) { + var self = this; + + this.invokeNextTest = function() { + process.nextTick(nextTestInvoker); + }; + + try { + if(this.async) { + this.timeout = setTimeout(function() { + self.handleResult(new AssertionError('Oups, test did never complete?')); + }, 1000); + } + + this.block.call(this, function(e) { + self.handleResult(e); + }); + + if (!this.async) { + this.handleResult(); + } + + } + catch (e) { + this.handleResult(e); + } +}; +Test.prototype.handleResult = function(error) { + if (this.status != Status.INIT) + return; + + clearTimeout(this.timeout); + this.timeout = null; + + this.status = Status.DONE; + + if (error) { + this.handleError(error); + } + + this.invokeNextTest(); +}; +Test.prototype.handleError = function(error) { + if (error instanceof Pending) { + this.status = Status.PENDING; + this.error = error; + } + else if (error instanceof AssertionError) { + this.testcase.passed = false; + this.status = Status.FAILED; + this.error = error; + } + else if (error instanceof Error) { + this.testcase.passed = false; + this.status = Status.ERROR; + this.error = error; + } +}; + + + + + +/** Testcase class */ +var Testcase = function(name, async) { + this.name = name; + this.async = async || false; + this.tests = []; + this.passed = true; +}; +Testcase.prototype.printSummary = function() { + this.printStatus(); + this.tests.forEach(function(test) { + test.printStatus(); + test.printError(); + }); +} +Testcase.prototype.printStatus = function() { + if (this.passed) { + p(color.green(this.name)); + } + else { + p(color.red(this.name)); + } +}; +Testcase.prototype.run = function(nextTestcaseInvoker) { + var self = this; + var testIndex = 0; + (function runTests() { + var test = self.tests[testIndex++]; + if (test) { + test.run(function() { + runTests.call(self); + }); + } + else { + self.printSummary(); + process.nextTick(nextTestcaseInvoker); + } + })(); +}; + + + + -var AssertionError = function(msg) { this.msg = msg; }; -var Pending = function() {}; var testcases = []; var testlib = { + asynctestcase: function(name) { + testcases.push(new Testcase(name, true)); + }, testcase: function(name) { - testcases.unshift({ - name: name, - tests: [] - }); + testcases.push(new Testcase(name, false)); }, - test : function(name, body) { - testcases[0].tests.push({ - name: name, - body: body - }); + test : function(name, block) { + var testcase = testcases[testcases.length - 1]; + testcase.tests.push(new Test(name, block, testcase.async, testcase)); }, - pending: function() { - throw new Pending(); - }, - run: function() { - var count = 0, - failed = 0, - errors = 0, - pending = 0; - - p('Running tests'); - testcases.forEach(function(testcase) { - - var didFail = false; - var status = []; - - testcase.tests.forEach(function(test) { - count++; - - try { - test.body.call(this); - status.push(color.green(test.name)); - } - catch(e) { - - if(e instanceof Pending) { - pending++; - status.push(color.yellow(test.name)) - } - else { - didFail = true; - status.push(color.red(test.name)); - - if(e instanceof AssertionError) { - failed++; - status.push(e.msg) - } - else { - errors++; - - if (e.type) { - status.push(e.type); - } - if(e.stack) { - status.push(e.stack) - } - } - } - } - - }); - - if(didFail) { - p(color.red(testcase.name)); - } - else { - p(color.green(testcase.name)); + run: function() { + p('\nRunning tests'); + + var testcaseIndex = 0; + (function runTestCases() { + var testcase = testcases[testcaseIndex++]; + if (testcase) { + testcase.run(runTestCases); } - status.forEach(function(status) { - p(' ' + status); - }); - }); - - p('\nTotal: ' + count + ', Failures: ' + failed + ', Errors: ' + errors + ', Pending: ' + pending); - }, - - assertEquals: function(expected, actual) { + })(); + }, + assertEquals: function(expected, actual, callback) { if(!equals(expected, actual)) { - expect(expected, actual); + var ex = expect(expected, actual); + handleExpectedException(ex, callback); } }, - assertTrue: function(actual) { - this.assertEquals(true, actual); + assertTrue: function(actual, callback) { + this.assertEquals(true, actual, callback); }, - assertFalse: function(actual) { - this.assertEquals(false, actual); + assertFalse: function(actual, callback) { + this.assertEquals(false, actual, callback); }, - shouldThrow: function(f, args, scope) { - var passed = false; - try { - f.apply(scope || this, args); - } catch (e) { - passed = true; - } - - if (!passed) { - throw new AssertionError('Exception expected, none thrown?'); - } + shouldThrow: function(f, args, scope, callback) { + this.assertThrow(f, args, scope, callback, true); }, - shouldNotThrow: function(f, args, scope) { - var passed = true; + shouldNotThrow: function(f, args, scope, callback) { + this.assertThrow(f, args, scope, callback, false); + }, + assertThrow: function(f, args, scope, callback, expectException) { + var thrown = false; try { f.apply(scope || this, args); } catch (e) { - passed = false; + thrown = true; } - - if (!passed) { - throw new AssertionError('Exception thrown, none expected?'); + + var ex = null; + if (thrown != expectException) { + ex = new AssertionError(!thrown && expectException ? 'Exception expected, none thrown?' : 'Exception thrown, none expected?'); } + handleExpectedException(ex, callback); }, - fail: function(msg) { - throw new AssertionError(msg); - } + fail: function(msg, callback) { + var ex = new AssertionError(msg); + handleExpectedException(ex, callback); + }, + pending: function() { + throw new Pending(); + } +}; + +function handleExpectedException(ex, callback) { + if(callback) callback(ex); + else throw ex; } function expect(expected, actual) { - throw new AssertionError([ + return new AssertionError([ 'Expected: ', - sys.inspect(expected), + color.bold(sys.inspect(expected)), ' but was: ', - sys.inspect(actual) + color.bold(sys.inspect(actual)) ].join('')); } function equals(expected, actual) { return expected === actual; } module.exports = testlib; \ No newline at end of file diff --git a/test/color_test.js b/test/color_test.js index 2d60253..0ca045b 100644 --- a/test/color_test.js +++ b/test/color_test.js @@ -1,22 +1,20 @@ var test = require('../lib/test'), color = require('../lib/color'); - -DEBUG = true; - + with(test) { testcase('Color'); test('should display terminal text in red', function() { assertEquals("\u001B[31msome text\u001B[0m", color.red('some text')); }); test('should display terminal text in green', function() { assertEquals("\u001B[32msome other text\u001B[0m", color.green('some other text')); }); test('should display terminal text in yellow', function() { assertEquals("\u001B[33meven more text\u001B[0m", color.yellow('even more text')); }); run(); } diff --git a/test/dispatcher_test.js b/test/dispatcher_test.js index 9f743c3..8d38bc4 100644 --- a/test/dispatcher_test.js +++ b/test/dispatcher_test.js @@ -1,53 +1,51 @@ var test = require('../lib/test'), dispatcher = require('../lib/dispatcher'); -DEBUG = true; - with(test) { testcase('Dispatcher'); test('Should write responses to response object for normal routes', function() { dispatcher.init({ routes: { '/': function(req, res) { res.respond('test'); } } }); var response; dispatcher.process({ url: '/', method: 'GET' }, { writeHead: function() {}, write: function(body) { response = body; }, end: function() {} }); assertEquals('test', response); }); test('Should write responses to response object for resource routes', function() { dispatcher.init({ resources: { blog: { list: function(req, res) { res.respond('content'); } } } }); var response; dispatcher.process({ url: '/blog/', method: 'GET' }, { writeHead: function() {}, write: function(body) { response = body; }, end: function() {} }); assertEquals('content', response); }); run(); } \ No newline at end of file diff --git a/test/mime_test.js b/test/mime_test.js index e28f833..deb4799 100644 --- a/test/mime_test.js +++ b/test/mime_test.js @@ -1,18 +1,16 @@ var test = require('../lib/test'), mime = require('../lib/mime'); - -DEBUG = true; - + with(test) { testcase('Mime type should be resolved from file extension'); test('File extension .js should result in mime type text/ecmascript', function() { assertEquals('text/ecmascript', mime.lookup('.js')); }); test('File extension .css should result in mime type text/css', function() { assertEquals('text/css', mime.lookup('.css')); }); run(); } \ No newline at end of file diff --git a/test/responder_test.js b/test/responder_test.js index 679527e..e334e25 100644 --- a/test/responder_test.js +++ b/test/responder_test.js @@ -1,85 +1,83 @@ var test = require('../lib/test'), responder = require('../lib/responder'); -DEBUG = true; - with(test) { testcase('Responder'); test('should write responses to response object', function() { var actualResponse, actualEncoding; var response = { write: function(body, encoding) { actualResponse = body; actualEncoding = encoding; }, writeHead: function() {}, end: function() {} } responder.respond(response, 'response'); assertEquals('response', actualResponse); assertEquals('utf-8', actualEncoding); }); test('should redirect', function() { var actualStatus, actualHeaders; var response = { writeHead: function(status, headers) { actualStatus = status; actualHeaders = headers; }, end: function() {} }; responder.redirect(response, 'http://fake.url'); assertEquals(302, actualStatus); assertEquals('http://fake.url', actualHeaders['Location']); }); test('should send 404', function() { var actualResponse, actualStatus; var response = { write: function(body) { actualResponse = body; }, writeHead: function(status) { actualStatus = status; }, end: function() {} } responder.respond404(response); assertEquals(404, actualStatus); assertEquals('<h1>404 Not Found</h1>', actualResponse); }); test('should send 500', function() { var actualResponse, actualStatus; var response = { write: function(body) { actualResponse = body; }, writeHead: function(status) { actualStatus = status; }, end: function() {} } responder.respond500(response); assertEquals(500, actualStatus); assertEquals('<h1>500 Internal Server Error</h1>', actualResponse); }); test('should serve files', function() { pending(); }); run(); } \ No newline at end of file diff --git a/test/router_test.js b/test/router_test.js index 97fbe6b..9cd240a 100644 --- a/test/router_test.js +++ b/test/router_test.js @@ -1,105 +1,104 @@ var test = require('../lib/test'), router = require('../lib/router'); -DEBUG = true; - +DEBUG = false; with(test) { testcase('Router - routing'); test('Without routes should throw exception', function() { shouldThrow(router.init, [], router); }); test('With routes should not throw exception', function() { shouldNotThrow(router.init, [{ '/': function() {} }], router); }); test('Should look up routes from simple urls', function() { router.init({ '/': function() {} }); var route = router.parse('GET', '/'); assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up routes from complex urls', function() { router.init({ '^/article/([0-9]+)/page/([a-z]+)$': function() {} }); var route = router.parse('GET', '/article/1/page/j'); assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up urls by name and fill url parameters from arguments', function() { router.init({ '/some/other/route': function() {}, '/article/([0-9]+)/': function articleByIndex() {}, '/another/route': function() {} }); assertEquals('<a href="/article/1/">text</a>', link('articleByIndex', 'text', 1)); }); test('Should look up routes using simple params', function() { pending(); }); testcase('Router - REST style routes'); test('Should map resources to rest style routes - list: GET /resource/?', function() { router.init({}, { blog: { list: function() {} } }); var list = router.parse('GET', '/blog'); assertEquals('GET', list.method); assertEquals('function', typeof list.callback); }); test('Should map resources to rest style routes - get: GET /resource/([^\/]+)/?', function() { router.init({}, { blog: { get: function() { } } }); var get = router.parse('GET', '/blog/1'); assertEquals('1', get.groups[1]); assertEquals('GET', get.method); assertEquals('function', typeof get.callback); }); test('Should map resources to rest style routes - save: POST /resource/?', function() { router.init({}, { blog: { save: function() {} } }); var save = router.parse('POST', '/blog'); assertEquals('POST', save.method); assertEquals('function', typeof save.callback); }); test('Should map resources to rest style routes - update: PUT /resource/([^\/]+)/?', function() { router.init({}, { blog: { update: function() {} } }); var update = router.parse('PUT', '/blog/1'); assertEquals('1', update.groups[1]); assertEquals('PUT', update.method); assertEquals('function', typeof update.callback); }); test('Should map resources to rest style routes - destroy: DELETE /resource/?', function() { router.init({}, { blog: { destroy: function() {} } }); var destroy = router.parse('DELETE', '/blog'); assertEquals('DELETE', destroy.method); assertEquals('function', typeof destroy.callback); }); test('Should throw error on undefined resource opereation', function() { shouldThrow(router.init, [{}, { blog: { undefinedResourceType: function() {} } }], router); }); run(); } \ No newline at end of file diff --git a/test/template_test.js b/test/template_test.js index 7a725bb..20d67bd 100644 --- a/test/template_test.js +++ b/test/template_test.js @@ -1,18 +1,16 @@ var test = require('../lib/test'), template = require('../lib/template'); -DEBUG = true; - with(test) { testcase('Template'); test('should look up templates names', function() { assertEquals('./templates/template.html', template.find('template')); }); test('should serve templates', function() { pending(); }); run(); } \ No newline at end of file
torgeir/tnode
1c1b3eea9f3f778fde02650a54b81b4e89d7cdcb
made template async
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5509140 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.DS_Store diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index 6a4e26f..c73f19a 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,29 +1,30 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$' : function index(req, res) { this.title = 'Welcome!' this.name = 'Torgeir'; - return 'welcome'; + + res.template('welcome') }, 'GET ^/hello/(\\w+)/?' : function hello(req, res, name) { res.respond([ '<h1>Again, welcome! ', name, ' this is raw html.. </h1><p>Try answering with ', link('page', 'json too', 2), '.</p><p>', link('index', 'Back to /'), '</p>' ].join('')); }, '^/page/(\\d+)/?$' : function page(req, res, page) { var json = { page: page }; - return json; + res.json(json); } } }); diff --git a/examples/3/verbs.js b/examples/3/verbs.js index 8eb04b5..4b8075e 100644 --- a/examples/3/verbs.js +++ b/examples/3/verbs.js @@ -1,13 +1,13 @@ var t = require('../../t'); t.app({ debug: true, routes: { - '^/$': function() { - return 'form'; + '^/$': function(req, res) { + res.template('form'); }, 'POST /ionlyhandleposts': function(req, res, data) { res.respond('POST is ok ' + JSON.stringify(data)); } } }) \ No newline at end of file diff --git a/examples/4/files.js b/examples/4/files.js index cd67d36..c6049e5 100644 --- a/examples/4/files.js +++ b/examples/4/files.js @@ -1,14 +1,14 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { - return 'index'; + res.template('index'); }, '^/(web/.*)$' : t.serve, /* serves all files from web/ */ '^/favicon\.ico$' : function(req, res) { res.respond('Nothing to see here.'); } } }) \ No newline at end of file diff --git a/examples/5/rest-style.js b/examples/5/rest-style.js index 65dc48a..6a8b1e6 100644 --- a/examples/5/rest-style.js +++ b/examples/5/rest-style.js @@ -1,21 +1,21 @@ var t = require('../../t'); t.app({ dump_headers: true, debug: true, resources: { blog: { list: function(req, res) { res.respond('list') }, get: function(req, res, id) { res.respond('get ' + id) }, save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } } }, routes: { '^/$': function(req, res) { - return 'html'; + res.template('html'); }, '^/(js/.*)$': t.serve } }) \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 39c1b04..0e1a6f3 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,129 +1,101 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { - function doRespond(res, callback, user, userArguments) { - - var retur = callback.apply(user.scope, userArguments); - - switch(typeof retur) { - case 'string': - - template.serve(retur, function(html) { - var body = _.template(html, user.scope), - title = user.scope.title; - - fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { - if(err && err.errno != 2) { // 2 => no such file - throw err; - } - - if(user.scope.layout && stats && stats.isFile()) { - template.serve('layout', function(layout) { - responder.respond(res, _.template(layout, { - body: body, - title: title, - partial: user.scope.partial - })); - }) - } - else { - responder.respond(res, body); - } - }); - }); - break; - case 'object': - responder.respond(res, JSON.stringify(retur)); - break; - default: - return; - } + function callUserCallback(res, callback, user, userArguments) { + callback.apply(user.scope, userArguments); } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { + var user = { + scope: { + layout: true, + partial: function (name, userScope) { + return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); + }, + log: log + } + } + res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; + res.json = function(obj) { + responder.json(res, obj); + }; + res.template = function(name) { + responder.template(res, name, user); + }; req.isAjax = function() { return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; - } - var user = { - scope: { - layout: true, - partial: function (name, userScope) { - return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); - }, - log: log - } - } - + }; + if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { - doRespond(res, mapping.callback, user, [req, res, data]); + callUserCallback(res, mapping.callback, user, [req, res, data]); }); } else { - doRespond(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); + callUserCallback(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { if(DUMP_HEADERS) { log(req.headers) } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/responder.js b/lib/responder.js index 50c6c3a..78fc452 100644 --- a/lib/responder.js +++ b/lib/responder.js @@ -1,65 +1,100 @@ var fs = require('fs'), mime = require('./mime'), + template = require('./template'), log = require('./logger').log; + +require('../vendor/underscore/underscore-min'); var responder = (function() { + + function json(res, json) { + respond(res, JSON.stringify(json)); + } + + function serveTemplate(res, name, user) { + template.serve(name, function(html) { + var body = _.template(html, user.scope), + title = user.scope.title; + + fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { + if(err && err.errno != 2) { // 2 => no such file + throw err; + } + + if(user.scope.layout && stats && stats.isFile()) { + template.serve('layout', function(layout) { + respond(res, _.template(layout, { + body: body, + title: title, + partial: user.scope.partial + })); + }) + } + else { + respond(res, body); + } + }); + }); + } function respond(res, body, contentType, status, encoding) { contentType = contentType || 'text/html'; body = body || ''; encoding = encoding || 'utf-8'; res.writeHead(status || 200, { 'Content-Length': (encoding === 'utf-8') ? encodeURIComponent(body).replace(/%../g, 'x').length : body.length, 'Content-Type' : contentType + '; charset=' + encoding }); res.write(body, encoding); res.end(); } function redirect(res, location, encoding) { log('Redirecting - ' + location) encoding = encoding || 'utf-8' res.writeHead(302, { 'Content-Type' : 'text/html; charset=' + encoding, 'Location' : location }); res.end(); } function respond404(res) { respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ log('Responding 500 - ' + error); respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } function serveFile(req, res, file) { var contentType = mime.lookup(file.substring(file.lastIndexOf('.'))); var encoding = (contentType.slice(0,4) === 'text') ? 'utf-8' : 'binary'; fs.readFile(file, encoding, function(error, data) { if(error) { log('Error serving file - ' + file); return respond404(res); } log('Serving file - ' + file); respond(res, data, contentType, 200, encoding); }); } return { respond: respond, redirect: redirect, respond404: respond404, respond500: respond500, - serveFile: serveFile + serveFile: serveFile, + json: json, + template: serveTemplate }; })(); module.exports = responder; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index fb522ac..8b2704c 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,156 +1,160 @@ var log = require('./logger').log; var sys = require('sys') var router = (function() { var compiledRoutes = {}; var routesByName = {}; function lookup() { var num = 0, args = arguments, route = routesByName[args[0]]; return route ? route.replace(/\([^\)]+?\)+/g, function() { return args[++num] || ''; }) : ''; } - function url(route) { + function url() { var args = []; for(var arg in arguments) { args.push(arguments[arg]); } - return lookup.apply(this, [route].concat(args.slice(2))); + return lookup.apply(this, args); } function link(route, linktext) { - return '<a href="' + url(route) + '">' + linktext + '</a>'; + var args = []; + for(var arg in arguments) { + args.push(arguments[arg]); + } + return '<a href="' + url.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; } global.link = link; global.url = url; function init(routes, resources) { if(!routes && !resources) { throw Error('You need to provide at minimum 1 route.') } routes = routes || {}; compiledRoutes = {}; routesByName = {}; /* list: GET /resource/? get: GET /resource/([^/]+)/? save: POST /resource/? update: PUT /resource/([^/]+)/? destroy: DELETE /resource/? */ for(var resource in resources) { var operations = resources[resource]; for(var operation in operations) { var callback = operations[operation]; var path = '^/' + resource + '/'; var group = '([^\/]+)/?' switch(operation) { case 'list': path = 'GET ' + path + '?'; break; case 'get': path = 'GET ' + path; path += group; break; case 'save': path = 'POST ' + path + '?'; break; case 'update': path = 'PUT ' + path; path += group; break; case 'destroy': path = 'DELETE ' + path + '?'; break; default: throw new Error('Unsupported resource operation'); break; } path += '$' routes[path] = callback; } } sys.puts('Serving routes:'); for(var path in routes) { var route = routes[path]; prepare(route, path); sys.puts(' ' + path) } } function prepare(route, path) { var verb = 'GET'; var httpVerbMatch = extractHttpVerb(path); if(httpVerbMatch) { verb = httpVerbMatch[1]; path = path.substring(verb.length); } var name = extractName(route) mapName(name, path); compiledRoutes[verb + ' ' + path] = { name: name, verb: verb, regex: new RegExp(path.trim(), ''), callback: route[name] || route }; } function extractHttpVerb(path) { return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); } function mapName(name, path) { routesByName[name] = path.trim() .replace(/^(\^)/, '') .replace(/\$$/, '') .replace(/\?/g, '') .replace(/\+/g, '') .replace(/\*/g, ''); } function extractName(route) { var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; return functionNameMatch ? functionNameMatch[1] : undefined; } return { init : init, parse : function(method, url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); if(matches && method === route.verb) { log('Route found! - ' + route.verb + ' - '+ url); return { groups: matches, method: route.verb, callback: route.callback }; } } log('Route not found for - ' + method + ' ' + url); return null; }, url: url }; })(); module.exports = router; \ No newline at end of file
torgeir/tnode
584f4d694dbf4b395808e0953aed697be01d4134
added req.isAjax()
diff --git a/examples/5/rest-style.js b/examples/5/rest-style.js index 3e15280..65dc48a 100644 --- a/examples/5/rest-style.js +++ b/examples/5/rest-style.js @@ -1,20 +1,21 @@ var t = require('../../t'); t.app({ + dump_headers: true, debug: true, resources: { blog: { list: function(req, res) { res.respond('list') }, get: function(req, res, id) { res.respond('get ' + id) }, save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } } }, routes: { '^/$': function(req, res) { return 'html'; }, '^/(js/.*)$': t.serve } }) \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 8ff11d4..39c1b04 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,126 +1,129 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { function doRespond(res, callback, user, userArguments) { var retur = callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(retur, function(html) { var body = _.template(html, user.scope), title = user.scope.title; fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { if(err && err.errno != 2) { // 2 => no such file throw err; } if(user.scope.layout && stats && stats.isFile()) { template.serve('layout', function(layout) { responder.respond(res, _.template(layout, { body: body, title: title, partial: user.scope.partial })); }) } else { responder.respond(res, body); } }); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; + req.isAjax = function() { + return 'x-requested-with' in req.headers && req.headers['x-requested-with'].toLowerCase() === 'xmlhttprequest'; + } var user = { scope: { layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { doRespond(res, mapping.callback, user, [req, res, data]); }); } else { doRespond(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { if(DUMP_HEADERS) { log(req.headers) } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file
torgeir/tnode
8f1ee692edb1a7525632ca290db990c28bc8d699
added conf parameter to dump headers
diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 1a27917..8ff11d4 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,123 +1,126 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { function doRespond(res, callback, user, userArguments) { var retur = callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(retur, function(html) { var body = _.template(html, user.scope), title = user.scope.title; fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { if(err && err.errno != 2) { // 2 => no such file throw err; } if(user.scope.layout && stats && stats.isFile()) { template.serve('layout', function(layout) { responder.respond(res, _.template(layout, { body: body, title: title, partial: user.scope.partial })); }) } else { responder.respond(res, body); } }); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { doRespond(res, mapping.callback, user, [req, res, data]); }); } else { doRespond(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { + if(DUMP_HEADERS) { + log(req.headers) + } try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/t.js b/t.js index b1b8eda..f31704e 100644 --- a/t.js +++ b/t.js @@ -1,27 +1,28 @@ // tnode var sys = require('sys'), http = require('http'); var dispatcher = require('./lib/dispatcher'), responder = require('./lib/responder'); var tnode = { serve : responder.serveFile, app: function(conf) { DEBUG = conf.debug || false; + DUMP_HEADERS = conf.dump_headers || false; var port = conf.port || 8888; dispatcher.init(conf); http.createServer(dispatcher.process).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); } }; module.exports = tnode; \ No newline at end of file
torgeir/tnode
d1b014afd3bb9a89049cf5d576bd3829e4605473
renamed url function link, added new url helper
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index 7344836..6a4e26f 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,29 +1,29 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$' : function index(req, res) { this.title = 'Welcome!' this.name = 'Torgeir'; return 'welcome'; }, 'GET ^/hello/(\\w+)/?' : function hello(req, res, name) { res.respond([ '<h1>Again, welcome! ', name, ' this is raw html.. </h1><p>Try answering with ', - url('page', 'json too', 2), + link('page', 'json too', 2), '.</p><p>', - url('index', 'Back to /'), + link('index', 'Back to /'), '</p>' ].join('')); }, '^/page/(\\d+)/?$' : function page(req, res, page) { var json = { page: page }; return json; } } }); diff --git a/examples/1/templates/welcome.html b/examples/1/templates/welcome.html index b654278..fbd04aa 100644 --- a/examples/1/templates/welcome.html +++ b/examples/1/templates/welcome.html @@ -1,8 +1,8 @@ <h2>Welcome! This is a template!</h2> <div> <%= partial('hello', { name: name, now: new Date() }) %> </div> -<div>Try <%= url('hello', 'answering with raw html too', name) %>!</div> \ No newline at end of file +<div>Try <%= link('hello', 'answering with raw html too', name) %>!</div> \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index 8895b0c..fb522ac 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,151 +1,156 @@ var log = require('./logger').log; var sys = require('sys') var router = (function() { var compiledRoutes = {}; var routesByName = {}; function lookup() { var num = 0, args = arguments, route = routesByName[args[0]]; return route ? route.replace(/\([^\)]+?\)+/g, function() { return args[++num] || ''; }) : ''; } - function url(route, linktext) { + function url(route) { var args = []; for(var arg in arguments) { args.push(arguments[arg]); } - return '<a href="' + lookup.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; + return lookup.apply(this, [route].concat(args.slice(2))); } + function link(route, linktext) { + return '<a href="' + url(route) + '">' + linktext + '</a>'; + } + + global.link = link; global.url = url; function init(routes, resources) { if(!routes && !resources) { throw Error('You need to provide at minimum 1 route.') } routes = routes || {}; compiledRoutes = {}; routesByName = {}; /* list: GET /resource/? get: GET /resource/([^/]+)/? save: POST /resource/? update: PUT /resource/([^/]+)/? destroy: DELETE /resource/? */ for(var resource in resources) { var operations = resources[resource]; for(var operation in operations) { var callback = operations[operation]; var path = '^/' + resource + '/'; var group = '([^\/]+)/?' switch(operation) { case 'list': path = 'GET ' + path + '?'; break; case 'get': path = 'GET ' + path; path += group; break; case 'save': path = 'POST ' + path + '?'; break; case 'update': path = 'PUT ' + path; path += group; break; case 'destroy': path = 'DELETE ' + path + '?'; break; default: throw new Error('Unsupported resource operation'); break; } path += '$' routes[path] = callback; } } sys.puts('Serving routes:'); for(var path in routes) { var route = routes[path]; prepare(route, path); sys.puts(' ' + path) } } function prepare(route, path) { var verb = 'GET'; var httpVerbMatch = extractHttpVerb(path); if(httpVerbMatch) { verb = httpVerbMatch[1]; path = path.substring(verb.length); } var name = extractName(route) mapName(name, path); compiledRoutes[verb + ' ' + path] = { name: name, verb: verb, regex: new RegExp(path.trim(), ''), callback: route[name] || route }; } function extractHttpVerb(path) { return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); } function mapName(name, path) { routesByName[name] = path.trim() .replace(/^(\^)/, '') .replace(/\$$/, '') .replace(/\?/g, '') .replace(/\+/g, '') .replace(/\*/g, ''); } function extractName(route) { var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; return functionNameMatch ? functionNameMatch[1] : undefined; } return { init : init, parse : function(method, url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); if(matches && method === route.verb) { log('Route found! - ' + route.verb + ' - '+ url); return { groups: matches, method: route.verb, callback: route.callback }; } } log('Route not found for - ' + method + ' ' + url); return null; }, url: url }; })(); module.exports = router; \ No newline at end of file diff --git a/test/router_test.js b/test/router_test.js index 3ef771a..97fbe6b 100644 --- a/test/router_test.js +++ b/test/router_test.js @@ -1,106 +1,105 @@ var test = require('../lib/test'), router = require('../lib/router'); DEBUG = true; with(test) { testcase('Router - routing'); test('Without routes should throw exception', function() { shouldThrow(router.init, [], router); }); test('With routes should not throw exception', function() { shouldNotThrow(router.init, [{ '/': function() {} }], router); }); test('Should look up routes from simple urls', function() { router.init({ '/': function() {} }); var route = router.parse('GET', '/'); assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up routes from complex urls', function() { router.init({ '^/article/([0-9]+)/page/([a-z]+)$': function() {} }); var route = router.parse('GET', '/article/1/page/j'); - log(route) assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up urls by name and fill url parameters from arguments', function() { router.init({ '/some/other/route': function() {}, '/article/([0-9]+)/': function articleByIndex() {}, '/another/route': function() {} }); - assertEquals('<a href="/article/1/">text</a>', url('articleByIndex', 'text', 1)); + assertEquals('<a href="/article/1/">text</a>', link('articleByIndex', 'text', 1)); }); test('Should look up routes using simple params', function() { pending(); }); testcase('Router - REST style routes'); test('Should map resources to rest style routes - list: GET /resource/?', function() { router.init({}, { blog: { list: function() {} } }); var list = router.parse('GET', '/blog'); assertEquals('GET', list.method); assertEquals('function', typeof list.callback); }); test('Should map resources to rest style routes - get: GET /resource/([^\/]+)/?', function() { router.init({}, { blog: { get: function() { } } }); var get = router.parse('GET', '/blog/1'); assertEquals('1', get.groups[1]); assertEquals('GET', get.method); assertEquals('function', typeof get.callback); }); test('Should map resources to rest style routes - save: POST /resource/?', function() { router.init({}, { blog: { save: function() {} } }); var save = router.parse('POST', '/blog'); assertEquals('POST', save.method); assertEquals('function', typeof save.callback); }); test('Should map resources to rest style routes - update: PUT /resource/([^\/]+)/?', function() { router.init({}, { blog: { update: function() {} } }); var update = router.parse('PUT', '/blog/1'); assertEquals('1', update.groups[1]); assertEquals('PUT', update.method); assertEquals('function', typeof update.callback); }); test('Should map resources to rest style routes - destroy: DELETE /resource/?', function() { router.init({}, { blog: { destroy: function() {} } }); var destroy = router.parse('DELETE', '/blog'); assertEquals('DELETE', destroy.method); assertEquals('function', typeof destroy.callback); }); test('Should throw error on undefined resource opereation', function() { shouldThrow(router.init, [{}, { blog: { undefinedResourceType: function() {} } }], router); }); run(); } \ No newline at end of file
torgeir/tnode
df41d4d2d2da610e93b5323cecb2933d02c0e1fc
added partial to layout scope
diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 6622449..1a27917 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,122 +1,123 @@ require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { function doRespond(res, callback, user, userArguments) { var retur = callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(retur, function(html) { var body = _.template(html, user.scope), title = user.scope.title; fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { if(err && err.errno != 2) { // 2 => no such file throw err; } if(user.scope.layout && stats && stats.isFile()) { template.serve('layout', function(layout) { responder.respond(res, _.template(layout, { body: body, - title: title + title: title, + partial: user.scope.partial })); }) } else { responder.respond(res, body); } }); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { doRespond(res, mapping.callback, user, [req, res, data]); }); } else { doRespond(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file
torgeir/tnode
d69d2a51c5f59e12733495e0a659fbfcbcb8e1e5
added .gitmodules file
diff --git a/.gitmodules b/.gitmodules index a7662a2..18348c8 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "underscore"] - path = underscore - url = http://github.com/documentcloud/underscore.git [submodule "vendor/underscore"] path = vendor/underscore url = http://github.com/documentcloud/underscore.git
torgeir/tnode
7b755de883913d8bf85e7345b10e0031c5656a3e
changed underscore require path
diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 6fdd067..6622449 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,122 +1,122 @@ -require('../vendor/underscore-min'); +require('../vendor/underscore/underscore-min'); var url = require('url'), fs = require('fs'), querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { function doRespond(res, callback, user, userArguments) { var retur = callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(retur, function(html) { var body = _.template(html, user.scope), title = user.scope.title; fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { if(err && err.errno != 2) { // 2 => no such file throw err; } if(user.scope.layout && stats && stats.isFile()) { template.serve('layout', function(layout) { responder.respond(res, _.template(layout, { body: body, title: title })); }) } else { responder.respond(res, body); } }); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } function extractData(req, callback) { var data = ''; req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { callback(querystring.parse(url.parse('http://fake/?' + data).query)); }); } function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { extractData(req, function(data) { doRespond(res, mapping.callback, user, [req, res, data]); }); } else { doRespond(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file
torgeir/tnode
5a3f5d31a209203be708a205f36c1fe9e39521b8
made underscore a submobule
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..a7662a2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "underscore"] + path = underscore + url = http://github.com/documentcloud/underscore.git +[submodule "vendor/underscore"] + path = vendor/underscore + url = http://github.com/documentcloud/underscore.git diff --git a/vendor/underscore b/vendor/underscore new file mode 160000 index 0000000..1a67c8d --- /dev/null +++ b/vendor/underscore @@ -0,0 +1 @@ +Subproject commit 1a67c8d3a7fead4fe5bc146eb91282b6833ce46d diff --git a/vendor/underscore-min.js b/vendor/underscore-min.js deleted file mode 100644 index 7cfbf99..0000000 --- a/vendor/underscore-min.js +++ /dev/null @@ -1,17 +0,0 @@ -(function(){var n=this,A=n._,r=typeof StopIteration!=="undefined"?StopIteration:"__break__",B=function(a){return a.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},j=Array.prototype,l=Object.prototype,o=j.slice,C=j.unshift,D=l.toString,p=l.hasOwnProperty,s=j.forEach,t=j.map,u=j.reduce,v=j.reduceRight,w=j.filter,x=j.every,y=j.some,m=j.indexOf,z=j.lastIndexOf;l=Array.isArray;var E=Object.keys,b=function(a){return new k(a)};if(typeof exports!=="undefined")exports._=b;n._=b;b.VERSION="1.0.2";var i=b.forEach= -function(a,c,d){try{if(s&&a.forEach===s)a.forEach(c,d);else if(b.isNumber(a.length))for(var e=0,f=a.length;e<f;e++)c.call(d,a[e],e,a);else for(e in a)p.call(a,e)&&c.call(d,a[e],e,a)}catch(g){if(g!=r)throw g;}return a};b.map=function(a,c,d){if(t&&a.map===t)return a.map(c,d);var e=[];i(a,function(f,g,h){e.push(c.call(d,f,g,h))});return e};b.reduce=function(a,c,d,e){if(u&&a.reduce===u)return a.reduce(b.bind(d,e),c);i(a,function(f,g,h){c=d.call(e,c,f,g,h)});return c};b.reduceRight=function(a,c,d,e){if(v&& -a.reduceRight===v)return a.reduceRight(b.bind(d,e),c);a=b.clone(b.toArray(a)).reverse();return b.reduce(a,c,d,e)};b.detect=function(a,c,d){var e;i(a,function(f,g,h){if(c.call(d,f,g,h)){e=f;b.breakLoop()}});return e};b.filter=function(a,c,d){if(w&&a.filter===w)return a.filter(c,d);var e=[];i(a,function(f,g,h){c.call(d,f,g,h)&&e.push(f)});return e};b.reject=function(a,c,d){var e=[];i(a,function(f,g,h){!c.call(d,f,g,h)&&e.push(f)});return e};b.every=function(a,c,d){c=c||b.identity;if(x&&a.every===x)return a.every(c, -d);var e=true;i(a,function(f,g,h){(e=e&&c.call(d,f,g,h))||b.breakLoop()});return e};b.some=function(a,c,d){c=c||b.identity;if(y&&a.some===y)return a.some(c,d);var e=false;i(a,function(f,g,h){if(e=c.call(d,f,g,h))b.breakLoop()});return e};b.include=function(a,c){if(m&&a.indexOf===m)return a.indexOf(c)!=-1;var d=false;i(a,function(e){if(d=e===c)b.breakLoop()});return d};b.invoke=function(a,c){var d=b.rest(arguments,2);return b.map(a,function(e){return(c?e[c]:e).apply(e,d)})};b.pluck=function(a,c){return b.map(a, -function(d){return d[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);var e={computed:-Infinity};i(a,function(f,g,h){g=c?c.call(d,f,g,h):f;g>=e.computed&&(e={value:f,computed:g})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);var e={computed:Infinity};i(a,function(f,g,h){g=c?c.call(d,f,g,h):f;g<e.computed&&(e={value:f,computed:g})});return e.value};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(e,f,g){return{value:e, -criteria:c.call(d,e,f,g)}}).sort(function(e,f){e=e.criteria;f=f.criteria;return e<f?-1:e>f?1:0}),"value")};b.sortedIndex=function(a,c,d){d=d||b.identity;for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?(e=g+1):(f=g)}return e};b.toArray=function(a){if(!a)return[];if(a.toArray)return a.toArray();if(b.isArray(a))return a;if(b.isArguments(a))return o.call(a);return b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=function(a,c,d){return c&&!d?o.call(a,0,c):a[0]};b.rest=function(a, -c,d){return o.call(a,b.isUndefined(c)||d?1:c)};b.last=function(a){return a[a.length-1]};b.compact=function(a){return b.filter(a,function(c){return!!c})};b.flatten=function(a){return b.reduce(a,[],function(c,d){if(b.isArray(d))return c.concat(b.flatten(d));c.push(d);return c})};b.without=function(a){var c=b.rest(arguments);return b.filter(a,function(d){return!b.include(c,d)})};b.uniq=function(a,c){return b.reduce(a,[],function(d,e,f){if(0==f||(c===true?b.last(d)!=e:!b.include(d,e)))d.push(e);return d})}; -b.intersect=function(a){var c=b.rest(arguments);return b.filter(b.uniq(a),function(d){return b.every(c,function(e){return b.indexOf(e,d)>=0})})};b.zip=function(){for(var a=b.toArray(arguments),c=b.max(b.pluck(a,"length")),d=new Array(c),e=0;e<c;e++)d[e]=b.pluck(a,String(e));return d};b.indexOf=function(a,c){if(m&&a.indexOf===m)return a.indexOf(c);for(var d=0,e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,c){if(z&&a.lastIndexOf===z)return a.lastIndexOf(c);for(var d=a.length;d--;)if(a[d]=== -c)return d;return-1};b.range=function(a,c,d){var e=b.toArray(arguments),f=e.length<=1;a=f?0:e[0];c=f?e[0]:e[1];d=e[2]||1;e=Math.ceil((c-a)/d);if(e<=0)return[];e=new Array(e);f=a;for(var g=0;;f+=d){if((d>0?f-c:c-f)>=0)return e;e[g++]=f}};b.bind=function(a,c){var d=b.rest(arguments,2);return function(){return a.apply(c||{},d.concat(b.toArray(arguments)))}};b.bindAll=function(a){var c=b.rest(arguments);if(c.length==0)c=b.functions(a);i(c,function(d){a[d]=b.bind(a[d],a)});return a};b.delay=function(a, -c){var d=b.rest(arguments,2);return setTimeout(function(){return a.apply(a,d)},c)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(b.rest(arguments)))};b.wrap=function(a,c){return function(){var d=[a].concat(b.toArray(arguments));return c.apply(c,d)}};b.compose=function(){var a=b.toArray(arguments);return function(){for(var c=b.toArray(arguments),d=a.length-1;d>=0;d--)c=[a[d].apply(this,c)];return c[0]}};b.keys=E||function(a){if(b.isArray(a))return b.range(0,a.length);var c=[];for(var d in a)p.call(a, -d)&&c.push(d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=function(a){return b.filter(b.keys(a),function(c){return b.isFunction(a[c])}).sort()};b.extend=function(a){i(b.rest(arguments),function(c){for(var d in c)a[d]=c[d]});return a};b.clone=function(a){if(b.isArray(a))return a.slice(0);return b.extend({},a)};b.tap=function(a,c){c(a);return a};b.isEqual=function(a,c){if(a===c)return true;var d=typeof a;if(d!=typeof c)return false;if(a==c)return true;if(!a&&c||a&&!c)return false; -if(a.isEqual)return a.isEqual(c);if(b.isDate(a)&&b.isDate(c))return a.getTime()===c.getTime();if(b.isNaN(a)&&b.isNaN(c))return true;if(b.isRegExp(a)&&b.isRegExp(c))return a.source===c.source&&a.global===c.global&&a.ignoreCase===c.ignoreCase&&a.multiline===c.multiline;if(d!=="object")return false;if(a.length&&a.length!==c.length)return false;d=b.keys(a);var e=b.keys(c);if(d.length!=e.length)return false;for(var f in a)if(!(f in c)||!b.isEqual(a[f],c[f]))return false;return true};b.isEmpty=function(a){if(b.isArray(a))return a.length=== -0;for(var c in a)if(p.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=l||function(a){return!!(a&&a.concat&&a.unshift&&!a.callee)};b.isArguments=function(a){return a&&a.callee};b.isFunction=function(a){return!!(a&&a.constructor&&a.call&&a.apply)};b.isString=function(a){return!!(a===""||a&&a.charCodeAt&&a.substr)};b.isNumber=function(a){return a===+a||D.call(a)==="[object Number]"};b.isBoolean=function(a){return a===true||a===false};b.isDate=function(a){return!!(a&& -a.getTimezoneOffset&&a.setUTCFullYear)};b.isRegExp=function(a){return!!(a&&a.test&&a.exec&&(a.ignoreCase||a.ignoreCase===false))};b.isNaN=function(a){return b.isNumber(a)&&isNaN(a)};b.isNull=function(a){return a===null};b.isUndefined=function(a){return typeof a=="undefined"};b.noConflict=function(){n._=A;return this};b.identity=function(a){return a};b.times=function(a,c,d){for(var e=0;e<a;e++)c.call(d,e)};b.breakLoop=function(){throw r;};b.mixin=function(a){i(b.functions(a),function(c){F(c,b[c]=a[c])})}; -var G=0;b.uniqueId=function(a){var c=G++;return a?a+c:c};b.templateSettings={start:"<%",end:"%>",interpolate:/<%=(.+?)%>/g};b.template=function(a,c){var d=b.templateSettings,e=new RegExp("'(?=[^"+d.end.substr(0,1)+"]*"+B(d.end)+")","g");a=new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+a.replace(/[\r\t\n]/g," ").replace(e,"\t").split("'").join("\\'").split("\t").join("'").replace(d.interpolate,"',$1,'").split(d.start).join("');").split(d.end).join("p.push('")+ -"');}return p.join('');");return c?a(c):a};b.each=b.forEach;b.foldl=b.inject=b.reduce;b.foldr=b.reduceRight;b.select=b.filter;b.all=b.every;b.any=b.some;b.head=b.first;b.tail=b.rest;b.methods=b.functions;var k=function(a){this._wrapped=a},q=function(a,c){return c?b(a).chain():a},F=function(a,c){k.prototype[a]=function(){var d=b.toArray(arguments);C.call(d,this._wrapped);return q(c.apply(b,d),this._chain)}};b.mixin(b);i(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var c=j[a]; -k.prototype[a]=function(){c.apply(this._wrapped,arguments);return q(this._wrapped,this._chain)}});i(["concat","join","slice"],function(a){var c=j[a];k.prototype[a]=function(){return q(c.apply(this._wrapped,arguments),this._chain)}});k.prototype.chain=function(){this._chain=true;return this};k.prototype.value=function(){return this._wrapped}})(); diff --git a/vendor/underscore.js b/vendor/underscore.js deleted file mode 100644 index 6254112..0000000 --- a/vendor/underscore.js +++ /dev/null @@ -1,694 +0,0 @@ -// Underscore.js -// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc. -// Underscore is freely distributable under the terms of the MIT license. -// Portions of Underscore are inspired by or borrowed from Prototype.js, -// Oliver Steele's Functional, and John Resig's Micro-Templating. -// For all details and documentation: -// http://documentcloud.github.com/underscore - -(function() { - // ------------------------- Baseline setup --------------------------------- - - // Establish the root object, "window" in the browser, or "global" on the server. - var root = this; - - // Save the previous value of the "_" variable. - var previousUnderscore = root._; - - // Establish the object that gets thrown to break out of a loop iteration. - var breaker = typeof StopIteration !== 'undefined' ? StopIteration : '__break__'; - - // Quick regexp-escaping function, because JS doesn't have RegExp.escape(). - var escapeRegExp = function(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; - - // Save bytes in the minified (but not gzipped) version: - var ArrayProto = Array.prototype, ObjProto = Object.prototype; - - // Create quick reference variables for speed access to core prototypes. - var slice = ArrayProto.slice, - unshift = ArrayProto.unshift, - toString = ObjProto.toString, - hasOwnProperty = ObjProto.hasOwnProperty, - propertyIsEnumerable = ObjProto.propertyIsEnumerable; - - // All ECMA5 native implementations we hope to use are declared here. - var - nativeForEach = ArrayProto.forEach, - nativeMap = ArrayProto.map, - nativeReduce = ArrayProto.reduce, - nativeReduceRight = ArrayProto.reduceRight, - nativeFilter = ArrayProto.filter, - nativeEvery = ArrayProto.every, - nativeSome = ArrayProto.some, - nativeIndexOf = ArrayProto.indexOf, - nativeLastIndexOf = ArrayProto.lastIndexOf, - nativeIsArray = Array.isArray, - nativeKeys = Object.keys; - - // Create a safe reference to the Underscore object for use below. - var _ = function(obj) { return new wrapper(obj); }; - - // Export the Underscore object for CommonJS. - if (typeof exports !== 'undefined') exports._ = _; - - // Export underscore to global scope. - root._ = _; - - // Current version. - _.VERSION = '1.0.2'; - - // ------------------------ Collection Functions: --------------------------- - - // The cornerstone, an each implementation. - // Handles objects implementing forEach, arrays, and raw objects. - // Delegates to JavaScript 1.6's native forEach if available. - var each = _.forEach = function(obj, iterator, context) { - try { - if (nativeForEach && obj.forEach === nativeForEach) { - obj.forEach(iterator, context); - } else if (_.isNumber(obj.length)) { - for (var i = 0, l = obj.length; i < l; i++) iterator.call(context, obj[i], i, obj); - } else { - for (var key in obj) { - if (hasOwnProperty.call(obj, key)) iterator.call(context, obj[key], key, obj); - } - } - } catch(e) { - if (e != breaker) throw e; - } - return obj; - }; - - // Return the results of applying the iterator to each element. - // Delegates to JavaScript 1.6's native map if available. - _.map = function(obj, iterator, context) { - if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); - var results = []; - each(obj, function(value, index, list) { - results.push(iterator.call(context, value, index, list)); - }); - return results; - }; - - // Reduce builds up a single result from a list of values, aka inject, or foldl. - // Delegates to JavaScript 1.8's native reduce if available. - _.reduce = function(obj, memo, iterator, context) { - if (nativeReduce && obj.reduce === nativeReduce) return obj.reduce(_.bind(iterator, context), memo); - each(obj, function(value, index, list) { - memo = iterator.call(context, memo, value, index, list); - }); - return memo; - }; - - // The right-associative version of reduce, also known as foldr. Uses - // Delegates to JavaScript 1.8's native reduceRight if available. - _.reduceRight = function(obj, memo, iterator, context) { - if (nativeReduceRight && obj.reduceRight === nativeReduceRight) return obj.reduceRight(_.bind(iterator, context), memo); - var reversed = _.clone(_.toArray(obj)).reverse(); - return _.reduce(reversed, memo, iterator, context); - }; - - // Return the first value which passes a truth test. - _.detect = function(obj, iterator, context) { - var result; - each(obj, function(value, index, list) { - if (iterator.call(context, value, index, list)) { - result = value; - _.breakLoop(); - } - }); - return result; - }; - - // Return all the elements that pass a truth test. - // Delegates to JavaScript 1.6's native filter if available. - _.filter = function(obj, iterator, context) { - if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); - var results = []; - each(obj, function(value, index, list) { - iterator.call(context, value, index, list) && results.push(value); - }); - return results; - }; - - // Return all the elements for which a truth test fails. - _.reject = function(obj, iterator, context) { - var results = []; - each(obj, function(value, index, list) { - !iterator.call(context, value, index, list) && results.push(value); - }); - return results; - }; - - // Determine whether all of the elements match a truth test. - // Delegates to JavaScript 1.6's native every if available. - _.every = function(obj, iterator, context) { - iterator = iterator || _.identity; - if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); - var result = true; - each(obj, function(value, index, list) { - if (!(result = result && iterator.call(context, value, index, list))) _.breakLoop(); - }); - return result; - }; - - // Determine if at least one element in the object matches a truth test. - // Delegates to JavaScript 1.6's native some if available. - _.some = function(obj, iterator, context) { - iterator = iterator || _.identity; - if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); - var result = false; - each(obj, function(value, index, list) { - if (result = iterator.call(context, value, index, list)) _.breakLoop(); - }); - return result; - }; - - // Determine if a given value is included in the array or object using '==='. - _.include = function(obj, target) { - if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; - var found = false; - each(obj, function(value) { - if (found = value === target) _.breakLoop(); - }); - return found; - }; - - // Invoke a method with arguments on every item in a collection. - _.invoke = function(obj, method) { - var args = _.rest(arguments, 2); - return _.map(obj, function(value) { - return (method ? value[method] : value).apply(value, args); - }); - }; - - // Convenience version of a common use case of map: fetching a property. - _.pluck = function(obj, key) { - return _.map(obj, function(value){ return value[key]; }); - }; - - // Return the maximum item or (item-based computation). - _.max = function(obj, iterator, context) { - if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); - var result = {computed : -Infinity}; - each(obj, function(value, index, list) { - var computed = iterator ? iterator.call(context, value, index, list) : value; - computed >= result.computed && (result = {value : value, computed : computed}); - }); - return result.value; - }; - - // Return the minimum element (or element-based computation). - _.min = function(obj, iterator, context) { - if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); - var result = {computed : Infinity}; - each(obj, function(value, index, list) { - var computed = iterator ? iterator.call(context, value, index, list) : value; - computed < result.computed && (result = {value : value, computed : computed}); - }); - return result.value; - }; - - // Sort the object's values by a criterion produced by an iterator. - _.sortBy = function(obj, iterator, context) { - return _.pluck(_.map(obj, function(value, index, list) { - return { - value : value, - criteria : iterator.call(context, value, index, list) - }; - }).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }), 'value'); - }; - - // Use a comparator function to figure out at what index an object should - // be inserted so as to maintain order. Uses binary search. - _.sortedIndex = function(array, obj, iterator) { - iterator = iterator || _.identity; - var low = 0, high = array.length; - while (low < high) { - var mid = (low + high) >> 1; - iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; - } - return low; - }; - - // Convert anything iterable into a real, live array. - _.toArray = function(iterable) { - if (!iterable) return []; - if (iterable.toArray) return iterable.toArray(); - if (_.isArray(iterable)) return iterable; - if (_.isArguments(iterable)) return slice.call(iterable); - return _.values(iterable); - }; - - // Return the number of elements in an object. - _.size = function(obj) { - return _.toArray(obj).length; - }; - - // -------------------------- Array Functions: ------------------------------ - - // Get the first element of an array. Passing "n" will return the first N - // values in the array. Aliased as "head". The "guard" check allows it to work - // with _.map. - _.first = function(array, n, guard) { - return n && !guard ? slice.call(array, 0, n) : array[0]; - }; - - // Returns everything but the first entry of the array. Aliased as "tail". - // Especially useful on the arguments object. Passing an "index" will return - // the rest of the values in the array from that index onward. The "guard" - //check allows it to work with _.map. - _.rest = function(array, index, guard) { - return slice.call(array, _.isUndefined(index) || guard ? 1 : index); - }; - - // Get the last element of an array. - _.last = function(array) { - return array[array.length - 1]; - }; - - // Trim out all falsy values from an array. - _.compact = function(array) { - return _.filter(array, function(value){ return !!value; }); - }; - - // Return a completely flattened version of an array. - _.flatten = function(array) { - return _.reduce(array, [], function(memo, value) { - if (_.isArray(value)) return memo.concat(_.flatten(value)); - memo.push(value); - return memo; - }); - }; - - // Return a version of the array that does not contain the specified value(s). - _.without = function(array) { - var values = _.rest(arguments); - return _.filter(array, function(value){ return !_.include(values, value); }); - }; - - // Produce a duplicate-free version of the array. If the array has already - // been sorted, you have the option of using a faster algorithm. - _.uniq = function(array, isSorted) { - return _.reduce(array, [], function(memo, el, i) { - if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo.push(el); - return memo; - }); - }; - - // Produce an array that contains every item shared between all the - // passed-in arrays. - _.intersect = function(array) { - var rest = _.rest(arguments); - return _.filter(_.uniq(array), function(item) { - return _.every(rest, function(other) { - return _.indexOf(other, item) >= 0; - }); - }); - }; - - // Zip together multiple lists into a single array -- elements that share - // an index go together. - _.zip = function() { - var args = _.toArray(arguments); - var length = _.max(_.pluck(args, 'length')); - var results = new Array(length); - for (var i = 0; i < length; i++) results[i] = _.pluck(args, String(i)); - return results; - }; - - // If the browser doesn't supply us with indexOf (I'm looking at you, MSIE), - // we need this function. Return the position of the first occurence of an - // item in an array, or -1 if the item is not included in the array. - // Delegates to JavaScript 1.8's native indexOf if available. - _.indexOf = function(array, item) { - if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); - for (var i = 0, l = array.length; i < l; i++) if (array[i] === item) return i; - return -1; - }; - - - // Delegates to JavaScript 1.6's native lastIndexOf if available. - _.lastIndexOf = function(array, item) { - if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); - var i = array.length; - while (i--) if (array[i] === item) return i; - return -1; - }; - - // Generate an integer Array containing an arithmetic progression. A port of - // the native Python range() function. See: - // http://docs.python.org/library/functions.html#range - _.range = function(start, stop, step) { - var a = _.toArray(arguments); - var solo = a.length <= 1; - var start = solo ? 0 : a[0], stop = solo ? a[0] : a[1], step = a[2] || 1; - var len = Math.ceil((stop - start) / step); - if (len <= 0) return []; - var range = new Array(len); - for (var i = start, idx = 0; true; i += step) { - if ((step > 0 ? i - stop : stop - i) >= 0) return range; - range[idx++] = i; - } - }; - - // ----------------------- Function Functions: ------------------------------ - - // Create a function bound to a given object (assigning 'this', and arguments, - // optionally). Binding with arguments is also known as 'curry'. - _.bind = function(func, obj) { - var args = _.rest(arguments, 2); - return function() { - return func.apply(obj || {}, args.concat(_.toArray(arguments))); - }; - }; - - // Bind all of an object's methods to that object. Useful for ensuring that - // all callbacks defined on an object belong to it. - _.bindAll = function(obj) { - var funcs = _.rest(arguments); - if (funcs.length == 0) funcs = _.functions(obj); - each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); - return obj; - }; - - // Delays a function for the given number of milliseconds, and then calls - // it with the arguments supplied. - _.delay = function(func, wait) { - var args = _.rest(arguments, 2); - return setTimeout(function(){ return func.apply(func, args); }, wait); - }; - - // Defers a function, scheduling it to run after the current call stack has - // cleared. - _.defer = function(func) { - return _.delay.apply(_, [func, 1].concat(_.rest(arguments))); - }; - - // Returns the first function passed as an argument to the second, - // allowing you to adjust arguments, run code before and after, and - // conditionally execute the original function. - _.wrap = function(func, wrapper) { - return function() { - var args = [func].concat(_.toArray(arguments)); - return wrapper.apply(wrapper, args); - }; - }; - - // Returns a function that is the composition of a list of functions, each - // consuming the return value of the function that follows. - _.compose = function() { - var funcs = _.toArray(arguments); - return function() { - var args = _.toArray(arguments); - for (var i=funcs.length-1; i >= 0; i--) { - args = [funcs[i].apply(this, args)]; - } - return args[0]; - }; - }; - - // ------------------------- Object Functions: ------------------------------ - - // Retrieve the names of an object's properties. - // Delegates to ECMA5's native Object.keys - _.keys = nativeKeys || function(obj) { - if (_.isArray(obj)) return _.range(0, obj.length); - var keys = []; - for (var key in obj) if (hasOwnProperty.call(obj, key)) keys.push(key); - return keys; - }; - - // Retrieve the values of an object's properties. - _.values = function(obj) { - return _.map(obj, _.identity); - }; - - // Return a sorted list of the function names available on the object. - _.functions = function(obj) { - return _.filter(_.keys(obj), function(key){ return _.isFunction(obj[key]); }).sort(); - }; - - // Extend a given object with all the properties in passed-in object(s). - _.extend = function(obj) { - each(_.rest(arguments), function(source) { - for (var prop in source) obj[prop] = source[prop]; - }); - return obj; - }; - - // Create a (shallow-cloned) duplicate of an object. - _.clone = function(obj) { - if (_.isArray(obj)) return obj.slice(0); - return _.extend({}, obj); - }; - - // Invokes interceptor with the obj, and then returns obj. - // The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. - _.tap = function(obj, interceptor) { - interceptor(obj); - return obj; - }; - - // Perform a deep comparison to check if two objects are equal. - _.isEqual = function(a, b) { - // Check object identity. - if (a === b) return true; - // Different types? - var atype = typeof(a), btype = typeof(b); - if (atype != btype) return false; - // Basic equality test (watch out for coercions). - if (a == b) return true; - // One is falsy and the other truthy. - if ((!a && b) || (a && !b)) return false; - // One of them implements an isEqual()? - if (a.isEqual) return a.isEqual(b); - // Check dates' integer values. - if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime(); - // Both are NaN? - if (_.isNaN(a) && _.isNaN(b)) return true; - // Compare regular expressions. - if (_.isRegExp(a) && _.isRegExp(b)) - return a.source === b.source && - a.global === b.global && - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline; - // If a is not an object by this point, we can't handle it. - if (atype !== 'object') return false; - // Check for different array lengths before comparing contents. - if (a.length && (a.length !== b.length)) return false; - // Nothing else worked, deep compare the contents. - var aKeys = _.keys(a), bKeys = _.keys(b); - // Different object sizes? - if (aKeys.length != bKeys.length) return false; - // Recursive comparison of contents. - for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false; - return true; - }; - - // Is a given array or object empty? - _.isEmpty = function(obj) { - if (_.isArray(obj)) return obj.length === 0; - for (var key in obj) if (hasOwnProperty.call(obj, key)) return false; - return true; - }; - - // Is a given value a DOM element? - _.isElement = function(obj) { - return !!(obj && obj.nodeType == 1); - }; - - // Is a given value an array? - // Delegates to ECMA5's native Array.isArray - _.isArray = nativeIsArray || function(obj) { - return !!(obj && obj.concat && obj.unshift && !obj.callee); - }; - - // Is a given variable an arguments object? - _.isArguments = function(obj) { - return obj && obj.callee; - }; - - // Is a given value a function? - _.isFunction = function(obj) { - return !!(obj && obj.constructor && obj.call && obj.apply); - }; - - // Is a given value a string? - _.isString = function(obj) { - return !!(obj === '' || (obj && obj.charCodeAt && obj.substr)); - }; - - // Is a given value a number? - _.isNumber = function(obj) { - return (obj === +obj) || (toString.call(obj) === '[object Number]'); - }; - - // Is a given value a boolean? - _.isBoolean = function(obj) { - return obj === true || obj === false; - }; - - // Is a given value a date? - _.isDate = function(obj) { - return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear); - }; - - // Is the given value a regular expression? - _.isRegExp = function(obj) { - return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false)); - }; - - // Is the given value NaN -- this one is interesting. NaN != NaN, and - // isNaN(undefined) == true, so we make sure it's a number first. - _.isNaN = function(obj) { - return _.isNumber(obj) && isNaN(obj); - }; - - // Is a given value equal to null? - _.isNull = function(obj) { - return obj === null; - }; - - // Is a given variable undefined? - _.isUndefined = function(obj) { - return typeof obj == 'undefined'; - }; - - // -------------------------- Utility Functions: ---------------------------- - - // Run Underscore.js in noConflict mode, returning the '_' variable to its - // previous owner. Returns a reference to the Underscore object. - _.noConflict = function() { - root._ = previousUnderscore; - return this; - }; - - // Keep the identity function around for default iterators. - _.identity = function(value) { - return value; - }; - - // Run a function n times. - _.times = function (n, iterator, context) { - for (var i = 0; i < n; i++) iterator.call(context, i); - }; - - // Break out of the middle of an iteration. - _.breakLoop = function() { - throw breaker; - }; - - // Add your own custom functions to the Underscore object, ensuring that - // they're correctly added to the OOP wrapper as well. - _.mixin = function(obj) { - each(_.functions(obj), function(name){ - addToWrapper(name, _[name] = obj[name]); - }); - }; - - // Generate a unique integer id (unique within the entire client session). - // Useful for temporary DOM ids. - var idCounter = 0; - _.uniqueId = function(prefix) { - var id = idCounter++; - return prefix ? prefix + id : id; - }; - - // By default, Underscore uses ERB-style template delimiters, change the - // following template settings to use alternative delimiters. - _.templateSettings = { - start : '<%', - end : '%>', - interpolate : /<%=(.+?)%>/g - }; - - // JavaScript templating a-la ERB, pilfered from John Resig's - // "Secrets of the JavaScript Ninja", page 83. - // Single-quote fix from Rick Strahl's version. - // With alterations for arbitrary delimiters. - _.template = function(str, data) { - var c = _.templateSettings; - var endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g"); - var fn = new Function('obj', - 'var p=[],print=function(){p.push.apply(p,arguments);};' + - 'with(obj){p.push(\'' + - str.replace(/[\r\t\n]/g, " ") - .replace(endMatch,"\t") - .split("'").join("\\'") - .split("\t").join("'") - .replace(c.interpolate, "',$1,'") - .split(c.start).join("');") - .split(c.end).join("p.push('") - + "');}return p.join('');"); - return data ? fn(data) : fn; - }; - - // ------------------------------- Aliases ---------------------------------- - - _.each = _.forEach; - _.foldl = _.inject = _.reduce; - _.foldr = _.reduceRight; - _.select = _.filter; - _.all = _.every; - _.any = _.some; - _.head = _.first; - _.tail = _.rest; - _.methods = _.functions; - - // ------------------------ Setup the OOP Wrapper: -------------------------- - - // If Underscore is called as a function, it returns a wrapped object that - // can be used OO-style. This wrapper holds altered versions of all the - // underscore functions. Wrapped objects may be chained. - var wrapper = function(obj) { this._wrapped = obj; }; - - // Helper function to continue chaining intermediate results. - var result = function(obj, chain) { - return chain ? _(obj).chain() : obj; - }; - - // A method to easily add functions to the OOP wrapper. - var addToWrapper = function(name, func) { - wrapper.prototype[name] = function() { - var args = _.toArray(arguments); - unshift.call(args, this._wrapped); - return result(func.apply(_, args), this._chain); - }; - }; - - // Add all of the Underscore functions to the wrapper object. - _.mixin(_); - - // Add all mutator Array functions to the wrapper. - each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { - var method = ArrayProto[name]; - wrapper.prototype[name] = function() { - method.apply(this._wrapped, arguments); - return result(this._wrapped, this._chain); - }; - }); - - // Add all accessor Array functions to the wrapper. - each(['concat', 'join', 'slice'], function(name) { - var method = ArrayProto[name]; - wrapper.prototype[name] = function() { - return result(method.apply(this._wrapped, arguments), this._chain); - }; - }); - - // Start chaining a wrapped Underscore object. - wrapper.prototype.chain = function() { - this._chain = true; - return this; - }; - - // Extracts the result from a wrapped and chained object. - wrapper.prototype.value = function() { - return this._wrapped; - }; - -})();
torgeir/tnode
c40a379775563d6cd43531c1293fde8b80ba7496
removed stale rest-resource function names
diff --git a/examples/5/rest-style.js b/examples/5/rest-style.js index 9c47af5..3e15280 100644 --- a/examples/5/rest-style.js +++ b/examples/5/rest-style.js @@ -1,20 +1,20 @@ var t = require('../../t'); t.app({ debug: true, resources: { blog: { - list: function list(req, res) { res.respond('list') }, - get: function get(req, res, id) { res.respond('get ' + id) }, + list: function(req, res) { res.respond('list') }, + get: function(req, res, id) { res.respond('get ' + id) }, save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } } }, routes: { '^/$': function(req, res) { return 'html'; }, '^/(js/.*)$': t.serve } }) \ No newline at end of file
torgeir/tnode
f94f12615a365d8208d3f80a58cd3147e258daec
added post put delete data support. added example for rest style routes
diff --git a/examples/3/templates/form.html b/examples/3/templates/form.html index 8cf2a3d..a1a92d9 100644 --- a/examples/3/templates/form.html +++ b/examples/3/templates/form.html @@ -1,4 +1,4 @@ <form action="/ionlyhandleposts" method="post"> - <input type="submit" value="This works.."/> + <input type="submit" name="submit" value="This works.."/> </form> <p><a href="/ionlyhandleposts">This</a>, on the other hand, does not work.</p> \ No newline at end of file diff --git a/examples/3/verbs.js b/examples/3/verbs.js index 2b5a474..8eb04b5 100644 --- a/examples/3/verbs.js +++ b/examples/3/verbs.js @@ -1,13 +1,13 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function() { return 'form'; }, - 'POST /ionlyhandleposts': function(req, res) { - res.respond('POST is ok'); + 'POST /ionlyhandleposts': function(req, res, data) { + res.respond('POST is ok ' + JSON.stringify(data)); } } }) \ No newline at end of file diff --git a/examples/4/files.js b/examples/4/files.js index fcf9d26..cd67d36 100644 --- a/examples/4/files.js +++ b/examples/4/files.js @@ -1,14 +1,14 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { return 'index'; }, - '^/(web/.*/.*)$' : t.serve, /* serves all files from web/js/ */ + '^/(web/.*)$' : t.serve, /* serves all files from web/ */ '^/favicon\.ico$' : function(req, res) { res.respond('Nothing to see here.'); } } }) \ No newline at end of file diff --git a/examples/5/js/jquery-1.4.2.js b/examples/5/js/jquery-1.4.2.js new file mode 100644 index 0000000..fff6776 --- /dev/null +++ b/examples/5/js/jquery-1.4.2.js @@ -0,0 +1,6240 @@ +/*! + * jQuery JavaScript Library v1.4.2 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Sat Feb 13 22:33:48 2010 -0500 + */ +(function( window, undefined ) { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // (both of which we optimize for) + quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, + + // Is it a simple selector + isSimple = /^.[^:#\[\.,]*$/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // Has the ready events already been bound? + readyBound = false, + + // The functions to execute on DOM ready + readyList = [], + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwnProperty = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + indexOf = Array.prototype.indexOf; + +jQuery.fn = jQuery.prototype = { + init: function( selector, context ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context ) { + this.context = document; + this[0] = document.body; + this.selector = "body"; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + match = quickExpr.exec( selector ); + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + doc = (context ? context.ownerDocument || context : document); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = buildFragment( [ match[1] ], [ doc ] ); + selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + if ( elem ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $("TAG") + } else if ( !context && /^\w+$/.test( selector ) ) { + this.selector = selector; + this.context = document; + selector = document.getElementsByTagName( selector ); + return jQuery.merge( this, selector ); + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return (context || rootjQuery).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return jQuery( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if (selector.selector !== undefined) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.4.2", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = jQuery(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + (this.selector ? " " : "") + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // If the DOM is already ready + if ( jQuery.isReady ) { + // Execute the function immediately + fn.call( document, jQuery ); + + // Otherwise, remember the function for later + } else if ( readyList ) { + // Add the function to the wait list + readyList.push( fn ); + } + + return this; + }, + + eq: function( i ) { + return i === -1 ? + this.slice( i ) : + this.slice( i, +i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || jQuery(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + // copy reference to target object + var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging object literal values or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { + var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src + : jQuery.isArray(copy) ? [] : {}; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + window.$ = _$; + + if ( deep ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // Handle when the DOM is ready + ready: function() { + // Make sure that the DOM is not already loaded + if ( !jQuery.isReady ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 13 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If there are functions bound, to execute + if ( readyList ) { + // Execute all of them + var fn, i = 0; + while ( (fn = readyList[ i++ ]) ) { + fn.call( document, jQuery ); + } + + // Reset the list of functions + readyList = null; + } + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyBound ) { + return; + } + + readyBound = true; + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + return jQuery.ready(); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent("onreadystatechange", DOMContentLoaded); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return toString.call(obj) === "[object Function]"; + }, + + isArray: function( obj ) { + return toString.call(obj) === "[object Array]"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { + return false; + } + + // Not own constructor property must be Object + if ( obj.constructor + && !hasOwnProperty.call(obj, "constructor") + && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwnProperty.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw msg; + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") + .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { + + // Try to use the native JSON parser first + return window.JSON && window.JSON.parse ? + window.JSON.parse( data ) : + (new Function("return " + data))(); + + } else { + jQuery.error( "Invalid JSON: " + data ); + } + }, + + noop: function() {}, + + // Evalulates a script in a global context + globalEval: function( data ) { + if ( data && rnotwhite.test(data) ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + + if ( jQuery.support.scriptEval ) { + script.appendChild( document.createTextNode( data ) ); + } else { + script.text = data; + } + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction(object); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} + } + } + + return object; + }, + + trim: function( text ) { + return (text || "").replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // The extra typeof function check is to prevent crashes + // in Safari 2 (See: #3039) + if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = []; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + if ( !inv !== !callback( elems[ i ], i ) ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var ret = [], value; + + // Go through the array, translating each of the items to their + // new value (or values). + for ( var i = 0, length = elems.length; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + proxy: function( fn, proxy, thisObject ) { + if ( arguments.length === 2 ) { + if ( typeof proxy === "string" ) { + thisObject = fn; + fn = thisObject[ proxy ]; + proxy = undefined; + + } else if ( proxy && !jQuery.isFunction( proxy ) ) { + thisObject = proxy; + proxy = undefined; + } + } + + if ( !proxy && fn ) { + proxy = function() { + return fn.apply( thisObject || this, arguments ); + }; + } + + // Set the guid of unique handler to the same of original handler, so it can be removed + if ( fn ) { + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + } + + // So proxy can be declared as an argument + return proxy; + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + browser: {} +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +if ( indexOf ) { + jQuery.inArray = function( elem, array ) { + return indexOf.call( array, elem ); + }; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch( error ) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +function evalScript( i, elem ) { + if ( elem.src ) { + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + } else { + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } +} + +// Mutifunctional method to get and set values to a collection +// The value/s can be optionally by executed if its a function +function access( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; +} + +function now() { + return (new Date).getTime(); +} +(function() { + + jQuery.support = {}; + + var root = document.documentElement, + script = document.createElement("script"), + div = document.createElement("div"), + id = "script" + now(); + + div.style.display = "none"; + div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; + + var all = div.getElementsByTagName("*"), + a = div.getElementsByTagName("a")[0]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return; + } + + jQuery.support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: div.firstChild.nodeType === 3, + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText insted) + style: /red/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: a.getAttribute("href") === "/a", + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55$/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: div.getElementsByTagName("input")[0].value === "on", + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected, + + parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null, + + // Will be defined later + deleteExpando: true, + checkClone: false, + scriptEval: false, + noCloneEvent: true, + boxModel: null + }; + + script.type = "text/javascript"; + try { + script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); + } catch(e) {} + + root.insertBefore( script, root.firstChild ); + + // Make sure that the execution of code works by injecting a script + // tag with appendChild/createTextNode + // (IE doesn't support this, fails, and uses .text instead) + if ( window[ id ] ) { + jQuery.support.scriptEval = true; + delete window[ id ]; + } + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete script.test; + + } catch(e) { + jQuery.support.deleteExpando = false; + } + + root.removeChild( script ); + + if ( div.attachEvent && div.fireEvent ) { + div.attachEvent("onclick", function click() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + jQuery.support.noCloneEvent = false; + div.detachEvent("onclick", click); + }); + div.cloneNode(true).fireEvent("onclick"); + } + + div = document.createElement("div"); + div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; + + var fragment = document.createDocumentFragment(); + fragment.appendChild( div.firstChild ); + + // WebKit doesn't clone checked state correctly in fragments + jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; + + // Figure out if the W3C box model works as expected + // document.body must exist before we can do this + jQuery(function() { + var div = document.createElement("div"); + div.style.width = div.style.paddingLeft = "1px"; + + document.body.appendChild( div ); + jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; + document.body.removeChild( div ).style.display = 'none'; + + div = null; + }); + + // Technique from Juriy Zaytsev + // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ + var eventSupported = function( eventName ) { + var el = document.createElement("div"); + eventName = "on" + eventName; + + var isSupported = (eventName in el); + if ( !isSupported ) { + el.setAttribute(eventName, "return;"); + isSupported = typeof el[eventName] === "function"; + } + el = null; + + return isSupported; + }; + + jQuery.support.submitBubbles = eventSupported("submit"); + jQuery.support.changeBubbles = eventSupported("change"); + + // release memory in IE + root = script = div = all = a = null; +})(); + +jQuery.props = { + "for": "htmlFor", + "class": "className", + readonly: "readOnly", + maxlength: "maxLength", + cellspacing: "cellSpacing", + rowspan: "rowSpan", + colspan: "colSpan", + tabindex: "tabIndex", + usemap: "useMap", + frameborder: "frameBorder" +}; +var expando = "jQuery" + now(), uuid = 0, windowData = {}; + +jQuery.extend({ + cache: {}, + + expando:expando, + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + "object": true, + "applet": true + }, + + data: function( elem, name, data ) { + if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { + return; + } + + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ], cache = jQuery.cache, thisCache; + + if ( !id && typeof name === "string" && data === undefined ) { + return null; + } + + // Compute a unique ID for the element + if ( !id ) { + id = ++uuid; + } + + // Avoid generating a new cache unless none exists and we + // want to manipulate it. + if ( typeof name === "object" ) { + elem[ expando ] = id; + thisCache = cache[ id ] = jQuery.extend(true, {}, name); + + } else if ( !cache[ id ] ) { + elem[ expando ] = id; + cache[ id ] = {}; + } + + thisCache = cache[ id ]; + + // Prevent overriding the named cache with undefined values + if ( data !== undefined ) { + thisCache[ name ] = data; + } + + return typeof name === "string" ? thisCache[ name ] : thisCache; + }, + + removeData: function( elem, name ) { + if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { + return; + } + + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; + + // If we want to remove a specific section of the element's data + if ( name ) { + if ( thisCache ) { + // Remove the section of cache data + delete thisCache[ name ]; + + // If we've removed all the data, remove the element's cache + if ( jQuery.isEmptyObject(thisCache) ) { + jQuery.removeData( elem ); + } + } + + // Otherwise, we want to remove all of the element's data + } else { + if ( jQuery.support.deleteExpando ) { + delete elem[ jQuery.expando ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } + + // Completely remove the data cache + delete cache[ id ]; + } + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + if ( typeof key === "undefined" && this.length ) { + return jQuery.data( this[0] ); + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + } + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } else { + return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { + jQuery.data( this, key, value ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); +jQuery.extend({ + queue: function( elem, type, data ) { + if ( !elem ) { + return; + } + + type = (type || "fx") + "queue"; + var q = jQuery.data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( !data ) { + return q || []; + } + + if ( !q || jQuery.isArray(data) ) { + q = jQuery.data( elem, type, jQuery.makeArray(data) ); + + } else { + q.push( data ); + } + + return q; + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), fn = queue.shift(); + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift("inprogress"); + } + + fn.call(elem, function() { + jQuery.dequeue(elem, type); + }); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function( i, elem ) { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; + type = type || "fx"; + + return this.queue( type, function() { + var elem = this; + setTimeout(function() { + jQuery.dequeue( elem, type ); + }, time ); + }); + }, + + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + } +}); +var rclass = /[\n\t]/g, + rspace = /\s+/, + rreturn = /\r/g, + rspecialurl = /href|src|style/, + rtype = /(button|input)/i, + rfocusable = /(button|input|object|select|textarea)/i, + rclickable = /^(a|area)$/i, + rradiocheck = /radio|checkbox/; + +jQuery.fn.extend({ + attr: function( name, value ) { + return access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name, fn ) { + return this.each(function(){ + jQuery.attr( this, name, "" ); + if ( this.nodeType === 1 ) { + this.removeAttribute( name ); + } + }); + }, + + addClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.addClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( value && typeof value === "string" ) { + var classNames = (value || "").split( rspace ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className ) { + elem.className = value; + + } else { + var className = " " + elem.className + " ", setClass = elem.className; + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { + setClass += " " + classNames[c]; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + self.removeClass( value.call(this, i, self.attr("class")) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + var classNames = (value || "").split(rspace); + + for ( var i = 0, l = this.length; i < l; i++ ) { + var elem = this[i]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + var className = (" " + elem.className + " ").replace(rclass, " "); + for ( var c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[c] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this); + self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, i = 0, self = jQuery(this), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery.data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " "; + for ( var i = 0, l = this.length; i < l; i++ ) { + if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + if ( value === undefined ) { + var elem = this[0]; + + if ( elem ) { + if ( jQuery.nodeName( elem, "option" ) ) { + return (elem.attributes.value || {}).specified ? elem.value : elem.text; + } + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + if ( option.selected ) { + // Get the specifc value for the option + value = jQuery(option).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + } + + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { + return elem.getAttribute("value") === null ? "on" : elem.value; + } + + + // Everything else, we just grab the value + return (elem.value || "").replace(rreturn, ""); + + } + + return undefined; + } + + var isFunction = jQuery.isFunction(value); + + return this.each(function(i) { + var self = jQuery(this), val = value; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call(this, i, self.val()); + } + + // Typecast each time if the value is a Function and the appended + // value is therefore different each time. + if ( typeof val === "number" ) { + val += ""; + } + + if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { + this.checked = jQuery.inArray( self.val(), val ) >= 0; + + } else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(val); + + jQuery( "option", this ).each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + this.selectedIndex = -1; + } + + } else { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + // don't set attributes on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery(elem)[name](value); + } + + var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), + // Whether we are setting (or getting) + set = value !== undefined; + + // Try to normalize/fix the name + name = notxml && jQuery.props[ name ] || name; + + // Only do all the following if this is a node (faster for style) + if ( elem.nodeType === 1 ) { + // These attributes require special treatment + var special = rspecialurl.test( name ); + + // Safari mis-reports the default selected property of an option + // Accessing the parent's selectedIndex property fixes it + if ( name === "selected" && !jQuery.support.optSelected ) { + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + + // If applicable, access the attribute via the DOM 0 way + if ( name in elem && notxml && !special ) { + if ( set ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } + + elem[ name ] = value; + } + + // browsers index elements by id/name on forms, give priority to attributes. + if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { + return elem.getAttributeNode( name ).nodeValue; + } + + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + if ( name === "tabIndex" ) { + var attributeNode = elem.getAttributeNode( "tabIndex" ); + + return attributeNode && attributeNode.specified ? + attributeNode.value : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + + return elem[ name ]; + } + + if ( !jQuery.support.style && notxml && name === "style" ) { + if ( set ) { + elem.style.cssText = "" + value; + } + + return elem.style.cssText; + } + + if ( set ) { + // convert the value to a string (all browsers do this but IE) see #1070 + elem.setAttribute( name, "" + value ); + } + + var attr = !jQuery.support.hrefNormalized && notxml && special ? + // Some attributes require a special call on IE + elem.getAttribute( name, 2 ) : + elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return attr === null ? undefined : attr; + } + + // elem is actually elem.style ... set the style + // Using attr for specific style information is now deprecated. Use style instead. + return jQuery.style( elem, name, value ); + } +}); +var rnamespaces = /\.(.*)$/, + fcleanup = function( nm ) { + return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { + return "\\" + ch; + }); + }; + +/* + * A number of helper functions used for managing events. + * Many of the ideas behind this code originated from + * Dean Edwards' addEvent library. + */ +jQuery.event = { + + // Bind an event to an element + // Original by Dean Edwards + add: function( elem, types, handler, data ) { + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // For whatever reason, IE has trouble passing the window object + // around, causing it to be cloned in the process + if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { + elem = window; + } + + var handleObjIn, handleObj; + + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure + var elemData = jQuery.data( elem ); + + // If no elemData is found then we must be trying to bind to one of the + // banned noData elements + if ( !elemData ) { + return; + } + + var events = elemData.events = elemData.events || {}, + eventHandle = elemData.handle, eventHandle; + + if ( !eventHandle ) { + elemData.handle = eventHandle = function() { + // Handle the second event of a trigger and when + // an event is called after a page has unloaded + return typeof jQuery !== "undefined" && !jQuery.event.triggered ? + jQuery.event.handle.apply( eventHandle.elem, arguments ) : + undefined; + }; + } + + // Add elem as a property of the handle function + // This is to prevent a memory leak with non-native events in IE. + eventHandle.elem = elem; + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = types.split(" "); + + var type, i = 0, namespaces; + + while ( (type = types[ i++ ]) ) { + handleObj = handleObjIn ? + jQuery.extend({}, handleObjIn) : + { handler: handler, data: data }; + + // Namespaced event handlers + if ( type.indexOf(".") > -1 ) { + namespaces = type.split("."); + type = namespaces.shift(); + handleObj.namespace = namespaces.slice(0).sort().join("."); + + } else { + namespaces = []; + handleObj.namespace = ""; + } + + handleObj.type = type; + handleObj.guid = handler.guid; + + // Get the current list of functions bound to this event + var handlers = events[ type ], + special = jQuery.event.special[ type ] || {}; + + // Init the event handler queue + if ( !handlers ) { + handlers = events[ type ] = []; + + // Check for a special event handler + // Only use addEventListener/attachEvent if the special + // events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add the function to the element's handler list + handlers.push( handleObj ); + + // Keep track of which events have been used, for global triggering + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, pos ) { + // don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, + elemData = jQuery.data( elem ), + events = elemData && elemData.events; + + if ( !elemData || !events ) { + return; + } + + // types is actually an event object here + if ( types && types.type ) { + handler = types.handler; + types = types.type; + } + + // Unbind all events for the element + if ( !types || typeof types === "string" && types.charAt(0) === "." ) { + types = types || ""; + + for ( type in events ) { + jQuery.event.remove( elem, type + types ); + } + + return; + } + + // Handle multiple events separated by a space + // jQuery(...).unbind("mouseover mouseout", fn); + types = types.split(" "); + + while ( (type = types[ i++ ]) ) { + origType = type; + handleObj = null; + all = type.indexOf(".") < 0; + namespaces = []; + + if ( !all ) { + // Namespaced event handlers + namespaces = type.split("."); + type = namespaces.shift(); + + namespace = new RegExp("(^|\\.)" + + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)") + } + + eventType = events[ type ]; + + if ( !eventType ) { + continue; + } + + if ( !handler ) { + for ( var j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( all || namespace.test( handleObj.namespace ) ) { + jQuery.event.remove( elem, origType, handleObj.handler, j ); + eventType.splice( j--, 1 ); + } + } + + continue; + } + + special = jQuery.event.special[ type ] || {}; + + for ( var j = pos || 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( handler.guid === handleObj.guid ) { + // remove the given handler for the given type + if ( all || namespace.test( handleObj.namespace ) ) { + if ( pos == null ) { + eventType.splice( j--, 1 ); + } + + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + + if ( pos != null ) { + break; + } + } + } + + // remove generic event handler if no more handlers exist + if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + removeEvent( elem, type, elemData.handle ); + } + + ret = null; + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + var handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + delete elemData.events; + delete elemData.handle; + + if ( jQuery.isEmptyObject( elemData ) ) { + jQuery.removeData( elem ); + } + } + }, + + // bubbling is internal + trigger: function( event, data, elem /*, bubbling */ ) { + // Event object or event type + var type = event.type || event, + bubbling = arguments[3]; + + if ( !bubbling ) { + event = typeof event === "object" ? + // jQuery.Event object + event[expando] ? event : + // Object literal + jQuery.extend( jQuery.Event(type), event ) : + // Just the event type (string) + jQuery.Event(type); + + if ( type.indexOf("!") >= 0 ) { + event.type = type = type.slice(0, -1); + event.exclusive = true; + } + + // Handle a global trigger + if ( !elem ) { + // Don't bubble custom events when global (to avoid too much overhead) + event.stopPropagation(); + + // Only trigger if we've ever bound an event for it + if ( jQuery.event.global[ type ] ) { + jQuery.each( jQuery.cache, function() { + if ( this.events && this.events[type] ) { + jQuery.event.trigger( event, data, this.handle.elem ); + } + }); + } + } + + // Handle triggering a single element + + // don't do events on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + // Clean up in case it is reused + event.result = undefined; + event.target = elem; + + // Clone the incoming data, if any + data = jQuery.makeArray( data ); + data.unshift( event ); + } + + event.currentTarget = elem; + + // Trigger the event, it is assumed that "handle" is a function + var handle = jQuery.data( elem, "handle" ); + if ( handle ) { + handle.apply( elem, data ); + } + + var parent = elem.parentNode || elem.ownerDocument; + + // Trigger an inline bound script + try { + if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { + if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { + event.result = false; + } + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (e) {} + + if ( !event.isPropagationStopped() && parent ) { + jQuery.event.trigger( event, data, parent, true ); + + } else if ( !event.isDefaultPrevented() ) { + var target = event.target, old, + isClick = jQuery.nodeName(target, "a") && type === "click", + special = jQuery.event.special[ type ] || {}; + + if ( (!special._default || special._default.call( elem, event ) === false) && + !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { + + try { + if ( target[ type ] ) { + // Make sure that we don't accidentally re-trigger the onFOO events + old = target[ "on" + type ]; + + if ( old ) { + target[ "on" + type ] = null; + } + + jQuery.event.triggered = true; + target[ type ](); + } + + // prevent IE from throwing an error for some elements with some event types, see #3533 + } catch (e) {} + + if ( old ) { + target[ "on" + type ] = old; + } + + jQuery.event.triggered = false; + } + } + }, + + handle: function( event ) { + var all, handlers, namespaces, namespace, events; + + event = arguments[0] = jQuery.event.fix( event || window.event ); + event.currentTarget = this; + + // Namespaced event handlers + all = event.type.indexOf(".") < 0 && !event.exclusive; + + if ( !all ) { + namespaces = event.type.split("."); + event.type = namespaces.shift(); + namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); + } + + var events = jQuery.data(this, "events"), handlers = events[ event.type ]; + + if ( events && handlers ) { + // Clone the handlers to prevent manipulation + handlers = handlers.slice(0); + + for ( var j = 0, l = handlers.length; j < l; j++ ) { + var handleObj = handlers[ j ]; + + // Filter the functions by class + if ( all || namespace.test( handleObj.namespace ) ) { + // Pass in a reference to the handler function itself + // So that we can later remove it + event.handler = handleObj.handler; + event.data = handleObj.data; + event.handleObj = handleObj; + + var ret = handleObj.handler.apply( this, arguments ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + + if ( event.isImmediatePropagationStopped() ) { + break; + } + } + } + } + + return event.result; + }, + + props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), + + fix: function( event ) { + if ( event[ expando ] ) { + return event; + } + + // store a copy of the original event object + // and "clone" to set read-only properties + var originalEvent = event; + event = jQuery.Event( originalEvent ); + + for ( var i = this.props.length, prop; i; ) { + prop = this.props[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary + if ( !event.target ) { + event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either + } + + // check if target is a textnode (safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && event.fromElement ) { + event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; + } + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && event.clientX != null ) { + var doc = document.documentElement, body = document.body; + event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); + event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); + } + + // Add which for key events + if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { + event.which = event.charCode || event.keyCode; + } + + // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) + if ( !event.metaKey && event.ctrlKey ) { + event.metaKey = event.ctrlKey; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && event.button !== undefined ) { + event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); + } + + return event; + }, + + // Deprecated, use jQuery.guid instead + guid: 1E8, + + // Deprecated, use jQuery.proxy instead + proxy: jQuery.proxy, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady, + teardown: jQuery.noop + }, + + live: { + add: function( handleObj ) { + jQuery.event.add( this, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); + }, + + remove: function( handleObj ) { + var remove = true, + type = handleObj.origType.replace(rnamespaces, ""); + + jQuery.each( jQuery.data(this, "events").live || [], function() { + if ( type === this.origType.replace(rnamespaces, "") ) { + remove = false; + return false; + } + }); + + if ( remove ) { + jQuery.event.remove( this, handleObj.origType, liveHandler ); + } + } + + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( this.setInterval ) { + this.onbeforeunload = eventHandle; + } + + return false; + }, + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + } +}; + +var removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + elem.removeEventListener( type, handle, false ); + } : + function( elem, type, handle ) { + elem.detachEvent( "on" + type, handle ); + }; + +jQuery.Event = function( src ) { + // Allow instantiation without the 'new' keyword + if ( !this.preventDefault ) { + return new jQuery.Event( src ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + // Event type + } else { + this.type = src; + } + + // timeStamp is buggy for some events on Firefox(#3843) + // So we won't rely on the native value + this.timeStamp = now(); + + // Mark it as fixed + this[ expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + } + // otherwise set the returnValue property of the original event to false (IE) + e.returnValue = false; + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Checks if an event happened on an element within another element +// Used in jQuery.event.special.mouseenter and mouseleave handlers +var withinElement = function( event ) { + // Check if mouse(over|out) are still within the same parent element + var parent = event.relatedTarget; + + // Firefox sometimes assigns relatedTarget a XUL element + // which we cannot access the parentNode property of + try { + // Traverse up the tree + while ( parent && parent !== this ) { + parent = parent.parentNode; + } + + if ( parent !== this ) { + // set the correct event type + event.type = event.data; + + // handle event if we actually just moused on to a non sub-element + jQuery.event.handle.apply( this, arguments ); + } + + // assuming we've left the element since we most likely mousedover a xul element + } catch(e) { } +}, + +// In case of event delegation, we only need to rename the event.type, +// liveHandler will take care of the rest. +delegate = function( event ) { + event.type = event.data; + jQuery.event.handle.apply( this, arguments ); +}; + +// Create mouseenter and mouseleave events +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + setup: function( data ) { + jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); + }, + teardown: function( data ) { + jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); + } + }; +}); + +// submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function( data, namespaces ) { + if ( this.nodeName.toLowerCase() !== "form" ) { + jQuery.event.add(this, "click.specialSubmit", function( e ) { + var elem = e.target, type = elem.type; + + if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { + return trigger( "submit", this, arguments ); + } + }); + + jQuery.event.add(this, "keypress.specialSubmit", function( e ) { + var elem = e.target, type = elem.type; + + if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { + return trigger( "submit", this, arguments ); + } + }); + + } else { + return false; + } + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialSubmit" ); + } + }; + +} + +// change delegation, happens here so we have bind. +if ( !jQuery.support.changeBubbles ) { + + var formElems = /textarea|input|select/i, + + changeFilters, + + getVal = function( elem ) { + var type = elem.type, val = elem.value; + + if ( type === "radio" || type === "checkbox" ) { + val = elem.checked; + + } else if ( type === "select-multiple" ) { + val = elem.selectedIndex > -1 ? + jQuery.map( elem.options, function( elem ) { + return elem.selected; + }).join("-") : + ""; + + } else if ( elem.nodeName.toLowerCase() === "select" ) { + val = elem.selectedIndex; + } + + return val; + }, + + testChange = function testChange( e ) { + var elem = e.target, data, val; + + if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { + return; + } + + data = jQuery.data( elem, "_change_data" ); + val = getVal(elem); + + // the current data will be also retrieved by beforeactivate + if ( e.type !== "focusout" || elem.type !== "radio" ) { + jQuery.data( elem, "_change_data", val ); + } + + if ( data === undefined || val === data ) { + return; + } + + if ( data != null || val ) { + e.type = "change"; + return jQuery.event.trigger( e, arguments[1], elem ); + } + }; + + jQuery.event.special.change = { + filters: { + focusout: testChange, + + click: function( e ) { + var elem = e.target, type = elem.type; + + if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { + return testChange.call( this, e ); + } + }, + + // Change has to be called before submit + // Keydown will be called before keypress, which is used in submit-event delegation + keydown: function( e ) { + var elem = e.target, type = elem.type; + + if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || + (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || + type === "select-multiple" ) { + return testChange.call( this, e ); + } + }, + + // Beforeactivate happens also before the previous element is blurred + // with this event you can't trigger a change event, but you can store + // information/focus[in] is not needed anymore + beforeactivate: function( e ) { + var elem = e.target; + jQuery.data( elem, "_change_data", getVal(elem) ); + } + }, + + setup: function( data, namespaces ) { + if ( this.type === "file" ) { + return false; + } + + for ( var type in changeFilters ) { + jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); + } + + return formElems.test( this.nodeName ); + }, + + teardown: function( namespaces ) { + jQuery.event.remove( this, ".specialChange" ); + + return formElems.test( this.nodeName ); + } + }; + + changeFilters = jQuery.event.special.change.filters; +} + +function trigger( type, elem, args ) { + args[0].type = type; + return jQuery.event.handle.apply( elem, args ); +} + +// Create "bubbling" focus and blur events +if ( document.addEventListener ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + jQuery.event.special[ fix ] = { + setup: function() { + this.addEventListener( orig, handler, true ); + }, + teardown: function() { + this.removeEventListener( orig, handler, true ); + } + }; + + function handler( e ) { + e = jQuery.event.fix( e ); + e.type = fix; + return jQuery.event.handle.call( this, e ); + } + }); +} + +jQuery.each(["bind", "one"], function( i, name ) { + jQuery.fn[ name ] = function( type, data, fn ) { + // Handle object literals + if ( typeof type === "object" ) { + for ( var key in type ) { + this[ name ](key, data, type[key], fn); + } + return this; + } + + if ( jQuery.isFunction( data ) ) { + fn = data; + data = undefined; + } + + var handler = name === "one" ? jQuery.proxy( fn, function( event ) { + jQuery( this ).unbind( event, handler ); + return fn.apply( this, arguments ); + }) : fn; + + if ( type === "unload" && name !== "one" ) { + this.one( type, data, fn ); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.add( this[i], type, handler, data ); + } + } + + return this; + }; +}); + +jQuery.fn.extend({ + unbind: function( type, fn ) { + // Handle object literals + if ( typeof type === "object" && !type.preventDefault ) { + for ( var key in type ) { + this.unbind(key, type[key]); + } + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + jQuery.event.remove( this[i], type, fn ); + } + } + + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.live( types, data, fn, selector ); + }, + + undelegate: function( selector, types, fn ) { + if ( arguments.length === 0 ) { + return this.unbind( "live" ); + + } else { + return this.die( types, null, fn, selector ); + } + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + + triggerHandler: function( type, data ) { + if ( this[0] ) { + var event = jQuery.Event( type ); + event.preventDefault(); + event.stopPropagation(); + jQuery.event.trigger( event, data, this[0] ); + return event.result; + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, i = 1; + + // link all the functions, so any of them can unbind this click handler + while ( i < args.length ) { + jQuery.proxy( fn, args[ i++ ] ); + } + + return this.click( jQuery.proxy( fn, function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + })); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +var liveMap = { + focus: "focusin", + blur: "focusout", + mouseenter: "mouseover", + mouseleave: "mouseout" +}; + +jQuery.each(["live", "die"], function( i, name ) { + jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { + var type, i = 0, match, namespaces, preType, + selector = origSelector || this.selector, + context = origSelector ? this : jQuery( this.context ); + + if ( jQuery.isFunction( data ) ) { + fn = data; + data = undefined; + } + + types = (types || "").split(" "); + + while ( (type = types[ i++ ]) != null ) { + match = rnamespaces.exec( type ); + namespaces = ""; + + if ( match ) { + namespaces = match[0]; + type = type.replace( rnamespaces, "" ); + } + + if ( type === "hover" ) { + types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); + continue; + } + + preType = type; + + if ( type === "focus" || type === "blur" ) { + types.push( liveMap[ type ] + namespaces ); + type = type + namespaces; + + } else { + type = (liveMap[ type ] || type) + namespaces; + } + + if ( name === "live" ) { + // bind live handler + context.each(function(){ + jQuery.event.add( this, liveConvert( type, selector ), + { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); + }); + + } else { + // unbind live handler + context.unbind( liveConvert( type, selector ), fn ); + } + } + + return this; + } +}); + +function liveHandler( event ) { + var stop, elems = [], selectors = [], args = arguments, + related, match, handleObj, elem, j, i, l, data, + events = jQuery.data( this, "events" ); + + // Make sure we avoid non-left-click bubbling in Firefox (#3861) + if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { + return; + } + + event.liveFired = this; + + var live = events.live.slice(0); + + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { + selectors.push( handleObj.selector ); + + } else { + live.splice( j--, 1 ); + } + } + + match = jQuery( event.target ).closest( selectors, event.currentTarget ); + + for ( i = 0, l = match.length; i < l; i++ ) { + for ( j = 0; j < live.length; j++ ) { + handleObj = live[j]; + + if ( match[i].selector === handleObj.selector ) { + elem = match[i].elem; + related = null; + + // Those two events require additional checking + if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { + related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; + } + + if ( !related || related !== elem ) { + elems.push({ elem: elem, handleObj: handleObj }); + } + } + } + } + + for ( i = 0, l = elems.length; i < l; i++ ) { + match = elems[i]; + event.currentTarget = match.elem; + event.data = match.handleObj.data; + event.handleObj = match.handleObj; + + if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) { + stop = false; + break; + } + } + + return stop; +} + +function liveConvert( type, selector ) { + return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); +} + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( fn ) { + return fn ? this.bind( name, fn ) : this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } +}); + +// Prevent memory leaks in IE +// Window isn't included so as not to unbind existing unload events +// More info: +// - http://isaacschlueter.com/2006/10/msie-memory-leaks/ +if ( window.attachEvent && !window.addEventListener ) { + window.attachEvent("onunload", function() { + for ( var id in jQuery.cache ) { + if ( jQuery.cache[ id ].handle ) { + // Try/Catch is to handle iframes being unloaded, see #4280 + try { + jQuery.event.remove( jQuery.cache[ id ].handle.elem ); + } catch(e) {} + } + } + }); +} +/*! + * Sizzle CSS Selector Engine - v1.0 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function(){ + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function(selector, context, results, seed) { + results = results || []; + var origContext = context = context || document; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set ); + } + } + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + var ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; + } + + if ( context ) { + var ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray(set); + } else { + prune = false; + } + + while ( parts.length ) { + var cur = parts.pop(), pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + } else if ( context && context.nodeType === 1 ) { + for ( var i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + } else { + for ( var i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function(results){ + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort(sortOrder); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[i-1] ) { + results.splice(i--, 1); + } + } + } + } + + return results; +}; + +Sizzle.matches = function(expr, set){ + return Sizzle(expr, null, null, set); +}; + +Sizzle.find = function(expr, context, isXML){ + var set, match; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var type = Expr.order[i], match; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice(1,1); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace(/\\/g, ""); + set = Expr.find[ type ]( match, context, isXML ); + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = context.getElementsByTagName("*"); + } + + return {set: set, expr: expr}; +}; + +Sizzle.filter = function(expr, set, inplace, not){ + var old = expr, result = [], curLoop = set, match, anyFound, + isXMLFilter = set && set[0] && isXML(set[0]); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + var filter = Expr.filter[ type ], found, item, left = match[1]; + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + } else { + curLoop[i] = false; + } + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw "Syntax error, unrecognized expression: " + msg; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + match: { + ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + leftMatch: {}, + attrMap: { + "class": "className", + "for": "htmlFor" + }, + attrHandle: { + href: function(elem){ + return elem.getAttribute("href"); + } + }, + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !/\W/.test(part), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + ">": function(checkSet, part){ + var isPartStr = typeof part === "string"; + + if ( isPartStr && !/\W/.test(part) ) { + part = part.toLowerCase(); + + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + } else { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + "": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + var nodeCheck = part = part.toLowerCase(); + checkFn = dirNodeCheck; + } + + checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); + }, + "~": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + var nodeCheck = part = part.toLowerCase(); + checkFn = dirNodeCheck; + } + + checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); + } + }, + find: { + ID: function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? [m] : []; + } + }, + NAME: function(match, context){ + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], results = context.getElementsByName(match[1]); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + TAG: function(match, context){ + return context.getElementsByTagName(match[1]); + } + }, + preFilter: { + CLASS: function(match, curLoop, inplace, result, not, isXML){ + match = " " + match[1].replace(/\\/g, "") + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + ID: function(match){ + return match[1].replace(/\\/g, ""); + }, + TAG: function(match, curLoop){ + return match[1].toLowerCase(); + }, + CHILD: function(match){ + if ( match[1] === "nth" ) { + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + ATTR: function(match, curLoop, inplace, result, not, isXML){ + var name = match[1].replace(/\\/g, ""); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + PSEUDO: function(match, curLoop, inplace, result, not){ + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + if ( !inplace ) { + result.push.apply( result, ret ); + } + return false; + } + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + POS: function(match){ + match.unshift( true ); + return match; + } + }, + filters: { + enabled: function(elem){ + return elem.disabled === false && elem.type !== "hidden"; + }, + disabled: function(elem){ + return elem.disabled === true; + }, + checked: function(elem){ + return elem.checked === true; + }, + selected: function(elem){ + // Accessing this property makes selected-by-default + // options in Safari work properly + elem.parentNode.selectedIndex; + return elem.selected === true; + }, + parent: function(elem){ + return !!elem.firstChild; + }, + empty: function(elem){ + return !elem.firstChild; + }, + has: function(elem, i, match){ + return !!Sizzle( match[3], elem ).length; + }, + header: function(elem){ + return /h\d/i.test( elem.nodeName ); + }, + text: function(elem){ + return "text" === elem.type; + }, + radio: function(elem){ + return "radio" === elem.type; + }, + checkbox: function(elem){ + return "checkbox" === elem.type; + }, + file: function(elem){ + return "file" === elem.type; + }, + password: function(elem){ + return "password" === elem.type; + }, + submit: function(elem){ + return "submit" === elem.type; + }, + image: function(elem){ + return "image" === elem.type; + }, + reset: function(elem){ + return "reset" === elem.type; + }, + button: function(elem){ + return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; + }, + input: function(elem){ + return /input|select|textarea|button/i.test(elem.nodeName); + } + }, + setFilters: { + first: function(elem, i){ + return i === 0; + }, + last: function(elem, i, match, array){ + return i === array.length - 1; + }, + even: function(elem, i){ + return i % 2 === 0; + }, + odd: function(elem, i){ + return i % 2 === 1; + }, + lt: function(elem, i, match){ + return i < match[3] - 0; + }, + gt: function(elem, i, match){ + return i > match[3] - 0; + }, + nth: function(elem, i, match){ + return match[3] - 0 === i; + }, + eq: function(elem, i, match){ + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function(elem, match, i, array){ + var name = match[1], filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + } else if ( name === "not" ) { + var not = match[3]; + + for ( var i = 0, l = not.length; i < l; i++ ) { + if ( not[i] === elem ) { + return false; + } + } + + return true; + } else { + Sizzle.error( "Syntax error, unrecognized expression: " + name ); + } + }, + CHILD: function(elem, match){ + var type = match[1], node = elem; + switch (type) { + case 'only': + case 'first': + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + if ( type === "first" ) { + return true; + } + node = elem; + case 'last': + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + return true; + case 'nth': + var first = match[2], last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + if ( first === 0 ) { + return diff === 0; + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + ID: function(elem, match){ + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + TAG: function(elem, match){ + return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; + }, + CLASS: function(elem, match){ + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + ATTR: function(elem, match){ + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + POS: function(elem, match, i, array){ + var name = match[2], filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ + return "\\" + (num - 0 + 1); + })); +} + +var makeArray = function(array, results) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch(e){ + makeArray = function(array, results) { + var ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + } else { + if ( typeof array.length === "number" ) { + for ( var i = 0, l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + } else { + for ( var i = 0; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.compareDocumentPosition ? -1 : 1; + } + + var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( "sourceIndex" in document.documentElement ) { + sortOrder = function( a, b ) { + if ( !a.sourceIndex || !b.sourceIndex ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.sourceIndex ? -1 : 1; + } + + var ret = a.sourceIndex - b.sourceIndex; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( document.createRange ) { + sortOrder = function( a, b ) { + if ( !a.ownerDocument || !b.ownerDocument ) { + if ( a == b ) { + hasDuplicate = true; + } + return a.ownerDocument ? -1 : 1; + } + + var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); + aRange.setStart(a, 0); + aRange.setEnd(a, 0); + bRange.setStart(b, 0); + bRange.setEnd(b, 0); + var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} + +// Utility function for retreiving the text value of an array of DOM nodes +function getText( elems ) { + var ret = "", elem; + + for ( var i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += getText( elem.childNodes ); + } + } + + return ret; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date).getTime(); + form.innerHTML = "<a name='" + id + "'/>"; + + // Inject it into the root element, check its status, and remove it quickly + var root = document.documentElement; + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; + } + }; + + Expr.filter.ID = function(elem, match){ + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + root = form = null; // release memory in IE +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function(match, context){ + var results = context.getElementsByTagName(match[1]); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = "<a href='#'></a>"; + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + Expr.attrHandle.href = function(elem){ + return elem.getAttribute("href", 2); + }; + } + + div = null; // release memory in IE +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, div = document.createElement("div"); + div.innerHTML = "<p class='TEST'></p>"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function(query, context, extra, seed){ + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && context.nodeType === 9 && !isXML(context) ) { + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(e){} + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + div = null; // release memory in IE + })(); +} + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "<div class='test e'></div><div class='test'></div>"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function(match, context, isXML) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + div = null; // release memory in IE +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +var contains = document.compareDocumentPosition ? function(a, b){ + return !!(a.compareDocumentPosition(b) & 16); +} : function(a, b){ + return a !== b && (a.contains ? a.contains(b) : true); +}; + +var isXML = function(elem){ + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function(selector, context){ + var tmpSet = [], later = "", match, + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = getText; +jQuery.isXMLDoc = isXML; +jQuery.contains = contains; + +return; + +window.Sizzle = Sizzle; + +})(); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + slice = Array.prototype.slice; + +// Implement the identical functionality for filter and not +var winnow = function( elements, qualifier, keep ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return (elem === qualifier) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return (jQuery.inArray( elem, qualifier ) >= 0) === keep; + }); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var ret = this.pushStack( "", "find", selector ), length = 0; + + for ( var i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( var n = length; n < ret.length; n++ ) { + for ( var r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && jQuery.filter( selector, this ).length > 0; + }, + + closest: function( selectors, context ) { + if ( jQuery.isArray( selectors ) ) { + var ret = [], cur = this[0], match, matches = {}, selector; + + if ( cur && selectors.length ) { + for ( var i = 0, l = selectors.length; i < l; i++ ) { + selector = selectors[i]; + + if ( !matches[selector] ) { + matches[selector] = jQuery.expr.match.POS.test( selector ) ? + jQuery( selector, context || this.context ) : + selector; + } + } + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( selector in matches ) { + match = matches[selector]; + + if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { + ret.push({ selector: selector, elem: cur }); + delete matches[selector]; + } + } + cur = cur.parentNode; + } + } + + return ret; + } + + var pos = jQuery.expr.match.POS.test( selectors ) ? + jQuery( selectors, context || this.context ) : null; + + return this.map(function( i, cur ) { + while ( cur && cur.ownerDocument && cur !== context ) { + if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { + return cur; + } + cur = cur.parentNode; + } + return null; + }); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + if ( !elem || typeof elem === "string" ) { + return jQuery.inArray( this[0], + // If it receives a string, the selector is used + // If it receives nothing, the siblings are used + elem ? jQuery( elem ) : this.parent().children() ); + } + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context || this.context ) : + jQuery.makeArray( selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call(arguments).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], cur = elem[dir]; + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); +var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, + rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, + rtagName = /<([\w:]+)/, + rtbody = /<tbody/i, + rhtml = /<|&#?\w+;/, + rnocache = /<script|<object|<embed|<option|<style/i, + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) + fcloseTag = function( all, front, tag ) { + return rselfClosing.test( tag ) ? + all : + front + "></" + tag + ">"; + }, + wrapMap = { + option: [ 1, "<select multiple='multiple'>", "</select>" ], + legend: [ 1, "<fieldset>", "</fieldset>" ], + thead: [ 1, "<table>", "</table>" ], + tr: [ 2, "<table><tbody>", "</tbody></table>" ], + td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], + col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], + area: [ 1, "<map>", "</map>" ], + _default: [ 0, "", "" ] + }; + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize <link> and <script> tags normally +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "div<div>", "</div>" ]; +} + +jQuery.fn.extend({ + text: function( text ) { + if ( jQuery.isFunction(text) ) { + return this.each(function(i) { + var self = jQuery(this); + self.text( text.call(this, i, self.text()) ); + }); + } + + if ( typeof text !== "object" && text !== undefined ) { + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + } + + return jQuery.text( this ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append(this); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + return this.each(function() { + jQuery( this ).wrapAll( html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } else if ( arguments.length ) { + var set = jQuery(arguments[0]); + set.push.apply( set, this.toArray() ); + return this.pushStack( set, "before", arguments ); + } + }, + + after: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } else if ( arguments.length ) { + var set = this.pushStack( this, "after", arguments ); + set.push.apply( set, jQuery(arguments[0]).toArray() ); + return set; + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + return this; + }, + + clone: function( events ) { + // Do the clone + var ret = this.map(function() { + if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { + // IE copies events bound via attachEvent when + // using cloneNode. Calling detachEvent on the + // clone will also remove the events from the orignal + // In order to get around this, we use innerHTML. + // Unfortunately, this means some modifications to + // attributes in IE that are actually only stored + // as properties will not be copied (such as the + // the name attribute on an input). + var html = this.outerHTML, ownerDocument = this.ownerDocument; + if ( !html ) { + var div = ownerDocument.createElement("div"); + div.appendChild( this.cloneNode(true) ); + html = div.innerHTML; + } + + return jQuery.clean([html.replace(rinlinejQuery, "") + // Handle the case in IE 8 where action=/test/> self-closes a tag + .replace(/=([^="'>\s]+\/)>/g, '="$1">') + .replace(rleadingWhitespace, "")], ownerDocument)[0]; + } else { + return this.cloneNode(true); + } + }); + + // Copy the events from the original to the clone + if ( events === true ) { + cloneCopyEvent( this, ret ); + cloneCopyEvent( this.find("*"), ret.find("*") ); + } + + // Return the cloned set + return ret; + }, + + html: function( value ) { + if ( value === undefined ) { + return this[0] && this[0].nodeType === 1 ? + this[0].innerHTML.replace(rinlinejQuery, "") : + null; + + // See if we can take a shortcut and just use innerHTML + } else if ( typeof value === "string" && !rnocache.test( value ) && + (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && + !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { + + value = value.replace(rxhtmlTag, fcloseTag); + + try { + for ( var i = 0, l = this.length; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + if ( this[i].nodeType === 1 ) { + jQuery.cleanData( this[i].getElementsByTagName("*") ); + this[i].innerHTML = value; + } + } + + // If using innerHTML throws an exception, use the fallback method + } catch(e) { + this.empty().append( value ); + } + + } else if ( jQuery.isFunction( value ) ) { + this.each(function(i){ + var self = jQuery(this), old = self.html(); + self.empty().append(function(){ + return value.call( this, i, old ); + }); + }); + + } else { + this.empty().append( value ); + } + + return this; + }, + + replaceWith: function( value ) { + if ( this[0] && this[0].parentNode ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery(value).detach(); + } + + return this.each(function() { + var next = this.nextSibling, parent = this.parentNode; + + jQuery(this).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } else { + return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); + } + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + var results, first, value = args[0], scripts = [], fragment, parent; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback, true ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call(this, i, table ? self.html() : undefined); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + parent = value && value.parentNode; + + // If we're in a fragment, just use that instead of building a new one + if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { + results = { fragment: parent }; + + } else { + results = buildFragment( args, this, scripts ); + } + + fragment = results.fragment; + + if ( fragment.childNodes.length === 1 ) { + first = fragment = fragment.firstChild; + } else { + first = fragment.firstChild; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + for ( var i = 0, l = this.length; i < l; i++ ) { + callback.call( + table ? + root(this[i], first) : + this[i], + i > 0 || results.cacheable || this.length > 1 ? + fragment.cloneNode(true) : + fragment + ); + } + } + + if ( scripts.length ) { + jQuery.each( scripts, evalScript ); + } + } + + return this; + + function root( elem, cur ) { + return jQuery.nodeName(elem, "table") ? + (elem.getElementsByTagName("tbody")[0] || + elem.appendChild(elem.ownerDocument.createElement("tbody"))) : + elem; + } + } +}); + +function cloneCopyEvent(orig, ret) { + var i = 0; + + ret.each(function() { + if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { + return; + } + + var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( var type in events ) { + for ( var handler in events[ type ] ) { + jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); + } + } + } + }); +} + +function buildFragment( args, nodes, scripts ) { + var fragment, cacheable, cacheresults, + doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); + + // Only cache "small" (1/2 KB) strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && + !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { + + cacheable = true; + cacheresults = jQuery.fragments[ args[0] ]; + if ( cacheresults ) { + if ( cacheresults !== 1 ) { + fragment = cacheresults; + } + } + } + + if ( !fragment ) { + fragment = doc.createDocumentFragment(); + jQuery.clean( args, doc, fragment, scripts ); + } + + if ( cacheable ) { + jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; + } + + return { fragment: fragment, cacheable: cacheable }; +} + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var ret = [], insert = jQuery( selector ), + parent = this.length === 1 && this[0].parentNode; + + if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { + insert[ original ]( this[0] ); + return this; + + } else { + for ( var i = 0, l = insert.length; i < l; i++ ) { + var elems = (i > 0 ? this.clone(true) : this).get(); + jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +jQuery.extend({ + clean: function( elems, context, fragment, scripts ) { + context = context || document; + + // !context.createElement fails in IE with an error but returns typeof 'object' + if ( typeof context.createElement === "undefined" ) { + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + } + + var ret = []; + + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" && !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + + } else if ( typeof elem === "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, fcloseTag); + + // Trim whitespace, otherwise indexOf won't work as expected + var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), + wrap = wrapMap[ tag ] || wrapMap._default, + depth = wrap[0], + div = context.createElement("div"); + + // Go to html and back, then peel off extra wrappers + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted <tbody> from table fragments + if ( !jQuery.support.tbody ) { + + // String was a <table>, *may* have spurious <tbody> + var hasBody = rtbody.test(elem), + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare <thead> or <tfoot> + wrap[1] === "<table>" && !hasBody ? + div.childNodes : + []; + + for ( var j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + ret = jQuery.merge( ret, elem ); + } + } + + if ( fragment ) { + for ( var i = 0; ret[i]; i++ ) { + if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { + scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); + + } else { + if ( ret[i].nodeType === 1 ) { + ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); + } + fragment.appendChild( ret[i] ); + } + } + } + + return ret; + }, + + cleanData: function( elems ) { + var data, id, cache = jQuery.cache, + special = jQuery.event.special, + deleteExpando = jQuery.support.deleteExpando; + + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + id = elem[ jQuery.expando ]; + + if ( id ) { + data = cache[ id ]; + + if ( data.events ) { + for ( var type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + } else { + removeEvent( elem, type, data.handle ); + } + } + } + + if ( deleteExpando ) { + delete elem[ jQuery.expando ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } + + delete cache[ id ]; + } + } + } +}); +// exclude the following css properties to add px +var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, + ralpha = /alpha\([^)]*\)/, + ropacity = /opacity=([^)]*)/, + rfloat = /float/i, + rdashAlpha = /-([a-z])/ig, + rupper = /([A-Z])/g, + rnumpx = /^-?\d+(?:px)?$/i, + rnum = /^-?\d/, + + cssShow = { position: "absolute", visibility: "hidden", display:"block" }, + cssWidth = [ "Left", "Right" ], + cssHeight = [ "Top", "Bottom" ], + + // cache check for defaultView.getComputedStyle + getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, + // normalize float css property + styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn.css = function( name, value ) { + return access( this, name, value, true, function( elem, name, value ) { + if ( value === undefined ) { + return jQuery.curCSS( elem, name ); + } + + if ( typeof value === "number" && !rexclude.test(name) ) { + value += "px"; + } + + jQuery.style( elem, name, value ); + }); +}; + +jQuery.extend({ + style: function( elem, name, value ) { + // don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { + return undefined; + } + + // ignore negative width and height values #1599 + if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { + value = undefined; + } + + var style = elem.style || elem, set = value !== undefined; + + // IE uses filters for opacity + if ( !jQuery.support.opacity && name === "opacity" ) { + if ( set ) { + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // Set the alpha filter to set the opacity + var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; + var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; + style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; + } + + return style.filter && style.filter.indexOf("opacity=") >= 0 ? + (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": + ""; + } + + // Make sure we're using the right name for getting the float value + if ( rfloat.test( name ) ) { + name = styleFloat; + } + + name = name.replace(rdashAlpha, fcamelCase); + + if ( set ) { + style[ name ] = value; + } + + return style[ name ]; + }, + + css: function( elem, name, force, extra ) { + if ( name === "width" || name === "height" ) { + var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; + + function getWH() { + val = name === "width" ? elem.offsetWidth : elem.offsetHeight; + + if ( extra === "border" ) { + return; + } + + jQuery.each( which, function() { + if ( !extra ) { + val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; + } + + if ( extra === "margin" ) { + val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; + } else { + val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; + } + }); + } + + if ( elem.offsetWidth !== 0 ) { + getWH(); + } else { + jQuery.swap( elem, props, getWH ); + } + + return Math.max(0, Math.round(val)); + } + + return jQuery.curCSS( elem, name, force ); + }, + + curCSS: function( elem, name, force ) { + var ret, style = elem.style, filter; + + // IE uses filters for opacity + if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { + ret = ropacity.test(elem.currentStyle.filter || "") ? + (parseFloat(RegExp.$1) / 100) + "" : + ""; + + return ret === "" ? + "1" : + ret; + } + + // Make sure we're using the right name for getting the float value + if ( rfloat.test( name ) ) { + name = styleFloat; + } + + if ( !force && style && style[ name ] ) { + ret = style[ name ]; + + } else if ( getComputedStyle ) { + + // Only "float" is needed here + if ( rfloat.test( name ) ) { + name = "float"; + } + + name = name.replace( rupper, "-$1" ).toLowerCase(); + + var defaultView = elem.ownerDocument.defaultView; + + if ( !defaultView ) { + return null; + } + + var computedStyle = defaultView.getComputedStyle( elem, null ); + + if ( computedStyle ) { + ret = computedStyle.getPropertyValue( name ); + } + + // We should always get a number back from opacity + if ( name === "opacity" && ret === "" ) { + ret = "1"; + } + + } else if ( elem.currentStyle ) { + var camelCase = name.replace(rdashAlpha, fcamelCase); + + ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { + // Remember the original values + var left = style.left, rsLeft = elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + elem.runtimeStyle.left = elem.currentStyle.left; + style.left = camelCase === "fontSize" ? "1em" : (ret || 0); + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + elem.runtimeStyle.left = rsLeft; + } + } + + return ret; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var old = {}; + + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( var name in options ) { + elem.style[ name ] = old[ name ]; + } + } +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + var width = elem.offsetWidth, height = elem.offsetHeight, + skip = elem.nodeName.toLowerCase() === "tr"; + + return width === 0 && height === 0 && !skip ? + true : + width > 0 && height > 0 && !skip ? + false : + jQuery.curCSS(elem, "display") === "none"; + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} +var jsc = now(), + rscript = /<script(.|\s)*?\/script>/gi, + rselectTextarea = /select|textarea/i, + rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, + jsre = /=\?(&|$)/, + rquery = /\?/, + rts = /(\?|&)_=.*?(&|$)/, + rurl = /^(\w+:)?\/\/([^\/?#]+)/, + r20 = /%20/g, + + // Keep a copy of the old load method + _load = jQuery.fn.load; + +jQuery.fn.extend({ + load: function( url, params, callback ) { + if ( typeof url !== "string" ) { + return _load.call( this, url ); + + // Don't do a request if no elements are being requested + } else if ( !this.length ) { + return this; + } + + var off = url.indexOf(" "); + if ( off >= 0 ) { + var selector = url.slice(off, url.length); + url = url.slice(0, off); + } + + // Default to a GET request + var type = "GET"; + + // If the second parameter was provided + if ( params ) { + // If it's a function + if ( jQuery.isFunction( params ) ) { + // We assume that it's the callback + callback = params; + params = null; + + // Otherwise, build a param string + } else if ( typeof params === "object" ) { + params = jQuery.param( params, jQuery.ajaxSettings.traditional ); + type = "POST"; + } + } + + var self = this; + + // Request the remote document + jQuery.ajax({ + url: url, + type: type, + dataType: "html", + data: params, + complete: function( res, status ) { + // If successful, inject the HTML into all the matched elements + if ( status === "success" || status === "notmodified" ) { + // See if a selector was specified + self.html( selector ? + // Create a dummy div to hold the results + jQuery("<div />") + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append(res.responseText.replace(rscript, "")) + + // Locate the specified elements + .find(selector) : + + // If not, just inject the full result + res.responseText ); + } + + if ( callback ) { + self.each( callback, [res.responseText, status, res] ); + } + } + }); + + return this; + }, + + serialize: function() { + return jQuery.param(this.serializeArray()); + }, + serializeArray: function() { + return this.map(function() { + return this.elements ? jQuery.makeArray(this.elements) : this; + }) + .filter(function() { + return this.name && !this.disabled && + (this.checked || rselectTextarea.test(this.nodeName) || + rinput.test(this.type)); + }) + .map(function( i, elem ) { + var val = jQuery(this).val(); + + return val == null ? + null : + jQuery.isArray(val) ? + jQuery.map( val, function( val, i ) { + return { name: elem.name, value: val }; + }) : + { name: elem.name, value: val }; + }).get(); + } +}); + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { + jQuery.fn[o] = function( f ) { + return this.bind(o, f); + }; +}); + +jQuery.extend({ + + get: function( url, data, callback, type ) { + // shift arguments if data argument was omited + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = null; + } + + return jQuery.ajax({ + type: "GET", + url: url, + data: data, + success: callback, + dataType: type + }); + }, + + getScript: function( url, callback ) { + return jQuery.get(url, null, callback, "script"); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get(url, data, callback, "json"); + }, + + post: function( url, data, callback, type ) { + // shift arguments if data argument was omited + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = {}; + } + + return jQuery.ajax({ + type: "POST", + url: url, + data: data, + success: callback, + dataType: type + }); + }, + + ajaxSetup: function( settings ) { + jQuery.extend( jQuery.ajaxSettings, settings ); + }, + + ajaxSettings: { + url: location.href, + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded", + processData: true, + async: true, + /* + timeout: 0, + data: null, + username: null, + password: null, + traditional: false, + */ + // Create the request object; Microsoft failed to properly + // implement the XMLHttpRequest in IE7 (can't request local files), + // so we use the ActiveXObject when it is available + // This function can be overriden by calling jQuery.ajaxSetup + xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? + function() { + return new window.XMLHttpRequest(); + } : + function() { + try { + return new window.ActiveXObject("Microsoft.XMLHTTP"); + } catch(e) {} + }, + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + script: "text/javascript, application/javascript", + json: "application/json, text/javascript", + text: "text/plain", + _default: "*/*" + } + }, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajax: function( origSettings ) { + var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); + + var jsonp, status, data, + callbackContext = origSettings && origSettings.context || s, + type = s.type.toUpperCase(); + + // convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Handle JSONP Parameter Callbacks + if ( s.dataType === "jsonp" ) { + if ( type === "GET" ) { + if ( !jsre.test( s.url ) ) { + s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; + } + } else if ( !s.data || !jsre.test(s.data) ) { + s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; + } + s.dataType = "json"; + } + + // Build temporary JSONP function + if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { + jsonp = s.jsonpCallback || ("jsonp" + jsc++); + + // Replace the =? sequence both in the query string and the data + if ( s.data ) { + s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); + } + + s.url = s.url.replace(jsre, "=" + jsonp + "$1"); + + // We need to make sure + // that a JSONP style response is executed properly + s.dataType = "script"; + + // Handle JSONP-style loading + window[ jsonp ] = window[ jsonp ] || function( tmp ) { + data = tmp; + success(); + complete(); + // Garbage collect + window[ jsonp ] = undefined; + + try { + delete window[ jsonp ]; + } catch(e) {} + + if ( head ) { + head.removeChild( script ); + } + }; + } + + if ( s.dataType === "script" && s.cache === null ) { + s.cache = false; + } + + if ( s.cache === false && type === "GET" ) { + var ts = now(); + + // try replacing _= if it is there + var ret = s.url.replace(rts, "$1_=" + ts + "$2"); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); + } + + // If data is available, append data to url for get requests + if ( s.data && type === "GET" ) { + s.url += (rquery.test(s.url) ? "&" : "?") + s.data; + } + + // Watch for a new set of requests + if ( s.global && ! jQuery.active++ ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Matches an absolute URL, and saves the domain + var parts = rurl.exec( s.url ), + remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); + + // If we're requesting a remote document + // and trying to load JSON or Script with a GET + if ( s.dataType === "script" && type === "GET" && remote ) { + var head = document.getElementsByTagName("head")[0] || document.documentElement; + var script = document.createElement("script"); + script.src = s.url; + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + // Handle Script loading + if ( !jsonp ) { + var done = false; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function() { + if ( !done && (!this.readyState || + this.readyState === "loaded" || this.readyState === "complete") ) { + done = true; + success(); + complete(); + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + if ( head && script.parentNode ) { + head.removeChild( script ); + } + } + }; + } + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + + // We handle everything using the script element injection + return undefined; + } + + var requestDone = false; + + // Create the request object + var xhr = s.xhr(); + + if ( !xhr ) { + return; + } + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open(type, s.url, s.async, s.username, s.password); + } else { + xhr.open(type, s.url, s.async); + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + // Set the correct header, if data is being sent + if ( s.data || origSettings && origSettings.contentType ) { + xhr.setRequestHeader("Content-Type", s.contentType); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[s.url] ) { + xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); + } + + if ( jQuery.etag[s.url] ) { + xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); + } + } + + // Set header so the called script knows that it's an XMLHttpRequest + // Only send the header if it's not a remote XHR + if ( !remote ) { + xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); + } + + // Set the Accepts header for the server, depending on the dataType + xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? + s.accepts[ s.dataType ] + ", */*" : + s.accepts._default ); + } catch(e) {} + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { + // Handle the global AJAX counter + if ( s.global && ! --jQuery.active ) { + jQuery.event.trigger( "ajaxStop" ); + } + + // close opended socket + xhr.abort(); + return false; + } + + if ( s.global ) { + trigger("ajaxSend", [xhr, s]); + } + + // Wait for a response to come back + var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { + // The request was aborted + if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { + // Opera doesn't call onreadystatechange before this point + // so we simulate the call + if ( !requestDone ) { + complete(); + } + + requestDone = true; + if ( xhr ) { + xhr.onreadystatechange = jQuery.noop; + } + + // The transfer is complete and the data is available, or the request timed out + } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { + requestDone = true; + xhr.onreadystatechange = jQuery.noop; + + status = isTimeout === "timeout" ? + "timeout" : + !jQuery.httpSuccess( xhr ) ? + "error" : + s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? + "notmodified" : + "success"; + + var errMsg; + + if ( status === "success" ) { + // Watch for, and catch, XML document parse errors + try { + // process the data (runs the xml through httpData regardless of callback) + data = jQuery.httpData( xhr, s.dataType, s ); + } catch(err) { + status = "parsererror"; + errMsg = err; + } + } + + // Make sure that the request was successful or notmodified + if ( status === "success" || status === "notmodified" ) { + // JSONP handles its own success callback + if ( !jsonp ) { + success(); + } + } else { + jQuery.handleError(s, xhr, status, errMsg); + } + + // Fire the complete handlers + complete(); + + if ( isTimeout === "timeout" ) { + xhr.abort(); + } + + // Stop memory leaks + if ( s.async ) { + xhr = null; + } + } + }; + + // Override the abort handler, if we can (IE doesn't allow it, but that's OK) + // Opera doesn't fire onreadystatechange at all on abort + try { + var oldAbort = xhr.abort; + xhr.abort = function() { + if ( xhr ) { + oldAbort.call( xhr ); + } + + onreadystatechange( "abort" ); + }; + } catch(e) { } + + // Timeout checker + if ( s.async && s.timeout > 0 ) { + setTimeout(function() { + // Check to see if the request is still happening + if ( xhr && !requestDone ) { + onreadystatechange( "timeout" ); + } + }, s.timeout); + } + + // Send the data + try { + xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); + } catch(e) { + jQuery.handleError(s, xhr, null, e); + // Fire the complete handlers + complete(); + } + + // firefox 1.5 doesn't fire statechange for sync requests + if ( !s.async ) { + onreadystatechange(); + } + + function success() { + // If a local callback was specified, fire it and pass it the data + if ( s.success ) { + s.success.call( callbackContext, data, status, xhr ); + } + + // Fire the global callback + if ( s.global ) { + trigger( "ajaxSuccess", [xhr, s] ); + } + } + + function complete() { + // Process result + if ( s.complete ) { + s.complete.call( callbackContext, xhr, status); + } + + // The request was completed + if ( s.global ) { + trigger( "ajaxComplete", [xhr, s] ); + } + + // Handle the global AJAX counter + if ( s.global && ! --jQuery.active ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + + function trigger(type, args) { + (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); + } + + // return XMLHttpRequest to allow aborting the request etc. + return xhr; + }, + + handleError: function( s, xhr, status, e ) { + // If a local callback was specified, fire it + if ( s.error ) { + s.error.call( s.context || s, xhr, status, e ); + } + + // Fire the global callback + if ( s.global ) { + (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); + } + }, + + // Counter for holding the number of active queries + active: 0, + + // Determines if an XMLHttpRequest was successful or not + httpSuccess: function( xhr ) { + try { + // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 + return !xhr.status && location.protocol === "file:" || + // Opera returns 0 when status is 304 + ( xhr.status >= 200 && xhr.status < 300 ) || + xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; + } catch(e) {} + + return false; + }, + + // Determines if an XMLHttpRequest returns NotModified + httpNotModified: function( xhr, url ) { + var lastModified = xhr.getResponseHeader("Last-Modified"), + etag = xhr.getResponseHeader("Etag"); + + if ( lastModified ) { + jQuery.lastModified[url] = lastModified; + } + + if ( etag ) { + jQuery.etag[url] = etag; + } + + // Opera returns 0 when status is 304 + return xhr.status === 304 || xhr.status === 0; + }, + + httpData: function( xhr, type, s ) { + var ct = xhr.getResponseHeader("content-type") || "", + xml = type === "xml" || !type && ct.indexOf("xml") >= 0, + data = xml ? xhr.responseXML : xhr.responseText; + + if ( xml && data.documentElement.nodeName === "parsererror" ) { + jQuery.error( "parsererror" ); + } + + // Allow a pre-filtering function to sanitize the response + // s is checked to keep backwards compatibility + if ( s && s.dataFilter ) { + data = s.dataFilter( data, type ); + } + + // The filter can actually parse the response + if ( typeof data === "string" ) { + // Get the JavaScript object, if JSON is used. + if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { + data = jQuery.parseJSON( data ); + + // If the type is "script", eval it in global context + } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { + jQuery.globalEval( data ); + } + } + + return data; + }, + + // Serialize an array of form elements or a set of + // key/values into a query string + param: function( a, traditional ) { + var s = []; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray(a) || a.jquery ) { + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + }); + + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( var prefix in a ) { + buildParams( prefix, a[prefix] ); + } + } + + // Return the resulting serialization + return s.join("&").replace(r20, "+"); + + function buildParams( prefix, obj ) { + if ( jQuery.isArray(obj) ) { + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || /\[\]$/.test( prefix ) ) { + // Treat each array item as a scalar. + add( prefix, v ); + } else { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); + } + }); + + } else if ( !traditional && obj != null && typeof obj === "object" ) { + // Serialize object item. + jQuery.each( obj, function( k, v ) { + buildParams( prefix + "[" + k + "]", v ); + }); + + } else { + // Serialize scalar item. + add( prefix, obj ); + } + } + + function add( key, value ) { + // If value is a function, invoke it and return its value + value = jQuery.isFunction(value) ? value() : value; + s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); + } + } +}); +var elemdisplay = {}, + rfxtypes = /toggle|show|hide/, + rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, + timerId, + fxAttrs = [ + // height animations + [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], + // width animations + [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], + // opacity animations + [ "opacity" ] + ]; + +jQuery.fn.extend({ + show: function( speed, callback ) { + if ( speed || speed === 0) { + return this.animate( genFx("show", 3), speed, callback); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + var old = jQuery.data(this[i], "olddisplay"); + + this[i].style.display = old || ""; + + if ( jQuery.css(this[i], "display") === "none" ) { + var nodeName = this[i].nodeName, display; + + if ( elemdisplay[ nodeName ] ) { + display = elemdisplay[ nodeName ]; + + } else { + var elem = jQuery("<" + nodeName + " />").appendTo("body"); + + display = elem.css("display"); + + if ( display === "none" ) { + display = "block"; + } + + elem.remove(); + + elemdisplay[ nodeName ] = display; + } + + jQuery.data(this[i], "olddisplay", display); + } + } + + // Set the display of the elements in a second loop + // to avoid the constant reflow + for ( var j = 0, k = this.length; j < k; j++ ) { + this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; + } + + return this; + } + }, + + hide: function( speed, callback ) { + if ( speed || speed === 0 ) { + return this.animate( genFx("hide", 3), speed, callback); + + } else { + for ( var i = 0, l = this.length; i < l; i++ ) { + var old = jQuery.data(this[i], "olddisplay"); + if ( !old && old !== "none" ) { + jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); + } + } + + // Set the display of the elements in a second loop + // to avoid the constant reflow + for ( var j = 0, k = this.length; j < k; j++ ) { + this[j].style.display = "none"; + } + + return this; + } + }, + + // Save the old toggle function + _toggle: jQuery.fn.toggle, + + toggle: function( fn, fn2 ) { + var bool = typeof fn === "boolean"; + + if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { + this._toggle.apply( this, arguments ); + + } else if ( fn == null || bool ) { + this.each(function() { + var state = bool ? fn : jQuery(this).is(":hidden"); + jQuery(this)[ state ? "show" : "hide" ](); + }); + + } else { + this.animate(genFx("toggle", 3), fn, fn2); + } + + return this; + }, + + fadeTo: function( speed, to, callback ) { + return this.filter(":hidden").css("opacity", 0).show().end() + .animate({opacity: to}, speed, callback); + }, + + animate: function( prop, speed, easing, callback ) { + var optall = jQuery.speed(speed, easing, callback); + + if ( jQuery.isEmptyObject( prop ) ) { + return this.each( optall.complete ); + } + + return this[ optall.queue === false ? "each" : "queue" ](function() { + var opt = jQuery.extend({}, optall), p, + hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), + self = this; + + for ( p in prop ) { + var name = p.replace(rdashAlpha, fcamelCase); + + if ( p !== name ) { + prop[ name ] = prop[ p ]; + delete prop[ p ]; + p = name; + } + + if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { + return opt.complete.call(this); + } + + if ( ( p === "height" || p === "width" ) && this.style ) { + // Store display property + opt.display = jQuery.css(this, "display"); + + // Make sure that nothing sneaks out + opt.overflow = this.style.overflow; + } + + if ( jQuery.isArray( prop[p] ) ) { + // Create (if needed) and add to specialEasing + (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; + prop[p] = prop[p][0]; + } + } + + if ( opt.overflow != null ) { + this.style.overflow = "hidden"; + } + + opt.curAnim = jQuery.extend({}, prop); + + jQuery.each( prop, function( name, val ) { + var e = new jQuery.fx( self, opt, name ); + + if ( rfxtypes.test(val) ) { + e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); + + } else { + var parts = rfxnum.exec(val), + start = e.cur(true) || 0; + + if ( parts ) { + var end = parseFloat( parts[2] ), + unit = parts[3] || "px"; + + // We need to compute starting value + if ( unit !== "px" ) { + self.style[ name ] = (end || 1) + unit; + start = ((end || 1) / e.cur(true)) * start; + self.style[ name ] = start + unit; + } + + // If a +=/-= token was provided, we're doing a relative animation + if ( parts[1] ) { + end = ((parts[1] === "-=" ? -1 : 1) * end) + start; + } + + e.custom( start, end, unit ); + + } else { + e.custom( start, val, "" ); + } + } + }); + + // For JS strict compliance + return true; + }); + }, + + stop: function( clearQueue, gotoEnd ) { + var timers = jQuery.timers; + + if ( clearQueue ) { + this.queue([]); + } + + this.each(function() { + // go in reverse order so anything added to the queue during the loop is ignored + for ( var i = timers.length - 1; i >= 0; i-- ) { + if ( timers[i].elem === this ) { + if (gotoEnd) { + // force the next step to be the last + timers[i](true); + } + + timers.splice(i, 1); + } + } + }); + + // start the next in the queue if the last step wasn't forced + if ( !gotoEnd ) { + this.dequeue(); + } + + return this; + } + +}); + +// Generate shortcuts for custom animations +jQuery.each({ + slideDown: genFx("show", 1), + slideUp: genFx("hide", 1), + slideToggle: genFx("toggle", 1), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, callback ) { + return this.animate( props, speed, callback ); + }; +}); + +jQuery.extend({ + speed: function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? speed : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction(easing) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : + jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; + + // Queueing + opt.old = opt.complete; + opt.complete = function() { + if ( opt.queue !== false ) { + jQuery(this).dequeue(); + } + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + }; + + return opt; + }, + + easing: { + linear: function( p, n, firstNum, diff ) { + return firstNum + diff * p; + }, + swing: function( p, n, firstNum, diff ) { + return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; + } + }, + + timers: [], + + fx: function( elem, options, prop ) { + this.options = options; + this.elem = elem; + this.prop = prop; + + if ( !options.orig ) { + options.orig = {}; + } + } + +}); + +jQuery.fx.prototype = { + // Simple function for setting a style value + update: function() { + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); + + // Set display property to block for height/width animations + if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { + this.elem.style.display = "block"; + } + }, + + // Get the current size + cur: function( force ) { + if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { + return this.elem[ this.prop ]; + } + + var r = parseFloat(jQuery.css(this.elem, this.prop, force)); + return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; + }, + + // Start an animation from one number to another + custom: function( from, to, unit ) { + this.startTime = now(); + this.start = from; + this.end = to; + this.unit = unit || this.unit || "px"; + this.now = this.start; + this.pos = this.state = 0; + + var self = this; + function t( gotoEnd ) { + return self.step(gotoEnd); + } + + t.elem = this.elem; + + if ( t() && jQuery.timers.push(t) && !timerId ) { + timerId = setInterval(jQuery.fx.tick, 13); + } + }, + + // Simple 'show' function + show: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); + this.options.show = true; + + // Begin the animation + // Make sure that we start at a small width/height to avoid any + // flash of content + this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); + + // Start by showing the element + jQuery( this.elem ).show(); + }, + + // Simple 'hide' function + hide: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); + this.options.hide = true; + + // Begin the animation + this.custom(this.cur(), 0); + }, + + // Each step of an animation + step: function( gotoEnd ) { + var t = now(), done = true; + + if ( gotoEnd || t >= this.options.duration + this.startTime ) { + this.now = this.end; + this.pos = this.state = 1; + this.update(); + + this.options.curAnim[ this.prop ] = true; + + for ( var i in this.options.curAnim ) { + if ( this.options.curAnim[i] !== true ) { + done = false; + } + } + + if ( done ) { + if ( this.options.display != null ) { + // Reset the overflow + this.elem.style.overflow = this.options.overflow; + + // Reset the display + var old = jQuery.data(this.elem, "olddisplay"); + this.elem.style.display = old ? old : this.options.display; + + if ( jQuery.css(this.elem, "display") === "none" ) { + this.elem.style.display = "block"; + } + } + + // Hide the element if the "hide" operation was done + if ( this.options.hide ) { + jQuery(this.elem).hide(); + } + + // Reset the properties, if the item has been hidden or shown + if ( this.options.hide || this.options.show ) { + for ( var p in this.options.curAnim ) { + jQuery.style(this.elem, p, this.options.orig[p]); + } + } + + // Execute the complete function + this.options.complete.call( this.elem ); + } + + return false; + + } else { + var n = t - this.startTime; + this.state = n / this.options.duration; + + // Perform the easing function, defaults to swing + var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; + var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); + this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); + this.now = this.start + ((this.end - this.start) * this.pos); + + // Perform the next step of the animation + this.update(); + } + + return true; + } +}; + +jQuery.extend( jQuery.fx, { + tick: function() { + var timers = jQuery.timers; + + for ( var i = 0; i < timers.length; i++ ) { + if ( !timers[i]() ) { + timers.splice(i--, 1); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + }, + + stop: function() { + clearInterval( timerId ); + timerId = null; + }, + + speeds: { + slow: 600, + fast: 200, + // Default speed + _default: 400 + }, + + step: { + opacity: function( fx ) { + jQuery.style(fx.elem, "opacity", fx.now); + }, + + _default: function( fx ) { + if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { + fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; + } else { + fx.elem[ fx.prop ] = fx.now; + } + } + } +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} + +function genFx( type, num ) { + var obj = {}; + + jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { + obj[ this ] = type; + }); + + return obj; +} +if ( "getBoundingClientRect" in document.documentElement ) { + jQuery.fn.offset = function( options ) { + var elem = this[0]; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, + clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, + top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, + left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; + + return { top: top, left: left }; + }; + +} else { + jQuery.fn.offset = function( options ) { + var elem = this[0]; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + jQuery.offset.initialize(); + + var offsetParent = elem.offsetParent, prevOffsetParent = elem, + doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, + body = doc.body, defaultView = doc.defaultView, + prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, + top = elem.offsetTop, left = elem.offsetLeft; + + while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { + if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { + break; + } + + computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; + top -= elem.scrollTop; + left -= elem.scrollLeft; + + if ( elem === offsetParent ) { + top += elem.offsetTop; + left += elem.offsetLeft; + + if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; + } + + if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevComputedStyle = computedStyle; + } + + if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { + top += body.offsetTop; + left += body.offsetLeft; + } + + if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { + top += Math.max( docElem.scrollTop, body.scrollTop ); + left += Math.max( docElem.scrollLeft, body.scrollLeft ); + } + + return { top: top, left: left }; + }; +} + +jQuery.offset = { + initialize: function() { + var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, + html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; + + jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); + + container.innerHTML = html; + body.insertBefore( container, body.firstChild ); + innerDiv = container.firstChild; + checkDiv = innerDiv.firstChild; + td = innerDiv.nextSibling.firstChild.firstChild; + + this.doesNotAddBorder = (checkDiv.offsetTop !== 5); + this.doesAddBorderForTableAndCells = (td.offsetTop === 5); + + checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; + // safari subtracts parent border width here which is 5px + this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); + checkDiv.style.position = checkDiv.style.top = ""; + + innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; + this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); + + this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); + + body.removeChild( container ); + body = container = innerDiv = checkDiv = table = td = null; + jQuery.offset.initialize = jQuery.noop; + }, + + bodyOffset: function( body ) { + var top = body.offsetTop, left = body.offsetLeft; + + jQuery.offset.initialize(); + + if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; + left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + // set position first, in-case top/left are set even on static elem + if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { + elem.style.position = "relative"; + } + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, + curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; + + if ( jQuery.isFunction( options ) ) { + options = options.call( elem, i, curOffset ); + } + + var props = { + top: (options.top - curOffset.top) + curTop, + left: (options.left - curOffset.left) + curLeft + }; + + if ( "using" in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + } +}; + + +jQuery.fn.extend({ + position: function() { + if ( !this[0] ) { + return null; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; + offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; + parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( ["Left", "Top"], function( i, name ) { + var method = "scroll" + name; + + jQuery.fn[ method ] = function(val) { + var elem = this[0], win; + + if ( !elem ) { + return null; + } + + if ( val !== undefined ) { + // Set the scroll offset + return this.each(function() { + win = getWindow( this ); + + if ( win ) { + win.scrollTo( + !i ? val : jQuery(win).scrollLeft(), + i ? val : jQuery(win).scrollTop() + ); + + } else { + this[ method ] = val; + } + }); + } else { + win = getWindow( elem ); + + // Return the scroll offset + return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : + jQuery.support.boxModel && win.document.documentElement[ method ] || + win.document.body[ method ] : + elem[ method ]; + } + }; +}); + +function getWindow( elem ) { + return ("scrollTo" in elem && elem.document) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} +// Create innerHeight, innerWidth, outerHeight and outerWidth methods +jQuery.each([ "Height", "Width" ], function( i, name ) { + + var type = name.toLowerCase(); + + // innerHeight and innerWidth + jQuery.fn["inner" + name] = function() { + return this[0] ? + jQuery.css( this[0], type, false, "padding" ) : + null; + }; + + // outerHeight and outerWidth + jQuery.fn["outer" + name] = function( margin ) { + return this[0] ? + jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : + null; + }; + + jQuery.fn[ type ] = function( size ) { + // Get window width or height + var elem = this[0]; + if ( !elem ) { + return size == null ? null : this; + } + + if ( jQuery.isFunction( size ) ) { + return this.each(function( i ) { + var self = jQuery( this ); + self[ type ]( size.call( this, i, self[ type ]() ) ); + }); + } + + return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? + // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode + elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || + elem.document.body[ "client" + name ] : + + // Get document width or height + (elem.nodeType === 9) ? // is it a document + // Either scroll[Width/Height] or offset[Width/Height], whichever is greater + Math.max( + elem.documentElement["client" + name], + elem.body["scroll" + name], elem.documentElement["scroll" + name], + elem.body["offset" + name], elem.documentElement["offset" + name] + ) : + + // Get or set width or height on the element + size === undefined ? + // Get width or height on the element + jQuery.css( elem, type ) : + + // Set the width or height on the element (default to pixels if value is unitless) + this.css( type, typeof size === "string" ? size : size + "px" ); + }; + +}); +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +})(window); diff --git a/examples/5/js/jquery-1.4.2.min.js b/examples/5/js/jquery-1.4.2.min.js new file mode 100644 index 0000000..7c24308 --- /dev/null +++ b/examples/5/js/jquery-1.4.2.min.js @@ -0,0 +1,154 @@ +/*! + * jQuery JavaScript Library v1.4.2 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Sat Feb 13 22:33:48 2010 -0500 + */ +(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? +e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= +j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, +"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= +true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, +Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& +(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, +a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== +"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, +function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| +c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", +L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, +"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ +a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], +d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== +a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& +!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= +true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; +var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, +parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= +false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= +s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, +applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; +else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, +a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== +w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, +cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", +i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", +" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= +this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= +e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= +c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); +a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, +function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); +k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), +C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= +null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= +e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& +f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; +if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), +fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| +d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, +"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= +a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, +isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= +{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; +if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", +e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, +"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, +d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& +!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, +toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, +u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "), +function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; +if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, +e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); +t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| +g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; +for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- +1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, +CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, +relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= +l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; +h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, +CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, +g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, +text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, +setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= +h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= +m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== +"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, +h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| +!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= +h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& +q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; +if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); +(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: +function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, +gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; +c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= +{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== +"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", +d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? +a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== +1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? +a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= +c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, +wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, +prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, +this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); +return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, +""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& +this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| +u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== +1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); +return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", +""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= +c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? +c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= +function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= +Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, +"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= +a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= +a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== +"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, +serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), +function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, +global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& +e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? +"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== +false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= +false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", +c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| +d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); +g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== +1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== +"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; +if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); +this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], +"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, +animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= +j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); +this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== +"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| +c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; +this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= +this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, +e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| +c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? +function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= +this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; +k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& +f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; +a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); +c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, +d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- +f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": +"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in +e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window); diff --git a/examples/5/rest-style.js b/examples/5/rest-style.js index 7ccb659..9c47af5 100644 --- a/examples/5/rest-style.js +++ b/examples/5/rest-style.js @@ -1,12 +1,20 @@ var t = require('../../t'); t.app({ debug: true, resources: { blog: { - list: function(req, res) { - res.respond('<h1>It works!</h1>'); - } + list: function list(req, res) { res.respond('list') }, + get: function get(req, res, id) { res.respond('get ' + id) }, + save: function(req, res, data) { res.respond('save ' + JSON.stringify(data)) }, + update: function(req, res, data) { res.respond('update ' + JSON.stringify(data)) }, + destroy: function(req, res, data) { res.respond('destroy ' + JSON.stringify(data)) } } + }, + routes: { + '^/$': function(req, res) { + return 'html'; + }, + '^/(js/.*)$': t.serve } }) \ No newline at end of file diff --git a/examples/5/templates/html.html b/examples/5/templates/html.html new file mode 100644 index 0000000..3efe736 --- /dev/null +++ b/examples/5/templates/html.html @@ -0,0 +1,28 @@ +<html> +<head> + <script src="/js/jquery-1.4.2.js" type="text/javascript"></script> + <script type="text/javascript"> + function ask(url, type, data) { + jQuery.ajax({ type: type, url: url, data: data, success: function(response) { alert(response) } }); + } + </script> +</head> +<body> +<h2>REST-style routes</h2> +<p> + <a href="javascript:ask('blog', 'get')">list</a> +</p> +<p> + <a href="javascript:ask('blog/1', 'get')">get</a> +</p> +<p> + <a href="javascript:ask('blog', 'post', 'type=save')">save</a> +</p> +<p> + <a href="javascript:ask('blog/1', 'put', 'type=update')">update</a> +</p> +<p> + <a href="javascript:ask('blog', 'delete', 'type=destoy')">destroy</a> +</p> +</body> +</html> \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index df637c7..6fdd067 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,96 +1,122 @@ require('../vendor/underscore-min'); var url = require('url'), fs = require('fs'), + querystring = require('querystring'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { + + function doRespond(res, callback, user, userArguments) { + + var retur = callback.apply(user.scope, userArguments); + + switch(typeof retur) { + case 'string': + + template.serve(retur, function(html) { + var body = _.template(html, user.scope), + title = user.scope.title; + + fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { + if(err && err.errno != 2) { // 2 => no such file + throw err; + } + + if(user.scope.layout && stats && stats.isFile()) { + template.serve('layout', function(layout) { + responder.respond(res, _.template(layout, { + body: body, + title: title + })); + }) + } + else { + responder.respond(res, body); + } + }); + }); + break; + case 'object': + responder.respond(res, JSON.stringify(retur)); + break; + default: + return; + } + } + + function extractData(req, callback) { + var data = ''; + req.addListener('data', function(chunk) { + data += chunk; + }); + req.addListener('end', function() { + callback(querystring.parse(url.parse('http://fake/?' + data).query)); + }); + } function process(req, res) { var path = url.parse(req.url).pathname; - var mapping = router.parse(path); + var mapping = router.parse(req.method, path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { - + res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } - var userArguments = [req, res].concat(mapping.groups.slice(1)); - var retur = mapping.callback.apply(user.scope, userArguments); - - switch(typeof retur) { - case 'string': - template.serve(retur, function(html) { - var body = _.template(html, user.scope), - title = user.scope.title; - fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { - if(err && err.errno != 2) { // 2 => no such file - throw err; - } - if(user.scope.layout && stats && stats.isFile()) { - template.serve('layout', function(layout) { - responder.respond(res, _.template(layout, { - body: body, - title: title - })); - }) - } - else { - responder.respond(res, body); - } - }); - }); - break; - case 'object': - responder.respond(res, JSON.stringify(retur)); - break; - default: - return; - } + if(req.method == 'POST' || req.method == 'PUT' || req.method == 'DELETE') { + extractData(req, function(data) { + doRespond(res, mapping.callback, user, [req, res, data]); + }); + } + else { + doRespond(res, mapping.callback, user, [req, res].concat(mapping.groups.slice(1))); + } + } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index 075ed0c..8895b0c 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,151 +1,151 @@ var log = require('./logger').log; var sys = require('sys') var router = (function() { var compiledRoutes = {}; var routesByName = {}; function lookup() { var num = 0, args = arguments, route = routesByName[args[0]]; return route ? route.replace(/\([^\)]+?\)+/g, function() { return args[++num] || ''; }) : ''; } function url(route, linktext) { var args = []; for(var arg in arguments) { args.push(arguments[arg]); } return '<a href="' + lookup.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; } global.url = url; function init(routes, resources) { if(!routes && !resources) { throw Error('You need to provide at minimum 1 route.') } routes = routes || {}; compiledRoutes = {}; routesByName = {}; /* list: GET /resource/? get: GET /resource/([^/]+)/? save: POST /resource/? update: PUT /resource/([^/]+)/? destroy: DELETE /resource/? */ for(var resource in resources) { var operations = resources[resource]; for(var operation in operations) { var callback = operations[operation]; var path = '^/' + resource + '/'; var group = '([^\/]+)/?' switch(operation) { case 'list': path = 'GET ' + path + '?'; break; case 'get': path = 'GET ' + path; path += group; break; case 'save': path = 'POST ' + path + '?'; break; case 'update': - path = 'PUT ' + path + '?'; + path = 'PUT ' + path; path += group; break; case 'destroy': path = 'DELETE ' + path + '?'; break; default: throw new Error('Unsupported resource operation'); break; } path += '$' routes[path] = callback; } } sys.puts('Serving routes:'); for(var path in routes) { var route = routes[path]; prepare(route, path); sys.puts(' ' + path) } } function prepare(route, path) { var verb = 'GET'; var httpVerbMatch = extractHttpVerb(path); if(httpVerbMatch) { verb = httpVerbMatch[1]; path = path.substring(verb.length); } var name = extractName(route) mapName(name, path); - compiledRoutes[path] = { + compiledRoutes[verb + ' ' + path] = { name: name, verb: verb, regex: new RegExp(path.trim(), ''), callback: route[name] || route }; } function extractHttpVerb(path) { return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); } function mapName(name, path) { routesByName[name] = path.trim() .replace(/^(\^)/, '') .replace(/\$$/, '') .replace(/\?/g, '') .replace(/\+/g, '') .replace(/\*/g, ''); } function extractName(route) { var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; return functionNameMatch ? functionNameMatch[1] : undefined; } return { init : init, - parse : function(url) { + parse : function(method, url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); - if(matches) { + if(matches && method === route.verb) { log('Route found! - ' + route.verb + ' - '+ url); return { groups: matches, method: route.verb, callback: route.callback }; } } - log('Route not found for url - ' + url); + log('Route not found for - ' + method + ' ' + url); return null; }, url: url }; })(); module.exports = router; \ No newline at end of file diff --git a/test/dispatcher_test.js b/test/dispatcher_test.js index 25f3bb7..9f743c3 100644 --- a/test/dispatcher_test.js +++ b/test/dispatcher_test.js @@ -1,52 +1,53 @@ var test = require('../lib/test'), dispatcher = require('../lib/dispatcher'); DEBUG = true; with(test) { testcase('Dispatcher'); test('Should write responses to response object for normal routes', function() { dispatcher.init({ routes: { '/': function(req, res) { res.respond('test'); } } }); var response; dispatcher.process({ url: '/', method: 'GET' }, { writeHead: function() {}, write: function(body) { response = body; }, end: function() {} }); assertEquals('test', response); }); test('Should write responses to response object for resource routes', function() { dispatcher.init({ resources: { blog: { list: function(req, res) { res.respond('content'); } } } }); var response; dispatcher.process({ url: '/blog/', method: 'GET' }, { writeHead: function() {}, write: function(body) { response = body; }, end: function() {} }); assertEquals('content', response); }); + run(); } \ No newline at end of file diff --git a/test/router_test.js b/test/router_test.js index 518692d..3ef771a 100644 --- a/test/router_test.js +++ b/test/router_test.js @@ -1,104 +1,106 @@ var test = require('../lib/test'), router = require('../lib/router'); DEBUG = true; with(test) { testcase('Router - routing'); test('Without routes should throw exception', function() { shouldThrow(router.init, [], router); }); test('With routes should not throw exception', function() { shouldNotThrow(router.init, [{ '/': function() {} }], router); }); test('Should look up routes from simple urls', function() { router.init({ '/': function() {} }); - var route = router.parse('/'); + var route = router.parse('GET', '/'); assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up routes from complex urls', function() { router.init({ '^/article/([0-9]+)/page/([a-z]+)$': function() {} }); - var route = router.parse('/article/1/page/j'); + var route = router.parse('GET', '/article/1/page/j'); log(route) assertTrue(route.method == 'GET'); assertTrue(typeof route.callback == 'function'); }); test('Should look up urls by name and fill url parameters from arguments', function() { router.init({ '/some/other/route': function() {}, '/article/([0-9]+)/': function articleByIndex() {}, '/another/route': function() {} }); assertEquals('<a href="/article/1/">text</a>', url('articleByIndex', 'text', 1)); }); test('Should look up routes using simple params', function() { pending(); }); testcase('Router - REST style routes'); + test('Should map resources to rest style routes - list: GET /resource/?', function() { router.init({}, { blog: { list: function() {} } }); - var list = router.parse('/blog'); + var list = router.parse('GET', '/blog'); assertEquals('GET', list.method); assertEquals('function', typeof list.callback); }); + test('Should map resources to rest style routes - get: GET /resource/([^\/]+)/?', function() { router.init({}, { - blog: { get: function() {} } + blog: { get: function() { } } }); - var get = router.parse('/blog/1'); + var get = router.parse('GET', '/blog/1'); assertEquals('1', get.groups[1]); assertEquals('GET', get.method); assertEquals('function', typeof get.callback); }); test('Should map resources to rest style routes - save: POST /resource/?', function() { router.init({}, { blog: { save: function() {} } }); - var save = router.parse('/blog'); + var save = router.parse('POST', '/blog'); assertEquals('POST', save.method); assertEquals('function', typeof save.callback); }); test('Should map resources to rest style routes - update: PUT /resource/([^\/]+)/?', function() { router.init({}, { blog: { update: function() {} } }); - var update = router.parse('/blog/1'); + var update = router.parse('PUT', '/blog/1'); assertEquals('1', update.groups[1]); assertEquals('PUT', update.method); assertEquals('function', typeof update.callback); }); test('Should map resources to rest style routes - destroy: DELETE /resource/?', function() { router.init({}, { blog: { destroy: function() {} } }); - var destroy = router.parse('/blog'); + var destroy = router.parse('DELETE', '/blog'); assertEquals('DELETE', destroy.method); assertEquals('function', typeof destroy.callback); }); test('Should throw error on undefined resource opereation', function() { shouldThrow(router.init, [{}, { blog: { undefinedResourceType: function() {} } }], router); }); run(); } \ No newline at end of file
torgeir/tnode
f2704955b897c8312233e48b20873b3b4a1aad38
added image for example 4
diff --git a/examples/4/files.js b/examples/4/files.js index 76d7690..fcf9d26 100644 --- a/examples/4/files.js +++ b/examples/4/files.js @@ -1,14 +1,14 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { return 'index'; }, - '^/(web/js/.*)$' : t.serve, /* serves all files from web/js/ */ + '^/(web/.*/.*)$' : t.serve, /* serves all files from web/js/ */ '^/favicon\.ico$' : function(req, res) { res.respond('Nothing to see here.'); } } }) \ No newline at end of file diff --git a/examples/4/templates/index.html b/examples/4/templates/index.html index b7a7624..312dd7e 100644 --- a/examples/4/templates/index.html +++ b/examples/4/templates/index.html @@ -1,10 +1,11 @@ <html> <head> <title>serving files</title> <script type="text/javascript" src="/web/js/jquery-1.4.2.js"></script> </head> <body> <p style="display: none">if jQuery is loaded, this will fade in!</p> - <script>$('p').first().fadeIn(1000)</script> + <img src="/web/images/test.png" style="display: none;"/> + <script>$('p, img').fadeIn(1000)</script> </body> </html> \ No newline at end of file diff --git a/examples/4/web/images/test.png b/examples/4/web/images/test.png new file mode 100644 index 0000000..c949353 Binary files /dev/null and b/examples/4/web/images/test.png differ
torgeir/tnode
7a8e04233eee04367530c6629ea8eecc6a866bce
added layout support
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index df9b64b..7344836 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,26 +1,29 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$' : function index(req, res) { + this.title = 'Welcome!' + this.name = 'Torgeir'; + return 'welcome'; + }, + 'GET ^/hello/(\\w+)/?' : function hello(req, res, name) { res.respond([ - '<h1>Welcome!</h1><p>Try ', - url('hello', 'this', 'you'), - ', or ', - url('page', 'this', 2), - '!' + '<h1>Again, welcome! ', + name, + ' this is raw html.. </h1><p>Try answering with ', + url('page', 'json too', 2), + '.</p><p>', + url('index', 'Back to /'), + '</p>' ].join('')); }, - 'GET ^/hello/([a-z]+)/?' : function hello(req, res, name) { - this.name = name; - return 'index'; - }, - '^/page/([0-9]+)/?$' : function page(req, res, page) { + '^/page/(\\d+)/?$' : function page(req, res, page) { var json = { page: page }; return json; } } }); diff --git a/examples/1/templates/hello.html b/examples/1/templates/hello.html index 41dc26a..cd067cb 100644 --- a/examples/1/templates/hello.html +++ b/examples/1/templates/hello.html @@ -1,2 +1,2 @@ -<p>Welcome, <strong><%= name %></strong>! I come from a partial..</p> +<p>Welcome, <strong><%= name %></strong>! This is a partial from another template..</p> <p>Did you know <%= now.getTime() %> seconds have passed since 1970?</p> \ No newline at end of file diff --git a/examples/1/templates/index.html b/examples/1/templates/index.html deleted file mode 100644 index 64f0e5a..0000000 --- a/examples/1/templates/index.html +++ /dev/null @@ -1,15 +0,0 @@ -<html> -<head> - <title>Welcome to tnode, <%= name %>!</title> -</head> -<body> - <h1>Again, welcome!</h1> - <div> - <%= partial('hello', { - name: name, - now: new Date() - }) %> - </div> - <div><%= url('index', 'Back to /')%></div> -</body> -</html> \ No newline at end of file diff --git a/examples/1/templates/layout.html b/examples/1/templates/layout.html new file mode 100644 index 0000000..5838637 --- /dev/null +++ b/examples/1/templates/layout.html @@ -0,0 +1,9 @@ +<html> +<head> + <title><%= title %></title> +</head> +<body> + <h1>Example 1</h1> + <%= body %> +</body> +</html> \ No newline at end of file diff --git a/examples/1/templates/welcome.html b/examples/1/templates/welcome.html new file mode 100644 index 0000000..b654278 --- /dev/null +++ b/examples/1/templates/welcome.html @@ -0,0 +1,8 @@ +<h2>Welcome! This is a template!</h2> +<div> + <%= partial('hello', { + name: name, + now: new Date() + }) %> +</div> +<div>Try <%= url('hello', 'answering with raw html too', name) %>!</div> \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index 3ff5e1d..df637c7 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,78 +1,96 @@ require('../vendor/underscore-min'); var url = require('url'), fs = require('fs'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { + layout: true, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } var userArguments = [req, res].concat(mapping.groups.slice(1)); var retur = mapping.callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(retur, function(html) { - responder.respond(res, _.template(html, user.scope)); + var body = _.template(html, user.scope), + title = user.scope.title; + fs.stat(TEMPLATES_DIR + '/layout.html', function(err, stats) { + if(err && err.errno != 2) { // 2 => no such file + throw err; + } + if(user.scope.layout && stats && stats.isFile()) { + template.serve('layout', function(layout) { + responder.respond(res, _.template(layout, { + body: body, + title: title + })); + }) + } + else { + responder.respond(res, body); + } + }); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes, conf.resources); }, process : function(req, res) { try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/template.js b/lib/template.js index 5cbff22..380aa7b 100644 --- a/lib/template.js +++ b/lib/template.js @@ -1,30 +1,30 @@ var fs = require('fs'), log = require('./logger').log; -var TEMPLATES_DIR = './templates'; +TEMPLATES_DIR = './templates'; var template = { find: function(name) { return TEMPLATES_DIR + '/' + name + '.html'; }, serve: function(name, callback) { var template = this.find(name); log('Serving template - ' + template) fs.readFile(template, function(error, data) { if(error) { throw error; } try { callback.call(this, data.toString()); } catch(error) { throw error; } }); } }; module.exports = template; \ No newline at end of file
torgeir/tnode
d2a1803e7bdb28e68aa32f93085b982c7669c010
finally, markdown in the readme, looks like * along with code doesnt work very well
diff --git a/README.md b/README.md index 4a12ecf..3a51e4b 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,46 @@ tnode ----- - Yet another node.js web application library Usage: ----- Check out - git clone git://github.com/torgeir/tnode.git && cd tnode + $ git clone git://github.com/torgeir/tnode.git && cd tnode Running the tests - make test + $ make test Running the examples - cd examples/1/ - node exampleapp.js +1: Routing - cd examples/2/ - node longpoll.js + $ cd examples/1/ + $ node exampleapp.js - cd examples/3/ - node verbs.js +2: Long polling/"push" - cd examples/4/ - node files.js + $ cd examples/2/ + $ node longpoll.js + +3: Http verbs + + $ cd examples/3/ + $ node verbs.js + +4: Serving files + + $ cd examples/4/ + $ node files.js Todo ----- - handle post requests - creating a test-runner - support async tests - refactor route parsing \ No newline at end of file
torgeir/tnode
bac54323883331f457515c2af2efb908d2d054ad
.md code does not work in readme
diff --git a/README.md b/README.md index 15b8b33..4a12ecf 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,38 @@ tnode ----- - Yet another node.js web application library Usage: ----- -* Check out +Check out git clone git://github.com/torgeir/tnode.git && cd tnode -* Running the tests +Running the tests make test -* Running the examples +Running the examples cd examples/1/ node exampleapp.js cd examples/2/ node longpoll.js cd examples/3/ node verbs.js cd examples/4/ node files.js Todo ----- - handle post requests - creating a test-runner - support async tests - refactor route parsing \ No newline at end of file
torgeir/tnode
4bf87decf8d019cc1f81fe50183dd7b26bd929cf
no luck? I give up..
diff --git a/README.md b/README.md index 40cd00c..15b8b33 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,38 @@ tnode ----- - Yet another node.js web application library Usage: ----- * Check out - $ git clone git://github.com/torgeir/tnode.git && cd tnode + git clone git://github.com/torgeir/tnode.git && cd tnode * Running the tests - $ make test + make test * Running the examples - $ cd examples/1/ - $ node exampleapp.js + cd examples/1/ + node exampleapp.js - $ cd examples/2/ - $ node longpoll.js + cd examples/2/ + node longpoll.js - $ cd examples/3/ - $ node verbs.js + cd examples/3/ + node verbs.js - $ cd examples/4/ - $ node files.js + cd examples/4/ + node files.js Todo ----- - handle post requests - creating a test-runner +- support async tests +- refactor route parsing \ No newline at end of file
torgeir/tnode
5416ef49f429f492b4910612eb61310772f92983
still trying to make markdown work for the readme, jebus
diff --git a/README.md b/README.md index 99f2ef8..40cd00c 100644 --- a/README.md +++ b/README.md @@ -1,40 +1,36 @@ tnode ----- - Yet another node.js web application library Usage: ----- * Check out - $ git clone git://github.com/torgeir/tnode.git && cd tnode + $ git clone git://github.com/torgeir/tnode.git && cd tnode * Running the tests - $ make test + $ make test * Running the examples - $ cd examples/1/ - - $ node exampleapp.js + $ cd examples/1/ + $ node exampleapp.js - $ cd examples/2/ - - $ node longpoll.js + $ cd examples/2/ + $ node longpoll.js - $ cd examples/3/ - - $ node verbs.js + $ cd examples/3/ + $ node verbs.js - $ cd examples/4/ - - $ node files.js + $ cd examples/4/ + $ node files.js Todo ----- - handle post requests - creating a test-runner \ No newline at end of file
torgeir/tnode
1059e40cdc98286716dc27a25e4ba227e73248ff
modified readme, making markdown work
diff --git a/README.md b/README.md index dbdfa29..99f2ef8 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,40 @@ tnode ----- - Yet another node.js web application library Usage: ----- * Check out $ git clone git://github.com/torgeir/tnode.git && cd tnode * Running the tests $ make test * Running the examples $ cd examples/1/ + $ node exampleapp.js $ cd examples/2/ + $ node longpoll.js $ cd examples/3/ + $ node verbs.js $ cd examples/4/ + $ node files.js Todo ----- - handle post requests - creating a test-runner \ No newline at end of file
torgeir/tnode
5e7f18c6680b78911b7f711d5dc4267dcabed634
modified readme
diff --git a/README.md b/README.md index f2c5398..dbdfa29 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,36 @@ tnode ----- - Yet another node.js web application library Usage: ----- * Check out $ git clone git://github.com/torgeir/tnode.git && cd tnode * Running the tests $ make test * Running the examples - $ cd examples/1/ - $ node exampleapp.js + $ cd examples/1/ + $ node exampleapp.js - $ cd examples/2/ - $ node longpoll.js + $ cd examples/2/ + $ node longpoll.js - $ cd examples/3/ + $ cd examples/3/ $ node verbs.js - $ cd examples/4/ - $ node files.js + $ cd examples/4/ + $ node files.js Todo ----- - handle post requests - creating a test-runner \ No newline at end of file
torgeir/tnode
bca3ca827f542bf5c220e1698a1dc620a9d447a4
modified readme
diff --git a/README.md b/README.md index c195e88..f2c5398 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,36 @@ tnode ----- -- Yet another node.js library +- Yet another node.js web application library Usage: ----- * Check out - $ git clone git://github.com/torgeir/tnode.git && cd tnode + $ git clone git://github.com/torgeir/tnode.git && cd tnode * Running the tests - $ make test + $ make test * Running the examples - $ cd examples/1/ - $ node exampleapp.js + $ cd examples/1/ + $ node exampleapp.js - $ cd examples/2/ - $ node longpoll.js + $ cd examples/2/ + $ node longpoll.js - $ cd examples/3/ - $ node verbs.js + $ cd examples/3/ + $ node verbs.js - $ cd examples/4/ - $ node files.js + $ cd examples/4/ + $ node files.js Todo ----- - handle post requests - creating a test-runner \ No newline at end of file
torgeir/tnode
8e01145c8543fe1922f9439c05153bd40f1b09b2
modified readme
diff --git a/README.md b/README.md index cba44bb..c195e88 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,36 @@ tnode ----- - Yet another node.js library Usage: ----- * Check out - $ git clone git://github.com/torgeir/tnode.git && cd tnode + $ git clone git://github.com/torgeir/tnode.git && cd tnode * Running the tests - $ make test + $ make test * Running the examples - $ cd examples/1/ - $ node exampleapp.js - - $ cd examples/2/ - $ node longpoll.js - - $ cd examples/3/ - $ node verbs.js - - $ cd examples/4/ - $ node files.js - + $ cd examples/1/ + $ node exampleapp.js + + $ cd examples/2/ + $ node longpoll.js + + $ cd examples/3/ + $ node verbs.js + + $ cd examples/4/ + $ node files.js + Todo ----- - - handle post requests - - creating a test-runner +- handle post requests +- creating a test-runner \ No newline at end of file
torgeir/tnode
41a6076f153e5913ead4bd61c68a280a518e2850
added readme
diff --git a/README.md b/README.md new file mode 100644 index 0000000..cba44bb --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +tnode +----- + +- Yet another node.js library + +Usage: +----- + +* Check out + + $ git clone git://github.com/torgeir/tnode.git && cd tnode + +* Running the tests + + $ make test + +* Running the examples + + $ cd examples/1/ + $ node exampleapp.js + + $ cd examples/2/ + $ node longpoll.js + + $ cd examples/3/ + $ node verbs.js + + $ cd examples/4/ + $ node files.js + +Todo +----- + - handle post requests + - creating a test-runner + + \ No newline at end of file
torgeir/tnode
f9914321ea4b6d18671aedf1561317c4e3d5387b
added more tests
diff --git a/Makefile b/Makefile index 4999690..7c6ebcf 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,9 @@ test: make make: node test/dispatcher_test.js node test/router_test.js - node test/mime_test.js \ No newline at end of file + node test/mime_test.js + node test/template_test.js + node test/responder_test.js + node test/color_test.js diff --git a/lib/dispatcher.js b/lib/dispatcher.js index a28d3c3..f529d89 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,78 +1,78 @@ require('../vendor/underscore-min'); var url = require('url'), fs = require('fs'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = (function() { function process(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } var userArguments = [req, res].concat(mapping.groups.slice(1)); var retur = mapping.callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': - template.serve(res, retur, function(html) { + template.serve(retur, function(html) { responder.respond(res, _.template(html, user.scope)); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } else { responder.respond404(res); } } return { init : function(conf) { router.init(conf.routes); }, process : function(req, res) { try { process(req, res); } catch(e) { responder.respond500(res, e); } } }; })(); module.exports = dispatcher; \ No newline at end of file diff --git a/lib/template.js b/lib/template.js index 1b80d6a..5cbff22 100644 --- a/lib/template.js +++ b/lib/template.js @@ -1,30 +1,30 @@ var fs = require('fs'), log = require('./logger').log; var TEMPLATES_DIR = './templates'; var template = { find: function(name) { return TEMPLATES_DIR + '/' + name + '.html'; }, - serve: function(res, name, callback) { + serve: function(name, callback) { var template = this.find(name); log('Serving template - ' + template) fs.readFile(template, function(error, data) { if(error) { throw error; } try { callback.call(this, data.toString()); } catch(error) { throw error; } }); } }; module.exports = template; \ No newline at end of file diff --git a/lib/test.js b/lib/test.js index 1258cda..522915b 100644 --- a/lib/test.js +++ b/lib/test.js @@ -1,142 +1,142 @@ var sys = require('sys'), p = sys.puts; color = require('./color'), log = require('./logger').log; var AssertionError = function(msg) { this.msg = msg; }; var Pending = function() {}; var testcases = []; var testlib = { testcase: function(name) { testcases.unshift({ name: name, tests: [] }); }, test : function(name, body) { testcases[0].tests.push({ name: name, body: body }); }, pending: function() { throw new Pending(); }, run: function() { var count = 0, failed = 0, errors = 0, pending = 0; p('Running tests'); testcases.forEach(function(testcase) { var didFail = false; var status = []; testcase.tests.forEach(function(test) { count++; try { test.body.call(this); status.push(color.green(test.name)); } catch(e) { if(e instanceof Pending) { pending++; - status.push(color.yellow('Pending: ' + test.name)) + status.push(color.yellow(test.name)) } else { didFail = true; status.push(color.red(test.name)); if(e instanceof AssertionError) { failed++; status.push(e.msg) } else { errors++; if (e.type) { status.push(e.type); } if(e.stack) { status.push(e.stack) } } } } }); if(didFail) { p(color.red(testcase.name)); } else { p(color.green(testcase.name)); } status.forEach(function(status) { p(' ' + status); }); }); p('\nTotal: ' + count + ', Failures: ' + failed + ', Errors: ' + errors + ', Pending: ' + pending); }, assertEquals: function(expected, actual) { if(!equals(expected, actual)) { expect(expected, actual); } }, assertTrue: function(actual) { this.assertEquals(true, actual); }, assertFalse: function(actual) { this.assertEquals(false, actual); }, shouldThrow: function(f, args, scope) { var passed = false; try { f.apply(scope || this, args); } catch (e) { passed = true; } if (!passed) { throw new AssertionError('Exception expected, none thrown?'); } }, shouldNotThrow: function(f, args, scope) { var passed = true; try { f.apply(scope || this, args); } catch (e) { passed = false; } if (!passed) { throw new AssertionError('Exception thrown, none expected?'); } }, fail: function(msg) { throw new AssertionError(msg); } } function expect(expected, actual) { throw new AssertionError([ 'Expected: ', sys.inspect(expected), ' but was: ', sys.inspect(actual) ].join('')); } function equals(expected, actual) { return expected === actual; } module.exports = testlib; \ No newline at end of file diff --git a/test/color_test.js b/test/color_test.js new file mode 100644 index 0000000..2d60253 --- /dev/null +++ b/test/color_test.js @@ -0,0 +1,22 @@ +var test = require('../lib/test'), + color = require('../lib/color'); + +DEBUG = true; + +with(test) { + testcase('Color'); + + test('should display terminal text in red', function() { + assertEquals("\u001B[31msome text\u001B[0m", color.red('some text')); + }); + + test('should display terminal text in green', function() { + assertEquals("\u001B[32msome other text\u001B[0m", color.green('some other text')); + }); + + test('should display terminal text in yellow', function() { + assertEquals("\u001B[33meven more text\u001B[0m", color.yellow('even more text')); + }); + + run(); +} diff --git a/test/dispatcher_test.js b/test/dispatcher_test.js index cacaa02..b018e61 100644 --- a/test/dispatcher_test.js +++ b/test/dispatcher_test.js @@ -1,34 +1,30 @@ var test = require('../lib/test'), dispatcher = require('../lib/dispatcher'); DEBUG = true; with(test) { testcase('Dispatcher'); test('Should write responses to response object', function() { dispatcher.init({ routes: { '/': function(req, res) { res.respond('test'); } } }); var response; dispatcher.process({ url: '/', method: 'GET' }, { sendHeader: function() {}, write: function(body) { response = body; }, end: function() {} }); assertEquals('test', response); }); - - test('Should respond with templates when user returns string', function() { - pending(); - }); run(); } \ No newline at end of file diff --git a/test/responder_test.js b/test/responder_test.js new file mode 100644 index 0000000..a494ead --- /dev/null +++ b/test/responder_test.js @@ -0,0 +1,85 @@ +var test = require('../lib/test'), + responder = require('../lib/responder'); + +DEBUG = true; + +with(test) { + testcase('Responder'); + + test('should write responses to response object', function() { + var actualResponse, + actualEncoding; + var response = { + write: function(body, encoding) { + actualResponse = body; + actualEncoding = encoding; + }, + sendHeader: function() {}, + end: function() {} + } + + responder.respond(response, 'response'); + + assertEquals('response', actualResponse); + assertEquals('utf-8', actualEncoding); + }); + + test('should redirect', function() { + var actualStatus, + actualHeaders; + var response = { + sendHeader: function(status, headers) { + actualStatus = status; + actualHeaders = headers; + }, + end: function() {} + }; + + responder.redirect(response, 'http://fake.url'); + + assertEquals(302, actualStatus); + assertEquals('http://fake.url', actualHeaders['Location']); + }); + + test('should send 404', function() { + var actualResponse, + actualStatus; + var response = { + write: function(body) { + actualResponse = body; + }, + sendHeader: function(status) { + actualStatus = status; + }, + end: function() {} + } + + responder.respond404(response); + assertEquals(404, actualStatus); + assertEquals('<h1>404 Not Found</h1>', actualResponse); + }); + + test('should send 500', function() { + var actualResponse, + actualStatus; + var response = { + write: function(body) { + actualResponse = body; + }, + sendHeader: function(status) { + actualStatus = status; + }, + end: function() {} + } + + responder.respond500(response); + assertEquals(500, actualStatus); + assertEquals('<h1>500 Internal Server Error</h1>', actualResponse); + }); + + test('should serve files', function() { + pending(); + }); + + run(); +} \ No newline at end of file diff --git a/test/template_test.js b/test/template_test.js new file mode 100644 index 0000000..7a725bb --- /dev/null +++ b/test/template_test.js @@ -0,0 +1,18 @@ +var test = require('../lib/test'), + template = require('../lib/template'); + +DEBUG = true; + +with(test) { + testcase('Template'); + + test('should look up templates names', function() { + assertEquals('./templates/template.html', template.find('template')); + }); + + test('should serve templates', function() { + pending(); + }); + + run(); +} \ No newline at end of file
torgeir/tnode
fc00d3e2df0cd971a5a96f2cf81349daa78599e0
added tests scripts and created test lib along with some tests
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4999690 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ +test: make + +make: + node test/dispatcher_test.js + node test/router_test.js + node test/mime_test.js \ No newline at end of file diff --git a/lib/color.js b/lib/color.js new file mode 100644 index 0000000..12327a9 --- /dev/null +++ b/lib/color.js @@ -0,0 +1,21 @@ +var color = (function() { + + function colorize(color) { + return function(string) { + return "\u001B[" + { + black : 30, + red : 31, + green : 32, + yellow : 33, + }[color] + 'm' + string + "\u001B[0m"; + }; + }; + + return { + red : colorize('red'), + green: colorize('green'), + yellow: colorize('yellow') + } +})(); + +module.exports = color; \ No newline at end of file diff --git a/lib/colorizer.js b/lib/colorizer.js deleted file mode 100644 index 1335083..0000000 --- a/lib/colorizer.js +++ /dev/null @@ -1,9 +0,0 @@ -var colorizer = function(string, color) { - return "\u001B[" + { - black : 30, - red : 31, - green : 32, - }[color] + 'm' + string + "\u001B[0m"; -}; - -module.exports = colorizer; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index c647659..3aad446 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,103 +1,106 @@ var log = require('./logger').log; var sys = require('sys') var router = (function() { var compiledRoutes = {}; var routesByName = {}; function lookup() { var num = 0, args = arguments, route = routesByName[args[0]]; return route ? route.replace(/\([^\)]+?\)+/g, function() { return args[++num] || ''; }) : ''; } function url(route, linktext) { var args = []; for(var arg in arguments) { args.push(arguments[arg]); } return '<a href="' + lookup.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; } global.url = url; function init(routes) { if(!routes) { throw Error('You need to provide some routes.') } + compiledRoutes = {}; + routesByName = {}; + for(var path in routes) { var route = routes[path]; - prepare(path, route); + prepare(route, path); } } - function prepare(path, route) { + function prepare(route, path) { var verb = 'GET'; var httpVerbMatch = extractHttpVerb(path); if(httpVerbMatch) { verb = httpVerbMatch[1]; path = path.substring(verb.length); } var name = extractName(route) mapName(name, path); compiledRoutes[path] = { name: name, verb: verb, regex: new RegExp(path.trim(), ''), callback: route[name] || route }; } function extractHttpVerb(path) { return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); } function mapName(name, path) { routesByName[name] = path.trim() .replace(/^(\^)/, '') .replace(/\$$/, '') .replace(/\?/g, '') .replace(/\+/g, '') .replace(/\*/g, ''); } function extractName(route) { var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; return functionNameMatch ? functionNameMatch[1] : undefined; } return { init : init, parse : function(url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); if(matches) { log('Route found! - ' + route.verb + ' - '+ url); return { groups: matches, method: route.verb, callback: route.callback }; } } log('Route not found for url - ' + url); return null; }, url: url }; })(); module.exports = router; \ No newline at end of file diff --git a/lib/test.js b/lib/test.js new file mode 100644 index 0000000..1258cda --- /dev/null +++ b/lib/test.js @@ -0,0 +1,142 @@ +var sys = require('sys'), + p = sys.puts; + color = require('./color'), + log = require('./logger').log; + +var AssertionError = function(msg) { this.msg = msg; }; +var Pending = function() {}; + +var testcases = []; + +var testlib = { + testcase: function(name) { + testcases.unshift({ + name: name, + tests: [] + }); + }, + test : function(name, body) { + testcases[0].tests.push({ + name: name, + body: body + }); + }, + pending: function() { + throw new Pending(); + }, + run: function() { + var count = 0, + failed = 0, + errors = 0, + pending = 0; + + p('Running tests'); + testcases.forEach(function(testcase) { + + var didFail = false; + var status = []; + + testcase.tests.forEach(function(test) { + count++; + + try { + test.body.call(this); + status.push(color.green(test.name)); + } + catch(e) { + + if(e instanceof Pending) { + pending++; + status.push(color.yellow('Pending: ' + test.name)) + } + else { + didFail = true; + status.push(color.red(test.name)); + + if(e instanceof AssertionError) { + failed++; + status.push(e.msg) + } + else { + errors++; + + if (e.type) { + status.push(e.type); + } + if(e.stack) { + status.push(e.stack) + } + } + } + } + + }); + + if(didFail) { + p(color.red(testcase.name)); + } + else { + p(color.green(testcase.name)); + } + status.forEach(function(status) { + p(' ' + status); + }); + }); + + p('\nTotal: ' + count + ', Failures: ' + failed + ', Errors: ' + errors + ', Pending: ' + pending); + }, + + assertEquals: function(expected, actual) { + if(!equals(expected, actual)) { + expect(expected, actual); + } + }, + assertTrue: function(actual) { + this.assertEquals(true, actual); + }, + assertFalse: function(actual) { + this.assertEquals(false, actual); + }, + shouldThrow: function(f, args, scope) { + var passed = false; + try { + f.apply(scope || this, args); + } catch (e) { + passed = true; + } + + if (!passed) { + throw new AssertionError('Exception expected, none thrown?'); + } + }, + shouldNotThrow: function(f, args, scope) { + var passed = true; + try { + f.apply(scope || this, args); + } catch (e) { + passed = false; + } + + if (!passed) { + throw new AssertionError('Exception thrown, none expected?'); + } + }, + fail: function(msg) { + throw new AssertionError(msg); + } +} + +function expect(expected, actual) { + throw new AssertionError([ + 'Expected: ', + sys.inspect(expected), + ' but was: ', + sys.inspect(actual) + ].join('')); +} + +function equals(expected, actual) { + return expected === actual; +} + +module.exports = testlib; \ No newline at end of file diff --git a/test/dispatcher_test.js b/test/dispatcher_test.js new file mode 100644 index 0000000..cacaa02 --- /dev/null +++ b/test/dispatcher_test.js @@ -0,0 +1,34 @@ +var test = require('../lib/test'), + dispatcher = require('../lib/dispatcher'); + +DEBUG = true; + +with(test) { + testcase('Dispatcher'); + + test('Should write responses to response object', function() { + dispatcher.init({ + routes: { + '/': function(req, res) { res.respond('test'); } + } + }); + var response; + dispatcher.process({ + url: '/', + method: 'GET' + }, { + sendHeader: function() {}, + write: function(body) { + response = body; + }, + end: function() {} + }); + assertEquals('test', response); + }); + + test('Should respond with templates when user returns string', function() { + pending(); + }); + + run(); +} \ No newline at end of file diff --git a/test/mime_test.js b/test/mime_test.js new file mode 100644 index 0000000..e28f833 --- /dev/null +++ b/test/mime_test.js @@ -0,0 +1,18 @@ +var test = require('../lib/test'), + mime = require('../lib/mime'); + +DEBUG = true; + +with(test) { + testcase('Mime type should be resolved from file extension'); + + test('File extension .js should result in mime type text/ecmascript', function() { + assertEquals('text/ecmascript', mime.lookup('.js')); + }); + + test('File extension .css should result in mime type text/css', function() { + assertEquals('text/css', mime.lookup('.css')); + }); + + run(); +} \ No newline at end of file diff --git a/test/router_test.js b/test/router_test.js new file mode 100644 index 0000000..f16201c --- /dev/null +++ b/test/router_test.js @@ -0,0 +1,46 @@ +var test = require('../lib/test'), + router = require('../lib/router'); + +DEBUG = true; + +with(test) { + + testcase('Router'); + + test('Without routes should throw exception', function() { + shouldThrow(router.init, [], router); + }); + + test('With routes should not throw exception', function() { + shouldNotThrow(router.init, [{ '/': function() {} }], router); + }); + + test('Should look up routes from simple urls', function() { + router.init({ + '/': function() {} + }); + var route = router.parse('/'); + assertTrue(route.method == 'GET'); + assertTrue(typeof route.callback == 'function'); + }); + + test('Should look up routes from complex urls', function() { + router.init({ + '^/article/([0-9]+)/page/([a-z]+)$': function() {} + }); + var route = router.parse('/article/1/page/j'); + assertTrue(route.method == 'GET'); + assertTrue(typeof route.callback == 'function'); + }); + + test('Should look up urls by name and fill url parameters from arguments', function() { + router.init({ + '/some/other/route': function() {}, + '/article/([0-9]+)/': function articleByIndex() {}, + '/another/route': function() {} + }); + assertEquals('<a href="/article/1/">text</a>', url('articleByIndex', 'text', 1)); + }); + + run(); +} \ No newline at end of file
torgeir/tnode
056981ff4fa2969016e9925725bc2f923ee49243
added route naming and global url helper
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index 2aef35b..df9b64b 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,20 +1,26 @@ var t = require('../../t'); t.app({ debug: true, routes: { - '^/$' : function(req, res) { - res.respond('<h1>Welcome!</h1><p>Try <a href="/hello/you">this</a>, or <a href="/page/1">this</a>!'); + '^/$' : function index(req, res) { + res.respond([ + '<h1>Welcome!</h1><p>Try ', + url('hello', 'this', 'you'), + ', or ', + url('page', 'this', 2), + '!' + ].join('')); }, - '^/hello/([a-z]+)/?' : function(req, res, name) { + 'GET ^/hello/([a-z]+)/?' : function hello(req, res, name) { this.name = name; return 'index'; }, - '^/page/([0-9]+)/?$' : function(req, res, page) { + '^/page/([0-9]+)/?$' : function page(req, res, page) { var json = { page: page }; return json; } } -}); \ No newline at end of file +}); diff --git a/examples/1/templates/index.html b/examples/1/templates/index.html index 0750f62..64f0e5a 100644 --- a/examples/1/templates/index.html +++ b/examples/1/templates/index.html @@ -1,14 +1,15 @@ <html> <head> <title>Welcome to tnode, <%= name %>!</title> </head> <body> <h1>Again, welcome!</h1> <div> <%= partial('hello', { name: name, now: new Date() }) %> </div> + <div><%= url('index', 'Back to /')%></div> </body> </html> \ No newline at end of file diff --git a/lib/colorizer.js b/lib/colorizer.js new file mode 100644 index 0000000..1335083 --- /dev/null +++ b/lib/colorizer.js @@ -0,0 +1,9 @@ +var colorizer = function(string, color) { + return "\u001B[" + { + black : 30, + red : 31, + green : 32, + }[color] + 'm' + string + "\u001B[0m"; +}; + +module.exports = colorizer; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index 16f6779..c647659 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,53 +1,103 @@ var log = require('./logger').log; +var sys = require('sys') var router = (function() { + var compiledRoutes = {}; + var routesByName = {}; + + function lookup() { + var num = 0, + args = arguments, + route = routesByName[args[0]]; + return route ? route.replace(/\([^\)]+?\)+/g, function() { + return args[++num] || ''; + }) : ''; + } + + function url(route, linktext) { + var args = []; + for(var arg in arguments) { + args.push(arguments[arg]); + } + return '<a href="' + lookup.apply(this, [route].concat(args.slice(2))) + '">' + linktext + '</a>'; + } + + global.url = url; function init(routes) { if(!routes) { throw Error('You need to provide some routes.') } for(var path in routes) { - var callback = routes[path]; - var verb = 'GET'; - var verbMatch = /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); - if(verbMatch) { - verb = verbMatch[1]; - path = path.substring(verb.length); - } - - compiledRoutes[path] = { - verb: verb, - regex: new RegExp(path.trim(), ''), - callback: callback - }; + var route = routes[path]; + prepare(path, route); + } + } + + function prepare(path, route) { + + var verb = 'GET'; + var httpVerbMatch = extractHttpVerb(path); + if(httpVerbMatch) { + verb = httpVerbMatch[1]; + path = path.substring(verb.length); } + + var name = extractName(route) + mapName(name, path); + + compiledRoutes[path] = { + name: name, + verb: verb, + regex: new RegExp(path.trim(), ''), + callback: route[name] || route + }; + } + + function extractHttpVerb(path) { + return /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); + } + + function mapName(name, path) { + routesByName[name] = path.trim() + .replace(/^(\^)/, '') + .replace(/\$$/, '') + .replace(/\?/g, '') + .replace(/\+/g, '') + .replace(/\*/g, ''); + } + + function extractName(route) { + var functionNameMatch = /function ([^\(]+)/.exec(route.toString());; + return functionNameMatch ? functionNameMatch[1] : undefined; } return { init : init, parse : function(url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); if(matches) { log('Route found! - ' + route.verb + ' - '+ url); return { groups: matches, method: route.verb, callback: route.callback }; } } log('Route not found for url - ' + url); return null; - } + }, + url: url }; })(); module.exports = router; \ No newline at end of file diff --git a/t.js b/t.js index 1375c61..b1b8eda 100644 --- a/t.js +++ b/t.js @@ -1,31 +1,27 @@ // tnode var sys = require('sys'), http = require('http'); var dispatcher = require('./lib/dispatcher'), responder = require('./lib/responder'); var tnode = { serve : responder.serveFile, app: function(conf) { DEBUG = conf.debug || false; var port = conf.port || 8888; dispatcher.init(conf); - - http.createServer(function(req, res) { - dispatcher.process(req, res); - }).listen(port); + http.createServer(dispatcher.process).listen(port); - sys.puts('Starting server at http://127.0.0.1:' + port); - + sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); } }; module.exports = tnode; \ No newline at end of file
torgeir/tnode
107b4a077c9a6f8d9b4e1d1381fd154b1abdd56f
moved exception handling into dispatcher
diff --git a/lib/dispatcher.js b/lib/dispatcher.js index ab4ec03..a28d3c3 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,66 +1,78 @@ require('../vendor/underscore-min'); var url = require('url'), fs = require('fs'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); -var dispatcher = { - init : function(conf) { - router.init(conf.routes); - }, - process : function(req, res) { - +var dispatcher = (function() { + + function process(req, res) { + var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { - + res.respond = function(body, contentType, status) { responder.respond(res, body, contentType, status); }; res.redirect = function(location) { responder.redirect(res, location); }; res.respond404 = function() { responder.respond404(res); }; res.respond500 = function(error) { responder.respond500(res, error); }; var user = { scope: { partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } - + var userArguments = [req, res].concat(mapping.groups.slice(1)); var retur = mapping.callback.apply(user.scope, userArguments); - + switch(typeof retur) { case 'string': template.serve(res, retur, function(html) { responder.respond(res, _.template(html, user.scope)); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } else { responder.respond404(res); } } -}; - + + return { + init : function(conf) { + router.init(conf.routes); + }, + process : function(req, res) { + try { + process(req, res); + } + catch(e) { + responder.respond500(res, e); + } + } + }; +})(); + module.exports = dispatcher; \ No newline at end of file diff --git a/t.js b/t.js index 8b967e1..1375c61 100644 --- a/t.js +++ b/t.js @@ -1,36 +1,31 @@ // tnode var sys = require('sys'), http = require('http'); var dispatcher = require('./lib/dispatcher'), responder = require('./lib/responder'); var tnode = { serve : responder.serveFile, app: function(conf) { DEBUG = conf.debug || false; var port = conf.port || 8888; dispatcher.init(conf); http.createServer(function(req, res) { - try { - dispatcher.process(req, res); - } - catch(e) { - responder.respond500(res, e); - } + dispatcher.process(req, res); }).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); } }; module.exports = tnode; \ No newline at end of file
torgeir/tnode
1b06f4981516951c1846a5a9b7ed32f950a3c6f7
moved user response methods to response object
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index 5900f62..2aef35b 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,20 +1,20 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$' : function(req, res) { - this.respond('<h1>Welcome!</h1><p>Try <a href="/hello/you">this</a>, or <a href="/page/1">this</a>!'); + res.respond('<h1>Welcome!</h1><p>Try <a href="/hello/you">this</a>, or <a href="/page/1">this</a>!'); }, '^/hello/([a-z]+)/?' : function(req, res, name) { this.name = name; return 'index'; }, '^/page/([0-9]+)/?$' : function(req, res, page) { var json = { page: page }; return json; } } }); \ No newline at end of file diff --git a/examples/2/longpoll.js b/examples/2/longpoll.js index 4822066..d31603a 100644 --- a/examples/2/longpoll.js +++ b/examples/2/longpoll.js @@ -1,21 +1,20 @@ var t = require('../../t'), events = require('events'); var bus = new events.EventEmitter(), MESSAGE_EVENT = 'message_event'; t.app({ debug: true, routes: { '^/wait$' : function(req, res) { - var self = this; bus.addListener(MESSAGE_EVENT, function(msg) { - self.respond(msg); + res.respond(msg); }) }, '^/done/(.*)$' : function(req, res, msg) { bus.emit(MESSAGE_EVENT, msg); - this.respond('done'); + res.respond('done'); } } }); \ No newline at end of file diff --git a/examples/3/verbs.js b/examples/3/verbs.js index 0a2f090..2b5a474 100644 --- a/examples/3/verbs.js +++ b/examples/3/verbs.js @@ -1,13 +1,13 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function() { return 'form'; }, 'POST /ionlyhandleposts': function(req, res) { - this.respond('POST is ok'); + res.respond('POST is ok'); } } }) \ No newline at end of file diff --git a/examples/4/files.js b/examples/4/files.js index aa5b994..76d7690 100644 --- a/examples/4/files.js +++ b/examples/4/files.js @@ -1,14 +1,14 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$': function(req, res) { return 'index'; }, '^/(web/js/.*)$' : t.serve, /* serves all files from web/js/ */ '^/favicon\.ico$' : function(req, res) { - this.respond('Nothing to see here.'); + res.respond('Nothing to see here.'); } } }) \ No newline at end of file diff --git a/lib/dispatcher.js b/lib/dispatcher.js index cf5551c..ab4ec03 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,66 +1,66 @@ require('../vendor/underscore-min'); var url = require('url'), fs = require('fs'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = { init : function(conf) { router.init(conf.routes); }, process : function(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { - + + res.respond = function(body, contentType, status) { + responder.respond(res, body, contentType, status); + }; + res.redirect = function(location) { + responder.redirect(res, location); + }; + res.respond404 = function() { + responder.respond404(res); + }; + res.respond500 = function(error) { + responder.respond500(res, error); + }; var user = { scope: { - respond: function(body, contentType, status) { - responder.respond(res, body, contentType, status); - }, - redirect: function(location) { - responder.redirect(res, location); - }, - respond404: function() { - responder.respond404(res); - }, - respond500: function(error) { - responder.respond500(res, error); - }, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } var userArguments = [req, res].concat(mapping.groups.slice(1)); var retur = mapping.callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(res, retur, function(html) { responder.respond(res, _.template(html, user.scope)); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: return; } } else { responder.respond404(res); } } }; module.exports = dispatcher; \ No newline at end of file
torgeir/tnode
57b5353d2bf06b8421536b10363eccc3381bab94
changed module layouts
diff --git a/lib/dispatcher.js b/lib/dispatcher.js index bf40d06..cf5551c 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,66 +1,66 @@ require('../vendor/underscore-min'); var url = require('url'), fs = require('fs'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = { init : function(conf) { router.init(conf.routes); }, process : function(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { var user = { scope: { respond: function(body, contentType, status) { responder.respond(res, body, contentType, status); }, redirect: function(location) { responder.redirect(res, location); }, respond404: function() { responder.respond404(res); }, respond500: function(error) { responder.respond500(res, error); }, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } var userArguments = [req, res].concat(mapping.groups.slice(1)); var retur = mapping.callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': - template.serve(res, retur, user.scope, function(html) { - responder.respond(res, html); + template.serve(res, retur, function(html) { + responder.respond(res, _.template(html, user.scope)); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: - break; + return; } } else { responder.respond404(res); } } }; module.exports = dispatcher; \ No newline at end of file diff --git a/lib/logger.js b/lib/logger.js index c9e3805..cc4c7dd 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -1,22 +1,28 @@ var sys = require('sys'); +if(typeof DEBUG) + DEBUG = false; + var logger = {  log: function (arg) { if(!!!DEBUG) return; var now = new Date(); switch (typeof arg) { case 'object': var str = ''; for (var k in arg) str += k + ': ' + arg[k] + '\n'; - sys.puts(now + ' ' + str); + logger.print(now + ' ' + str); break; default: - sys.puts(now + ' ' + arg); + logger.print(now + ' ' + arg); } + }, + print: function(str) { + sys.puts(str); } }; module.exports = logger; \ No newline at end of file diff --git a/lib/responder.js b/lib/responder.js index 236d030..5d48ad2 100644 --- a/lib/responder.js +++ b/lib/responder.js @@ -1,63 +1,65 @@ var fs = require('fs'), mime = require('./mime'), log = require('./logger').log; -module.exports = (function() { +var responder = (function() { function respond(res, body, contentType, status, encoding) { contentType = contentType || 'text/html'; body = body || ''; encoding = encoding || 'utf-8'; res.sendHeader(status || 200, { 'Content-Length': (encoding === 'utf-8') ? encodeURIComponent(body).replace(/%../g, 'x').length : body.length, 'Content-Type' : contentType + '; charset=' + encoding }); res.write(body, encoding); res.end(); } function redirect(res, location, encoding) { log('Redirecting - ' + location) encoding = encoding || 'utf-8' res.sendHeader(302, { 'Content-Type' : 'text/html; charset=' + encoding, 'Location' : location }); res.end(); } function respond404(res) { respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ log('Responding 500 - ' + error); respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } function serveFile(req, res, file) { var contentType = mime.lookup(file.substring(file.lastIndexOf('.'))); var encoding = (contentType.slice(0,4) === 'text') ? 'utf-8' : 'binary'; fs.readFile(file, encoding, function(error, data) { if(error) { log('Error serving file - ' + file); return respond404(res); } log('Serving file - ' + file); respond(res, data, contentType, 200, encoding); }); } return { respond: respond, redirect: redirect, respond404: respond404, respond500: respond500, serveFile: serveFile }; })(); + +module.exports = responder; \ No newline at end of file diff --git a/lib/router.js b/lib/router.js index 870970e..16f6779 100644 --- a/lib/router.js +++ b/lib/router.js @@ -1,51 +1,53 @@ var log = require('./logger').log; -module.exports = (function() { +var router = (function() { var compiledRoutes = {}; function init(routes) { if(!routes) { throw Error('You need to provide some routes.') } for(var path in routes) { var callback = routes[path]; var verb = 'GET'; var verbMatch = /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); if(verbMatch) { verb = verbMatch[1]; path = path.substring(verb.length); } compiledRoutes[path] = { verb: verb, regex: new RegExp(path.trim(), ''), callback: callback }; } } return { init : init, parse : function(url) { for(var path in compiledRoutes) { var route = compiledRoutes[path]; var matches = route.regex.exec(url); if(matches) { log('Route found! - ' + route.verb + ' - '+ url); return { groups: matches, method: route.verb, callback: route.callback }; } } - log('Route not found - ' + url); + log('Route not found for url - ' + url); return null; } }; -})(); \ No newline at end of file +})(); + +module.exports = router; \ No newline at end of file diff --git a/lib/template.js b/lib/template.js index 86bee11..1b80d6a 100644 --- a/lib/template.js +++ b/lib/template.js @@ -1,31 +1,30 @@ -require('../vendor/underscore'); - var fs = require('fs'), log = require('./logger').log; var TEMPLATES_DIR = './templates'; -module.exports = { +var template = { find: function(name) { return TEMPLATES_DIR + '/' + name + '.html'; }, - serve: function(res, name, scope, callback) { + serve: function(res, name, callback) { var template = this.find(name); log('Serving template - ' + template) fs.readFile(template, function(error, data) { if(error) { throw error; } try { - callback.call(this, _.template(data.toString(), scope)); + callback.call(this, data.toString()); } catch(error) { throw error; } }); } -}; \ No newline at end of file +}; +module.exports = template; \ No newline at end of file diff --git a/t.js b/t.js index 0245507..8b967e1 100644 --- a/t.js +++ b/t.js @@ -1,32 +1,36 @@ // tnode var sys = require('sys'), http = require('http'); var dispatcher = require('./lib/dispatcher'), responder = require('./lib/responder'); -exports.serve = responder.serveFile; -exports.app = function(conf) { +var tnode = { + serve : responder.serveFile, + app: function(conf) { - DEBUG = conf.debug || false; - var port = conf.port || 8888; + DEBUG = conf.debug || false; + var port = conf.port || 8888; - dispatcher.init(conf); + dispatcher.init(conf); - http.createServer(function(req, res) { - try { - dispatcher.process(req, res); - } - catch(e) { - responder.respond500(res, e); - } - }).listen(port); + http.createServer(function(req, res) { + try { + dispatcher.process(req, res); + } + catch(e) { + responder.respond500(res, e); + } + }).listen(port); - sys.puts('Starting server at http://127.0.0.1:' + port); + sys.puts('Starting server at http://127.0.0.1:' + port); - process.addListener('SIGINT', function() { - sys.puts('\nShutting down..'); - process.exit(0); - }); -}; \ No newline at end of file + process.addListener('SIGINT', function() { + sys.puts('\nShutting down..'); + process.exit(0); + }); + } +}; + +module.exports = tnode; \ No newline at end of file
torgeir/tnode
7e208ae0e0cbc5ad4025582e175e44dc341496c9
removed underscore stale import
diff --git a/lib/dispatcher.js b/lib/dispatcher.js index a58018f..bf40d06 100644 --- a/lib/dispatcher.js +++ b/lib/dispatcher.js @@ -1,64 +1,66 @@ +require('../vendor/underscore-min'); + var url = require('url'), fs = require('fs'), responder = require('./responder'), template = require('./template'), router = require('./router'), log = require('./logger').log, mime = require('./mime'); var dispatcher = { init : function(conf) { router.init(conf.routes); }, process : function(req, res) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping && (mapping.method == req.method || req.method == 'HEAD')) { var user = { scope: { respond: function(body, contentType, status) { responder.respond(res, body, contentType, status); }, redirect: function(location) { responder.redirect(res, location); }, respond404: function() { responder.respond404(res); }, respond500: function(error) { responder.respond500(res, error); }, partial: function (name, userScope) { return _.template(fs.readFileSync(template.find(name), 'utf-8'), userScope || user.scope); }, log: log } } var userArguments = [req, res].concat(mapping.groups.slice(1)); var retur = mapping.callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': template.serve(res, retur, user.scope, function(html) { responder.respond(res, html); }); break; case 'object': responder.respond(res, JSON.stringify(retur)); break; default: break; } } else { responder.respond404(res); } } }; module.exports = dispatcher; \ No newline at end of file diff --git a/t.js b/t.js index 8d04307..0245507 100644 --- a/t.js +++ b/t.js @@ -1,34 +1,32 @@ -// t library - -require('./vendor/underscore-min'); +// tnode var sys = require('sys'), http = require('http'); var dispatcher = require('./lib/dispatcher'), responder = require('./lib/responder'); exports.serve = responder.serveFile; exports.app = function(conf) { DEBUG = conf.debug || false; var port = conf.port || 8888; dispatcher.init(conf); http.createServer(function(req, res) { try { dispatcher.process(req, res); } catch(e) { responder.respond500(res, e); } }).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); }; \ No newline at end of file
torgeir/tnode
54d4b4e3d6cbc70e377803157ee898b726f47add
added http verb support in path
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js index 19170f6..23227b6 100644 --- a/examples/1/exampleapp.js +++ b/examples/1/exampleapp.js @@ -1,20 +1,20 @@ var t = require('../../t'); t.app({ debug: true, routes: { '^/$' : function(req, res) { this.respond(res, '<h1>Welcome!</h1><p>Try <a href="/hello/you">this</a>, or <a href="/page/1">this</a>!'); }, '^/hello/([a-z]+)/?' : function(req, res, name) { this.name = name; return 'index'; }, '^/page/([0-9]+)/?$' : function(req, res, page) { var json = { page: page }; return json; } } -}) \ No newline at end of file +}); \ No newline at end of file diff --git a/t.js b/t.js index fbd77ee..174108f 100644 --- a/t.js +++ b/t.js @@ -1,185 +1,212 @@ // t library require('./vendor/underscore-min'); var sys = require('sys'), http = require('http'), fs = require('fs'), url = require('url'), querystring = require("querystring"); var ENCODING = 'utf-8', TEMPLATES_DIR = './templates'; + exports.app = function(conf) { var DEBUG = conf.debug; function log(arg) { if(!!!DEBUG) return; switch (typeof arg) { case 'object': var str = ''; for (var k in arg) str += k + ': ' + arg[k] + '\n'; sys.puts(str); break; default: sys.puts(arg); } }; var router = (function() { - var compiledRoutes = (function(routes) { if(!routes) { throw Error('You need to provide some routes.') } var compiled = {}; for(var path in routes) { - compiled[path] = new RegExp(path, ''); + + var callback = routes[path]; + var verb = 'GET'; + var verbMatch = /^(GET|POST|PUT|DELETE|TRACE|CONNECT|HEAD|OPTIONS) .*/.exec(path); + if(verbMatch) { + verb = verbMatch[1]; + path = path.substring(verb.length); + } + + compiled[path] = { + verb: verb, + regex: new RegExp(path.trim(), ''), + callback: callback + }; } + return compiled; })(conf.routes); return { parse : function(url) { + for(var path in compiledRoutes) { - var matches = compiledRoutes[path].exec(url); + var route = compiledRoutes[path]; + + var matches = route.regex.exec(url); if(matches) { - log('Route found! - '+ url); + log('Route found! - ' + route.verb + ' - '+ url); return { - matches: matches, - callback: conf.routes[path] + groups: matches, + method: route.verb, + callback: route.callback }; } } log('Route not found - ' + url); return null; } }; })(); var templates = { - get: function(name) { + find: function(name) { return TEMPLATES_DIR + '/' + name + '.html'; }, serve: function(res, name, scope, callback) { - fs.readFile(this.get(name), function(error, data) { + fs.readFile(this.find(name), function(error, data) { if(error) { log('Template missing - ' + name + ' - ' + error); responder.respond500(res, error); } try { responder.respond(res, _.template(data.toString(), scope)); } catch(error) { responder.respond500(res, error); } }); } }; var responder = (function() { function respond(res, body, contentType, status) { contentType = contentType || 'text/html'; body = body || ''; res.sendHeader(status || 200, { 'Content-Length': body.length, 'Content-Type' : contentType + '; charset=' + ENCODING }); res.write(body, ENCODING); res.end(); } + + function redirect(res, location) { + res.sendHeader(302, { + 'Content-Type' : 'text/html; charset=' + ENCODING, + 'Location' : location + }); + res.end(); + } function respond404(res) { respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ if(DEBUG) log(error); respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } - + function handle(req, res, conf) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); - if (mapping) { + + if (mapping && mapping.method == req.method) { - var user = { - scope: { - respond: respond, - respond404: respond404, - respond500: respond500, - partial: function (name, scope) { - return _.template(fs.readFileSync(templates.get(name), ENCODING), scope || user.scope); - }, - log: log - } + var scope = { + respond: respond, + redirect: redirect, + respond404: respond404, + respond500: respond500, + partial: function (name, scope) { + return _.template(fs.readFileSync(templates.find(name), ENCODING), scope || user.scope); + }, + log: log }; - var userArguments = [req, res].concat(mapping.matches.slice(1)); - var retur = mapping.callback.apply(user.scope, userArguments); + var userArguments = [req, res].concat(mapping.groups.slice(1)); + var retur = mapping.callback.apply(scope, userArguments); + switch(typeof retur) { case 'string': - templates.serve(res, retur, user.scope); + templates.serve(res, retur, scope); break; case 'object': respond(res, JSON.stringify(retur)); break; default: break; } } else { respond404(res); } } return { respond: respond, respond404: respond404, respond500: respond500, handle: handle }; })(); var port = conf.port || 8888; http.createServer(function(req, res) { try { responder.handle(req, res, conf); } catch(e) { responder.respond500(res, e); } }).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); }; \ No newline at end of file
torgeir/tnode
e58b7f69d15d176efba2e2521e2381c0d314969b
added http verbs support in path along with example
diff --git a/examples/3/templates/form.html b/examples/3/templates/form.html new file mode 100644 index 0000000..8cf2a3d --- /dev/null +++ b/examples/3/templates/form.html @@ -0,0 +1,4 @@ +<form action="/ionlyhandleposts" method="post"> + <input type="submit" value="This works.."/> +</form> +<p><a href="/ionlyhandleposts">This</a>, on the other hand, does not work.</p> \ No newline at end of file diff --git a/examples/3/verbs.js b/examples/3/verbs.js new file mode 100644 index 0000000..4fbfd69 --- /dev/null +++ b/examples/3/verbs.js @@ -0,0 +1,13 @@ +var t = require('../../t'); + +t.app({ + debug: true, + routes: { + '^/$': function() { + return 'form'; + }, + 'POST /ionlyhandleposts': function(req, res) { + this.respond(res, 'POST is ok'); + } + } +}) \ No newline at end of file
torgeir/tnode
ba1f0e5a7c84de2cbbc48f72354f10beb049d4bc
added long polling example
diff --git a/examples/1/exampleapp.js b/examples/1/exampleapp.js new file mode 100644 index 0000000..19170f6 --- /dev/null +++ b/examples/1/exampleapp.js @@ -0,0 +1,20 @@ +var t = require('../../t'); + +t.app({ + debug: true, + routes: { + '^/$' : function(req, res) { + this.respond(res, '<h1>Welcome!</h1><p>Try <a href="/hello/you">this</a>, or <a href="/page/1">this</a>!'); + }, + '^/hello/([a-z]+)/?' : function(req, res, name) { + this.name = name; + return 'index'; + }, + '^/page/([0-9]+)/?$' : function(req, res, page) { + var json = { + page: page + }; + return json; + } + } +}) \ No newline at end of file diff --git a/examples/1/templates/hello.html b/examples/1/templates/hello.html new file mode 100644 index 0000000..1c1ba94 --- /dev/null +++ b/examples/1/templates/hello.html @@ -0,0 +1,2 @@ +<p>Welcome, <%= name %>! I come from a partial..</p> +<p>Did you know <%= now.getTime() %> seconds have passed since 1970?</p> \ No newline at end of file diff --git a/examples/templates/index.html b/examples/1/templates/index.html similarity index 100% rename from examples/templates/index.html rename to examples/1/templates/index.html diff --git a/examples/2/longpoll.js b/examples/2/longpoll.js new file mode 100644 index 0000000..1aac7f4 --- /dev/null +++ b/examples/2/longpoll.js @@ -0,0 +1,21 @@ +var t = require('../../t'), + events = require('events'); + +var bus = new events.EventEmitter(), + MESSAGE_EVENT = 'message_event'; + +t.app({ + debug: true, + routes: { + '^/wait$' : function(req, res) { + var self = this; + bus.addListener(MESSAGE_EVENT, function(msg) { + self.respond(res, msg); + }) + }, + '^/done/(.*)$' : function(req, res, msg) { + bus.emit(MESSAGE_EVENT, msg); + this.respond(res, 'done'); + } + } +}); \ No newline at end of file diff --git a/examples/exampleapp.js b/examples/exampleapp.js deleted file mode 100644 index f5c7f9b..0000000 --- a/examples/exampleapp.js +++ /dev/null @@ -1,20 +0,0 @@ -var t = require('../t'); - -t.app({ - debug: true, - routes: { - '^/$' : function(req, res) { - this.respond(res, 'Welcome! Try <a href="/hello/you">this</a>, or <a href="/page/1/">this</a>!'); - }, - '^/hello/([a-zA-Z]+)' : function(req, res, name) { - this.name = name; - return 'hello'; - }, - '^/page/([0-9]+)/?$' : function(req, res, page) { - var json = { - page: page - }; - return json; - } - } -}) \ No newline at end of file diff --git a/examples/templates/hello.html b/examples/templates/hello.html deleted file mode 100644 index 36e2a33..0000000 --- a/examples/templates/hello.html +++ /dev/null @@ -1,8 +0,0 @@ -<html> -<head> - <title>Hello!</title> -</head> -<body> - <p>Welcome, <%= name %></p> -</body> -</html> \ No newline at end of file diff --git a/t.js b/t.js index f5a069a..fbd77ee 100644 --- a/t.js +++ b/t.js @@ -1,176 +1,185 @@ // t library require('./vendor/underscore-min'); var sys = require('sys'), http = require('http'), fs = require('fs'), - url = require('url'); + url = require('url'), + querystring = require("querystring"); var ENCODING = 'utf-8', TEMPLATES_DIR = './templates'; exports.app = function(conf) { var DEBUG = conf.debug; function log(arg) { if(!!!DEBUG) return; switch (typeof arg) { case 'object': var str = ''; for (var k in arg) str += k + ': ' + arg[k] + '\n'; sys.puts(str); break; default: sys.puts(arg); } }; var router = (function() { var compiledRoutes = (function(routes) { if(!routes) { throw Error('You need to provide some routes.') } var compiled = {}; for(var path in routes) { compiled[path] = new RegExp(path, ''); } return compiled; })(conf.routes); return { parse : function(url) { for(var path in compiledRoutes) { var matches = compiledRoutes[path].exec(url); if(matches) { log('Route found! - '+ url); return { matches: matches, callback: conf.routes[path] }; } } log('Route not found - ' + url); return null; } }; })(); var templates = { - - serve: function(res, name, scope) { - - var file = name + '.html'; - fs.readFile(TEMPLATES_DIR + '/' + file, function(error, data) { + get: function(name) { + return TEMPLATES_DIR + '/' + name + '.html'; + }, + serve: function(res, name, scope, callback) { + fs.readFile(this.get(name), function(error, data) { if(error) { log('Template missing - ' + name + ' - ' + error); responder.respond500(res, error); } try { responder.respond(res, _.template(data.toString(), scope)); } catch(error) { responder.respond500(res, error); } }); } }; - var responder = (function() { + var responder = (function() { + function respond(res, body, contentType, status) { contentType = contentType || 'text/html'; body = body || ''; res.sendHeader(status || 200, { 'Content-Length': body.length, 'Content-Type' : contentType + '; charset=' + ENCODING }); res.write(body, ENCODING); res.end(); } function respond404(res) { respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ if(DEBUG) log(error); respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } function handle(req, res, conf) { var path = url.parse(req.url).pathname; var mapping = router.parse(path); if (mapping) { - var userScope = { - respond: respond, - respond404: respond404, - respond500: respond500, - log: log + var user = { + scope: { + respond: respond, + respond404: respond404, + respond500: respond500, + partial: function (name, scope) { + return _.template(fs.readFileSync(templates.get(name), ENCODING), scope || user.scope); + }, + log: log + } }; - - var userArguments = [req, res].concat(mapping.matches.slice(1)); - var retur = mapping.callback.apply(userScope, userArguments); + var userArguments = [req, res].concat(mapping.matches.slice(1)); + var retur = mapping.callback.apply(user.scope, userArguments); switch(typeof retur) { case 'string': - templates.serve(res, retur, userScope); + templates.serve(res, retur, user.scope); break; - default: + case 'object': respond(res, JSON.stringify(retur)); break; + default: + break; } + } else { respond404(res); } } return { respond: respond, respond404: respond404, respond500: respond500, handle: handle }; })(); var port = conf.port || 8888; http.createServer(function(req, res) { - + try { responder.handle(req, res, conf); } catch(e) { responder.respond500(res, e); } }).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); }; \ No newline at end of file
torgeir/tnode
06eb1df7f74ef03bf27847540976136bcfcaf152
added partials to templates.
diff --git a/examples/templates/index.html b/examples/templates/index.html new file mode 100644 index 0000000..0750f62 --- /dev/null +++ b/examples/templates/index.html @@ -0,0 +1,14 @@ +<html> +<head> + <title>Welcome to tnode, <%= name %>!</title> +</head> +<body> + <h1>Again, welcome!</h1> + <div> + <%= partial('hello', { + name: name, + now: new Date() + }) %> + </div> +</body> +</html> \ No newline at end of file
torgeir/tnode
2066702cf8b74eb5a6c40f1b33fe3a078f812189
refactoring
diff --git a/t.js b/t.js index 5069ada..f5a069a 100644 --- a/t.js +++ b/t.js @@ -1,148 +1,176 @@ // t library require('./vendor/underscore-min'); var sys = require('sys'), http = require('http'), - fs = require('fs'); + fs = require('fs'), + url = require('url'); -var DEBUG = false, - ENCODING = 'utf-8', +var ENCODING = 'utf-8', TEMPLATES_DIR = './templates'; - -process.addListener('SIGINT', function() { - sys.puts('\nShutting down..'); - process.exit(0); -}); - -function parse(routes, url) { - if(!routes) { - throw Error('You need to provide some routes.') - } - for(var path in routes) { - - var regex = new RegExp(path, ''), - matches = regex.exec(url); - if(matches) { - log('Route found! - '+ path); - - return { - matches: matches, - callback: routes[path] - }; - } - } +exports.app = function(conf) { - log('Route not found - ' + url); - return null; -} - -function respond(res, body, contentType, status) { - contentType = contentType || 'text/html'; - body = body || ''; - res.sendHeader(status || 200, { - 'Content-Length': body.length, - 'Content-Type' : contentType + '; charset=' + ENCODING - }); - writeResponseBody(res, body); - res.end(); -} + var DEBUG = conf.debug; + + function log(arg) { + if(!!!DEBUG) + return; + switch (typeof arg) { + case 'object': + var str = ''; + for (var k in arg) str += k + ': ' + arg[k] + '\n'; + sys.puts(str); -function writeResponseBody(res, body) { - res.write(body, ENCODING); -} + break; + default: + sys.puts(arg); + } + }; -function respond404(res) { - respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); -} -function respond500(res, error){ - if(DEBUG) - log(error); - - respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); -} - -function log(arg) { - if(!DEBUG) - return; - - switch (typeof arg) { - case 'object': - var str = ''; - for (var k in arg) { - str += k + ': ' + arg[k] + '\n'; + var router = (function() { + + var compiledRoutes = (function(routes) { + if(!routes) { + throw Error('You need to provide some routes.') } - sys.puts(str); - break; - default: - sys.puts(arg); - } -} - -function handleResponse(req, res, conf) { - var url = req.url; - var mapping = parse(conf.routes, url); - if (mapping) { - - var scope = { - respond: respond, - log: log + var compiled = {}; + for(var path in routes) { + compiled[path] = new RegExp(path, ''); + } + return compiled; + })(conf.routes); + + return { + parse : function(url) { + for(var path in compiledRoutes) { + var matches = compiledRoutes[path].exec(url); + if(matches) { + + log('Route found! - '+ url); + return { + matches: matches, + callback: conf.routes[path] + }; + } + } + + log('Route not found - ' + url); + return null; + } }; - var args = [req, res].concat(mapping.matches.slice(1)); - var retur = mapping.callback.apply(scope, args); - switch(typeof retur) { - case 'string': + + })(); + + var templates = { + + serve: function(res, name, scope) { - var templateName = retur + '.html', - template = TEMPLATES_DIR + '/' + templateName; - - fs.readFile(template, function(err, data) { - - if(err) { - log('Template missing - ' + retur + ' - ' + err); - respond500(res, err); - } - - try { - respond(res, _.template(data.toString(), scope)); - } - catch(err) { - respond500(res, err); - } - - }); + var file = name + '.html'; + fs.readFile(TEMPLATES_DIR + '/' + file, function(error, data) { + + if(error) { + log('Template missing - ' + name + ' - ' + error); + responder.respond500(res, error); + } + + try { + responder.respond(res, _.template(data.toString(), scope)); + } + catch(error) { + responder.respond500(res, error); + } + + }); + } + }; + + var responder = (function() { + + function respond(res, body, contentType, status) { + contentType = contentType || 'text/html'; + body = body || ''; + res.sendHeader(status || 200, { + 'Content-Length': body.length, + 'Content-Type' : contentType + '; charset=' + ENCODING + }); + res.write(body, ENCODING); + res.end(); + } + + function respond404(res) { + respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); + } + + function respond500(res, error){ + if(DEBUG) + log(error); + + respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); + } + + function handle(req, res, conf) { + + var path = url.parse(req.url).pathname; + var mapping = router.parse(path); + if (mapping) { - break; - default: - respond(res, JSON.stringify(retur)); - break; + var userScope = { + respond: respond, + respond404: respond404, + respond500: respond500, + log: log + }; + + var userArguments = [req, res].concat(mapping.matches.slice(1)); + var retur = mapping.callback.apply(userScope, userArguments); + + switch(typeof retur) { + case 'string': + templates.serve(res, retur, userScope); + break; + default: + respond(res, JSON.stringify(retur)); + break; + } + } + else { + respond404(res); + } } - } - else { - respond404(res); - } -} -exports.app = function(conf){ + return { + respond: respond, + respond404: respond404, + respond500: respond500, + handle: handle + }; + + })(); - DEBUG = conf.debug || DEBUG; var port = conf.port || 8888; http.createServer(function(req, res) { try { - handleResponse(req, res, conf); + responder.handle(req, res, conf); } catch(e) { - respond500(res, e); + responder.respond500(res, e); } }).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); -} + + process.addListener('SIGINT', function() { + sys.puts('\nShutting down..'); + process.exit(0); + }); + +}; \ No newline at end of file
torgeir/tnode
92d808b4d941810f44ac5bda5ffe209903884dd5
added templates to example
diff --git a/examples/templates/hello.html b/examples/templates/hello.html new file mode 100644 index 0000000..36e2a33 --- /dev/null +++ b/examples/templates/hello.html @@ -0,0 +1,8 @@ +<html> +<head> + <title>Hello!</title> +</head> +<body> + <p>Welcome, <%= name %></p> +</body> +</html> \ No newline at end of file diff --git a/t.js b/t.js index ba147df..5069ada 100644 --- a/t.js +++ b/t.js @@ -1,148 +1,148 @@ // t library require('./vendor/underscore-min'); var sys = require('sys'), http = require('http'), fs = require('fs'); var DEBUG = false, ENCODING = 'utf-8', TEMPLATES_DIR = './templates'; process.addListener('SIGINT', function() { sys.puts('\nShutting down..'); process.exit(0); }); function parse(routes, url) { if(!routes) { throw Error('You need to provide some routes.') } for(var path in routes) { var regex = new RegExp(path, ''), matches = regex.exec(url); if(matches) { log('Route found! - '+ path); return { matches: matches, callback: routes[path] }; } } log('Route not found - ' + url); return null; } function respond(res, body, contentType, status) { contentType = contentType || 'text/html'; body = body || ''; res.sendHeader(status || 200, { 'Content-Length': body.length, 'Content-Type' : contentType + '; charset=' + ENCODING }); writeResponseBody(res, body); res.end(); } function writeResponseBody(res, body) { res.write(body, ENCODING); } function respond404(res) { respond(res,'<h1>404 Not Found</h1>', 'text/html', 404); } function respond500(res, error){ if(DEBUG) log(error); respond(res, '<h1>500 Internal Server Error</h1>', 'text/html', 500); } function log(arg) { if(!DEBUG) return; switch (typeof arg) { case 'object': var str = ''; for (var k in arg) { str += k + ': ' + arg[k] + '\n'; } sys.puts(str); break; default: sys.puts(arg); } } function handleResponse(req, res, conf) { var url = req.url; var mapping = parse(conf.routes, url); if (mapping) { var scope = { respond: respond, log: log }; var args = [req, res].concat(mapping.matches.slice(1)); var retur = mapping.callback.apply(scope, args); switch(typeof retur) { case 'string': var templateName = retur + '.html', template = TEMPLATES_DIR + '/' + templateName; fs.readFile(template, function(err, data) { if(err) { log('Template missing - ' + retur + ' - ' + err); respond500(res, err); } try { - respond(res, _.template(data, scope)); + respond(res, _.template(data.toString(), scope)); } catch(err) { respond500(res, err); } }); break; default: respond(res, JSON.stringify(retur)); break; } } else { respond404(res); } } exports.app = function(conf){ DEBUG = conf.debug || DEBUG; var port = conf.port || 8888; http.createServer(function(req, res) { try { handleResponse(req, res, conf); } catch(e) { respond500(res, e); } }).listen(port); sys.puts('Starting server at http://127.0.0.1:' + port); }
torgeir/tnode
79cf8d13f575d6a76be8eeea234bd15f91b5e5da
added example app
diff --git a/examples/exampleapp.js b/examples/exampleapp.js new file mode 100644 index 0000000..f5c7f9b --- /dev/null +++ b/examples/exampleapp.js @@ -0,0 +1,20 @@ +var t = require('../t'); + +t.app({ + debug: true, + routes: { + '^/$' : function(req, res) { + this.respond(res, 'Welcome! Try <a href="/hello/you">this</a>, or <a href="/page/1/">this</a>!'); + }, + '^/hello/([a-zA-Z]+)' : function(req, res, name) { + this.name = name; + return 'hello'; + }, + '^/page/([0-9]+)/?$' : function(req, res, page) { + var json = { + page: page + }; + return json; + } + } +}) \ No newline at end of file
torgeir/tnode
63f017a2706e7af2c2cfb4fd03b6730934035cc4
added example app
diff --git a/examples/tnodeapp/.DS_Store b/examples/tnodeapp/.DS_Store new file mode 100644 index 0000000..2d13c08 Binary files /dev/null and b/examples/tnodeapp/.DS_Store differ diff --git a/examples/tnodeapp/exampleapp.js b/examples/tnodeapp/exampleapp.js new file mode 100644 index 0000000..679bf0b --- /dev/null +++ b/examples/tnodeapp/exampleapp.js @@ -0,0 +1,20 @@ +var t = require('../../t'); + +t.app({ + debug: true, + routes: { + '^/$' : function(req, res) { + this.respond(res, 'Welcome! Try <a href="/hello/you">this</a>, or <a href="/page/1/">this</a>!'); + }, + '^/hello/([a-zA-Z]+)' : function(req, res, name) { + this.name = name; + return 'hello'; + }, + '^/page/([0-9]+)/?$' : function(req, res, page) { + var json = { + page: page + }; + return json; + } + } +}) \ No newline at end of file diff --git a/examples/tnodeapp/templates/.tmp_test.html.33556~ b/examples/tnodeapp/templates/.tmp_test.html.33556~ new file mode 100644 index 0000000..e69de29 diff --git a/examples/tnodeapp/templates/hello.html b/examples/tnodeapp/templates/hello.html new file mode 100644 index 0000000..a2d51f5 --- /dev/null +++ b/examples/tnodeapp/templates/hello.html @@ -0,0 +1,9 @@ +<html> + <head> + <title>Welome!</title> + </head> + <body> + <h1>Hello!</h1> + <p>And welcome, <%= name %>!</p> + </body> +</html> \ No newline at end of file
itszero/eLib2
fed5f9c81598e6269ee856fd6220cf9967f68e68
book suggest support and blog comments
diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb index 293ee89..6316904 100644 --- a/app/controllers/books_controller.rb +++ b/app/controllers/books_controller.rb @@ -1,126 +1,149 @@ class BooksController < ApplicationController layout 'service' before_filter :admin_required, :except => [:index, :show, :latest_xml, :search] def index end def latest_xml @books = Book.find(:all, :order => "created_at DESC", :limit => 20) render :layout => false end def circulation @in_admin_function = true end def admin @in_admin_function = true if params[:filter] @books = Book.filter(params[:filter]).paginate :page => params[:page] else @books = Book.paginate :page => params[:page] end end def new @in_admin_function = true if request.post? @b = Book.new(params[:book]) if @b.save notice_stickie "館藏 #{params[:book][:title]} 新增成功!" else error_stickie '館藏無法新增,請檢查資料。 #{@b.errors.inspect}' end redirect_to :action => 'admin' end @b = Book.new end def edit @in_admin_function = true if request.post? @b = Book.find(params[:id]) @b.update_attributes params[:book] @b.save redirect_to :action => 'admin' return end @is_edit = true @b = Book.find(params[:id]) if !@b redirect_to :action => 'admin' return end render :action => 'new' end def delete Book.find(params[:id]).destroy redirect_to :action => 'admin' end def show @in_books_function = true @b = Book.find(params[:id]) end def get_book_status_by_isbn @b = Book.find_by_isbn(params[:isbn]) if !@b render :text => 'fail:isbn' return end if @b.rentout? render :text => 'fail:rent' return end render :text => @b.title end def rent_book @b = Book.find_by_isbn(params[:isbn]) if !@b render :text => 'fail' return end @u = User.find_by_student_id(params[:stuid]) if !@u render :text => 'fail' return end @b.rent_to(@u) render :text => 'ok' end def return_book @b = Book.find_by_isbn(params[:isbn]) @b.return_book render :text => 'ok' end def overdue @r = RentLog.find(:all, :conditions => ['start_date <= ? AND end_date IS NULL', 1.week.ago]) end def search @in_books_function = true @books = Book.filter(params[:keyword]).paginate :page => params[:page], :per_page => 10 end + + def suggests + if params[:do] + case params[:do] + when "accept" then + Suggest.find(params[:id]).accept! + notice_stickie "圖書推薦已經同意。" + when "reject" then + Suggest.find(params[:id]).reject! + warning_stickie "圖書推薦退件完成。" + when "reset" then + Suggest.find(params[:id]).reset! + notice_stickie "圖書推薦重新設定為審查中。" + when "delete" then + Suggest.find(params[:id]).destroy + notice_stickie "圖書推薦資料已經刪除。" + end + + redirect_to :back + end + + @suggests = Suggest.find(:all, :order => 'created_at DESC').paginate :page => params[:page], :per_page => 20 + end end diff --git a/app/controllers/news_controller.rb b/app/controllers/news_controller.rb index 5fd1f66..62eb108 100644 --- a/app/controllers/news_controller.rb +++ b/app/controllers/news_controller.rb @@ -1,55 +1,75 @@ class NewsController < ApplicationController layout 'service' - before_filter :admin_required, :except => [:index, :show] + before_filter :admin_required, :except => [:index, :show, :write_comment] + before_filter :login_required, :only => [:write_comment] def index @in_reader_function = true @news = Blog.find(:all, :order => "created_at DESC") end def admin @in_admin_function = true if !params[:id] @news = Blog.paginate :page => params[:page], :order => 'created_at DESC' else @n = Blog.find(params[:id]) render :partial => 'news_list_item' end end def show @in_reader_function = true @news = Blog.find(params[:id]) warning_stickie "找不到您指定的新聞。" if !@news redirect_to '/news' if !@news end def new @news = Blog.new @news.title = params[:title] @news.content = params[:content] @news.save redirect_to :action => 'admin' end def delete Blog.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? @news = Blog.find(params[:id]) @news.title = params[:title] @news.content = params[:content] @news.created_at = params[:date] @news.save redirect_to '/news/admin' else @news = Blog.find(params[:id]) render :layout => false end end + + def write_comment + comment = Comment.new + comment.comment = params[:comment] + comment.user_id = current_user.id + comment.save + @news = Blog.find(params[:id]) + @news.comments << comment + + notice_stickie "您的意見已經張貼完成。" + redirect_to :back + end + + def delete_comment + Comment.find(params[:id]).destroy + + warning_stickie "留言已經刪除。" + redirect_to :back + end end \ No newline at end of file diff --git a/app/controllers/reader_controller.rb b/app/controllers/reader_controller.rb index eae762d..3402042 100644 --- a/app/controllers/reader_controller.rb +++ b/app/controllers/reader_controller.rb @@ -1,114 +1,127 @@ class ReaderController < ApplicationController before_filter :admin_required, :only => [:rate, :admin] before_filter :login_required, :except => [:rate, :admin] layout 'service' def index @in_reader_function = true @u = current_user @r = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id], :limit => 5, :order => 'created_at DESC') - @c = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC') + @c = Comment.find(:all, :conditions => ['user_id = ? and commentable_type = ?', @current_user.id, "Book"], :order => 'created_at DESC') + @suggests = Suggest.find(:all, :order => "created_at DESC", :limit => 15) end def rentlogs @r = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC').paginate :page => params[:page] end def list @c = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC').paginate :page => params[:page] end def admin @c = Comment if params[:isbn] && params[:isbn] != '' @b = Book.find_by_isbn(params[:isbn]) if @b @c = @c.book_is(@b.id) else warning_stickie "找不到指定的ISBN號碼。" params[:isbn] = nil end end if params[:sid] && params[:sid] != '' @u = User.find_by_student_id(params[:sid]) if @u @c = @c.user_is(@u.id) else warning_stickie "找不到指定的學號。" params[:sid] = nil end end @c1 = @c.find(:all, :order => 'created_at DESC', :conditions => 'score IS NULL') @c2 = @c.find(:all, :order => 'created_at DESC', :conditions => 'score IS NOT NULL') @c = (@c1 + @c2).paginate :page => params[:page] end def write @book = Book.find(params[:id]) if request.post? @comment = Comment.new @comment.comment = params[:content] @comment.user_id = @current_user.id @book.comments << @comment notice_stickie '心得已經儲存成功囉。' redirect_to "/reader/read/#{@comment.id}" return end end def read @comment = Comment.find(params[:id]) if @comment.user_id != @current_user.id && @current_user.permission < 1 redirect_to '/reader' return end @book = @comment.commentable end def load_text render :text => Comment.find(params[:id]).comment end def edit @comment = Comment.find(params[:id]) if @comment.user_id != @current_user.id && @current_user.permission < 1 redirect_to '/reader' return end @comment.comment = params[:value] @comment.save render :nothing => true end def delete @comment = Comment.find(params[:id]) if @comment.user_id != @current_user.id && @current_user.permission < 1 redirect_to '/reader' return end @comment.destroy notice_stickie "您的心得已經刪除。" redirect_to '/reader' end def rate @comment = Comment.find(params[:id]) if @current_user.permission < 1 redirect_to '/reader' return end notice_stickie "給分成功!" @comment.score = params[:score] @comment.save redirect_to "/reader/read/#{@comment.id}" end + + def suggest + @in_reader_function = true + + if request.post? + @suggest = Suggest.new(params[:suggest]) + @suggest.save + + notice_stickie "書籍推薦送出,請耐心等候審查。" + redirect_to :action => :index + end + end end diff --git a/app/models/blog.rb b/app/models/blog.rb index c5569eb..efab7f9 100644 --- a/app/models/blog.rb +++ b/app/models/blog.rb @@ -1,15 +1,16 @@ # == Schema Information # Schema version: 20080926035923 # # Table name: blogs # # id :integer not null, primary key # title :string(255) # content :string(255) # user_id :integer # created_at :datetime # updated_at :datetime # class Blog < ActiveRecord::Base + acts_as_commentable end diff --git a/app/models/suggest.rb b/app/models/suggest.rb new file mode 100644 index 0000000..80ebd2d --- /dev/null +++ b/app/models/suggest.rb @@ -0,0 +1,23 @@ +class Suggest < ActiveRecord::Base + belongs_to :user + acts_as_state_machine :initial => :wait + + state :wait + state :accept + state :reject + + event :accept do + transitions :from => :wait, :to => :accept + transitions :from => :reject, :to => :accept + end + + event :reject do + transitions :from => :wait, :to => :reject + transitions :from => :accept, :to => :reject + end + + event :reset do + transitions :from => :accept, :to => :wait + transitions :from => :reject, :to => :wait + end +end diff --git a/app/views/books/suggests.html.erb b/app/views/books/suggests.html.erb new file mode 100644 index 0000000..153a1b6 --- /dev/null +++ b/app/views/books/suggests.html.erb @@ -0,0 +1,36 @@ +<h1>圖書推薦</h1> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a> +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-6">書名</div> + <div class="span-5">出版社</div> + <div class="span-5">作者</div> + <div class="span-3">狀態</div> + <div class="span-4 last">行動</div> + </div> + </div> + +<% @suggests.each do |s| %> + <div class="tbody"> + <div class="container"> + <div class="span-6"><%=s.title%></div> + <div class="span-5"><%=s.publisher%></div> + <div class="span-5"><%=s.author%></div> + <div class="span-3"><%if s.accept? %><span color="color: green;">通過<%elsif s.reject?%><span style="color: red;">退回</span><%else%><span>審查中</span><%end%></div> + <div class="span-4 last"> + <p class="clearfix"><a href="/books/suggests/<%=s.id%>?do=accept" class="button alt star" style="margin-right: 10px;" onclick="this.blur();" id="btn-pass<%=s.id%>"><span><span>同意</span></span></a><a href="/books/suggests/<%=s.id%>?do=reject" class="button pink minus"><span><span>退件</span></span></a></p> + </div> + </div> + <div class="container"> + <div class="span-3">原因:</div> + <div class="span-16"><%=s.reason%></div> + <div class="span-4 last"> + <p class="clearfix"><a href="/books/suggests/<%=s.id%>?do=reset" class="button normal back" style="margin-right: 10px;" onclick="this.blur();" id="btn-pass<%=s.id%>"><span><span>重設</span></span></a><a href="/books/suggests/<%=s.id%>?do=delete" class="button dark x"><span><span>刪除</span></span></a></p> + </div> + </div> + </div> +<% end %> +</div> + +<%=will_paginate @suggests, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> diff --git a/app/views/news/index.html.erb b/app/views/news/index.html.erb index 045e591..b0bc268 100644 --- a/app/views/news/index.html.erb +++ b/app/views/news/index.html.erb @@ -1,38 +1,38 @@ <!-- YUI css --> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/calendar/assets/skins/sam/calendar.css"> <!-- YUI js --> <script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/calendar/calendar-min.js"></script> <h1>圖書館部落格</h1> <div class="container"> <div class="span-8"> <div id="sidebar"> <h1>月曆</h1> <div id="calendar_panel" class="blog_panel yui-skin-sam"> <div id="cal1Container"></div> <span class="clear"></span> </div> <div id="metal_holder">&nbsp;</div> </div> </div> <div class="span-15 last"> <% @news.each do |news| %> <p class="blog-date"><%=news.created_at.strftime("%Yå¹´%m月%d日")%></p> <p class="blog-title"><%=news.title%></p> - <p class="blog-content"><%=news.content.gsub("\n", "<br/>")%></p> + <p class="blog-content"><%=news.content.gsub("\n", "<br/>")%><br/><%=link_to "發表意見(#{news.comments.size})...", :action => :show, :id => news%></p> <% end %> </div> </div> <script type="text/javascript" charset="utf-8"> var cal1 = new YAHOO.widget.Calendar("cal1Container"); cal1.cfg.setProperty("DATE_FIELD_DELIMITER", "."); cal1.cfg.setProperty("navigator", true); cal1.cfg.setProperty("MONTHS_SHORT", ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]); cal1.cfg.setProperty("MONTHS_LONG", ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]); cal1.cfg.setProperty("WEEKDAYS_1CHAR", ["S", "M", "D", "M", "D", "F", "S"]); cal1.cfg.setProperty("WEEKDAYS_SHORT", ["日", "一", "二", "三", "四", "五", "六"]); cal1.cfg.setProperty("WEEKDAYS_MEDIUM",["週日", "週一", "週二", "週三", "週四", "週五", "週六"]); cal1.cfg.setProperty("WEEKDAYS_LONG", ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]); cal1.render(); </script> \ No newline at end of file diff --git a/app/views/news/show.html.erb b/app/views/news/show.html.erb index 0c27fb6..fe33e02 100644 --- a/app/views/news/show.html.erb +++ b/app/views/news/show.html.erb @@ -1,14 +1,34 @@ <!-- YUI css --> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/calendar/assets/skins/sam/calendar.css"> <!-- YUI js --> <script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/calendar/calendar-min.js"></script> <h1>圖書館部落格</h1> <div class="container"> <div class="span-23 last"> <a href="/news">&larr; 回圖書館部落格</a> <p class="blog-date"><%[email protected]_at.strftime("%Yå¹´%m月%d日")%></p> <p class="blog-title"><%[email protected]%></p> <p class="blog-content"><%[email protected]("\n", "<br/>")%></p> </div> </div> +<% if @news.comments.size > 0 %> +<hr/> +<h3>意見</h3> +<% i = 1 + @news.comments.each do |c| %> +<p style="margin-left: 2em;"><%=c.comment%></p> +<p><%=i%>. 由 <%=c.user.name%> 於 <%=c.created_at.strftime("%Y-%m-%d %H:%M")%> 發表 <% if current_user.permission > 1 %>| <%=link_to '刪除', {:action => 'delete_comment', :id => c.id}, :confirm => "您確定要刪除這則留言嗎?"%><%end%></p> +<hr/> +<% i += 1 + end %> +<% end %> +<% if logged_in? %> +<form action="<%=url_for :action => :write_comment%>" method="post" accept-charset="utf-8"> +<h3>發表意見</h3> + <p>意見<br/><textarea name="comment" rows="8" cols="40"></textarea></p> + <p><input type="submit" value="送出 &rarr;"></p> + <input type="hidden" name="id" value="<%[email protected]%>" id="id"> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> +</form> +<% end %> diff --git a/app/views/reader/index.html.erb b/app/views/reader/index.html.erb index 31ed7c4..c137a38 100644 --- a/app/views/reader/index.html.erb +++ b/app/views/reader/index.html.erb @@ -1,59 +1,83 @@ <h1>讀者服務與資訊</h1> <h2>您的個人資料</h2> <div style="font-size: 1.2em; border-top: 1px solid #000;"> 以下個人資料若有疑問,請向我們聯絡。以免您的借閱權利受到損害。<br/> 登入帳號:<%[email protected]%><br/> 學生證號:<%[email protected]_id%><br/> 班級:<%[email protected]_class%><br/> 姓名:<%[email protected]%><br/> E-mail:<%[email protected]%><br/> </div> <br/> <h2>您最近的借閱記錄</h2> <div id="book-list" class="table"> <div class="thead"> <div class="container"> <div class="span-10">書名</div> <div class="span-4">ISBN</div> <div class="span-4">借出日期</div> <div class="span-4">歸還日期</div> </div> </div> <% @r.each do |r| %> <div class="tbody"> <div class="container"> <div class="span-10"><%=r.book.title%></div> <div class="span-4"><%=r.book.isbn%></div> <div class="span-4 last"><%=r.start_date.strftime("%Y/%m/%d")%></div> <div class="span-4 last"><%if r.end_date%><%=r.end_date.strftime("%Y/%m/%d")%><%else%><span style="color: red;">尚未歸還</span><%end%></div> </div> </div> <% end %> </div> <a href="/reader/rentlogs">更多紀錄...</a> <br/> <br/> <h2>您撰寫過的讀書心得</h2> <div id="book-list" class="table"> <div class="thead"> <div class="container"> <div class="span-7">書名</div> <div class="span-9">內容</div> <div class="span-4">撰寫日期</div> <div class="span-3">分數</div> </div> </div> <% @c.each do |c| %> <div class="tbody"> <div class="container"> <div class="span-7"><%=c.commentable.title%></div> <div class="span-9"><%=c.comment.chars[0..10]%>... (<a href="/reader/read/<%=c.id%>">完整內容</a>)</div> <div class="span-4"><%=c.created_at.strftime("%Y/%m/%d")%></div> <div class="span-3 last"><%if c.score%><%=c.score%><%else%><span style="color: red;">尚未評分</span><%end%></div> </div> </div> <% end %> </div> <a href="/reader/list">更多紀錄...</a> +<br/> +<br/> +<h2>您的書籍推薦記錄</h2> +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-7">書名</div> + <div class="span-9">作者/出版社</div> + <div class="span-4">推薦日期</div> + <div class="span-3">狀態</div> + </div> + </div> + <% @suggests.each do |s| %> + <div class="tbody"> + <div class="container"> + <div class="span-7"><%=s.title%></div> + <div class="span-9"><%=s.author%> / <%=s.publisher%></div> + <div class="span-4"><%=s.created_at.strftime("%Y/%m/%d")%></div> + <div class="span-3 last"><%if s.accept? %><span color="color: green;">通過<%elsif s.reject?%><span style="color: red;">退回</span><%else%><span>審查中</span><%end%></div> + </div> + </div> + <% end %> +</div> +<a href="/reader/suggest">推薦書籍...</a> \ No newline at end of file diff --git a/app/views/reader/suggest.html.erb b/app/views/reader/suggest.html.erb new file mode 100644 index 0000000..fba4298 --- /dev/null +++ b/app/views/reader/suggest.html.erb @@ -0,0 +1,13 @@ +<h1>推薦書籍</h1> +<p class="clearfix"><a href="/reader" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a></p> +<p>歡迎使用本系統推薦圖書館目前尚沒有但是您認為值得收藏的書籍,請寫下列表單即可送出推薦。</p> +<form action="<%=url_for :action => :suggest%>" method="post" accept-charset="utf-8"> + <p>書名<br/><input type="text" name="suggest[title]" value="" id="suggest[title]"></p> + <p>作者<br/><input type="text" name="suggest[author]" value="" id="suggest[author]"></p> + <p>出版社<br/><input type="text" name="suggest[publisher]" value="" id="suggest[publisher]"></p> + <p>相關網址<br/><input type="text" name="suggest[url]" value="" id="suggest[url]"></p> + <p>理由及相關資訊<br/><textarea name="suggest[reason]" rows="8" cols="40"></textarea></p> + + <p><input type="submit" value="推薦 &rarr;"></p> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> +</form> \ No newline at end of file diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb index f90a975..f5e3f76 100644 --- a/app/views/welcome/admin.html.erb +++ b/app/views/welcome/admin.html.erb @@ -1,36 +1,37 @@ <div class="bkgwhite"> <div class="container"> <div class="span-11"> <p class="admin-title">圖書管理</p> <div class="admin-menu"> <a href="/books/admin">搜尋/維護館藏<span class="arrow">&raquo;</span></a> <a href="/books/new">新增館藏<span class="arrow">&raquo;</span></a> + <a href="/books/suggests">圖書建議<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">館藏流通</p> <div class="admin-menu"> <a href="/books/circulation">借閱/還書介面<span class="arrow">&raquo;</span></a> <a href="/books/overdue">列出逾期館藏<span class="arrow">&raquo;</span></a> </div> </div> </div> <div class="container" style="margin-top: 10px;"> <div class="span-11"> <p class="admin-title">讀者資料</p> <div class="admin-menu"> <a href="/users/admin">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> <a href="/users/bulk_add">大批新增讀者<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">公告及其他</p> <div class="admin-menu"> <a href="/news/admin">公告管理<span class="arrow">&raquo;</span></a> <a href="/users/staff">工作人員權限管理<span class="arrow">&raquo;</span></a> <a href="/reader/admin">讀書心得管理<span class="arrow">&raquo;</span></a> </div> </div> </div> </div> \ No newline at end of file diff --git a/db/migrate/20081114181618_create_book_suggest.rb b/db/migrate/20081114181618_create_book_suggest.rb new file mode 100644 index 0000000..56e597d --- /dev/null +++ b/db/migrate/20081114181618_create_book_suggest.rb @@ -0,0 +1,18 @@ +class CreateBookSuggest < ActiveRecord::Migration + def self.up + create_table :suggests do |t| + t.column :title, :string + t.column :author, :string + t.column :publisher, :string + t.column :reason, :string + t.column :url, :string + t.column :state, :string + t.column :user_id, :string + t.timestamps + end + end + + def self.down + drop_table :suggests + end +end diff --git a/db/schema.rb b/db/schema.rb index 8d61192..e26f64e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,77 +1,89 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20080930191254) do +ActiveRecord::Schema.define(:version => 20081114181618) do create_table "blogs", :force => true do |t| t.string "title" t.string "content" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "books", :force => true do |t| t.string "cover" t.string "author" t.string "title" t.string "publisher" t.string "published_at" t.text "content" t.text "toc" t.text "problems" t.string "state" t.text "note", :limit => 255 t.string "isbn" t.datetime "created_at" t.datetime "updated_at" end create_table "comments", :force => true do |t| t.string "title", :limit => 50, :default => "" t.text "comment", :default => "" t.datetime "created_at", :null => false t.integer "commentable_id", :default => 0, :null => false t.string "commentable_type", :limit => 15, :default => "", :null => false t.integer "user_id", :default => 0, :null => false t.integer "score" end add_index "comments", ["user_id"], :name => "fk_comments_user" create_table "rent_logs", :force => true do |t| t.integer "book_id" t.integer "user_id" t.datetime "start_date" t.datetime "end_date" t.datetime "created_at" t.datetime "updated_at" end + create_table "suggests", :force => true do |t| + t.string "title" + t.string "author" + t.string "publisher" + t.string "reason" + t.string "url" + t.string "state" + t.string "user_id" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" t.string "student_class" t.string "student_id" t.string "nickname" t.integer "permission" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end diff --git a/test/fixtures/suggests.yml b/test/fixtures/suggests.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/suggests.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/unit/suggest_test.rb b/test/unit/suggest_test.rb new file mode 100644 index 0000000..90ac276 --- /dev/null +++ b/test/unit/suggest_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class SuggestTest < ActiveSupport::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end
itszero/eLib2
24c9b9f74ec5cd6d2eddf504010455e5652b1ef6
add contact support
diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb index 7c100c0..619be56 100644 --- a/app/controllers/welcome_controller.rb +++ b/app/controllers/welcome_controller.rb @@ -1,32 +1,49 @@ class WelcomeController < ApplicationController layout 'service' before_filter :admin_required, :only => :admin def index @in_homepage_function = true @news = Blog.find(:all, :order => "created_at DESC", :limit => 5) if !@current_user @random_books = [] maxid = Book.find(:first, :order => "id DESC") if maxid != nil maxid = maxid.id until @random_books.size >= 6 b = nil suppress(ActiveRecord::RecordNotFound) do b = Book.find(rand(maxid) + 1) end @random_books << b if b && !@random_books.include?(b) end end else @rentlog_size = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id]).size @needreturn_size = RentLog.find(:all, :conditions => ['start_date > ? AND start_date < ?', 1.weeks.ago, 2.weeks.ago]).size @comments_size = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id]).size end end def admin @in_admin_function = true end + + def books + @books = Book.find(:all, :order => "created_at DESC", :limit => 20) + headers["Content-Type"] = "application/xml; charset=utf-8" + render :layout => false + end + + def contact + if request.post? + if params[:name] != "" && params[:phone] != "" && params[:email] != "" && params[:content] != "" + Notifier.deliver_contact params[:name], params[:email], params[:phone], params[:content] + notice_stickie "您的意見我們已經收到了,我們會儘快改善並且與您聯絡。" + else + error_stickie "請先填滿所有資訊再送出。" + end + end + end end diff --git a/app/models/notifier.rb b/app/models/notifier.rb new file mode 100644 index 0000000..d3dc5f6 --- /dev/null +++ b/app/models/notifier.rb @@ -0,0 +1,9 @@ +class Notifier < ActionMailer::Base + def contact(name, email, phone, content) + recipients LIBRARY_CONTACT_EMAIL + from email + subject "讀者聯絡 #{name}" + content_type "text/plain" + body :content => content, :name => name, :phone => phone + end +end diff --git a/app/views/books/latest_xml.rxml b/app/views/books/latest_xml.rxml index 4116865..547cc9d 100644 --- a/app/views/books/latest_xml.rxml +++ b/app/views/books/latest_xml.rxml @@ -1,13 +1,13 @@ xml.instruct! xml.coverflowinfo do @books.each do |b| xml.bookinfo do - xml.cover url_for_file_column b, 'cover' + xml.cover url_for_file_column(b, 'cover') xml.bookname b.title xml.author b.author xml.authorLink "" xml.bookLink "/books/show/#{b.id}" end end end \ No newline at end of file diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index de4fc37..f5ed686 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,65 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> + <title>eLib^2 - Your personal library</title> + <% if params[:controller] == 'welcome' && params[:action] == 'index' %> + <link rel="alternate" type="application/rss+xml" title="eLib^2 最新上架書籍" href="<%=url_for(:only_path => false, :controller => 'welcome', :action => 'books')%>"> + <% end %> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png" alt="Site Logo"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> <li <%='class="menu-current"' if @in_books_function%>><a href="/books/search">搜尋書籍</a></li> <li <%='class="menu-current"' if @in_reader_function%>><a href="/reader">讀者服務</a></li> - <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> + <li <%='class="menu-current"' if @in_contact_function%>><a href="/welcome/contact">聯絡我們</a></li> <% if @current_user && @current_user.permission > 0%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> <a href="/logout"><img src="/images/img_power.png" width="20" height="20" alt="logout">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> <% else %> <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" alt=\"login\"/>", {:url => '/login'}, :id => 'login-link' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> diff --git a/app/views/notifier/contact.html.erb b/app/views/notifier/contact.html.erb new file mode 100644 index 0000000..69182b8 --- /dev/null +++ b/app/views/notifier/contact.html.erb @@ -0,0 +1,5 @@ +來自圖書館讀者 "<%=@name%>" 的意見: + +<%=@content%> + +<% if @phone != "" %>聯絡電話:<%=@phone%><% end %> \ No newline at end of file diff --git a/app/views/welcome/books.rxml b/app/views/welcome/books.rxml new file mode 100644 index 0000000..48551f4 --- /dev/null +++ b/app/views/welcome/books.rxml @@ -0,0 +1,16 @@ +xml.instruct! + +xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do + xml.title "eLib2 最新圖書" + xml.link url_for(:only_path => false, :controller => 'welcome') + xml.description "為您送上最新上架的書籍資訊,歡迎各位讀者多多利用。" + @books.each do |b| + xml.item do + xml.t + xml.title b.title + xml.guid b.id + xml.link url_for(:only_path => false, :controller => 'books', :action => 'show' , :id => b.id) + xml.description "<img src='#{url_for_file_column(b, 'cover', :only_path => false)}' alt='cover'><br/><br/>#{h(b.content).gsub("\n", "\n<br/>").chars[0..500]}......" + end + end +end \ No newline at end of file diff --git a/app/views/welcome/contact.html.erb b/app/views/welcome/contact.html.erb new file mode 100644 index 0000000..72c434a --- /dev/null +++ b/app/views/welcome/contact.html.erb @@ -0,0 +1,16 @@ +<h1>聯絡我們</h1> +<p>我們十分重視讀者的意見,如果您能給我們一些指教那就再好不過了!隨時歡迎您利用下面的表單給我們一些意見喔。</p> + +<form action="/welcome/contact" method="post"> + <p>姓名<br/><input type="text" name="name" value="<%=params[:name]%>" id="name"></p> + <div style="float:left;"> + <p>Email<br/><input type="text" name="email" value="<%=params[:email]%>" id="email"></p> + </div> + <div style="float:left; margin-left: 20px;"> + <p>聯絡電話<br/><input type="text" name="phone" value="<%=params[:phone]%>" id="phone"></p> + </div> + <div style="clear: both;"></div> + <p>意見內容<br/><textarea cols="50" rows="25" name="content"><%=params[:content]%></textarea></p> + <input type="submit" value="送出意見 &rarr;"> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> +</form> \ No newline at end of file diff --git a/config/initializers/contact_info.rb b/config/initializers/contact_info.rb new file mode 100644 index 0000000..5b6e22d --- /dev/null +++ b/config/initializers/contact_info.rb @@ -0,0 +1,2 @@ +LIBRARY_CONTACT_EMAIL = "[email protected]" +ActionMailer::Base.delivery_method = :sendmail \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index fc902b8..b9f5498 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,54 +1,57 @@ ActionController::Routing::Routes.draw do |map| map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.resource :session # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. map.admin '/admin', :controller => "welcome", :action => 'admin' map.root :controller => "welcome" # Coverflow info map.connect '/booksinfo.xml', :controller => "books", :action => 'latest_xml' + + # RSS + map.connect '/latest_books.rss', :controller => "welcome", :action => 'books' # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/test/unit/notifier_test.rb b/test/unit/notifier_test.rb new file mode 100644 index 0000000..5a00def --- /dev/null +++ b/test/unit/notifier_test.rb @@ -0,0 +1,9 @@ +require 'test_helper' + +class NotifierTest < ActionMailer::TestCase + tests Notifier + # replace this with your real tests + def test_truth + assert true + end +end
itszero/eLib2
3006fc185d70d1008d3c69a2caadd062c183d2ec
accessbility support and title fix
diff --git a/app/views/books/search.html.erb b/app/views/books/search.html.erb index 25fe3a4..f4246a0 100644 --- a/app/views/books/search.html.erb +++ b/app/views/books/search.html.erb @@ -1,48 +1,48 @@ <h1>搜尋書籍</h1> <p>請在下面搜尋框中輸入關鍵字,系統會幫您在 標題、作者、出版社、ISBN以及內容摘要中搜尋。</p> <form action="/books/search" method="get" accept-charset="utf-8" style="background-color: #444; color: #FFF; padding: 5px;"> <div class="container"> <div class="span-3" style="font-size: 22pt; text-align: right;">關鍵字</div> <div class="span-15"><input type="text" name="keyword" value="<%=params[:keyword]%>" id="keyword" style="width: 100%;"></div> <div class="span-3"><input type="submit" value="搜尋 &rarr;" class="bigbutton"></div> </div> <input type="hidden" name="show" value="<%=params[:show]%>" id="show"> <input type="hidden" name="page" value="<%=params[:page] || 1%>" id="page"> </form> <% if params[:keyword] && params[:keyword] != ''%> 共找到 <%[email protected]%> 筆資料 | 顯示模式:<a href="/books/search?keyword=<%=params[:keyword]%>&page=<%=params[:page] || 1%>&show=grid">封面網格</a> | <a href="/books/search?keyword=<%=params[:keyword]%>&page=<%=params[:page] || 1%>&show=list">簡明資料</a> <% if !params[:show] || params[:show] == '' || params[:show] == 'list' %> <div class="table"> <% @books.each do |b| %> <div class="tbody"> <div class="container"> - <div class="span-3"><a href="/books/show/<%=b.id%>"><img src="<%=url_for_file_column b, 'cover'%>" width="100" style="border: 2px solid #222; padding: 2px; margin: 2px;"></a></div> + <div class="span-3"><a href="/books/show/<%=b.id%>"><img src="<%=url_for_file_column b, 'cover'%>" width="100" style="border: 2px solid #222; padding: 2px; margin: 2px;" alt="<%=b.title%>"></a></div> <div class="span-20" style="margin: 2px;"> 書名:<%=b.title%><br/> 作者:<%=b.author%><br/> 出版社:<%=b.publisher%><br/> 出版時間:<%=b.published_at%><br/> ISBN:<%=b.isbn%><br/> </div> </div> </div> <% end %> <% elsif params[:show] == 'grid' %> <% @i = 0 until @i >= @books.size b = @books[@i] %> <% if @i % 3 == 0 %> <div class="container"> <% end %> - <div class="span-7"><a href="/books/show/<%=b.id%>"><img src="<%=url_for_file_column b, 'cover'%>" width="200" style="border: 2px solid #222; padding: 2px; margin: 10px;"></a></div> + <div class="span-7"><a href="/books/show/<%=b.id%>"><img src="<%=url_for_file_column b, 'cover'%>" width="200" style="border: 2px solid #222; padding: 2px; margin: 10px;" alt="<%=b.title%>"></a></div> <% if @i % 3 == 2%> </div> <% end %> <% @i += 1%> <% end %> <% end %> </div> <%=will_paginate @books, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> -<% end %> \ No newline at end of file +<% end %> diff --git a/app/views/books/show.html.erb b/app/views/books/show.html.erb index 79650a1..dc74bcb 100644 --- a/app/views/books/show.html.erb +++ b/app/views/books/show.html.erb @@ -1,20 +1,20 @@ <p class="clearfix"><a href="javascript:history.go(-1);" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a><% if @current_user %><a href="/reader/write/<%[email protected]%>" class="button dark thumb" style="margin-right: 10px;"><span><span>撰寫心得</span></span></a><% end %></p> <h1>館藏簡介</h1> -<div style="float: left; border: 2px solid #222; padding: 2px; margin: 2px;"><img src="<%=url_for_file_column @b, 'cover'%>" width="150"></div> +<div style="float: left; border: 2px solid #222; padding: 2px; margin: 2px;"><img src="<%=url_for_file_column @b, 'cover'%>" width="150" alt="Book Cover"></div> <div style="float: left; padding: 2px; margin: 2px; font-size: 1.5em;"> 書名:<%[email protected]%><br/> 作者:<%[email protected]%><br/> 出版社:<%[email protected]%><br/> 出版時間:<%[email protected]_at%><br/> ISBN:<%[email protected]%><br/> <p>目前本書 <span style="color: red;"><% if @b.state == 'on_shelf'%>可外借<% elsif @b.state == 'rentout' %>借出中<% end %></span>。</p></div> <div style="clear: both;"></div> <br/> <h1>內容簡介</h1> <%[email protected]("\n", "<br/>")%> <br/><br/> <% if @current_user && @current_user.permission > 0 %> <h1 style="color: red">館員備註</h1> <%[email protected]("\n", "<br/>")%> <% end %> diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index 62d4f56..de4fc37 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> - <img src="/images/img_sitetitle.png"/> + <img src="/images/img_sitetitle.png" alt="Site Logo"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> <li <%='class="menu-current"' if @in_books_function%>><a href="/books/search">搜尋書籍</a></li> <li <%='class="menu-current"' if @in_reader_function%>><a href="/reader">讀者服務</a></li> <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> <% if @current_user && @current_user.permission > 0%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> - <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> + <a href="/logout"><img src="/images/img_power.png" width="20" height="20" alt="logout">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> <% else %> - <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", {:url => '/login'}, :id => 'login-link' %> 後才能使用使用個人化服務。 + <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" alt=\"login\"/>", {:url => '/login'}, :id => 'login-link' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb index 8dda9d1..bf80091 100644 --- a/app/views/welcome/index.html.erb +++ b/app/views/welcome/index.html.erb @@ -1,50 +1,50 @@ <script src="/javascripts/jquery.browser.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ $('#login-link').click(function(){ if ($.os.name == 'linux') $('#iTunesAlbumArt').slideUp(); }); }); </script> <div style="text-align: center; border: 1px solid #000; width:900px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="iTunesAlbumArt" align="middle" width="900" height="329"> <param name="allowScriptAccess" value="always"> <param name="allowFullScreen" value="false"> <param name="movie" value="/coverflow/iTunesAlbumArt.swf"> <param name="quality" value="high"> <param name="wmode" value="opaque"> <param name="bgcolor" value="#000000"> <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329" wmode="opaque"> </object> </div> <div class="container" style="margin-top: 5px;"> <div class="span-11" style="padding-right: 5px;"> <h2>圖書館部落格</h2> <ul style="margin-left: 30px;"> <% @news.each do |news| %> <li id="news-<%=news.id%>"><a href="/news/show/<%=news.id%>"><%=news.title%></a> - <%=news.created_at.strftime("%Y-%m-%d")%></li> <% end %> </ul> <%=link_to '更多消息...', :controller => 'news'%> </div> <div class="span-12 last" > <% if @current_user %> <h2>資訊快遞</h2> <ul style="margin-left: 30px;"> <li>您目前共借閱 <%=@rentlog_size%> 本書,<%=@needreturn_size%> 本書即將到期。</li> <li>寫過了 <%=@comments_size%> 篇心得</li> </ul> <%=link_to '詳細資訊...', :controller => 'reader'%> <% else %> <h2>隨機好書</h2> <ul style="margin-left: 30px;"> <% @random_books.each do |book| %> - <a href="/books/show/<%=book.id%>"><img src="<%=url_for_file_column book, :cover%>" style="border: 2px solid #000; margin: 5px; padding: 5px; width: 80px;"></a> + <a href="/books/show/<%=book.id%>"><img src="<%=url_for_file_column book, :cover%>" style="border: 2px solid #000; margin: 5px; padding: 5px; width: 80px;" alt="<%=book.title%>"></a> <% end %> </ul> <% end %> </div> </div> diff --git a/log/mongrel.pid b/log/mongrel.pid index b9d5dc7..e3fd28c 100644 --- a/log/mongrel.pid +++ b/log/mongrel.pid @@ -1 +1 @@ -92279 \ No newline at end of file +51561 \ No newline at end of file
itszero/eLib2
fb32db0e3a4a11f81f4560f34a6bbdff1f1f86fc
contest version
diff --git a/app/controllers/reader_controller.rb b/app/controllers/reader_controller.rb index 700b0c5..eae762d 100644 --- a/app/controllers/reader_controller.rb +++ b/app/controllers/reader_controller.rb @@ -1,112 +1,114 @@ class ReaderController < ApplicationController before_filter :admin_required, :only => [:rate, :admin] before_filter :login_required, :except => [:rate, :admin] layout 'service' def index @in_reader_function = true @u = current_user @r = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id], :limit => 5, :order => 'created_at DESC') @c = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC') end def rentlogs @r = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC').paginate :page => params[:page] end def list @c = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC').paginate :page => params[:page] end def admin @c = Comment if params[:isbn] && params[:isbn] != '' @b = Book.find_by_isbn(params[:isbn]) if @b @c = @c.book_is(@b.id) else warning_stickie "找不到指定的ISBN號碼。" params[:isbn] = nil end end if params[:sid] && params[:sid] != '' @u = User.find_by_student_id(params[:sid]) if @u @c = @c.user_is(@u.id) else warning_stickie "找不到指定的學號。" params[:sid] = nil end end - - @c = @c.find(:all, :order => 'created_at DESC').paginate :page => params[:page] + + @c1 = @c.find(:all, :order => 'created_at DESC', :conditions => 'score IS NULL') + @c2 = @c.find(:all, :order => 'created_at DESC', :conditions => 'score IS NOT NULL') + @c = (@c1 + @c2).paginate :page => params[:page] end def write @book = Book.find(params[:id]) if request.post? @comment = Comment.new @comment.comment = params[:content] @comment.user_id = @current_user.id @book.comments << @comment notice_stickie '心得已經儲存成功囉。' redirect_to "/reader/read/#{@comment.id}" return end end def read @comment = Comment.find(params[:id]) if @comment.user_id != @current_user.id && @current_user.permission < 1 redirect_to '/reader' return end @book = @comment.commentable end def load_text render :text => Comment.find(params[:id]).comment end def edit @comment = Comment.find(params[:id]) if @comment.user_id != @current_user.id && @current_user.permission < 1 redirect_to '/reader' return end @comment.comment = params[:value] @comment.save render :nothing => true end def delete @comment = Comment.find(params[:id]) if @comment.user_id != @current_user.id && @current_user.permission < 1 redirect_to '/reader' return end @comment.destroy notice_stickie "您的心得已經刪除。" redirect_to '/reader' end def rate @comment = Comment.find(params[:id]) if @current_user.permission < 1 redirect_to '/reader' return end notice_stickie "給分成功!" @comment.score = params[:score] @comment.save redirect_to "/reader/read/#{@comment.id}" end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index e796715..58c1eb4 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,206 +1,208 @@ require 'csv' class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem layout 'service' before_filter :super_required, :only => [:staff, :demote, :promote] before_filter :admin_required, :except => [:index, :edit, :bulk_add, :demote, :promote] before_filter :login_required, :only => [:edit] def index redirect_to '/' end def admin @in_admin_function = true if !params[:id] @user = User.paginate :page => params[:page] else @u = User.find(params[:id]) render :partial => 'user_list_item' end end def details @u = User.find(params[:id]) @r = RentLog.find(:all, :conditions => ['user_id = ?', params[:id]]).paginate :page => params[:page] end def staff @in_admin_function = true @user = User.find(:all, :conditions => 'permission > 0', :order => 'permission DESC, id ASC') end def promote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission+=1 if @user.permission < 2 @user.save notice_stickie "使用者 「#{@user.name}」 已提昇權限" redirect_to :action => :staff end def demote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission-=1 if @user.permission > 1 @user.save notice_stickie "使用者 「#{@user.name}」 已降低權限" redirect_to :action => :staff end def set_permission suppress(ActiveRecord::RecordNotFound) do @user = User.find(params[:id]) end suppress(ActiveRecord::RecordNotFound) do @user = User.find_by_login(params[:id]) if !@user end if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission = params[:permission] if params[:permission].to_i == 0 notice_stickie "使用者 「#{@user.name}」 的權限已取消。" elsif params[:permission].to_i > 0 notice_stickie "使用者 「#{@user.name}」 已經設定為工作人員。" end @user.save redirect_to :action => :staff end def uid_autocomplete @users = User.find(:all, :conditions => "login LIKE '%#{params[:q]}%'") render :text => (@users.map &:login).join("\n") end def bulk_add @in_admin_function = true if request.post? csv = CSV.parse(params[:csv].read) header = csv.shift # check reader expect_header = ['login', 'email', 'password', 'name', 'student_id', 'student_class'] pass = true expect_header.each do |h| pass = false if !header.include? h end if !pass error_stickie "匯入的欄位有缺失,請檢查CSV檔案!" redirect_to :action => :bulk_add return end # read it result = [] csv.each do |row| result << Hash[*header.zip(row.to_a).flatten] end errors = [] # add it result.each do |r| u = User.new(r) u.password_confirmation = u.password + u.permission = 0 if !u.save errors << "使用者 #{r["login"]} 無法新增,請檢查資料。" end end if errors != [] error_stickie errors.join("<br/>") end notice_stickie("收到 #{result.size} 筆資料,成功新增 #{result.size - errors.size} 筆,失敗 #{errors.size} 筆。") redirect_to :action => :bulk_add end end def create @user = User.new @user.login = params[:login] @user.password = params[:password] @user.password_confirmation = params[:password_confirmation] @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] + @user.permission = 0 if @user.save notice_stickie "使用者 #{params[:login]} 建立成功" else error_stickie "無法建立使用者 #{params[:login]}<br/>#{@user.errors.inspect}" end redirect_to :action => 'admin' end def delete User.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? if @current_user.permission == 2 || @current_user.id == params[:id] @user = User.find(params[:id]) @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] @user.password = @user.password_confirmation = params[:password] if params[:password] && params[:password] != '' @user.save end if @current_user.permission > 0 redirect_to '/users/admin' else redirect_to '/users/edit' end else if @current_user.permission == 0 @u = User.find(@current_user.id) else @u = User.find(params[:id]) render :layout => false end end end def get_reader_status_by_student_id @u = User.find_by_student_id(params[:id]) if !@u render :text => 'fail:noid' return end render :text => @u.name end end diff --git a/app/models/book.rb b/app/models/book.rb index 95b06f1..ce897f9 100644 --- a/app/models/book.rb +++ b/app/models/book.rb @@ -1,59 +1,59 @@ # == Schema Information # Schema version: 20080930191254 # # Table name: books # # id :integer not null, primary key # cover :string(255) # author :string(255) # title :string(255) # publisher :string(255) # published_at :string(255) # content :text # toc :text # problems :text # state :string(255) # note :text(255) # isbn :string(255) # created_at :datetime # updated_at :datetime # class Book < ActiveRecord::Base acts_as_commentable acts_as_state_machine :initial => :on_shelf file_column :cover validates_file_format_of :cover, :in => ['jpg', 'gif', 'png'] named_scope :filter, lambda { |args| {:conditions => "title LIKE '%#{args}%' OR author LIKE '%#{args}%' OR publisher LIKE '%#{args}%' OR content LIKE '%#{args}%' OR isbn LIKE '%#{args}%' OR note LIKE '%#{args}%'"}} state :on_shelf state :rentout event :rent do transitions :from => :on_shelf, :to => :rentout end event :return do transitions :from => :rentout, :to => :on_shelf end def rent_to(user) rent! @log = RentLog.new @log.book_id = self.id @log.user_id = user.id @log.start_date = DateTime.now @log.save end def return_book return! - @log = RentLog.find(:first, :conditions => ['book_id = ?', self.id]) + @log = RentLog.find(:last, :conditions => ['book_id = ?', self.id]) @log.end_date = DateTime.now @log.save end end diff --git a/app/views/books/show.html.erb b/app/views/books/show.html.erb index c6d991e..79650a1 100644 --- a/app/views/books/show.html.erb +++ b/app/views/books/show.html.erb @@ -1,20 +1,20 @@ <p class="clearfix"><a href="javascript:history.go(-1);" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a><% if @current_user %><a href="/reader/write/<%[email protected]%>" class="button dark thumb" style="margin-right: 10px;"><span><span>撰寫心得</span></span></a><% end %></p> <h1>館藏簡介</h1> <div style="float: left; border: 2px solid #222; padding: 2px; margin: 2px;"><img src="<%=url_for_file_column @b, 'cover'%>" width="150"></div> <div style="float: left; padding: 2px; margin: 2px; font-size: 1.5em;"> 書名:<%[email protected]%><br/> 作者:<%[email protected]%><br/> 出版社:<%[email protected]%><br/> 出版時間:<%[email protected]_at%><br/> ISBN:<%[email protected]%><br/> <p>目前本書 <span style="color: red;"><% if @b.state == 'on_shelf'%>可外借<% elsif @b.state == 'rentout' %>借出中<% end %></span>。</p></div> <div style="clear: both;"></div> <br/> <h1>內容簡介</h1> <%[email protected]("\n", "<br/>")%> <br/><br/> -<% if @current_user.permission > 0 %> +<% if @current_user && @current_user.permission > 0 %> <h1 style="color: red">館員備註</h1> <%[email protected]("\n", "<br/>")%> <% end %> diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index 74232c1..62d4f56 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> <li <%='class="menu-current"' if @in_books_function%>><a href="/books/search">搜尋書籍</a></li> <li <%='class="menu-current"' if @in_reader_function%>><a href="/reader">讀者服務</a></li> <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> - <% if @current_user && @current_user.permission == 2%> + <% if @current_user && @current_user.permission > 0%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> <% else %> <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", {:url => '/login'}, :id => 'login-link' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> diff --git a/app/views/reader/admin.html.erb b/app/views/reader/admin.html.erb index 56e3b4f..09c98cb 100644 --- a/app/views/reader/admin.html.erb +++ b/app/views/reader/admin.html.erb @@ -1,38 +1,40 @@ <h1>讀書心得管理</h1> <p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a></p> <form action="/reader/admin" method="get" accept-charset="utf-8"> <p class="filter-title"> 以ISBN過濾:<input type="text" name="isbn" value="<%=params[:isbn]%>" id="isbn"><br/> 以讀者學號過濾:<input type="text" name="sid" value="<%=params[:sid]%>" id="sid"><br/> <input type="submit" value="過濾 &rarr;"> </p> </form> <div id="book-list" class="table"> <div class="thead"> <div class="container"> <div class="span-7">書名</div> - <div class="span-7">內容</div> + <div class="span-4">內容</div> + <div class="span-3">學號</div> <div class="span-4">撰寫日期</div> <div class="span-3">分數</div> <div class="span-2">行動</div> </div> </div> <% @c.each do |c| %> <div class="tbody"> <div class="container"> <div class="span-7"><%=c.commentable.title%></div> - <div class="span-7"><%=c.comment.chars[0..10]%>... (<a href="/reader/read/<%=c.id%>">完整內容</a>)</div> + <div class="span-4"><%=c.comment.chars[0..10]%>... (<a href="/reader/read/<%=c.id%>">完整內容</a>)</div> + <div class="span-3"><%=User.find(c.user_id).student_id%></div> <div class="span-4"><%=c.created_at.strftime("%Y/%m/%d")%></div> <div class="span-3"><%if c.score%><%=c.score%><%else%><span style="color: red;">尚未評分</span><%end%></div> <div class="span-2"> <p class="clearfix"> <a href="/reader/delete/<%=c.id%>" class="button pink minus" onclick="return confirm('確定要刪除心得嗎?')"><span><span>刪除</span></span></a> </p> </div> </div> </div> <% end %> </div> -<%=will_paginate @c, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> \ No newline at end of file +<%=will_paginate @c, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> diff --git a/lib/authenticated_system.rb b/lib/authenticated_system.rb index 894bf13..e3e7fc1 100644 --- a/lib/authenticated_system.rb +++ b/lib/authenticated_system.rb @@ -1,201 +1,201 @@ module AuthenticatedSystem protected # Returns true or false if the user is logged in. # Preloads @current_user with the user model if they're logged in. def logged_in? !!current_user end # Accesses the current user from the session. # Future calls avoid the database because nil is not equal to false. def current_user @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false end # Store the given user id in the session. def current_user=(new_user) session[:user_id] = new_user ? new_user.id : nil @current_user = new_user || false end # Check if the user is authorized # # Override this method in your controllers if you want to restrict access # to only a few actions or if you want to check if the user # has the correct rights. # # Example: # # # only allow nonbobs # def authorized? # current_user.login != "bob" # end # def authorized?(action = action_name, resource = nil) logged_in? end # Filter method to enforce a login requirement. # # To require logins for all actions, use this in your controllers: # # before_filter :login_required # # To require logins for specific actions, use this in your controllers: # # before_filter :login_required, :only => [ :edit, :update ] # # To skip this in a subclassed controller: # # skip_before_filter :login_required # def login_required authorized? || access_denied end def admin_required authorized? && @current_user.permission >= 1 end def super_required authorized? && @current_user.permission >= 2 end # Redirect as appropriate when an access request fails. # # The default action is to redirect to the login screen. # # Override this method in your controllers if you want to have special # behavior in case the user is not authorized # to access the requested action. For example, a popup window might # simply close itself. def access_denied respond_to do |format| format.html do store_location - redirect_to new_session_path + redirect_to '/' end # format.any doesn't work in rails version < http://dev.rubyonrails.org/changeset/8987 # Add any other API formats here. (Some browsers, notably IE6, send Accept: */* and trigger # the 'format.any' block incorrectly. See http://bit.ly/ie6_borken or http://bit.ly/ie6_borken2 # for a workaround.) format.any(:json, :xml) do request_http_basic_authentication 'Web Password' end end end # Store the URI of the current request in the session. # # We can return to this location by calling #redirect_back_or_default. def store_location session[:return_to] = request.request_uri end # Redirect to the URI stored by the most recent store_location call or # to the passed default. Set an appropriately modified # after_filter :store_location, :only => [:index, :new, :show, :edit] # for any controller you want to be bounce-backable. def redirect_back_or_default(default, facebox=false) if (facebox) redirect_from_facebox(session[:return_to] || default) else redirect_to(session[:return_to] || default) end session[:return_to] = nil end # Inclusion hook to make #current_user and #logged_in? # available as ActionView helper methods. def self.included(base) base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method end # # Login # # Called from #current_user. First attempt to login by the user id stored in the session. def login_from_session self.current_user = User.find_by_id(session[:user_id]) if session[:user_id] end # Called from #current_user. Now, attempt to login by basic authentication information. def login_from_basic_auth authenticate_with_http_basic do |login, password| self.current_user = User.authenticate(login, password) end end # # Logout # # Called from #current_user. Finaly, attempt to login by an expiring token in the cookie. # for the paranoid: we _should_ be storing user_token = hash(cookie_token, request IP) def login_from_cookie user = cookies[:auth_token] && User.find_by_remember_token(cookies[:auth_token]) if user && user.remember_token? self.current_user = user handle_remember_cookie! false # freshen cookie token (keeping date) self.current_user end end # This is ususally what you want; resetting the session willy-nilly wreaks # havoc with forgery protection, and is only strictly necessary on login. # However, **all session state variables should be unset here**. def logout_keeping_session! # Kill server-side auth cookie @current_user.forget_me if @current_user.is_a? User @current_user = false # not logged in, and don't do it for me kill_remember_cookie! # Kill client-side auth cookie session[:user_id] = nil # keeps the session but kill our variable # explicitly kill any other session variables you set end # The session should only be reset at the tail end of a form POST -- # otherwise the request forgery protection fails. It's only really necessary # when you cross quarantine (logged-out to logged-in). def logout_killing_session! logout_keeping_session! reset_session end # # Remember_me Tokens # # Cookies shouldn't be allowed to persist past their freshness date, # and they should be changed at each login # Cookies shouldn't be allowed to persist past their freshness date, # and they should be changed at each login def valid_remember_cookie? return nil unless @current_user (@current_user.remember_token?) && (cookies[:auth_token] == @current_user.remember_token) end # Refresh the cookie auth token if it exists, create it otherwise def handle_remember_cookie!(new_cookie_flag) return unless @current_user case when valid_remember_cookie? then @current_user.refresh_token # keeping same expiry date when new_cookie_flag then @current_user.remember_me else @current_user.forget_me end send_remember_cookie! end def kill_remember_cookie! cookies.delete :auth_token end def send_remember_cookie! cookies[:auth_token] = { :value => @current_user.remember_token, :expires => @current_user.remember_token_expires_at } end end
itszero/eLib2
7783c4cfa71eb6a96face3adbad3c66cb900e0ab
ver 0.1
diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb index 66e368f..293ee89 100644 --- a/app/controllers/books_controller.rb +++ b/app/controllers/books_controller.rb @@ -1,117 +1,126 @@ class BooksController < ApplicationController layout 'service' - before_filter :admin_required, :except => [:index, :show] + before_filter :admin_required, :except => [:index, :show, :latest_xml, :search] def index end def latest_xml @books = Book.find(:all, :order => "created_at DESC", :limit => 20) render :layout => false end def circulation @in_admin_function = true end def admin @in_admin_function = true if params[:filter] @books = Book.filter(params[:filter]).paginate :page => params[:page] else @books = Book.paginate :page => params[:page] end end def new @in_admin_function = true if request.post? @b = Book.new(params[:book]) if @b.save notice_stickie "館藏 #{params[:book][:title]} 新增成功!" else error_stickie '館藏無法新增,請檢查資料。 #{@b.errors.inspect}' end redirect_to :action => 'admin' end @b = Book.new end def edit @in_admin_function = true if request.post? @b = Book.find(params[:id]) @b.update_attributes params[:book] @b.save redirect_to :action => 'admin' return end @is_edit = true @b = Book.find(params[:id]) if !@b redirect_to :action => 'admin' return end render :action => 'new' end def delete Book.find(params[:id]).destroy redirect_to :action => 'admin' end def show @in_books_function = true @b = Book.find(params[:id]) end def get_book_status_by_isbn @b = Book.find_by_isbn(params[:isbn]) if !@b render :text => 'fail:isbn' return end if @b.rentout? render :text => 'fail:rent' return end render :text => @b.title end def rent_book @b = Book.find_by_isbn(params[:isbn]) if !@b render :text => 'fail' return end @u = User.find_by_student_id(params[:stuid]) if !@u render :text => 'fail' return end @b.rent_to(@u) render :text => 'ok' end def return_book @b = Book.find_by_isbn(params[:isbn]) @b.return_book render :text => 'ok' end + + def overdue + @r = RentLog.find(:all, :conditions => ['start_date <= ? AND end_date IS NULL', 1.week.ago]) + end + + def search + @in_books_function = true + @books = Book.filter(params[:keyword]).paginate :page => params[:page], :per_page => 10 + end end diff --git a/app/controllers/reader_controller.rb b/app/controllers/reader_controller.rb new file mode 100644 index 0000000..700b0c5 --- /dev/null +++ b/app/controllers/reader_controller.rb @@ -0,0 +1,112 @@ +class ReaderController < ApplicationController + before_filter :admin_required, :only => [:rate, :admin] + before_filter :login_required, :except => [:rate, :admin] + layout 'service' + + def index + @in_reader_function = true + @u = current_user + @r = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id], :limit => 5, :order => 'created_at DESC') + @c = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC') + end + + def rentlogs + @r = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC').paginate :page => params[:page] + end + + def list + @c = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id], :order => 'created_at DESC').paginate :page => params[:page] + end + + def admin + @c = Comment + + if params[:isbn] && params[:isbn] != '' + @b = Book.find_by_isbn(params[:isbn]) + if @b + @c = @c.book_is(@b.id) + else + warning_stickie "找不到指定的ISBN號碼。" + params[:isbn] = nil + end + end + + if params[:sid] && params[:sid] != '' + @u = User.find_by_student_id(params[:sid]) + if @u + @c = @c.user_is(@u.id) + else + warning_stickie "找不到指定的學號。" + params[:sid] = nil + end + end + + @c = @c.find(:all, :order => 'created_at DESC').paginate :page => params[:page] + end + + def write + @book = Book.find(params[:id]) + + if request.post? + @comment = Comment.new + @comment.comment = params[:content] + @comment.user_id = @current_user.id + @book.comments << @comment + + notice_stickie '心得已經儲存成功囉。' + redirect_to "/reader/read/#{@comment.id}" + return + end + end + + def read + @comment = Comment.find(params[:id]) + if @comment.user_id != @current_user.id && @current_user.permission < 1 + redirect_to '/reader' + return + end + @book = @comment.commentable + end + + def load_text + render :text => Comment.find(params[:id]).comment + end + + def edit + @comment = Comment.find(params[:id]) + if @comment.user_id != @current_user.id && @current_user.permission < 1 + redirect_to '/reader' + return + end + + @comment.comment = params[:value] + @comment.save + + render :nothing => true + end + + def delete + @comment = Comment.find(params[:id]) + if @comment.user_id != @current_user.id && @current_user.permission < 1 + redirect_to '/reader' + return + end + + @comment.destroy + notice_stickie "您的心得已經刪除。" + redirect_to '/reader' + end + + def rate + @comment = Comment.find(params[:id]) + if @current_user.permission < 1 + redirect_to '/reader' + return + end + + notice_stickie "給分成功!" + @comment.score = params[:score] + @comment.save + redirect_to "/reader/read/#{@comment.id}" + end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index ed901c7..e796715 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,200 +1,206 @@ require 'csv' class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem layout 'service' before_filter :super_required, :only => [:staff, :demote, :promote] before_filter :admin_required, :except => [:index, :edit, :bulk_add, :demote, :promote] before_filter :login_required, :only => [:edit] def index redirect_to '/' end def admin @in_admin_function = true if !params[:id] @user = User.paginate :page => params[:page] else @u = User.find(params[:id]) render :partial => 'user_list_item' end end + def details + @u = User.find(params[:id]) + @r = RentLog.find(:all, :conditions => ['user_id = ?', params[:id]]).paginate :page => params[:page] + end + def staff @in_admin_function = true @user = User.find(:all, :conditions => 'permission > 0', :order => 'permission DESC, id ASC') end def promote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission+=1 if @user.permission < 2 @user.save notice_stickie "使用者 「#{@user.name}」 已提昇權限" redirect_to :action => :staff end def demote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission-=1 if @user.permission > 1 @user.save notice_stickie "使用者 「#{@user.name}」 已降低權限" redirect_to :action => :staff end def set_permission suppress(ActiveRecord::RecordNotFound) do @user = User.find(params[:id]) end suppress(ActiveRecord::RecordNotFound) do @user = User.find_by_login(params[:id]) if !@user end if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission = params[:permission] if params[:permission].to_i == 0 notice_stickie "使用者 「#{@user.name}」 的權限已取消。" elsif params[:permission].to_i > 0 notice_stickie "使用者 「#{@user.name}」 已經設定為工作人員。" end @user.save redirect_to :action => :staff end def uid_autocomplete @users = User.find(:all, :conditions => "login LIKE '%#{params[:q]}%'") render :text => (@users.map &:login).join("\n") end def bulk_add @in_admin_function = true if request.post? csv = CSV.parse(params[:csv].read) header = csv.shift # check reader expect_header = ['login', 'email', 'password', 'name', 'student_id', 'student_class'] pass = true expect_header.each do |h| pass = false if !header.include? h end if !pass error_stickie "匯入的欄位有缺失,請檢查CSV檔案!" redirect_to :action => :bulk_add return end # read it result = [] csv.each do |row| result << Hash[*header.zip(row.to_a).flatten] end errors = [] # add it result.each do |r| u = User.new(r) u.password_confirmation = u.password if !u.save errors << "使用者 #{r["login"]} 無法新增,請檢查資料。" end end if errors != [] error_stickie errors.join("<br/>") end notice_stickie("收到 #{result.size} 筆資料,成功新增 #{result.size - errors.size} 筆,失敗 #{errors.size} 筆。") redirect_to :action => :bulk_add end end def create @user = User.new @user.login = params[:login] @user.password = params[:password] @user.password_confirmation = params[:password_confirmation] @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] if @user.save notice_stickie "使用者 #{params[:login]} 建立成功" else error_stickie "無法建立使用者 #{params[:login]}<br/>#{@user.errors.inspect}" end redirect_to :action => 'admin' end def delete User.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? if @current_user.permission == 2 || @current_user.id == params[:id] @user = User.find(params[:id]) @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] + @user.password = @user.password_confirmation = params[:password] if params[:password] && params[:password] != '' @user.save end if @current_user.permission > 0 redirect_to '/users/admin' else redirect_to '/users/edit' end else if @current_user.permission == 0 @u = User.find(@current_user.id) else @u = User.find(params[:id]) render :layout => false end end end def get_reader_status_by_student_id @u = User.find_by_student_id(params[:id]) if !@u render :text => 'fail:noid' return end render :text => @u.name end end diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb index 95339db..7c100c0 100644 --- a/app/controllers/welcome_controller.rb +++ b/app/controllers/welcome_controller.rb @@ -1,22 +1,32 @@ class WelcomeController < ApplicationController layout 'service' before_filter :admin_required, :only => :admin def index @in_homepage_function = true @news = Blog.find(:all, :order => "created_at DESC", :limit => 5) - @random_books = [] - maxid = Book.find(:first, :order => "id DESC").id - until @random_books.size >= 6 - b = nil - suppress(ActiveRecord::RecordNotFound) do - b = Book.find(rand(maxid) + 1) + + if !@current_user + @random_books = [] + maxid = Book.find(:first, :order => "id DESC") + if maxid != nil + maxid = maxid.id + until @random_books.size >= 6 + b = nil + suppress(ActiveRecord::RecordNotFound) do + b = Book.find(rand(maxid) + 1) + end + @random_books << b if b && !@random_books.include?(b) + end end - @random_books << b if b && !@random_books.include?(b) + else + @rentlog_size = RentLog.find(:all, :conditions => ['user_id = ?', @current_user.id]).size + @needreturn_size = RentLog.find(:all, :conditions => ['start_date > ? AND start_date < ?', 1.weeks.ago, 2.weeks.ago]).size + @comments_size = Comment.find(:all, :conditions => ['user_id = ?', @current_user.id]).size end end def admin @in_admin_function = true end end diff --git a/app/helpers/reader_helper.rb b/app/helpers/reader_helper.rb new file mode 100644 index 0000000..795edbc --- /dev/null +++ b/app/helpers/reader_helper.rb @@ -0,0 +1,2 @@ +module ReaderHelper +end diff --git a/app/models/book.rb b/app/models/book.rb index afac9c5..95b06f1 100644 --- a/app/models/book.rb +++ b/app/models/book.rb @@ -1,58 +1,59 @@ # == Schema Information -# Schema version: 20080929055605 +# Schema version: 20080930191254 # # Table name: books # # id :integer not null, primary key # cover :string(255) # author :string(255) # title :string(255) # publisher :string(255) # published_at :string(255) # content :text # toc :text # problems :text # state :string(255) -# note :string(255) +# note :text(255) # isbn :string(255) # created_at :datetime # updated_at :datetime # class Book < ActiveRecord::Base + acts_as_commentable acts_as_state_machine :initial => :on_shelf file_column :cover validates_file_format_of :cover, :in => ['jpg', 'gif', 'png'] - named_scope :filter, lambda { |args| {:conditions => "title LIKE '%#{args}%' OR author LIKE '%#{args}%' OR publisher LIKE '%#{args}%' OR content LIKE '%#{args}%' OR isbn LIKE '%#{args}%' OR note LIKE '%#{args}%"}} + named_scope :filter, lambda { |args| {:conditions => "title LIKE '%#{args}%' OR author LIKE '%#{args}%' OR publisher LIKE '%#{args}%' OR content LIKE '%#{args}%' OR isbn LIKE '%#{args}%' OR note LIKE '%#{args}%'"}} state :on_shelf state :rentout event :rent do transitions :from => :on_shelf, :to => :rentout end event :return do transitions :from => :rentout, :to => :on_shelf end def rent_to(user) rent! @log = RentLog.new @log.book_id = self.id @log.user_id = user.id @log.start_date = DateTime.now @log.save end def return_book return! @log = RentLog.find(:first, :conditions => ['book_id = ?', self.id]) @log.end_date = DateTime.now @log.save end end diff --git a/app/models/rent_log.rb b/app/models/rent_log.rb index 22ddc9d..6014420 100644 --- a/app/models/rent_log.rb +++ b/app/models/rent_log.rb @@ -1,2 +1,18 @@ +# == Schema Information +# Schema version: 20080930191254 +# +# Table name: rent_logs +# +# id :integer not null, primary key +# book_id :integer +# user_id :integer +# start_date :datetime +# end_date :datetime +# created_at :datetime +# updated_at :datetime +# + class RentLog < ActiveRecord::Base + belongs_to :book + belongs_to :user end diff --git a/app/views/books/admin.html.erb b/app/views/books/admin.html.erb index df807e0..41d6fdf 100644 --- a/app/views/books/admin.html.erb +++ b/app/views/books/admin.html.erb @@ -1,45 +1,45 @@ <h1>搜尋/維護館藏</h1> <p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a> <a href="/books/new" class="button pink plus" style="margin-right: 10px;" onclick="this.blur();"><span><span>新增館藏資料</span></span></a></p> <p class="filter-title">過濾館藏資訊:<input type="text" name="filter" value="<%=params[:filter]%>" id="filter"><input type="button" value="過濾" id="btn-filter">(標題, 作者, 出版社, ISBN, 內容簡介, 備註)</p> <script type="text/javascript" charset="utf-8"> $('#filter').keydown(function(e){ if (e.keyCode == 13) $('#btn-filter').click(); }); $('#btn-filter').click(function(){ location.href='/books/admin?page=<%=params[:page] || 1%>&filter=' + $('#filter').val(); }); </script> -<div id="news-list" class="table"> +<div id="book-list" class="table"> <div class="thead"> <div class="container"> <div class="span-3">封面</div> <div class="span-4">書名</div> <div class="span-4">出版社</div> <div class="span-4">作者</div> <div class="span-4">ISBN</div> <div class="span-4 last">行動</div> </div> </div> <% @books.each do |b| %> <div class="tbody"> <div class="container"> <div class="span-3 book-cover"><img src="<%=url_for_file_column b, 'cover'%>"></div> <div class="span-4"><%=b.title%></div> <div class="span-4"><%=b.publisher%></div> <div class="span-4"><%=b.author%></div> <div class="span-4"><%=b.isbn%></div> <div class="span-4 last"> <p class="clearfix"><a href="/books/edit/<%=b.id%>" class="button dark pencil" style="margin-right: 10px;" onclick="this.blur();" id="btn-edit-"><span><span>編輯</span></span></a><a href="/books/show/<%=b.id%>" class="button alt star" style="margin-right: 10px;" onclick="this.blur();" id="btn-detail-<%=b.id%>"><span><span>詳細記錄</span></span></a><a href="/books/delete/<%=b.id%>" class="button pink minus" onclick="return confirm('請確認是否刪除館藏 <%=b.title%> ?');"><span><span>刪除</span></span></a></p> </div> </div> </div> <% end %> </div> <%=will_paginate @books, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> diff --git a/app/views/books/overdue.html.erb b/app/views/books/overdue.html.erb new file mode 100644 index 0000000..1ea3432 --- /dev/null +++ b/app/views/books/overdue.html.erb @@ -0,0 +1,25 @@ +<h1>逾期未歸還館藏列表</h1> + +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a></p> + +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-8">書名</div> + <div class="span-4">借閱者</div> + <div class="span-4">ISBN</div> + <div class="span-3">借出日期</div> + </div> + </div> + <% @r.each do |r| %> + <div class="tbody"> + <div class="container"> + <div class="span-8"><%=r.book.title%></div> + <div class="span-4"><%=r.user.name%></div> + <div class="span-4"><%=r.book.isbn%></div> + <div class="span-3 last"><%=r.start_date.strftime("%Y/%m/%d")%></div> + </div> + </div> + <% end %> + +</div> diff --git a/app/views/books/search.html.erb b/app/views/books/search.html.erb new file mode 100644 index 0000000..25fe3a4 --- /dev/null +++ b/app/views/books/search.html.erb @@ -0,0 +1,48 @@ +<h1>搜尋書籍</h1> + +<p>請在下面搜尋框中輸入關鍵字,系統會幫您在 標題、作者、出版社、ISBN以及內容摘要中搜尋。</p> +<form action="/books/search" method="get" accept-charset="utf-8" style="background-color: #444; color: #FFF; padding: 5px;"> + <div class="container"> + <div class="span-3" style="font-size: 22pt; text-align: right;">關鍵字</div> + <div class="span-15"><input type="text" name="keyword" value="<%=params[:keyword]%>" id="keyword" style="width: 100%;"></div> + <div class="span-3"><input type="submit" value="搜尋 &rarr;" class="bigbutton"></div> + </div> + <input type="hidden" name="show" value="<%=params[:show]%>" id="show"> + <input type="hidden" name="page" value="<%=params[:page] || 1%>" id="page"> +</form> + +<% if params[:keyword] && params[:keyword] != ''%> +共找到 <%[email protected]%> 筆資料 | 顯示模式:<a href="/books/search?keyword=<%=params[:keyword]%>&page=<%=params[:page] || 1%>&show=grid">封面網格</a> | <a href="/books/search?keyword=<%=params[:keyword]%>&page=<%=params[:page] || 1%>&show=list">簡明資料</a> +<% if !params[:show] || params[:show] == '' || params[:show] == 'list' %> +<div class="table"> +<% @books.each do |b| %> +<div class="tbody"> + <div class="container"> + <div class="span-3"><a href="/books/show/<%=b.id%>"><img src="<%=url_for_file_column b, 'cover'%>" width="100" style="border: 2px solid #222; padding: 2px; margin: 2px;"></a></div> + <div class="span-20" style="margin: 2px;"> + 書名:<%=b.title%><br/> + 作者:<%=b.author%><br/> + 出版社:<%=b.publisher%><br/> + 出版時間:<%=b.published_at%><br/> + ISBN:<%=b.isbn%><br/> + </div> + </div> +</div> +<% end %> +<% elsif params[:show] == 'grid' %> +<% @i = 0 + until @i >= @books.size + b = @books[@i] %> +<% if @i % 3 == 0 %> + <div class="container"> +<% end %> + <div class="span-7"><a href="/books/show/<%=b.id%>"><img src="<%=url_for_file_column b, 'cover'%>" width="200" style="border: 2px solid #222; padding: 2px; margin: 10px;"></a></div> +<% if @i % 3 == 2%> + </div> +<% end %> +<% @i += 1%> +<% end %> +<% end %> +</div> +<%=will_paginate @books, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> +<% end %> \ No newline at end of file diff --git a/app/views/books/show.html.erb b/app/views/books/show.html.erb index 3a8c080..c6d991e 100644 --- a/app/views/books/show.html.erb +++ b/app/views/books/show.html.erb @@ -1,20 +1,20 @@ -<p class="clearfix"><a href="javascript:history.go(-1);" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a></p> +<p class="clearfix"><a href="javascript:history.go(-1);" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a><% if @current_user %><a href="/reader/write/<%[email protected]%>" class="button dark thumb" style="margin-right: 10px;"><span><span>撰寫心得</span></span></a><% end %></p> <h1>館藏簡介</h1> <div style="float: left; border: 2px solid #222; padding: 2px; margin: 2px;"><img src="<%=url_for_file_column @b, 'cover'%>" width="150"></div> <div style="float: left; padding: 2px; margin: 2px; font-size: 1.5em;"> 書名:<%[email protected]%><br/> 作者:<%[email protected]%><br/> 出版社:<%[email protected]%><br/> 出版時間:<%[email protected]_at%><br/> ISBN:<%[email protected]%><br/> <p>目前本書 <span style="color: red;"><% if @b.state == 'on_shelf'%>可外借<% elsif @b.state == 'rentout' %>借出中<% end %></span>。</p></div> <div style="clear: both;"></div> <br/> <h1>內容簡介</h1> <%[email protected]("\n", "<br/>")%> <br/><br/> <% if @current_user.permission > 0 %> <h1 style="color: red">館員備註</h1> <%[email protected]("\n", "<br/>")%> <% end %> diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index e1e2873..74232c1 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> - <li <%='class="menu-current"' if @in_books_function%>><a href="#">搜尋書籍</a></li> - <li <%='class="menu-current"' if @in_reader_function%>><a href="#">讀者服務</a></li> + <li <%='class="menu-current"' if @in_books_function%>><a href="/books/search">搜尋書籍</a></li> + <li <%='class="menu-current"' if @in_reader_function%>><a href="/reader">讀者服務</a></li> <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> <% if @current_user && @current_user.permission == 2%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> <% else %> - <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", :url => '/login' %> 後才能使用使用個人化服務。 + <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", {:url => '/login'}, :id => 'login-link' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> -</html> \ No newline at end of file +</html> diff --git a/app/views/reader/admin.html.erb b/app/views/reader/admin.html.erb new file mode 100644 index 0000000..56e3b4f --- /dev/null +++ b/app/views/reader/admin.html.erb @@ -0,0 +1,38 @@ +<h1>讀書心得管理</h1> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a></p> + +<form action="/reader/admin" method="get" accept-charset="utf-8"> +<p class="filter-title"> + 以ISBN過濾:<input type="text" name="isbn" value="<%=params[:isbn]%>" id="isbn"><br/> + 以讀者學號過濾:<input type="text" name="sid" value="<%=params[:sid]%>" id="sid"><br/> + <input type="submit" value="過濾 &rarr;"> +</p> +</form> + +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-7">書名</div> + <div class="span-7">內容</div> + <div class="span-4">撰寫日期</div> + <div class="span-3">分數</div> + <div class="span-2">行動</div> + </div> + </div> + <% @c.each do |c| %> + <div class="tbody"> + <div class="container"> + <div class="span-7"><%=c.commentable.title%></div> + <div class="span-7"><%=c.comment.chars[0..10]%>... (<a href="/reader/read/<%=c.id%>">完整內容</a>)</div> + <div class="span-4"><%=c.created_at.strftime("%Y/%m/%d")%></div> + <div class="span-3"><%if c.score%><%=c.score%><%else%><span style="color: red;">尚未評分</span><%end%></div> + <div class="span-2"> + <p class="clearfix"> + <a href="/reader/delete/<%=c.id%>" class="button pink minus" onclick="return confirm('確定要刪除心得嗎?')"><span><span>刪除</span></span></a> + </p> + </div> + </div> + </div> + <% end %> +</div> +<%=will_paginate @c, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> \ No newline at end of file diff --git a/app/views/reader/index.html.erb b/app/views/reader/index.html.erb new file mode 100644 index 0000000..31ed7c4 --- /dev/null +++ b/app/views/reader/index.html.erb @@ -0,0 +1,59 @@ +<h1>讀者服務與資訊</h1> + +<h2>您的個人資料</h2> +<div style="font-size: 1.2em; border-top: 1px solid #000;"> + 以下個人資料若有疑問,請向我們聯絡。以免您的借閱權利受到損害。<br/> + 登入帳號:<%[email protected]%><br/> + 學生證號:<%[email protected]_id%><br/> + 班級:<%[email protected]_class%><br/> + 姓名:<%[email protected]%><br/> + E-mail:<%[email protected]%><br/> +</div> +<br/> + +<h2>您最近的借閱記錄</h2> +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-10">書名</div> + <div class="span-4">ISBN</div> + <div class="span-4">借出日期</div> + <div class="span-4">歸還日期</div> + </div> + </div> + <% @r.each do |r| %> + <div class="tbody"> + <div class="container"> + <div class="span-10"><%=r.book.title%></div> + <div class="span-4"><%=r.book.isbn%></div> + <div class="span-4 last"><%=r.start_date.strftime("%Y/%m/%d")%></div> + <div class="span-4 last"><%if r.end_date%><%=r.end_date.strftime("%Y/%m/%d")%><%else%><span style="color: red;">尚未歸還</span><%end%></div> + </div> + </div> + <% end %> +</div> +<a href="/reader/rentlogs">更多紀錄...</a> +<br/> +<br/> +<h2>您撰寫過的讀書心得</h2> +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-7">書名</div> + <div class="span-9">內容</div> + <div class="span-4">撰寫日期</div> + <div class="span-3">分數</div> + </div> + </div> + <% @c.each do |c| %> + <div class="tbody"> + <div class="container"> + <div class="span-7"><%=c.commentable.title%></div> + <div class="span-9"><%=c.comment.chars[0..10]%>... (<a href="/reader/read/<%=c.id%>">完整內容</a>)</div> + <div class="span-4"><%=c.created_at.strftime("%Y/%m/%d")%></div> + <div class="span-3 last"><%if c.score%><%=c.score%><%else%><span style="color: red;">尚未評分</span><%end%></div> + </div> + </div> + <% end %> +</div> +<a href="/reader/list">更多紀錄...</a> diff --git a/app/views/reader/list.html.erb b/app/views/reader/list.html.erb new file mode 100644 index 0000000..e43b0d1 --- /dev/null +++ b/app/views/reader/list.html.erb @@ -0,0 +1,24 @@ +<h2>您撰寫過的讀書心得</h2> +<p class="clearfix"><a href="/reader" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a></p> + +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-7">書名</div> + <div class="span-9">內容</div> + <div class="span-4">撰寫日期</div> + <div class="span-3">分數</div> + </div> + </div> + <% @c.each do |c| %> + <div class="tbody"> + <div class="container"> + <div class="span-7"><%=c.commentable.title%></div> + <div class="span-9"><%=c.comment.chars[0..10]%>... (<a href="/reader/read/<%=c.id%>">完整內容</a>)</div> + <div class="span-4"><%=c.created_at.strftime("%Y/%m/%d")%></div> + <div class="span-3 last"><%if c.score%><%=c.score%><%else%><span style="color: red;">尚未評分</span><%end%></div> + </div> + </div> + <% end %> +</div> +<%=will_paginate @c, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> diff --git a/app/views/reader/read.html.erb b/app/views/reader/read.html.erb new file mode 100644 index 0000000..c2d82cc --- /dev/null +++ b/app/views/reader/read.html.erb @@ -0,0 +1,45 @@ +<script type="text/javascript" charset="utf-8" src="/javascripts/jquery.jeditable.pack.js"></script> +<script type="text/javascript" charset="utf-8"> + var post_token = '<%=form_authenticity_token%>'; + + $(function(){ + $('#comment-content').editable(function(v, s){ + $.post('/reader/edit/<%[email protected]%>', {value: v, authenticity_token: post_token}); + return v.replace(/\n/g,"<br/>"); + }, { + loadurl: '/reader/load_text/<%[email protected]%>', + id: 'eid', + type: 'textarea', + cancel: '取消', + submit: '編輯', + indicator: '<img src="/images/load.gif">', + tooltip: '點選以編輯心得...' + }); + }); +</script> +<h1>閱讀心得</h1> +<p class="clearfix"><a href="/books/show/<%[email protected]%>" class="button green back" style="margin-right: 10px;"><span><span>返回簡介</span></span></a></p> + +<div class="container"> + <div class="span-3"><a href="/books/show/<%[email protected]%>"><img src="<%=url_for_file_column @book, 'cover'%>" width="100" style="border: 2px solid #222; padding: 2px; margin: 2px;"></a></div> + <div class="span-20" style="margin: 2px;"> + 書名:<%[email protected]%><br/> + 作者:<%[email protected]%><br/> + 出版社:<%[email protected]%><br/> + 出版時間:<%[email protected]_at%><br/> + ISBN:<%[email protected]%><br/> + </div> +</div> +<br/> +<hr noshade/> +<h2>心得內容</h2> +<p>小技巧:若想編輯心得,請點選您的心得內容。</p> +<% if @comment.score %><span style="color: red;">評分:<%[email protected]%></span><% end %> +<div id="comment-content"><%[email protected]("\n", "<br/>")%></div> + +<p class="clearfix" style="border-top: 1px solid #DDD; padding-top: 5px;"><a href="/reader/delete/<%[email protected]%>" class="button dark x" style="margin-right: 10px;" onclick="this.blur();"><span><span>刪除心得</span></span></a></p> + +<% if @current_user.permission > 0%> +給分:<input type="text" name="score" value="" id="score"> +<p class="clearfix"><a href="#" class="button pink thumb" onclick="location.href='/reader/rate/<%[email protected]%>?score=' + $('#score').val();"><span><span>評分</span></span></a></p> +<% end %> diff --git a/app/views/reader/rentlogs.html.erb b/app/views/reader/rentlogs.html.erb new file mode 100644 index 0000000..7634475 --- /dev/null +++ b/app/views/reader/rentlogs.html.erb @@ -0,0 +1,24 @@ +<h1>館藏借閱歷史紀錄</h1> +<p class="clearfix"><a href="/reader" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a></p> + +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-10">書名</div> + <div class="span-4">ISBN</div> + <div class="span-4">借出日期</div> + <div class="span-4">歸還日期</div> + </div> + </div> + <% @r.each do |r| %> + <div class="tbody"> + <div class="container"> + <div class="span-10"><%=r.book.title%></div> + <div class="span-4"><%=r.book.isbn%></div> + <div class="span-4 last"><%=r.start_date.strftime("%Y/%m/%d")%></div> + <div class="span-4 last"><%if r.end_date%><%=r.end_date.strftime("%Y/%m/%d")%><%else%><span style="color: red;">尚未歸還</span><%end%></div> + </div> + </div> + <% end %> +</div> +<%=will_paginate @r, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> diff --git a/app/views/reader/write.html.erb b/app/views/reader/write.html.erb new file mode 100644 index 0000000..6ac8c56 --- /dev/null +++ b/app/views/reader/write.html.erb @@ -0,0 +1,26 @@ +<h1>撰寫心得</h1> +<p class="clearfix"><a href="/books/show/<%[email protected]%>" class="button green back" style="margin-right: 10px;"><span><span>返回簡介</span></span></a></p> +<div class="container"> + <div class="span-3"><a href="/books/show/<%[email protected]%>"><img src="<%=url_for_file_column @book, 'cover'%>" width="100" style="border: 2px solid #222; padding: 2px; margin: 2px;"></a></div> + <div class="span-20" style="margin: 2px;"> + 書名:<%[email protected]%><br/> + 作者:<%[email protected]%><br/> + 出版社:<%[email protected]%><br/> + 出版時間:<%[email protected]_at%><br/> + ISBN:<%[email protected]%><br/> + </div> +</div> +<br/> +<hr noshade/> +<% s = @book.comments.find(:all, :conditions => ['user_id = ?', @current_user.id]).size +if s > 0%> + <span style="color: red">提醒: 您已經寫過 <%=s%> 篇心得了。</span> +<% end %> +<form action="/reader/write/<%[email protected]%>" method="post" accept-charset="utf-8"> + <p>我的心得<br/> + <textarea name="content" rows="8" cols="40"></textarea> + </p> + + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + <p><input type="submit" value="送出心得 &rarr;"></p> +</form> \ No newline at end of file diff --git a/app/views/users/details.html.erb b/app/views/users/details.html.erb new file mode 100644 index 0000000..8c95457 --- /dev/null +++ b/app/views/users/details.html.erb @@ -0,0 +1,35 @@ +<h1>使用者詳細資料</h1> + +<p class="clearfix"><a href="/users/admin" class="button green back" style="margin-right: 10px;"><span><span>返回列表</span></span></a></p> + +<div style="font-size: 1.2em"> + 登入帳號:<%[email protected]%><br/> + 學生證號:<%[email protected]_id%><br/> + 班級:<%[email protected]_class%><br/> + 姓名:<%[email protected]%><br/> + E-mail:<%[email protected]%><br/> +</div> +<br/> +<div id="book-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-10">書名</div> + <div class="span-4">ISBN</div> + <div class="span-4">借出日期</div> + <div class="span-4">歸還日期</div> + </div> + </div> + <% @r.each do |r| %> + <div class="tbody"> + <div class="container"> + <div class="span-10"><%=r.book.title%></div> + <div class="span-4"><%=r.book.isbn%></div> + <div class="span-4 last"><%=r.start_date.strftime("%Y/%m/%d")%></div> + <div class="span-4 last"><%if r.end_date%><%=r.end_date.strftime("%Y/%m/%d")%><%else%><span style="color: red;">尚未歸還</span><%end%></div> + </div> + </div> + <% end %> +</div> + +<%=will_paginate @r, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> + diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index 829541b..95d48a4 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -1,12 +1,14 @@ <form action="/users/edit" method="post" accept-charset="utf-8" id="user-edit-form"> 登入帳號:<%[email protected]%><br/> <div style="float: left;">學生證號<br/><input type="text" name="student_id" value="<%[email protected]_id%>" id="student_id"></div> <div style="float: left;">班級<br/><input type="text" name="student_class" value="<%[email protected]_class%>" id="student_class"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">姓名<br/><input type="text" name="name" value="<%[email protected]%>" id="name"></div> <div style="float: left;">E-mail<br/><input type="text" name="email" value="<%[email protected]%>" id="email"></div> <div style="clear: both;">&nbsp;</div> + <div style="float: left;">密碼(不更動請留白)<br/><input type="text" name="password" value="" id="password"></div> + <div style="clear: both;">&nbsp;</div> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <input type="hidden" name="id" value="<%[email protected]%>" id="id"> <p class="clearfix"><a href="#" class="button normal check" onclick="$('#user-edit-form').submit(); this.blur(); return false;" style="margin-right: 10px;"><span><span>儲存修改</span></span></a> <a href="#" class="button dark x" onclick="restore_user(<%[email protected]%>); return false;"><span><span>取消</span></span></a></p> </form> diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb index 57c614d..f90a975 100644 --- a/app/views/welcome/admin.html.erb +++ b/app/views/welcome/admin.html.erb @@ -1,35 +1,36 @@ <div class="bkgwhite"> <div class="container"> <div class="span-11"> <p class="admin-title">圖書管理</p> <div class="admin-menu"> <a href="/books/admin">搜尋/維護館藏<span class="arrow">&raquo;</span></a> <a href="/books/new">新增館藏<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">館藏流通</p> <div class="admin-menu"> <a href="/books/circulation">借閱/還書介面<span class="arrow">&raquo;</span></a> - <a href="#">列出逾期書籍<span class="arrow">&raquo;</span></a> + <a href="/books/overdue">列出逾期館藏<span class="arrow">&raquo;</span></a> </div> </div> </div> <div class="container" style="margin-top: 10px;"> <div class="span-11"> <p class="admin-title">讀者資料</p> <div class="admin-menu"> <a href="/users/admin">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> <a href="/users/bulk_add">大批新增讀者<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">公告及其他</p> <div class="admin-menu"> <a href="/news/admin">公告管理<span class="arrow">&raquo;</span></a> <a href="/users/staff">工作人員權限管理<span class="arrow">&raquo;</span></a> + <a href="/reader/admin">讀書心得管理<span class="arrow">&raquo;</span></a> </div> </div> </div> </div> \ No newline at end of file diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb index 616aeed..8dda9d1 100644 --- a/app/views/welcome/index.html.erb +++ b/app/views/welcome/index.html.erb @@ -1,40 +1,50 @@ +<script src="/javascripts/jquery.browser.min.js" type="text/javascript"></script> + +<script type="text/javascript"> +$(function(){ + $('#login-link').click(function(){ + if ($.os.name == 'linux') + $('#iTunesAlbumArt').slideUp(); + }); +}); +</script> <div style="text-align: center; border: 1px solid #000; width:900px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="iTunesAlbumArt" align="middle" width="900" height="329"> <param name="allowScriptAccess" value="always"> <param name="allowFullScreen" value="false"> <param name="movie" value="/coverflow/iTunesAlbumArt.swf"> <param name="quality" value="high"> <param name="wmode" value="opaque"> <param name="bgcolor" value="#000000"> <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329" wmode="opaque"> </object> </div> <div class="container" style="margin-top: 5px;"> <div class="span-11" style="padding-right: 5px;"> <h2>圖書館部落格</h2> <ul style="margin-left: 30px;"> <% @news.each do |news| %> <li id="news-<%=news.id%>"><a href="/news/show/<%=news.id%>"><%=news.title%></a> - <%=news.created_at.strftime("%Y-%m-%d")%></li> <% end %> </ul> <%=link_to '更多消息...', :controller => 'news'%> </div> <div class="span-12 last" > <% if @current_user %> <h2>資訊快遞</h2> <ul style="margin-left: 30px;"> - <li>您目前共借閱 5 本書,2 本書即將到期。</li> - <li>您還需要繳交 3 篇讀書心得。</li> - </ul> + <li>您目前共借閱 <%=@rentlog_size%> 本書,<%=@needreturn_size%> 本書即將到期。</li> + <li>寫過了 <%=@comments_size%> 篇心得</li> + </ul> <%=link_to '詳細資訊...', :controller => 'reader'%> <% else %> <h2>隨機好書</h2> <ul style="margin-left: 30px;"> <% @random_books.each do |book| %> <a href="/books/show/<%=book.id%>"><img src="<%=url_for_file_column book, :cover%>" style="border: 2px solid #000; margin: 5px; padding: 5px; width: 80px;"></a> <% end %> </ul> <% end %> </div> -</div> \ No newline at end of file +</div> diff --git a/db/migrate/20080929222445_create_comments.rb b/db/migrate/20080929222445_create_comments.rb new file mode 100644 index 0000000..237ca1b --- /dev/null +++ b/db/migrate/20080929222445_create_comments.rb @@ -0,0 +1,18 @@ +class CreateComments < ActiveRecord::Migration + def self.up + create_table "comments", :force => true do |t| + t.column "title", :string, :limit => 50, :default => "" + t.column "comment", :text, :default => "" + t.column "created_at", :datetime, :null => false + t.column "commentable_id", :integer, :default => 0, :null => false + t.column "commentable_type", :string, :limit => 15, :default => "", :null => false + t.column "user_id", :integer, :default => 0, :null => false + end + + add_index "comments", ["user_id"], :name => "fk_comments_user" + end + + def self.down + drop_table :comments + end +end diff --git a/db/migrate/20080930191254_add_score_to_comment.rb b/db/migrate/20080930191254_add_score_to_comment.rb new file mode 100644 index 0000000..fce1595 --- /dev/null +++ b/db/migrate/20080930191254_add_score_to_comment.rb @@ -0,0 +1,9 @@ +class AddScoreToComment < ActiveRecord::Migration + def self.up + add_column :comments, :score, :interger + end + + def self.down + remove_column :comments, :score + end +end diff --git a/db/schema.rb b/db/schema.rb index fc9e9e7..8d61192 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,65 +1,77 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20080929193433) do +ActiveRecord::Schema.define(:version => 20080930191254) do create_table "blogs", :force => true do |t| t.string "title" t.string "content" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "books", :force => true do |t| t.string "cover" t.string "author" t.string "title" t.string "publisher" t.string "published_at" t.text "content" t.text "toc" t.text "problems" t.string "state" t.text "note", :limit => 255 t.string "isbn" t.datetime "created_at" t.datetime "updated_at" end + create_table "comments", :force => true do |t| + t.string "title", :limit => 50, :default => "" + t.text "comment", :default => "" + t.datetime "created_at", :null => false + t.integer "commentable_id", :default => 0, :null => false + t.string "commentable_type", :limit => 15, :default => "", :null => false + t.integer "user_id", :default => 0, :null => false + t.integer "score" + end + + add_index "comments", ["user_id"], :name => "fk_comments_user" + create_table "rent_logs", :force => true do |t| t.integer "book_id" t.integer "user_id" t.datetime "start_date" t.datetime "end_date" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" t.string "student_class" t.string "student_id" t.string "nickname" t.integer "permission" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end diff --git a/nbproject/private/rake-t.txt b/nbproject/private/rake-t.txt new file mode 100644 index 0000000..567080d --- /dev/null +++ b/nbproject/private/rake-t.txt @@ -0,0 +1,2 @@ +(in C:/Documents and Settings/Zero/My Documents/My Dropbox/Sites/2009csc) +Rails requires RubyGems >= 1.1.1 (you have 0.9.4). Please `gem update --system` and try again. diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..1e4b128 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,2 @@ +rails.port=3000 +source.encoding=UTF-8 diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..2c7b0b6 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.ruby.railsprojects</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/rails-project/1"> + <name>2009csc</name> + </data> + </configuration> +</project> diff --git a/public/facebox/facebox.css b/public/facebox/facebox.css index 97ebe3c..492e8fc 100644 --- a/public/facebox/facebox.css +++ b/public/facebox/facebox.css @@ -1,95 +1,96 @@ #facebox .b { background:url(/facebox/b.png); } #facebox .tl { background:url(/facebox/tl.png); } #facebox .tr { background:url(/facebox/tr.png); } #facebox .bl { background:url(/facebox/bl.png); } #facebox .br { background:url(/facebox/br.png); } #facebox { position: absolute; top: 0; left: 0; - z-index: 100; + z-index: 10000; text-align: left; + max-width: 500px; } #facebox .popup { position: relative; } #facebox table { border-collapse: collapse; } #facebox td { border-bottom: 0; padding: 0; } #facebox .body { padding: 10px; background: #fff; width: 370px; } #facebox .loading { text-align: center; } #facebox .image { text-align: center; } #facebox img { border: 0; margin: 0; } #facebox .footer { border-top: 1px solid #DDDDDD; padding-top: 5px; margin-top: 10px; text-align: right; } #facebox .tl, #facebox .tr, #facebox .bl, #facebox .br { height: 10px; width: 10px; overflow: hidden; padding: 0; } #facebox_overlay { position: fixed; top: 0px; left: 0px; height:100%; width:100%; } .facebox_hide { z-index:-100; } .facebox_overlayBG { background-color: #000; z-index: 99; } * html #facebox_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } diff --git a/public/javascripts/jquery.browser.min.js b/public/javascripts/jquery.browser.min.js new file mode 100644 index 0000000..4e21278 --- /dev/null +++ b/public/javascripts/jquery.browser.min.js @@ -0,0 +1 @@ +(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery); \ No newline at end of file diff --git a/public/javascripts/jquery.jeditable.pack.js b/public/javascripts/jquery.jeditable.pack.js new file mode 100644 index 0000000..ce99276 --- /dev/null +++ b/public/javascripts/jquery.jeditable.pack.js @@ -0,0 +1 @@ +eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.Q.b=5(E,16){4 1={E:E,A:\'29\',F:\'F\',i:\'Y\',g:\'X\',k:\'X\',z:\'12\',O:\'l\',1j:\'28\',1k:\'26...\',D:\'25 24 23\',s:{},n:{}};3(16){$.N(1,16)}4 13=$.b.f[1.i].13||5(){};4 a=$.b.f[1.i].a||5(){};4 L=$.b.f[1.i].L||$.b.f[\'C\'].L;4 x=$.b.f[1.i].x||$.b.f[\'C\'].x;4 u=$.b.f[1.i].u||$.b.f[\'C\'].u;4 h=$.b.f[1.i].h||$.b.f[\'C\'].h;4 U=1.U||5(){};3(!$.y($(7)[1.z])){$.Q[1.z]=5(Q){q Q?7.22(1.z,Q):7.21(1.z)}}$(7).j(\'20\',1.1Z);1.1s=\'X\'==1.g;1.1r=\'X\'==1.k;q 7.17(5(){4 2=7;4 1u=$(2).g();4 1t=$(2).k();3(!$.T($(7).9())){$(7).9(1.D)}$(7)[1.z](5(e){3(2.M){q}3(0==$(2).g()){1.g=1u;1.k=1t}c{3(1.g!=\'S\'){1.g=1.1s?$(2).g():1.g}3(1.k!=\'S\'){1.k=1.1r?$(2).k():1.k}}3($(7).9().1q().1p(/;/,\'\')==1.D.1q().1p(/;/,\'\')){$(7).9(\'\')}2.M=1l;2.w=$(2).9();$(2).9(\'\');4 8=$(\'<8/>\');3(1.14){3(\'1o\'==1.14){8.j(\'15\',$(2).j(\'15\'))}c{8.j(\'15\',1.14)}}3(1.H){3(\'1o\'==1.H){8.j(\'H\',$(2).j(\'H\'));8.1n(\'1m\',$(2).1n(\'1m\'))}c{8.j(\'H\',1.H)}}4 6=u.d(8,[1,2]);4 G;3(1.1i){4 t=1f(5(){6.1g=1l;x.d(8,[1.1k,1,2])},1Y);4 s={};s[1.F]=2.F;3($.y(1.s)){$.N(s,1.s.d(2,[2.w,1]))}c{$.N(s,1.s)}$.1X({i:1.1j,1W:1.1i,P:s,1V:v,1U:5(1h){1T.1e(t);G=1h;6.1g=v}})}c 3(1.P){G=1.P;3($.y(1.P)){G=1.P.d(2,[2.w,1])}}c{G=2.w}x.d(8,[G,1,2]);6.j(\'A\',1.A);L.d(8,[1,2]);$(2).p(8);13.d(8,[1,2]);$(\':6:1S:1R:1b\',8).1Q();3(1.o){6.o()}6.1P(5(e){3(e.1O==27){e.1d();h.d(8,[1,2])}});4 t;3(\'l\'==1.O){6.W(5(e){t=1f(5(){h.d(8,[1,2])},1N)})}c 3(\'a\'==1.O){6.W(5(e){8.a()})}c 3($.y(1.O)){6.W(5(e){1.O.d(2,[6.B(),1])})}c{6.W(5(e){})}8.a(5(e){3(t){1e(t)}e.1d();3(v!==a.d(8,[1,2])){3($.y(1.E)){4 V=1.E.d(2,[6.B(),1]);$(2).9(V);2.M=v;U.d(2,[2.1c,1]);3(!$.T($(2).9())){$(2).9(1.D)}}c{4 n={};n[1.A]=6.B();n[1.F]=2.F;3($.y(1.n)){$.N(n,1.n.d(2,[2.w,1]))}c{$.N(n,1.n)}3(\'1M\'==1.1L){n[\'1K\']=\'1J\'}$(2).9(1.1I);$.1H(1.E,n,5(V){$(2).9(V);2.M=v;U.d(2,[2.1c,1]);3(!$.T($(2).9())){$(2).9(1.D)}})}}q v})});7.h=5(){$(2).9(2.w);2.M=v;3(!$.T($(2).9())){$(2).9(1.D)}}})};$.b={f:{C:{u:5(1,m){4 6=$(\'<6 i="1G">\');$(7).p(6);q(6)},x:5(K,1,m){$(\':6:1b\',7).B(K)},h:5(1,m){m.h()},L:5(1,m){4 8=7;3(1.a){3(1.a.1a(/>$/)){4 a=$(1.a).12(5(){3(a.j("i")!="a"){8.a()}});}c{4 a=$(\'<19 i="a">\');a.9(1.a)}$(7).p(a)}3(1.l){3(1.l.1a(/>$/)){4 l=$(1.l);}c{4 l=$(\'<19 i="l">\');l.9(1.l)}$(7).p(l);$(l).12(5(z){3($.y($.b.f[1.i].h)){4 h=$.b.f[1.i].h}c{4 h=$.b.f[\'C\'].h}h.d(8,[1,m]);q v})}}},Y:{u:5(1,m){4 6=$(\'<6>\');3(1.g!=\'S\'){6.g(1.g)}3(1.k!=\'S\'){6.k(1.k)}6.j(\'1F\',\'1E\');$(7).p(6);q(6)}},r:{u:5(1,m){4 r=$(\'<r>\');3(1.11){r.j(\'11\',1.11)}c{r.k(1.k)}3(1.10){r.j(\'10\',1.10)}c{r.g(1.g)}$(7).p(r);q(r)}},o:{u:5(1,m){4 o=$(\'<o>\');$(7).p(o);q(o)},x:5(K,1,m){3(1D==K.1C){1B(\'4 I = \'+K);1A(4 J 1z I){3(!I.1y(J)){18}3(\'R\'==J){18}4 Z=$(\'<Z>\').B(J).p(I[J]);$(\'o\',7).p(Z)}}$(\'o\',7).1x().17(5(){3($(7).B()==I[\'R\']||$(7).Y()==m.w){$(7).j(\'R\',\'R\')}})}}},1w:5(A,6){$.b.f[A]=6}}})(1v);',62,134,'|settings|self|if|var|function|input|this|form|html|submit|editable|else|apply||types|width|reset|type|attr|height|cancel|original|submitdata|select|append|return|textarea|loaddata||element|false|revert|content|isFunction|event|name|val|defaults|placeholder|target|id|input_content|style|json|key|string|buttons|editing|extend|onblur|data|fn|selected|none|trim|callback|str|blur|auto|text|option|cols|rows|click|plugin|cssclass|class|options|each|continue|button|match|first|innerHTML|preventDefault|clearTimeout|setTimeout|disabled|result|loadurl|loadtype|loadtext|true|display|css|inherit|replace|toLowerCase|autoheight|autowidth|savedheight|savedwidth|jQuery|addInputType|children|hasOwnProperty|in|for|eval|constructor|String|off|autocomplete|hidden|post|indicator|put|_method|method|PUT|500|keyCode|keydown|focus|enabled|visible|window|success|async|url|ajax|100|tooltip|title|trigger|bind|edit|to|Click|Loading||GET|value'.split('|'),0,{})) diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index 8fbbcdc..b850a0b 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,299 +1,305 @@ /* layout */ body { background-color: #7C6255; font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; font-size: 11pt; } h1 { margin-top: 5px; border-bottom: 1px solid #CCC; } h2 { margin: 0; } #content { background-color: #FFF; padding: 10px; margin-top: -10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; padding-top: 5px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; border-left: 2px solid #FFF; border-top: 2px solid #FFF; border-right: 1px solid #FFF; background-color: #222; background-image: -webkit-gradient(linear, left top, left bottom, from(#666), to(#222)); padding: 5px; padding-top: 60px; margin-left: -1px; } #header-title ul li a { color: #fff; } #header-title ul li:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#444)); background-color: #444; } .menu-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#FFF)) !important; background-color: #FFF !important; } .menu-current a { color: #000 !important; } .menu-backstage { background-image: -webkit-gradient(linear, left top, left bottom, from(#C30017), to(#73000E)) !important; background-color: #73000E !important; } .menu-backstage:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#B20014)) !important; background-color: #920011 !important; } .menu-backstage-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#FFF), color-stop(0.8, #FFF)) !important; background-color: #FFF !important; } .menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; color: #FFF; word-spacing: 4px; font-family: Helvetica; } /* admin css */ .admin-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#C17436), to(#A9652F)); background-color: #C17436; color: #FFF; font-size: 2em; border-top: 1px solid #000; border-left: 1px solid #000; border-right: 1px solid #000; } .admin-menu { margin: 0; padding: 0; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; font-size: 1.75em; } .admin-menu a { display: block; padding: 2px; } .admin-menu .arrow { float: right; display: none; } .admin-menu a:hover { display: block; background-image: -webkit-gradient(linear, left top, left bottom, from(#0000FF), to(#000099)) !important; background-color: #000099; color: #FFF; text-decoration: none; } .table { font-size: 1.25em; border-bottom: 1px solid #000; } .table .thead { border-top: 1px solid #000; font-size: 1.25em; border-bottom: 1px dashed #000; } .table .tbody { border-top: 1px dashed #000; margin-top: -1px; } .table .tbody .container div { line-height: 30px; } .table .tbody .container p.clearfix { margin: 0px; } .table .tbody .container a.button { margin-top: 2px; } form input { font-size: 22pt; } form input[type="file"] { font-size: 1em !important; } form textarea { font-size: 18pt; } /* blog front */ .blog-date { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#444), to(#000)); background-color: #000; color: #FFF; letter-spacing: 0.3em; } .blog-title { font-size: 2em; color: rgb(99, 60, 17); margin: 0px; } .blog-content { margin-left: 10px; text-indent: 2em; } /* sidebar */ #sidebar { width: 230px; height: 600px; background: url('../images/bkg_blackboard.jpg') repeat-y; color: white; padding: 10px; padding-right: 35px; margin-left: -10px; -webkit-box-shadow: 0px 3px 5px black; -moz-box-shadow: 0px 3px 5px black; position: relative; float: left; } #sidebar { /* Damn IE fix */ height: auto; min-height: 600px; } #sidebar #metal_holder { width: 68px; height: 213px; background: url('../images/img_blackboard_holder.png') no-repeat; position: absolute; top: 200px; left: 240px; } #sidebar h1 { color: #FFF; border: none; } /* pagination */ .pagination { margin: 5px; font-size: 1.2em; } .pagination * { padding: 2px; } .pagination a { border: 1px solid #00F; } .pagination a:hover { border: 1px solid #00F; background-color: #00A; color: #FFF; } .pagination span.current { border: 1px solid #00E; background-color: #00F; color: #FFF; } /* filter css */ .filter-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#0D0099), to(#3D4C99)); background-color: #C17436; color: #FFF; font-size: 1.3em; border: 3px solid #333; } .filter-title input { font-size: 1.2em; } /* book admin */ .book-cover img { margin: 2px; border: 1px solid #000; width: 80px; } /* book circulation */ .mode-selector { display: inline; padding: 2px; margin-right: 2px; background-color: #00A; border: 2px solid #FF0; } .mode-selector a { color: #FFF; +} + +/* big button */ +.bigbutton { + border: 2px solid #000; + font-size: 22pt; } \ No newline at end of file diff --git a/test/fixtures/books.yml b/test/fixtures/books.yml index c004b20..f2437cf 100644 --- a/test/fixtures/books.yml +++ b/test/fixtures/books.yml @@ -1,28 +1,28 @@ # == Schema Information -# Schema version: 20080929055605 +# Schema version: 20080930191254 # # Table name: books # # id :integer not null, primary key # cover :string(255) # author :string(255) # title :string(255) # publisher :string(255) # published_at :string(255) # content :text # toc :text # problems :text # state :string(255) -# note :string(255) +# note :text(255) # isbn :string(255) # created_at :datetime # updated_at :datetime # # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # one: # column: value # # two: # column: value diff --git a/test/fixtures/rent_logs.yml b/test/fixtures/rent_logs.yml index 5bf0293..7109822 100644 --- a/test/fixtures/rent_logs.yml +++ b/test/fixtures/rent_logs.yml @@ -1,7 +1,21 @@ +# == Schema Information +# Schema version: 20080930191254 +# +# Table name: rent_logs +# +# id :integer not null, primary key +# book_id :integer +# user_id :integer +# start_date :datetime +# end_date :datetime +# created_at :datetime +# updated_at :datetime +# + # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # one: # column: value # # two: # column: value diff --git a/test/functional/reader_controller_test.rb b/test/functional/reader_controller_test.rb new file mode 100644 index 0000000..d698c4f --- /dev/null +++ b/test/functional/reader_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class ReaderControllerTest < ActionController::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/acts_as_commentable/CHANGELOG b/vendor/plugins/acts_as_commentable/CHANGELOG new file mode 100644 index 0000000..e8d823a --- /dev/null +++ b/vendor/plugins/acts_as_commentable/CHANGELOG @@ -0,0 +1,7 @@ +* revision 8: Changed has_many :dependent => true to :dependent => :destroy for Rails 1.2.2 + + Thanks Josh Martin + Added an order clause in the has_many relationship. + Made comment column type to text from string in migration example in README + + Thanks Patrick Crowley + Added this CHANGELOG file. + \ No newline at end of file diff --git a/vendor/plugins/acts_as_commentable/MIT-LICENSE b/vendor/plugins/acts_as_commentable/MIT-LICENSE new file mode 100644 index 0000000..f1929fb --- /dev/null +++ b/vendor/plugins/acts_as_commentable/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2006 Cosmin Radoi + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/plugins/acts_as_commentable/README b/vendor/plugins/acts_as_commentable/README new file mode 100644 index 0000000..813deb5 --- /dev/null +++ b/vendor/plugins/acts_as_commentable/README @@ -0,0 +1,59 @@ +Acts As Commentable +================= + +Allows for comments to be added to multiple and different models. + +== Resources + +Install + * Run the following command: + + script/plugin install http://juixe.com/svn/acts_as_commentable + + * Create a new rails migration and add the following self.up and self.down methods + + def self.up + create_table "comments", :force => true do |t| + t.column "title", :string, :limit => 50, :default => "" + t.column "comment", :text, :default => "" + t.column "created_at", :datetime, :null => false + t.column "commentable_id", :integer, :default => 0, :null => false + t.column "commentable_type", :string, :limit => 15, :default => "", :null => false + t.column "user_id", :integer, :default => 0, :null => false + end + + add_index "comments", ["user_id"], :name => "fk_comments_user" + end + + def self.down + drop_table :comments + end + +== Usage + + * Make you ActiveRecord model act as commentable. + + class Model < ActiveRecord::Base + acts_as_commentable + end + + * Add a comment to a model instance + + model = Model.new + comment = Comment.new + comment.comment = 'Some comment' + model.comments << comment + + * Each comment reference commentable object + + model = Model.find(1) + model.comments.get(0).commtable == model + +== Credits + +Xelipe - This plugin is heavily influced by Acts As Tagglable. + +== More + +http://www.juixe.com/techknow/index.php/2006/06/18/acts-as-commentable-plugin/ +http://www.juixe.com/projects/acts_as_commentable diff --git a/vendor/plugins/acts_as_commentable/init.rb b/vendor/plugins/acts_as_commentable/init.rb new file mode 100644 index 0000000..5e21861 --- /dev/null +++ b/vendor/plugins/acts_as_commentable/init.rb @@ -0,0 +1,3 @@ +# Include hook code here +require 'acts_as_commentable' +ActiveRecord::Base.send(:include, Juixe::Acts::Commentable) diff --git a/vendor/plugins/acts_as_commentable/install.rb b/vendor/plugins/acts_as_commentable/install.rb new file mode 100644 index 0000000..f7732d3 --- /dev/null +++ b/vendor/plugins/acts_as_commentable/install.rb @@ -0,0 +1 @@ +# Install hook code here diff --git a/vendor/plugins/acts_as_commentable/lib/acts_as_commentable.rb b/vendor/plugins/acts_as_commentable/lib/acts_as_commentable.rb new file mode 100644 index 0000000..73f31ad --- /dev/null +++ b/vendor/plugins/acts_as_commentable/lib/acts_as_commentable.rb @@ -0,0 +1,62 @@ +# ActsAsCommentable +module Juixe + module Acts #:nodoc: + module Commentable #:nodoc: + + def self.included(base) + base.extend ClassMethods + end + + module ClassMethods + def acts_as_commentable + has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at ASC' + include Juixe::Acts::Commentable::InstanceMethods + extend Juixe::Acts::Commentable::SingletonMethods + end + end + + # This module contains class methods + module SingletonMethods + # Helper method to lookup for comments for a given object. + # This method is equivalent to obj.comments. + def find_comments_for(obj) + commentable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s + + Comment.find(:all, + :conditions => ["commentable_id = ? and commentable_type = ?", obj.id, commentable], + :order => "created_at DESC" + ) + end + + # Helper class method to lookup comments for + # the mixin commentable type written by a given user. + # This method is NOT equivalent to Comment.find_comments_for_user + def find_comments_by_user(user) + commentable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s + + Comment.find(:all, + :conditions => ["user_id = ? and commentable_type = ?", user.id, commentable], + :order => "created_at DESC" + ) + end + end + + # This module contains instance methods + module InstanceMethods + # Helper method to sort comments by date + def comments_ordered_by_submitted + Comment.find(:all, + :conditions => ["commentable_id = ? and commentable_type = ?", id, self.type.name], + :order => "created_at DESC" + ) + end + + # Helper method that defaults the submitted time. + def add_comment(comment) + comments << comment + end + end + + end + end +end diff --git a/vendor/plugins/acts_as_commentable/lib/comment.rb b/vendor/plugins/acts_as_commentable/lib/comment.rb new file mode 100644 index 0000000..7a7ebba --- /dev/null +++ b/vendor/plugins/acts_as_commentable/lib/comment.rb @@ -0,0 +1,36 @@ +class Comment < ActiveRecord::Base + belongs_to :commentable, :polymorphic => true + named_scope :book_is, lambda { |args| {:conditions => "commentable_id = #{args}"}} + named_scope :user_is, lambda { |args| {:conditions => "user_id = #{args}"}} + + # NOTE: install the acts_as_votable plugin if you + # want user to vote on the quality of comments. + #acts_as_voteable + + # NOTE: Comments belong to a user + belongs_to :user + + # Helper class method to lookup all comments assigned + # to all commentable types for a given user. + def self.find_comments_by_user(user) + find(:all, + :conditions => ["user_id = ?", user.id], + :order => "created_at DESC" + ) + end + + # Helper class method to look up all comments for + # commentable class name and commentable id. + def self.find_comments_for_commentable(commentable_str, commentable_id) + find(:all, + :conditions => ["commentable_type = ? and commentable_id = ?", commentable_str, commentable_id], + :order => "created_at DESC" + ) + end + + # Helper class method to look up a commentable object + # given the commentable class name and id + def self.find_commentable(commentable_str, commentable_id) + commentable_str.constantize.find(commentable_id) + end +end \ No newline at end of file diff --git a/vendor/plugins/acts_as_commentable/tasks/acts_as_commentable_tasks.rake b/vendor/plugins/acts_as_commentable/tasks/acts_as_commentable_tasks.rake new file mode 100644 index 0000000..345eccb --- /dev/null +++ b/vendor/plugins/acts_as_commentable/tasks/acts_as_commentable_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :acts_as_commentable do +# # Task goes here +# end \ No newline at end of file diff --git a/vendor/plugins/acts_as_commentable/test/acts_as_commentable_test.rb b/vendor/plugins/acts_as_commentable/test/acts_as_commentable_test.rb new file mode 100644 index 0000000..32331b7 --- /dev/null +++ b/vendor/plugins/acts_as_commentable/test/acts_as_commentable_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class ActsAsCommentableTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end +end
itszero/eLib2
e4148a68bdeba501fe1c7b1eb92534430dbc1f2b
some fix, and circulation done
diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb index 7e643fb..66e368f 100644 --- a/app/controllers/books_controller.rb +++ b/app/controllers/books_controller.rb @@ -1,69 +1,117 @@ class BooksController < ApplicationController layout 'service' before_filter :admin_required, :except => [:index, :show] def index end def latest_xml @books = Book.find(:all, :order => "created_at DESC", :limit => 20) render :layout => false end + def circulation + @in_admin_function = true + end + def admin @in_admin_function = true if params[:filter] @books = Book.filter(params[:filter]).paginate :page => params[:page] else @books = Book.paginate :page => params[:page] end end def new @in_admin_function = true if request.post? @b = Book.new(params[:book]) if @b.save notice_stickie "館藏 #{params[:book][:title]} 新增成功!" else error_stickie '館藏無法新增,請檢查資料。 #{@b.errors.inspect}' end redirect_to :action => 'admin' end @b = Book.new end def edit @in_admin_function = true if request.post? @b = Book.find(params[:id]) @b.update_attributes params[:book] @b.save redirect_to :action => 'admin' return end @is_edit = true @b = Book.find(params[:id]) if !@b redirect_to :action => 'admin' return end render :action => 'new' end def delete Book.find(params[:id]).destroy redirect_to :action => 'admin' end def show + @in_books_function = true + @b = Book.find(params[:id]) end + + def get_book_status_by_isbn + @b = Book.find_by_isbn(params[:isbn]) + if !@b + render :text => 'fail:isbn' + return + end + + if @b.rentout? + render :text => 'fail:rent' + return + end + + render :text => @b.title + end + + def rent_book + @b = Book.find_by_isbn(params[:isbn]) + + if !@b + render :text => 'fail' + return + end + + @u = User.find_by_student_id(params[:stuid]) + + if !@u + render :text => 'fail' + return + end + + @b.rent_to(@u) + render :text => 'ok' + end + + def return_book + @b = Book.find_by_isbn(params[:isbn]) + + @b.return_book + + render :text => 'ok' + end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 5fba158..ed901c7 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,189 +1,200 @@ require 'csv' class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem layout 'service' before_filter :super_required, :only => [:staff, :demote, :promote] before_filter :admin_required, :except => [:index, :edit, :bulk_add, :demote, :promote] before_filter :login_required, :only => [:edit] def index redirect_to '/' end def admin @in_admin_function = true if !params[:id] @user = User.paginate :page => params[:page] else @u = User.find(params[:id]) render :partial => 'user_list_item' end end def staff @in_admin_function = true @user = User.find(:all, :conditions => 'permission > 0', :order => 'permission DESC, id ASC') end def promote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission+=1 if @user.permission < 2 @user.save notice_stickie "使用者 「#{@user.name}」 已提昇權限" redirect_to :action => :staff end def demote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission-=1 if @user.permission > 1 @user.save notice_stickie "使用者 「#{@user.name}」 已降低權限" redirect_to :action => :staff end def set_permission suppress(ActiveRecord::RecordNotFound) do @user = User.find(params[:id]) end suppress(ActiveRecord::RecordNotFound) do @user = User.find_by_login(params[:id]) if !@user end if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission = params[:permission] if params[:permission].to_i == 0 notice_stickie "使用者 「#{@user.name}」 的權限已取消。" elsif params[:permission].to_i > 0 notice_stickie "使用者 「#{@user.name}」 已經設定為工作人員。" end @user.save redirect_to :action => :staff end def uid_autocomplete @users = User.find(:all, :conditions => "login LIKE '%#{params[:q]}%'") render :text => (@users.map &:login).join("\n") end def bulk_add @in_admin_function = true if request.post? csv = CSV.parse(params[:csv].read) header = csv.shift # check reader expect_header = ['login', 'email', 'password', 'name', 'student_id', 'student_class'] pass = true expect_header.each do |h| pass = false if !header.include? h end if !pass error_stickie "匯入的欄位有缺失,請檢查CSV檔案!" redirect_to :action => :bulk_add return end # read it result = [] csv.each do |row| result << Hash[*header.zip(row.to_a).flatten] end errors = [] # add it result.each do |r| u = User.new(r) u.password_confirmation = u.password if !u.save errors << "使用者 #{r["login"]} 無法新增,請檢查資料。" end end if errors != [] error_stickie errors.join("<br/>") end notice_stickie("收到 #{result.size} 筆資料,成功新增 #{result.size - errors.size} 筆,失敗 #{errors.size} 筆。") redirect_to :action => :bulk_add end end def create @user = User.new @user.login = params[:login] @user.password = params[:password] @user.password_confirmation = params[:password_confirmation] @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] if @user.save notice_stickie "使用者 #{params[:login]} 建立成功" else error_stickie "無法建立使用者 #{params[:login]}<br/>#{@user.errors.inspect}" end redirect_to :action => 'admin' end def delete User.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? if @current_user.permission == 2 || @current_user.id == params[:id] @user = User.find(params[:id]) @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] @user.save end if @current_user.permission > 0 redirect_to '/users/admin' else redirect_to '/users/edit' end else if @current_user.permission == 0 @u = User.find(@current_user.id) else @u = User.find(params[:id]) render :layout => false end end end + + def get_reader_status_by_student_id + @u = User.find_by_student_id(params[:id]) + + if !@u + render :text => 'fail:noid' + return + end + + render :text => @u.name + end end diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb index 73c8a31..95339db 100644 --- a/app/controllers/welcome_controller.rb +++ b/app/controllers/welcome_controller.rb @@ -1,13 +1,22 @@ class WelcomeController < ApplicationController layout 'service' before_filter :admin_required, :only => :admin def index @in_homepage_function = true @news = Blog.find(:all, :order => "created_at DESC", :limit => 5) + @random_books = [] + maxid = Book.find(:first, :order => "id DESC").id + until @random_books.size >= 6 + b = nil + suppress(ActiveRecord::RecordNotFound) do + b = Book.find(rand(maxid) + 1) + end + @random_books << b if b && !@random_books.include?(b) + end end def admin @in_admin_function = true end end diff --git a/app/models/book.rb b/app/models/book.rb index 6404dc5..afac9c5 100644 --- a/app/models/book.rb +++ b/app/models/book.rb @@ -1,40 +1,58 @@ # == Schema Information # Schema version: 20080929055605 # # Table name: books # # id :integer not null, primary key # cover :string(255) # author :string(255) # title :string(255) # publisher :string(255) # published_at :string(255) # content :text # toc :text # problems :text # state :string(255) # note :string(255) # isbn :string(255) # created_at :datetime # updated_at :datetime # class Book < ActiveRecord::Base acts_as_state_machine :initial => :on_shelf file_column :cover validates_file_format_of :cover, :in => ['jpg', 'gif', 'png'] named_scope :filter, lambda { |args| {:conditions => "title LIKE '%#{args}%' OR author LIKE '%#{args}%' OR publisher LIKE '%#{args}%' OR content LIKE '%#{args}%' OR isbn LIKE '%#{args}%' OR note LIKE '%#{args}%"}} state :on_shelf state :rentout event :rent do transitions :from => :on_shelf, :to => :rentout end event :return do transitions :from => :rentout, :to => :on_shelf end + + def rent_to(user) + rent! + + @log = RentLog.new + @log.book_id = self.id + @log.user_id = user.id + @log.start_date = DateTime.now + @log.save + end + + def return_book + return! + + @log = RentLog.find(:first, :conditions => ['book_id = ?', self.id]) + @log.end_date = DateTime.now + @log.save + end end diff --git a/app/models/rent_log.rb b/app/models/rent_log.rb new file mode 100644 index 0000000..22ddc9d --- /dev/null +++ b/app/models/rent_log.rb @@ -0,0 +1,2 @@ +class RentLog < ActiveRecord::Base +end diff --git a/app/views/books/circulation.html.erb b/app/views/books/circulation.html.erb new file mode 100644 index 0000000..3c1aee0 --- /dev/null +++ b/app/views/books/circulation.html.erb @@ -0,0 +1,115 @@ +<h1>借閱/還書介面</h1> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a> +</p> + +<div id="rent-form" style="font-size: 1.5em;"> + ISBN條碼<br/> + <form onsubmit="return false;"> + <input type="text" name="isbn" value="" id="rent-isbn" style="font-size: 1.5em;"><img src="/images/load.gif" id="chk-rent-isbn" style="display: none;"><span id="rent-isbn-msg"></span><br/> + 學生證號<br/> + <input type="text" name="stuid" value="" id="rent-stuid" style="font-size: 1.5em;"><img src="/images/load.gif" id="chk-rent-stuid" style="display: none;"><span id="rent-stuid-msg"></span><br/> + <br/> + 狀態:<span id="rent-status">等候輸入</span> + </form> +</div> + +<script type="text/javascript" charset="utf-8"> + $(function(){ + $('#rent-form input').val(''); + $('#rent-isbn').focus(); + }); + + $('#rent-isbn').keydown(function(e){ + if (e.keyCode == 13) + { + $('#chk-rent-isbn').show(); + $('#rent-status').html('檢查書本狀態中...'); + + $.get('/books/get_book_status_by_isbn', {isbn: $('#rent-isbn').val()}, function(data) + { + $('#chk-rent-isbn').hide(); + if (data == 'fail:isbn') + { + $('#rent-status').html('找不到對應的書籍,請檢查ISBN是否正確。') + $('#rent-isbn').val(''); + $('#rent-isbn').focus(); + } + else if (data == 'fail:rent') + { + $('#rent-status').html('此書已外借,正在進行還書作業...<img src="/images/load.gif">'); + do_return_book(); + } + else + { + $('#rent-isbn-msg').html(data); + $('#rent-status').html('ISBN 正確,請輸入學生證號。'); + $('#rent-stuid').focus(); + } + }); + } + }); + + $('#rent-stuid').keydown(function(e){ + if (e.keyCode == 13) + { + $('#chk-rent-stuid').show(); + $('#rent-status').html('檢查學生證號中...'); + + $.get('/users/get_reader_status_by_student_id', {id: $('#rent-stuid').val()}, function(data) + { + $('#chk-rent-stuid').hide(); + if (data == 'fail:noid') + { + $('#rent-status').html('找不到學生,請檢查學號是否正確。') + $('#rent-stuid').val(''); + $('#rent-stuid').focus(); + } + else + { + $('#rent-stuid-msg').html(data); + $('#rent-status').html('學生證號正確,處理借書中...<img src="/images/load.gif">'); + do_rent_book(); + } + }); + } + }); + + function do_rent_book() + { + var stuid = $('#rent-stuid').val(); + var isbn = $('#rent-isbn').val(); + + $.get('/books/rent_book', {isbn: isbn, stuid: stuid}, function(data){ + if (data == 'ok') + $('#rent-status').html('館藏外借成功!'); + else + $('#rent-status').html('館藏外借失敗,請再嘗試一次。'); + + $('#rent-isbn').val(''); + $('#rent-stuid').val(''); + $('#rent-isbn-msg').html(''); + $('#rent-stuid-msg').html(''); + $('#rent-isbn').focus(); + }); + } + + function do_return_book() + { + var isbn = $('#rent-isbn').val(); + + $.get('/books/return_book', {isbn: isbn}, function(data){ + if (data == 'ok') + $('#rent-status').html('館藏歸還成功!'); + else + $('#rent-status').html('館藏歸還作業失敗,請再嘗試一次。'); + + $('#rent-isbn').val(''); + $('#rent-stuid').val(''); + $('#rent-isbn-msg').html(''); + $('#rent-stuid-msg').html(''); + $('#rent-isbn').focus(); + }); + } + +</script> + diff --git a/app/views/books/show.html.erb b/app/views/books/show.html.erb index 02cd82a..3a8c080 100644 --- a/app/views/books/show.html.erb +++ b/app/views/books/show.html.erb @@ -1,18 +1,20 @@ <p class="clearfix"><a href="javascript:history.go(-1);" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a></p> <h1>館藏簡介</h1> <div style="float: left; border: 2px solid #222; padding: 2px; margin: 2px;"><img src="<%=url_for_file_column @b, 'cover'%>" width="150"></div> <div style="float: left; padding: 2px; margin: 2px; font-size: 1.5em;"> 書名:<%[email protected]%><br/> 作者:<%[email protected]%><br/> 出版社:<%[email protected]%><br/> 出版時間:<%[email protected]_at%><br/> ISBN:<%[email protected]%><br/> <p>目前本書 <span style="color: red;"><% if @b.state == 'on_shelf'%>可外借<% elsif @b.state == 'rentout' %>借出中<% end %></span>。</p></div> <div style="clear: both;"></div> <br/> <h1>內容簡介</h1> <%[email protected]("\n", "<br/>")%> <br/><br/> +<% if @current_user.permission > 0 %> <h1 style="color: red">館員備註</h1> <%[email protected]("\n", "<br/>")%> +<% end %> diff --git a/app/views/news/_news_list_item.html.erb b/app/views/news/_news_list_item.html.erb index 8ffe7fb..37adf69 100644 --- a/app/views/news/_news_list_item.html.erb +++ b/app/views/news/_news_list_item.html.erb @@ -1,11 +1,11 @@ <div class="container"> <div class="span-3"><%[email protected]_at.strftime("%Y-%m-%d")%></div> - <div class="span-15"><a href="#" id="btn-content-<%[email protected]%>" class="button no-text down" style="margin-right: 10px;" onclick="return toggle_content(this);"><span><span>&nbsp;</span></span></a><%[email protected]%></div> + <div class="span-15"><a href="#" id="btn-content-<%[email protected]%>" class="button down" style="margin-right: 10px;" onclick="return toggle_content(this);"><span><span>詳細</span></span></a><%[email protected]%></div> <div class="span-4 last"> <p class="clearfix"><a href="#" class="button dark pencil" style="margin-right: 10px;" onclick="edit_news(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/news/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除新聞 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> </div> </div> <div class="container" id="content-<%[email protected]%>" style="display: none;"> <div class="span-3">&nbsp;</div> <div class="span-19 last"><%[email protected]("\n", "<br/>")%></div> </div> diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb index d15cdca..57c614d 100644 --- a/app/views/welcome/admin.html.erb +++ b/app/views/welcome/admin.html.erb @@ -1,35 +1,35 @@ <div class="bkgwhite"> <div class="container"> <div class="span-11"> <p class="admin-title">圖書管理</p> <div class="admin-menu"> <a href="/books/admin">搜尋/維護館藏<span class="arrow">&raquo;</span></a> <a href="/books/new">新增館藏<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">館藏流通</p> <div class="admin-menu"> - <a href="#">借閱/還書介面<span class="arrow">&raquo;</span></a> + <a href="/books/circulation">借閱/還書介面<span class="arrow">&raquo;</span></a> <a href="#">列出逾期書籍<span class="arrow">&raquo;</span></a> </div> </div> </div> <div class="container" style="margin-top: 10px;"> <div class="span-11"> <p class="admin-title">讀者資料</p> <div class="admin-menu"> <a href="/users/admin">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> <a href="/users/bulk_add">大批新增讀者<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">公告及其他</p> <div class="admin-menu"> <a href="/news/admin">公告管理<span class="arrow">&raquo;</span></a> <a href="/users/staff">工作人員權限管理<span class="arrow">&raquo;</span></a> </div> </div> </div> </div> \ No newline at end of file diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb index f43dab5..616aeed 100644 --- a/app/views/welcome/index.html.erb +++ b/app/views/welcome/index.html.erb @@ -1,35 +1,40 @@ <div style="text-align: center; border: 1px solid #000; width:900px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="iTunesAlbumArt" align="middle" width="900" height="329"> <param name="allowScriptAccess" value="always"> <param name="allowFullScreen" value="false"> <param name="movie" value="/coverflow/iTunesAlbumArt.swf"> <param name="quality" value="high"> <param name="wmode" value="opaque"> <param name="bgcolor" value="#000000"> <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329" wmode="opaque"> </object> </div> <div class="container" style="margin-top: 5px;"> - <div class="span-11" style="padding-right: 5px; border-right: 2px dashed #000;"> + <div class="span-11" style="padding-right: 5px;"> <h2>圖書館部落格</h2> <ul style="margin-left: 30px;"> <% @news.each do |news| %> <li id="news-<%=news.id%>"><a href="/news/show/<%=news.id%>"><%=news.title%></a> - <%=news.created_at.strftime("%Y-%m-%d")%></li> <% end %> </ul> <%=link_to '更多消息...', :controller => 'news'%> </div> - <div class="span-12 last"> + <div class="span-12 last" > <% if @current_user %> <h2>資訊快遞</h2> <ul style="margin-left: 30px;"> <li>您目前共借閱 5 本書,2 本書即將到期。</li> <li>您還需要繳交 3 篇讀書心得。</li> </ul> <%=link_to '詳細資訊...', :controller => 'reader'%> <% else %> - <h2>熱門書籍</h2> + <h2>隨機好書</h2> + <ul style="margin-left: 30px;"> + <% @random_books.each do |book| %> + <a href="/books/show/<%=book.id%>"><img src="<%=url_for_file_column book, :cover%>" style="border: 2px solid #000; margin: 5px; padding: 5px; width: 80px;"></a> + <% end %> + </ul> <% end %> </div> </div> \ No newline at end of file diff --git a/db/migrate/20080929193433_create_rent_logs.rb b/db/migrate/20080929193433_create_rent_logs.rb new file mode 100644 index 0000000..98aa9ef --- /dev/null +++ b/db/migrate/20080929193433_create_rent_logs.rb @@ -0,0 +1,15 @@ +class CreateRentLogs < ActiveRecord::Migration + def self.up + create_table :rent_logs do |t| + t.column :book_id, :integer + t.column :user_id, :integer + t.column :start_date, :datetime + t.column :end_date, :datetime + t.timestamps + end + end + + def self.down + drop_table :rent_logs + end +end diff --git a/db/schema.rb b/db/schema.rb index 1a45866..fc9e9e7 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,56 +1,65 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20080929183826) do +ActiveRecord::Schema.define(:version => 20080929193433) do create_table "blogs", :force => true do |t| t.string "title" t.string "content" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "books", :force => true do |t| t.string "cover" t.string "author" t.string "title" t.string "publisher" t.string "published_at" t.text "content" t.text "toc" t.text "problems" t.string "state" t.text "note", :limit => 255 t.string "isbn" t.datetime "created_at" t.datetime "updated_at" end + create_table "rent_logs", :force => true do |t| + t.integer "book_id" + t.integer "user_id" + t.datetime "start_date" + t.datetime "end_date" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" t.string "student_class" t.string "student_id" t.string "nickname" t.integer "permission" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end diff --git a/public/images/load.gif b/public/images/load.gif new file mode 100644 index 0000000..3c2f7c0 Binary files /dev/null and b/public/images/load.gif differ diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index 9108cf8..8fbbcdc 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,286 +1,299 @@ /* layout */ body { background-color: #7C6255; font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; font-size: 11pt; } h1 { margin-top: 5px; border-bottom: 1px solid #CCC; } h2 { margin: 0; } #content { background-color: #FFF; padding: 10px; margin-top: -10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; padding-top: 5px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; border-left: 2px solid #FFF; border-top: 2px solid #FFF; border-right: 1px solid #FFF; background-color: #222; background-image: -webkit-gradient(linear, left top, left bottom, from(#666), to(#222)); padding: 5px; padding-top: 60px; margin-left: -1px; } #header-title ul li a { color: #fff; } #header-title ul li:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#444)); background-color: #444; } .menu-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#FFF)) !important; background-color: #FFF !important; } .menu-current a { color: #000 !important; } .menu-backstage { background-image: -webkit-gradient(linear, left top, left bottom, from(#C30017), to(#73000E)) !important; background-color: #73000E !important; } .menu-backstage:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#B20014)) !important; background-color: #920011 !important; } .menu-backstage-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#FFF), color-stop(0.8, #FFF)) !important; background-color: #FFF !important; } .menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; color: #FFF; word-spacing: 4px; font-family: Helvetica; } /* admin css */ .admin-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#C17436), to(#A9652F)); background-color: #C17436; color: #FFF; font-size: 2em; border-top: 1px solid #000; border-left: 1px solid #000; border-right: 1px solid #000; } .admin-menu { margin: 0; padding: 0; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; font-size: 1.75em; } .admin-menu a { display: block; padding: 2px; } .admin-menu .arrow { float: right; display: none; } .admin-menu a:hover { display: block; background-image: -webkit-gradient(linear, left top, left bottom, from(#0000FF), to(#000099)) !important; background-color: #000099; color: #FFF; text-decoration: none; } .table { font-size: 1.25em; border-bottom: 1px solid #000; } .table .thead { border-top: 1px solid #000; font-size: 1.25em; border-bottom: 1px dashed #000; } .table .tbody { border-top: 1px dashed #000; margin-top: -1px; } .table .tbody .container div { line-height: 30px; } .table .tbody .container p.clearfix { margin: 0px; } .table .tbody .container a.button { margin-top: 2px; } form input { font-size: 22pt; } form input[type="file"] { font-size: 1em !important; } form textarea { font-size: 18pt; } /* blog front */ .blog-date { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#444), to(#000)); background-color: #000; color: #FFF; letter-spacing: 0.3em; } .blog-title { font-size: 2em; color: rgb(99, 60, 17); margin: 0px; } .blog-content { margin-left: 10px; text-indent: 2em; } /* sidebar */ #sidebar { width: 230px; height: 600px; background: url('../images/bkg_blackboard.jpg') repeat-y; color: white; padding: 10px; padding-right: 35px; margin-left: -10px; -webkit-box-shadow: 0px 3px 5px black; -moz-box-shadow: 0px 3px 5px black; position: relative; float: left; } #sidebar { /* Damn IE fix */ height: auto; min-height: 600px; } #sidebar #metal_holder { width: 68px; height: 213px; background: url('../images/img_blackboard_holder.png') no-repeat; position: absolute; top: 200px; left: 240px; } #sidebar h1 { color: #FFF; border: none; } /* pagination */ .pagination { margin: 5px; font-size: 1.2em; } .pagination * { padding: 2px; } .pagination a { border: 1px solid #00F; } .pagination a:hover { border: 1px solid #00F; background-color: #00A; color: #FFF; } .pagination span.current { border: 1px solid #00E; background-color: #00F; color: #FFF; } /* filter css */ .filter-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#0D0099), to(#3D4C99)); background-color: #C17436; color: #FFF; font-size: 1.3em; border: 3px solid #333; } .filter-title input { font-size: 1.2em; } /* book admin */ .book-cover img { margin: 2px; border: 1px solid #000; width: 80px; +} + +/* book circulation */ +.mode-selector { + display: inline; + padding: 2px; + margin-right: 2px; + background-color: #00A; + border: 2px solid #FF0; +} + +.mode-selector a { + color: #FFF; } \ No newline at end of file diff --git a/test/fixtures/rent_logs.yml b/test/fixtures/rent_logs.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/rent_logs.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/unit/rent_log_test.rb b/test/unit/rent_log_test.rb new file mode 100644 index 0000000..12800e0 --- /dev/null +++ b/test/unit/rent_log_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class RentLogTest < ActiveSupport::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end
itszero/eLib2
6daa23d99d6bcdb498df1589de32012b3fc25be4
books, coverflow
diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb new file mode 100644 index 0000000..7e643fb --- /dev/null +++ b/app/controllers/books_controller.rb @@ -0,0 +1,69 @@ +class BooksController < ApplicationController + layout 'service' + before_filter :admin_required, :except => [:index, :show] + + def index + end + + def latest_xml + @books = Book.find(:all, :order => "created_at DESC", :limit => 20) + + render :layout => false + end + + def admin + @in_admin_function = true + if params[:filter] + @books = Book.filter(params[:filter]).paginate :page => params[:page] + else + @books = Book.paginate :page => params[:page] + end + end + + def new + @in_admin_function = true + if request.post? + @b = Book.new(params[:book]) + + if @b.save + notice_stickie "館藏 #{params[:book][:title]} 新增成功!" + else + error_stickie '館藏無法新增,請檢查資料。 #{@b.errors.inspect}' + end + redirect_to :action => 'admin' + end + + @b = Book.new + end + + def edit + @in_admin_function = true + if request.post? + @b = Book.find(params[:id]) + @b.update_attributes params[:book] + @b.save + + redirect_to :action => 'admin' + return + end + + @is_edit = true + + @b = Book.find(params[:id]) + if !@b + redirect_to :action => 'admin' + return + end + + render :action => 'new' + end + + def delete + Book.find(params[:id]).destroy + redirect_to :action => 'admin' + end + + def show + @b = Book.find(params[:id]) + end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 93a897a..5fba158 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,188 +1,189 @@ require 'csv' class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem layout 'service' before_filter :super_required, :only => [:staff, :demote, :promote] before_filter :admin_required, :except => [:index, :edit, :bulk_add, :demote, :promote] before_filter :login_required, :only => [:edit] def index redirect_to '/' end def admin @in_admin_function = true if !params[:id] @user = User.paginate :page => params[:page] else @u = User.find(params[:id]) render :partial => 'user_list_item' end end def staff + @in_admin_function = true @user = User.find(:all, :conditions => 'permission > 0', :order => 'permission DESC, id ASC') end def promote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission+=1 if @user.permission < 2 @user.save notice_stickie "使用者 「#{@user.name}」 已提昇權限" redirect_to :action => :staff end def demote @user = User.find(params[:id]) if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission-=1 if @user.permission > 1 @user.save notice_stickie "使用者 「#{@user.name}」 已降低權限" redirect_to :action => :staff end def set_permission suppress(ActiveRecord::RecordNotFound) do @user = User.find(params[:id]) end suppress(ActiveRecord::RecordNotFound) do @user = User.find_by_login(params[:id]) if !@user end if !@user error_stickie "找不到使用者 ##{params[:id]}" redirect_to :action => :staff return end @user.permission = params[:permission] if params[:permission].to_i == 0 notice_stickie "使用者 「#{@user.name}」 的權限已取消。" elsif params[:permission].to_i > 0 notice_stickie "使用者 「#{@user.name}」 已經設定為工作人員。" end @user.save redirect_to :action => :staff end def uid_autocomplete @users = User.find(:all, :conditions => "login LIKE '%#{params[:q]}%'") render :text => (@users.map &:login).join("\n") end def bulk_add @in_admin_function = true if request.post? csv = CSV.parse(params[:csv].read) header = csv.shift # check reader expect_header = ['login', 'email', 'password', 'name', 'student_id', 'student_class'] pass = true expect_header.each do |h| pass = false if !header.include? h end if !pass error_stickie "匯入的欄位有缺失,請檢查CSV檔案!" redirect_to :action => :bulk_add return end # read it result = [] csv.each do |row| result << Hash[*header.zip(row.to_a).flatten] end errors = [] # add it result.each do |r| u = User.new(r) u.password_confirmation = u.password if !u.save errors << "使用者 #{r["login"]} 無法新增,請檢查資料。" end end if errors != [] error_stickie errors.join("<br/>") end notice_stickie("收到 #{result.size} 筆資料,成功新增 #{result.size - errors.size} 筆,失敗 #{errors.size} 筆。") redirect_to :action => :bulk_add end end def create @user = User.new @user.login = params[:login] @user.password = params[:password] @user.password_confirmation = params[:password_confirmation] @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] if @user.save notice_stickie "使用者 #{params[:login]} 建立成功" else error_stickie "無法建立使用者 #{params[:login]}<br/>#{@user.errors.inspect}" end redirect_to :action => 'admin' end def delete User.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? if @current_user.permission == 2 || @current_user.id == params[:id] @user = User.find(params[:id]) @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] @user.save end if @current_user.permission > 0 redirect_to '/users/admin' else redirect_to '/users/edit' end else if @current_user.permission == 0 @u = User.find(@current_user.id) else @u = User.find(params[:id]) render :layout => false end end end end diff --git a/app/helpers/books_helper.rb b/app/helpers/books_helper.rb new file mode 100644 index 0000000..4b9311e --- /dev/null +++ b/app/helpers/books_helper.rb @@ -0,0 +1,2 @@ +module BooksHelper +end diff --git a/app/models/book.rb b/app/models/book.rb new file mode 100644 index 0000000..6404dc5 --- /dev/null +++ b/app/models/book.rb @@ -0,0 +1,40 @@ +# == Schema Information +# Schema version: 20080929055605 +# +# Table name: books +# +# id :integer not null, primary key +# cover :string(255) +# author :string(255) +# title :string(255) +# publisher :string(255) +# published_at :string(255) +# content :text +# toc :text +# problems :text +# state :string(255) +# note :string(255) +# isbn :string(255) +# created_at :datetime +# updated_at :datetime +# + +class Book < ActiveRecord::Base + acts_as_state_machine :initial => :on_shelf + + file_column :cover + validates_file_format_of :cover, :in => ['jpg', 'gif', 'png'] + + named_scope :filter, lambda { |args| {:conditions => "title LIKE '%#{args}%' OR author LIKE '%#{args}%' OR publisher LIKE '%#{args}%' OR content LIKE '%#{args}%' OR isbn LIKE '%#{args}%' OR note LIKE '%#{args}%"}} + + state :on_shelf + state :rentout + + event :rent do + transitions :from => :on_shelf, :to => :rentout + end + + event :return do + transitions :from => :rentout, :to => :on_shelf + end +end diff --git a/app/views/books/admin.html.erb b/app/views/books/admin.html.erb new file mode 100644 index 0000000..df807e0 --- /dev/null +++ b/app/views/books/admin.html.erb @@ -0,0 +1,45 @@ +<h1>搜尋/維護館藏</h1> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a> +<a href="/books/new" class="button pink plus" style="margin-right: 10px;" onclick="this.blur();"><span><span>新增館藏資料</span></span></a></p> + +<p class="filter-title">過濾館藏資訊:<input type="text" name="filter" value="<%=params[:filter]%>" id="filter"><input type="button" value="過濾" id="btn-filter">(標題, 作者, 出版社, ISBN, 內容簡介, 備註)</p> + +<script type="text/javascript" charset="utf-8"> + $('#filter').keydown(function(e){ + if (e.keyCode == 13) $('#btn-filter').click(); + }); + + $('#btn-filter').click(function(){ + location.href='/books/admin?page=<%=params[:page] || 1%>&filter=' + $('#filter').val(); + }); +</script> + +<div id="news-list" class="table"> + <div class="thead"> + <div class="container"> + <div class="span-3">封面</div> + <div class="span-4">書名</div> + <div class="span-4">出版社</div> + <div class="span-4">作者</div> + <div class="span-4">ISBN</div> + <div class="span-4 last">行動</div> + </div> + </div> + +<% @books.each do |b| %> + <div class="tbody"> + <div class="container"> + <div class="span-3 book-cover"><img src="<%=url_for_file_column b, 'cover'%>"></div> + <div class="span-4"><%=b.title%></div> + <div class="span-4"><%=b.publisher%></div> + <div class="span-4"><%=b.author%></div> + <div class="span-4"><%=b.isbn%></div> + <div class="span-4 last"> + <p class="clearfix"><a href="/books/edit/<%=b.id%>" class="button dark pencil" style="margin-right: 10px;" onclick="this.blur();" id="btn-edit-"><span><span>編輯</span></span></a><a href="/books/show/<%=b.id%>" class="button alt star" style="margin-right: 10px;" onclick="this.blur();" id="btn-detail-<%=b.id%>"><span><span>詳細記錄</span></span></a><a href="/books/delete/<%=b.id%>" class="button pink minus" onclick="return confirm('請確認是否刪除館藏 <%=b.title%> ?');"><span><span>刪除</span></span></a></p> + </div> + </div> + </div> +<% end %> +</div> + +<%=will_paginate @books, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> diff --git a/app/views/books/latest_xml.rxml b/app/views/books/latest_xml.rxml new file mode 100644 index 0000000..4116865 --- /dev/null +++ b/app/views/books/latest_xml.rxml @@ -0,0 +1,13 @@ +xml.instruct! + +xml.coverflowinfo do + @books.each do |b| + xml.bookinfo do + xml.cover url_for_file_column b, 'cover' + xml.bookname b.title + xml.author b.author + xml.authorLink "" + xml.bookLink "/books/show/#{b.id}" + end + end +end \ No newline at end of file diff --git a/app/views/books/new.html.erb b/app/views/books/new.html.erb new file mode 100644 index 0000000..4ec16de --- /dev/null +++ b/app/views/books/new.html.erb @@ -0,0 +1,43 @@ +<% if @is_edit %> +<h1>編輯館藏資料</h1> +<%else%> +<h1>新增館藏資料</h1> +<% end %> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a></p> + +<% if @is_edit %> +<form action="/books/edit" method="post" accept-charset="utf-8" id="book-new-form" enctype="multipart/form-data"> +<% else %> +<form action="/books/new" method="post" accept-charset="utf-8" id="book-new-form" enctype="multipart/form-data"> +<% end %> + <div class="container"> + <div class="span-11">書名<br/><input type="text" name="book[title]" value="<%[email protected]%>" id="book_title"></div> + <div class="span-11 last">封面<br/><% if @b.cover %><img src="<%=url_for_file_column @b, 'cover'%>" width="80"><br/><%end%><input type="file" name="book[cover]" value="" id="book_cover"></div> + </div> + + <div class="container"> + <div class="span-11">作者<br/><input type="text" name="book[author]" value="<%[email protected]%>" id="book_author"></div> + <div class="span-11">出版社<br/><input type="text" name="book[publisher]" value="<%[email protected]%>" id="book_publisher"></div> + </div> + + <div class="container"> + <div class="span-11">出版時間<br/><input type="text" name="book[published_at]" value="<%[email protected]_at%>" id="book_published_at"></div> + <div class="span-11">ISBN<br/><input type="text" name="book[isbn]" value="<%[email protected]%>" id="book_isbn"></div> + </div> + + <div class="container"> + <div class="span-11">內容簡介<br/><textarea name="book[content]" rows="8" cols="40"><%[email protected]%></textarea></div> + <div class="span-11">備註<br/><textarea name="book[note]" rows="8" cols="40"><%[email protected]%></textarea></div> + </div> + + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + + <% if @b.id %> + <input type="hidden" name="id" value="<%[email protected]%>" id="id"> + <% end %> + <% if @is_edit %> + <p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#book-new-form').submit(); this.blur(); return false;"><span><span>編輯館藏</span></span></a></p> + <% else %> + <p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#book-new-form').submit(); this.blur(); return false;"><span><span>新增館藏</span></span></a></p> + <% end %> +</form> diff --git a/app/views/books/show.html.erb b/app/views/books/show.html.erb new file mode 100644 index 0000000..02cd82a --- /dev/null +++ b/app/views/books/show.html.erb @@ -0,0 +1,18 @@ +<p class="clearfix"><a href="javascript:history.go(-1);" class="button green back" style="margin-right: 10px;"><span><span>返回</span></span></a></p> + +<h1>館藏簡介</h1> +<div style="float: left; border: 2px solid #222; padding: 2px; margin: 2px;"><img src="<%=url_for_file_column @b, 'cover'%>" width="150"></div> +<div style="float: left; padding: 2px; margin: 2px; font-size: 1.5em;"> + 書名:<%[email protected]%><br/> + 作者:<%[email protected]%><br/> + 出版社:<%[email protected]%><br/> + 出版時間:<%[email protected]_at%><br/> + ISBN:<%[email protected]%><br/> +<p>目前本書 <span style="color: red;"><% if @b.state == 'on_shelf'%>可外借<% elsif @b.state == 'rentout' %>借出中<% end %></span>。</p></div> +<div style="clear: both;"></div> +<br/> +<h1>內容簡介</h1> +<%[email protected]("\n", "<br/>")%> +<br/><br/> +<h1 style="color: red">館員備註</h1> +<%[email protected]("\n", "<br/>")%> diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index 2e5ea7b..e1e2873 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> - <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> + <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> <li <%='class="menu-current"' if @in_books_function%>><a href="#">搜尋書籍</a></li> <li <%='class="menu-current"' if @in_reader_function%>><a href="#">讀者服務</a></li> <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> <% if @current_user && @current_user.permission == 2%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> <% else %> <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", :url => '/login' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> \ No newline at end of file diff --git a/app/views/news/_news_list_item.html.erb b/app/views/news/_news_list_item.html.erb index 555dbf3..8ffe7fb 100644 --- a/app/views/news/_news_list_item.html.erb +++ b/app/views/news/_news_list_item.html.erb @@ -1,11 +1,11 @@ <div class="container"> <div class="span-3"><%[email protected]_at.strftime("%Y-%m-%d")%></div> <div class="span-15"><a href="#" id="btn-content-<%[email protected]%>" class="button no-text down" style="margin-right: 10px;" onclick="return toggle_content(this);"><span><span>&nbsp;</span></span></a><%[email protected]%></div> <div class="span-4 last"> - <p class="clearfix"><a href="#" class="button dark right" style="margin-right: 10px;" onclick="edit_news(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/news/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除新聞 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> + <p class="clearfix"><a href="#" class="button dark pencil" style="margin-right: 10px;" onclick="edit_news(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/news/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除新聞 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> </div> </div> <div class="container" id="content-<%[email protected]%>" style="display: none;"> <div class="span-3">&nbsp;</div> <div class="span-19 last"><%[email protected]("\n", "<br/>")%></div> </div> diff --git a/app/views/news/admin.html.erb b/app/views/news/admin.html.erb index f9c8812..f3ba878 100644 --- a/app/views/news/admin.html.erb +++ b/app/views/news/admin.html.erb @@ -1,56 +1,57 @@ <h1>公告管理</h1> -<p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#news-add').toggle('blind'); $('#news-add-form input[type=\'text\'], #news-add-form textarea').val(''); this.blur();"><span><span>新增公告</span></span></a><a href="/news" class="button green right"><span><span>前往圖書館部落格</span></span></a></p> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a> + <a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#news-add').toggle('blind'); $('#news-add-form input[type=\'text\'], #news-add-form textarea').val(''); this.blur();"><span><span>新增公告</span></span></a><a href="/news" class="button green right"><span><span>前往圖書館部落格</span></span></a></p> <div id="news-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> <form action="/news/new" method="post" accept-charset="utf-8" id="news-add-form"> <p>公告標題<br/><input type="text" name="title" value="" id="title"></p> <p>公告內容<br/><textarea name="content" rows="8" cols="40"></textarea></p> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <p class="clearfix"><a href="#" class="button dark check" onclick="$('#news-add-form').submit(); this.blur();"><span><span>確定送出</span></span></a></p> </form> </div> <div id="news-list" class="table"> <div class="thead"> <div class="container"> <div class="span-3">日期</div> <div class="span-15">公告</div> <div class="span-4 last">行動</div> </div> </div> <% @news.each do |news| @n = news%> <div class="tbody" id="news-<%=news.id%>"> <%=render_partial "news_list_item"%> </div> <% end %> </div> <%=will_paginate @news, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> <script type="text/javascript" charset="utf-8"> function toggle_content(e) { if ($(e).hasClass("down")) { $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); $(e).removeClass("down").addClass("up"); } else { $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); $(e).removeClass("up").addClass("down"); } return false; } function edit_news(id) { $('#btn-edit-' + id).children('span').children('span').html('...'); $.get('/news/edit/' + id, {}, function(data){ $('#news-' + id).html(data); }); } function restore_news(id) { $.get('/news/admin/' + id, {}, function(data){ $('#news-' + id).html(data); }) } </script> \ No newline at end of file diff --git a/app/views/users/_user_list_item.html.erb b/app/views/users/_user_list_item.html.erb index d92e6de..4703c7d 100644 --- a/app/views/users/_user_list_item.html.erb +++ b/app/views/users/_user_list_item.html.erb @@ -1,9 +1,9 @@ <div class="container"> <div class="span-3"><%[email protected]_id%></div> <div class="span-5"><%[email protected]%> <%if @u.permission == 2%><span style="color: red; font-size: small;">系統管理員</span><%end%><%if @u.permission == 1%><span style="color: red; font-size: small;">工作人員</span><%end%></div> <div class="span-3"><%[email protected]_class%></div> <div class="span-5"><%[email protected]%></div> <div class="span-8 last"> - <p class="clearfix"><a href="#" class="button dark right" style="margin-right: 10px;" onclick="edit_user(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/users/details/<%[email protected]%>" class="button alt star" style="margin-right: 10px;" onclick="this.blur();" id="btn-detail-<%[email protected]%>"><span><span>詳細記錄</span></span></a><a href="/users/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除使用者 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> + <p class="clearfix"><a href="#" class="button dark pencil" style="margin-right: 10px;" onclick="edit_user(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/users/details/<%[email protected]%>" class="button alt star" style="margin-right: 10px;" onclick="this.blur();" id="btn-detail-<%[email protected]%>"><span><span>詳細記錄</span></span></a><a href="/users/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除使用者 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> </div> </div> \ No newline at end of file diff --git a/app/views/users/admin.html.erb b/app/views/users/admin.html.erb index ad65556..5385d17 100644 --- a/app/views/users/admin.html.erb +++ b/app/views/users/admin.html.erb @@ -1,55 +1,56 @@ <h1>讀者資料查詢/ç¶­è­·</h1> -<p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#user-add').toggle('blind'); $('#user-add-form input[type=\'text\']').val(''); this.blur();"><span><span>新增讀者</span></span></a><a href="/users/bulk_add" class="button dark right"><span><span>大批新增讀者</span></span></a></p> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a> +<a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#user-add').toggle('blind'); $('#user-add-form input[type=\'text\']').val(''); this.blur();"><span><span>新增讀者</span></span></a><a href="/users/bulk_add" class="button dark right"><span><span>大批新增讀者</span></span></a></p> <div id="user-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> <form action="/users/create" method="post" accept-charset="utf-8" id="user-add-form"> <div style="float: left;">登入帳號<br/><input type="text" name="login" id="login"></div> <div style="float: left;">暱稱<br/><input type="text" name="nickname" value=">" id="nickname"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">密碼<br/><input type="password" name="password" id="password"></div> <div style="float: left;">確認密碼<br/><input type="password" name="password_confirmation" id="password_confirmation"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">學生證號<br/><input type="text" name="student_id" value="" id="student_id"></div> <div style="float: left;">班級<br/><input type="text" name="student_class" value="" id="student_class"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">姓名<br/><input type="text" name="name" value="" id="name"></div> <div style="float: left;">E-mail<br/><input type="text" name="email" value="" id="email"></div> <div style="clear: both;">&nbsp;</div> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <p class="clearfix"><a href="#" class="button normal plus" onclick="$('#user-add-form').submit(); this.blur(); return false;" style="margin-right: 10px;"><span><span>新增讀者</span></span></a></p> </form> </div> <div id="user-list" class="table"> <div class="thead"> <div class="container"> <div class="span-3">學號</div> <div class="span-5">姓名</div> <div class="span-3">班級</div> <div class="span-5">電子郵件</div> <div class="span-8 last">行動</div> </div> </div> <% @user.each do |user| @u = user%> <div class="tbody" id="user-<%=user.id%>"> <%=render_partial "user_list_item"%> </div> <% end %> </div> <%=will_paginate @user, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> <script type="text/javascript" charset="utf-8"> function edit_user(id) { $('#btn-edit-' + id).children('span').children('span').html('...'); $.get('/users/edit/' + id, {}, function(data){ $('#user-' + id).html(data); }); } function restore_user(id) { $.get('/users/admin/' + id, {}, function(data){ $('#user-' + id).html(data); }) } </script> \ No newline at end of file diff --git a/app/views/users/bulk_add.html.erb b/app/views/users/bulk_add.html.erb index 949c8ad..4422bdd 100644 --- a/app/views/users/bulk_add.html.erb +++ b/app/views/users/bulk_add.html.erb @@ -1,17 +1,18 @@ <h1>大量新增讀者</h1> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a></p> 您可以使用這個功能匯入CSV資料來快速建立讀者名單。請注意您的CSV資料必須包含以下欄位: <ul> <li>login - 帳號</li> <li>email - 電子郵件地址</li> <li>password - 密碼(需要六位以上)</li> <li>name - 姓名</li> <li>student_id - 學生證號</li> <li>student_class - 學生系級(班級)</li> </ul> <h2>進行匯入</h2> <form action="/users/bulk_add" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <p>CSV檔案<br/> <input type="file" name="csv" id="csv"></p> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <p><input type="submit" value="開始匯入 &rarr;"></p> </form> \ No newline at end of file diff --git a/app/views/users/staff.html.erb b/app/views/users/staff.html.erb index 555d131..68e3e97 100644 --- a/app/views/users/staff.html.erb +++ b/app/views/users/staff.html.erb @@ -1,43 +1,44 @@ <link rel="stylesheet" href="/stylesheets/jquery.autocomplete.css" type="text/css" media="screen" charset="utf-8"/> <script type="text/javascript" charset="utf-8" src="/javascripts/jquery.autocomplete.js"></script> <script type="text/javascript" charset="utf-8"> $(function(){ $('#uid').autocomplete("/users/uid_autocomplete"); }); </script> <h1>工作人員權限管理</h1> +<p class="clearfix"><a href="/admin" class="button green back" style="margin-right: 10px;"><span><span>返回選單</span></span></a></p> <div id="staff-add" style="margin: 10px; border: 2px solid #AAB; padding: 10px; width: 250px; height: 80px;"> <form id="staff-add-form" action="/users/set_permission" method="get" accept-charset="utf-8"> <p>讀者帳號:<input type="text" name="id" id="uid" style="font-size: 1em;" size="14"><br/> 目標權限:<select name="permission"><option value="1">工作人員</option><option value="2">系統管理員</option></select></p> <p class="clearfix" style="margin-top: -20px;"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#staff-add-form').submit(); this.blur();"><span><span>提昇讀者權限為工作人員</span></span></a></p> </form> </div> <h2>工作人員名單</h2> <div id="staff-list" class="table"> <div class="thead"> <div class="container"> <div class="span-4">權限</div> <div class="span-2">帳號</div> <div class="span-4">姓名</div> <div class="span-6">電子郵件</div> <div class="span-7 last">行動</div> </div> </div> <% @user.each do |user| @u = user%> <div class="tbody" id="staff-<%[email protected]%>"> <div class="container"> <div class="span-4"><%if @u.permission == 2%><span style="color: red;">系統管理員</span><%end%><%if @u.permission == 1%><span style="color: red;">工作人員</span><%end%></div> <div class="span-2"><%[email protected]%></div> <div class="span-4"><%[email protected]%></div> <div class="span-6"><%[email protected]%></div> <div class="span-7 last"> - <p class="clearfix"><% if @u.permission < 2 %><a href="/users/promote/<%[email protected]%>" class="button dark plus" style="margin-right: 10px;" onclick="this.blur();return confirm('您確定要將使用者 「<%[email protected]%>」 昇級嗎?');"><span><span>提昇</span></span></a><% end %><% if @u.permission > 1 %><a href="/users/demote/<%[email protected]%>" class="button alt minus" style="margin-right: 10px;" onclick="this.blur(); return confirm('您確定要將使用者 「<%[email protected]%>」 降級嗎?');"><span><span>降級</span></span></a><% end %><a href="/users/set_permission/<%[email protected]%>?permission=0" class="button pink check" onclick="return confirm('確定要取消使用者 「<%[email protected]%>」的管理權限嗎?')"><span><span>刪除權限</span></span></a></p> + <p class="clearfix"><% if @u.permission < 2 %><a href="/users/promote/<%[email protected]%>" class="button dark plus" style="margin-right: 10px;" onclick="this.blur();return confirm('您確定要將使用者 「<%[email protected]%>」 昇級嗎?');"><span><span>提昇</span></span></a><% end %><% if @u.permission > 1 %><a href="/users/demote/<%[email protected]%>" class="button alt minus" style="margin-right: 10px;" onclick="this.blur(); return confirm('您確定要將使用者 「<%[email protected]%>」 降級嗎?');"><span><span>降級</span></span></a><% end %><a href="/users/set_permission/<%[email protected]%>?permission=0" class="button pink x" onclick="return confirm('確定要取消使用者 「<%[email protected]%>」的管理權限嗎?')"><span><span>刪除權限</span></span></a></p> </div> </div> </div> <% end %> </div> diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb index d12115f..d15cdca 100644 --- a/app/views/welcome/admin.html.erb +++ b/app/views/welcome/admin.html.erb @@ -1,35 +1,35 @@ <div class="bkgwhite"> <div class="container"> <div class="span-11"> <p class="admin-title">圖書管理</p> <div class="admin-menu"> - <a href="#">搜尋/維護館藏<span class="arrow">&raquo;</span></a> - <a href="#">新增館藏<span class="arrow">&raquo;</span></a> + <a href="/books/admin">搜尋/維護館藏<span class="arrow">&raquo;</span></a> + <a href="/books/new">新增館藏<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">館藏流通</p> <div class="admin-menu"> <a href="#">借閱/還書介面<span class="arrow">&raquo;</span></a> <a href="#">列出逾期書籍<span class="arrow">&raquo;</span></a> </div> </div> </div> <div class="container" style="margin-top: 10px;"> <div class="span-11"> <p class="admin-title">讀者資料</p> <div class="admin-menu"> <a href="/users/admin">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> <a href="/users/bulk_add">大批新增讀者<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">公告及其他</p> <div class="admin-menu"> <a href="/news/admin">公告管理<span class="arrow">&raquo;</span></a> <a href="/users/staff">工作人員權限管理<span class="arrow">&raquo;</span></a> </div> </div> </div> </div> \ No newline at end of file diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb index 9eb7ccd..f43dab5 100644 --- a/app/views/welcome/index.html.erb +++ b/app/views/welcome/index.html.erb @@ -1,35 +1,35 @@ <div style="text-align: center; border: 1px solid #000; width:900px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="iTunesAlbumArt" align="middle" width="900" height="329"> <param name="allowScriptAccess" value="always"> <param name="allowFullScreen" value="false"> - <param name="movie" value="iTunesAlbumArt.swf"> + <param name="movie" value="/coverflow/iTunesAlbumArt.swf"> <param name="quality" value="high"> <param name="wmode" value="opaque"> <param name="bgcolor" value="#000000"> - <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329"> + <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329" wmode="opaque"> </object> </div> <div class="container" style="margin-top: 5px;"> <div class="span-11" style="padding-right: 5px; border-right: 2px dashed #000;"> <h2>圖書館部落格</h2> <ul style="margin-left: 30px;"> <% @news.each do |news| %> <li id="news-<%=news.id%>"><a href="/news/show/<%=news.id%>"><%=news.title%></a> - <%=news.created_at.strftime("%Y-%m-%d")%></li> <% end %> </ul> <%=link_to '更多消息...', :controller => 'news'%> </div> <div class="span-12 last"> <% if @current_user %> <h2>資訊快遞</h2> <ul style="margin-left: 30px;"> <li>您目前共借閱 5 本書,2 本書即將到期。</li> <li>您還需要繳交 3 篇讀書心得。</li> </ul> <%=link_to '詳細資訊...', :controller => 'reader'%> <% else %> <h2>熱門書籍</h2> <% end %> </div> </div> \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index dd28539..fc902b8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,51 +1,54 @@ ActionController::Routing::Routes.draw do |map| map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.resource :session # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. map.admin '/admin', :controller => "welcome", :action => 'admin' map.root :controller => "welcome" + + # Coverflow info + map.connect '/booksinfo.xml', :controller => "books", :action => 'latest_xml' # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20080929055605_create_books.rb b/db/migrate/20080929055605_create_books.rb new file mode 100644 index 0000000..70ab773 --- /dev/null +++ b/db/migrate/20080929055605_create_books.rb @@ -0,0 +1,22 @@ +class CreateBooks < ActiveRecord::Migration + def self.up + create_table :books do |t| + t.column :cover, :string + t.column :author, :string + t.column :title, :string + t.column :publisher, :string + t.column :published_at, :string + t.column :content, :text + t.column :toc, :text + t.column :problems, :text # Problems for homework, YAML formatted + t.column :state, :string + t.column :note, :string + t.column :isbn, :string + t.timestamps + end + end + + def self.down + drop_table :books + end +end diff --git a/db/migrate/20080929183826_alter_books.rb b/db/migrate/20080929183826_alter_books.rb new file mode 100644 index 0000000..e3d96bc --- /dev/null +++ b/db/migrate/20080929183826_alter_books.rb @@ -0,0 +1,9 @@ +class AlterBooks < ActiveRecord::Migration + def self.up + change_column :books, :note, :text + end + + def self.down + # Sorry, one way ticket. + end +end diff --git a/db/schema.rb b/db/schema.rb index 0a839a9..1a45866 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,40 +1,56 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20080926035923) do +ActiveRecord::Schema.define(:version => 20080929183826) do create_table "blogs", :force => true do |t| t.string "title" t.string "content" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end + create_table "books", :force => true do |t| + t.string "cover" + t.string "author" + t.string "title" + t.string "publisher" + t.string "published_at" + t.text "content" + t.text "toc" + t.text "problems" + t.string "state" + t.text "note", :limit => 255 + t.string "isbn" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" t.string "student_class" t.string "student_id" t.string "nickname" t.integer "permission" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end diff --git a/log/mongrel.pid b/log/mongrel.pid new file mode 100644 index 0000000..b9d5dc7 --- /dev/null +++ b/log/mongrel.pid @@ -0,0 +1 @@ +92279 \ No newline at end of file diff --git a/public/bkg_bookflow.png b/public/bkg_bookflow.png new file mode 100644 index 0000000..48213b0 Binary files /dev/null and b/public/bkg_bookflow.png differ diff --git a/public/book/cover/10/image.jpg b/public/book/cover/10/image.jpg new file mode 100644 index 0000000..adcca77 Binary files /dev/null and b/public/book/cover/10/image.jpg differ diff --git a/public/book/cover/12/image.jpg b/public/book/cover/12/image.jpg new file mode 100644 index 0000000..3878d69 Binary files /dev/null and b/public/book/cover/12/image.jpg differ diff --git a/public/book/cover/13/image.jpg b/public/book/cover/13/image.jpg new file mode 100644 index 0000000..d4b7783 Binary files /dev/null and b/public/book/cover/13/image.jpg differ diff --git a/public/book/cover/14/image.jpg b/public/book/cover/14/image.jpg new file mode 100644 index 0000000..bb77730 Binary files /dev/null and b/public/book/cover/14/image.jpg differ diff --git a/public/book/cover/2/0010415580.jpg b/public/book/cover/2/0010415580.jpg new file mode 100644 index 0000000..d439087 Binary files /dev/null and b/public/book/cover/2/0010415580.jpg differ diff --git a/public/book/cover/4/image.jpg b/public/book/cover/4/image.jpg new file mode 100644 index 0000000..77477e4 Binary files /dev/null and b/public/book/cover/4/image.jpg differ diff --git a/public/book/cover/5/image.jpg b/public/book/cover/5/image.jpg new file mode 100644 index 0000000..12287d8 Binary files /dev/null and b/public/book/cover/5/image.jpg differ diff --git a/public/book/cover/6/image.jpg b/public/book/cover/6/image.jpg new file mode 100644 index 0000000..4bad715 Binary files /dev/null and b/public/book/cover/6/image.jpg differ diff --git a/public/book/cover/7/image.jpg b/public/book/cover/7/image.jpg new file mode 100644 index 0000000..a587d81 Binary files /dev/null and b/public/book/cover/7/image.jpg differ diff --git a/public/book/cover/8/image.jpg b/public/book/cover/8/image.jpg new file mode 100644 index 0000000..75b5d1b Binary files /dev/null and b/public/book/cover/8/image.jpg differ diff --git a/public/book/cover/9/image.jpg b/public/book/cover/9/image.jpg new file mode 100644 index 0000000..cab84b9 Binary files /dev/null and b/public/book/cover/9/image.jpg differ diff --git a/public/book/cover/tmp/1222712545.686270.91758/image.php.jpeg b/public/book/cover/tmp/1222712545.686270.91758/image.php.jpeg new file mode 100644 index 0000000..77477e4 Binary files /dev/null and b/public/book/cover/tmp/1222712545.686270.91758/image.php.jpeg differ diff --git a/public/book/cover/tmp/1222712648.488148.91758/image.php.jpeg b/public/book/cover/tmp/1222712648.488148.91758/image.php.jpeg new file mode 100644 index 0000000..77477e4 Binary files /dev/null and b/public/book/cover/tmp/1222712648.488148.91758/image.php.jpeg differ diff --git a/public/book/cover/tmp/1222713285.367401.91758/image.jpg b/public/book/cover/tmp/1222713285.367401.91758/image.jpg new file mode 100644 index 0000000..a587d81 Binary files /dev/null and b/public/book/cover/tmp/1222713285.367401.91758/image.jpg differ diff --git a/public/book/cover/tmp/1222713286.846309.4066/image.php.jpg b/public/book/cover/tmp/1222713286.846309.4066/image.php.jpg new file mode 100644 index 0000000..f670c17 Binary files /dev/null and b/public/book/cover/tmp/1222713286.846309.4066/image.php.jpg differ diff --git a/public/book/cover/tmp/1222713300.80838.91758/image.jpg b/public/book/cover/tmp/1222713300.80838.91758/image.jpg new file mode 100644 index 0000000..a587d81 Binary files /dev/null and b/public/book/cover/tmp/1222713300.80838.91758/image.jpg differ diff --git a/public/book/cover/tmp/1222713379.855033.91758/image.jpg b/public/book/cover/tmp/1222713379.855033.91758/image.jpg new file mode 100644 index 0000000..a587d81 Binary files /dev/null and b/public/book/cover/tmp/1222713379.855033.91758/image.jpg differ diff --git a/public/coverflow/iTunesAlbumArt.swf b/public/coverflow/iTunesAlbumArt.swf index 049f369..09f8b5b 100644 Binary files a/public/coverflow/iTunesAlbumArt.swf and b/public/coverflow/iTunesAlbumArt.swf differ diff --git a/public/demo.jpg b/public/demo.jpg new file mode 100644 index 0000000..7290007 Binary files /dev/null and b/public/demo.jpg differ diff --git a/public/javascripts/IE8.js b/public/javascripts/IE8.js new file mode 100644 index 0000000..efa7758 --- /dev/null +++ b/public/javascripts/IE8.js @@ -0,0 +1,2 @@ +/* IE7/IE8.js - copyright 2004-2008, Dean Edwards */ +(function(){IE7={toString:function(){return"IE7 version 2.0 (beta3)"}};var m=IE7.appVersion=navigator.appVersion.match(/MSIE (\d\.\d)/)[1];if(/ie7_off/.test(top.location.search)||m<5)return;var U=bT();var G=document.compatMode!="CSS1Compat";var bx=document.documentElement,w,t;var bN="!";var J=":link{ie7-link:link}:visited{ie7-link:visited}";var cB=/^[\w\.]+[^:]*$/;function bc(a,b){if(cB.test(a))a=(b||"")+a;return a};function by(a,b){a=bc(a,b);return a.slice(0,a.lastIndexOf("/")+1)};var bO=document.scripts[document.scripts.length-1];var cC=by(bO.src);try{var K=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}var bd={};function cD(a,b){try{a=bc(a,b);if(!bd[a]){K.open("GET",a,false);K.send();if(K.status==0||K.status==200){bd[a]=K.responseText}}}catch(e){}finally{return bd[a]||""}};if(m<5.5){undefined=U();bN="HTML:!";var cE=/(g|gi)$/;var cF=String.prototype.replace;String.prototype.replace=function(a,b){if(typeof b=="function"){if(a&&a.constructor==RegExp){var c=a;var d=c.global;if(d==null)d=cE.test(c);if(d)c=new RegExp(c.source)}else{c=new RegExp(W(a))}var f,g=this,h="";while(g&&(f=c.exec(g))){h+=g.slice(0,f.index)+b.apply(this,f);g=g.slice(f.index+f[0].length);if(!d)break}return h+g}return cF.apply(this,arguments)};Array.prototype.pop=function(){if(this.length){var a=this[this.length-1];this.length--;return a}return undefined};Array.prototype.push=function(){for(var a=0;a<arguments.length;a++){this[this.length]=arguments[a]}return this.length};var cG=this;Function.prototype.apply=function(a,b){if(a===undefined)a=cG;else if(a==null)a=window;else if(typeof a=="string")a=new String(a);else if(typeof a=="number")a=new Number(a);else if(typeof a=="boolean")a=new Boolean(a);if(arguments.length==1)b=[];else if(b[0]&&b[0].writeln)b[0]=b[0].documentElement.document||b[0];var c="#ie7_apply",d;a[c]=this;switch(b.length){case 0:d=a[c]();break;case 1:d=a[c](b[0]);break;case 2:d=a[c](b[0],b[1]);break;case 3:d=a[c](b[0],b[1],b[2]);break;case 4:d=a[c](b[0],b[1],b[2],b[3]);break;case 5:d=a[c](b[0],b[1],b[2],b[3],b[4]);break;default:var f=[],g=b.length-1;do f[g]="a["+g+"]";while(g--);eval("r=o[$]("+f+")")}if(typeof a.valueOf=="function"){delete a[c]}else{a[c]=undefined;if(d&&d.writeln)d=d.documentElement.document||d}return d};Function.prototype.call=function(a){return this.apply(a,bP.apply(arguments,[1]))};J+="address,blockquote,body,dd,div,dt,fieldset,form,"+"frame,frameset,h1,h2,h3,h4,h5,h6,iframe,noframes,object,p,"+"hr,applet,center,dir,menu,pre,dl,li,ol,ul{display:block}"}var bP=Array.prototype.slice;var cZ=/%([1-9])/g;var cH=/^\s\s*/;var cI=/\s\s*$/;var cJ=/([\/()[\]{}|*+-.,^$?\\])/g;var bQ=/\bbase\b/;var bR=["constructor","toString"];var be;function B(){};B.extend=function(a,b){be=true;var c=new this;bf(c,a);be=false;var d=c.constructor;function f(){if(!be)d.apply(this,arguments)};c.constructor=f;f.extend=arguments.callee;bf(f,b);f.prototype=c;return f};B.prototype.extend=function(a){return bf(this,a)};var bz="#";var V="~";var cK=/\\./g;var cL=/\(\?[:=!]|\[[^\]]+\]/g;var cM=/\(/g;var H=B.extend({constructor:function(a){this[V]=[];this.merge(a)},exec:function(g){var h=this,j=this[V];return String(g).replace(new RegExp(this,this.ignoreCase?"gi":"g"),function(){var a,b=1,c=0;while((a=h[bz+j[c++]])){var d=b+a.length+1;if(arguments[b]){var f=a.replacement;switch(typeof f){case"function":return f.apply(h,bP.call(arguments,b,d));case"number":return arguments[b+f];default:return f}}b=d}})},add:function(a,b){if(a instanceof RegExp){a=a.source}if(!this[bz+a])this[V].push(String(a));this[bz+a]=new H.Item(a,b)},merge:function(a){for(var b in a)this.add(b,a[b])},toString:function(){return"("+this[V].join(")|(")+")"}},{IGNORE:"$0",Item:B.extend({constructor:function(a,b){a=a instanceof RegExp?a.source:String(a);if(typeof b=="number")b=String(b);else if(b==null)b="";if(typeof b=="string"&&/\$(\d+)/.test(b)){if(/^\$\d+$/.test(b)){b=parseInt(b.slice(1))}else{var c=/'/.test(b.replace(/\\./g,""))?'"':"'";b=b.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\$(\d+)/g,c+"+(arguments[$1]||"+c+c+")+"+c);b=new Function("return "+c+b.replace(/(['"])\1\+(.*)\+\1\1$/,"$1")+c)}}this.length=H.count(a);this.replacement=b;this.toString=bT(a)}}),count:function(a){a=String(a).replace(cK,"").replace(cL,"");return L(a,cM).length}});function bf(a,b){if(a&&b){var c=(typeof b=="function"?Function:Object).prototype;var d=bR.length,f;if(be)while(f=bR[--d]){var g=b[f];if(g!=c[f]){if(bQ.test(g)){bS(a,f,g)}else{a[f]=g}}}for(f in b)if(c[f]===undefined){var g=b[f];if(a[f]&&typeof g=="function"&&bQ.test(g)){bS(a,f,g)}else{a[f]=g}}}return a};function bS(c,d,f){var g=c[d];c[d]=function(){var a=this.base;this.base=g;var b=f.apply(this,arguments);this.base=a;return b}};function cN(a,b){if(!b)b=a;var c={};for(var d in a)c[d]=b[d];return c};function i(c){var d=arguments;var f=new RegExp("%([1-"+arguments.length+"])","g");return String(c).replace(f,function(a,b){return b<d.length?d[b]:a})};function L(a,b){return String(a).match(b)||[]};function W(a){return String(a).replace(cJ,"\\$1")};function da(a){return String(a).replace(cH,"").replace(cI,"")};function bT(a){return function(){return a}};var bU=H.extend({ignoreCase:true});var cO=/\x01(\d+)/g,cP=/'/g,cQ=/^\x01/,cR=/\\([\da-fA-F]{1,4})/g;var bA=[];var bV=new bU({"<!\\-\\-|\\-\\->":"","\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/":"","@(namespace|import)[^;\\n]+[;\\n]":"","'(\\\\.|[^'\\\\])*'":bW,'"(\\\\.|[^"\\\\])*"':bW,"\\s+":" "});function cS(a){return bV.exec(a)};function bg(c){return c.replace(cO,function(a,b){return bA[b-1]})};function bW(c){return"\x01"+bA.push(c.replace(cR,function(a,b){return eval("'\\u"+"0000".slice(b.length)+b+"'")}).slice(1,-1).replace(cP,"\\'"))};function bB(a){return cQ.test(a)?bA[a.slice(1)-1]:a};var cT=new H({Width:"Height",width:"height",Left:"Top",left:"top",Right:"Bottom",right:"bottom",onX:"onY"});function C(a){return cT.exec(a)};var bX=[];function bC(a){cV(a);v(window,"onresize",a)};function v(a,b,c){a.attachEvent(b,c);bX.push(arguments)};function cU(a,b,c){try{a.detachEvent(b,c)}catch(ignore){}};v(window,"onunload",function(){var a;while(a=bX.pop()){cU(a[0],a[1],a[2])}});function X(a,b,c){if(!a.elements)a.elements={};if(c)a.elements[b.uniqueID]=b;else delete a.elements[b.uniqueID];return c};v(window,"onbeforeprint",function(){if(!IE7.CSS.print)new bJ("print");IE7.CSS.print.recalc()});var bY=/^\d+(px)?$/i;var M=/^\d+%$/;var D=function(a,b){if(bY.test(b))return parseInt(b);var c=a.style.left;var d=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;a.style.left=b||0;b=a.style.pixelLeft;a.style.left=c;a.runtimeStyle.left=d;return b};var bD="ie7-";var bZ=B.extend({constructor:function(){this.fixes=[];this.recalcs=[]},init:U});var bE=[];function cV(a){bE.push(a)};IE7.recalc=function(){IE7.HTML.recalc();IE7.CSS.recalc();for(var a=0;a<bE.length;a++)bE[a]()};function bh(a){return a.currentStyle["ie7-position"]=="fixed"};function bF(a,b){return a.currentStyle[bD+b]||a.currentStyle[b]};function N(a,b,c){if(a.currentStyle[bD+b]==null){a.runtimeStyle[bD+b]=a.currentStyle[b]}a.runtimeStyle[b]=c};function ca(a){var b=document.createElement(a||"object");b.style.cssText="position:absolute;padding:0;display:block;border:none;clip:rect(0 0 0 0);left:-9999";b.ie7_anon=true;return b};function x(a,b,c){if(!bj[a]){I=[];var d="";var f=E.escape(a).split(",");for(var g=0;g<f.length;g++){p=l=y=0;Y=f.length>1?2:0;var h=E.exec(f[g])||"if(0){";if(p){h+=i("if(e%1.nodeName!='!'){",l)}var j=Y>1?ch:"";h+=i(j+ci,l);h+=Array(L(h,/\{/g).length+1).join("}");d+=h}eval(i(cj,I)+E.unescape(d)+"return s?null:r}");bj[a]=_k}return bj[a](b||document,c)};var bi=m<6;var cb=/^(href|src)$/;var bG={"class":"className","for":"htmlFor"};IE7._1=1;IE7._e=function(a,b){var c=a.all[b]||null;if(!c||c.id==b)return c;for(var d=0;d<c.length;d++){if(c[d].id==b)return c[d]}return null};IE7._f=function(a,b){if(b=="src"&&a.pngSrc)return a.pngSrc;var c=bi?(a.attributes[b]||a.attributes[bG[b.toLowerCase()]]):a.getAttributeNode(b);if(c&&(c.specified||b=="value")){if(cb.test(b)){return a.getAttribute(b,2)}else if(b=="class"){return a.className.replace(/\sie7_\w+/g,"")}else if(b=="style"){return a.style.cssText}else{return c.nodeValue}}return null};var cc="colSpan,rowSpan,vAlign,dateTime,accessKey,tabIndex,encType,maxLength,readOnly,longDesc";bf(bG,cN(cc.toLowerCase().split(","),cc.split(",")));IE7._3=function(a){while(a&&(a=a.nextSibling)&&(a.nodeType!=1||a.nodeName=="!"))continue;return a};IE7._4=function(a){while(a&&(a=a.previousSibling)&&(a.nodeType!=1||a.nodeName=="!"))continue;return a};var cW=/([\s>+~,]|[^(]\+|^)([#.:\[])/g,cX=/(^|,)([^\s>+~])/g,cY=/\s*([\s>+~(),]|^|$)\s*/g,cd=/\s\*\s/g;var ce=H.extend({constructor:function(a){this.base(a);this.sorter=new H;this.sorter.add(/:not\([^)]*\)/,H.IGNORE);this.sorter.add(/([ >](\*|[\w-]+))([^: >+~]*)(:\w+-child(\([^)]+\))?)([^: >+~]*)/,"$1$3$6$4")},ignoreCase:true,escape:function(a){return this.optimise(this.format(a))},format:function(a){return a.replace(cY,"$1").replace(cX,"$1 $2").replace(cW,"$1*$2")},optimise:function(a){return this.sorter.exec(a.replace(cd,">* "))},unescape:function(a){return bg(a)}});var cf={"":"%1!=null","=":"%1=='%2'","~=":/(^| )%1( |$)/,"|=":/^%1(-|$)/,"^=":/^%1/,"$=":/%1$/,"*=":/%1/};var bH={"first-child":"!IE7._4(e%1)","link":"e%1.currentStyle['ie7-link']=='link'","visited":"e%1.currentStyle['ie7-link']=='visited'"};var bI="var p%2=0,i%2,e%2,n%2=e%1.";var cg="e%1.sourceIndex";var ch="var g="+cg+";if(!p[g]){p[g]=1;";var ci="r[r.length]=e%1;if(s)return e%1;";var cj="var _k=function(e0,s){IE7._1++;var r=[],p={},reg=[%1],d=document;";var I;var l;var p;var y;var Y;var bj={};var E=new ce({" (\\*|[\\w-]+)#([\\w-]+)":function(a,b,c){p=false;var d="var e%2=IE7._e(d,'%4');if(e%2&&";if(b!="*")d+="e%2.nodeName=='%3'&&";d+="(e%1==d||e%1.contains(e%2))){";if(y)d+=i("i%1=n%1.length;",y);return i(d,l++,l,b.toUpperCase(),c)}," (\\*|[\\w-]+)":function(a,b){Y++;p=b=="*";var c=bI;c+=(p&&bi)?"all":"getElementsByTagName('%3')";c+=";for(i%2=0;(e%2=n%2[i%2]);i%2++){";return i(c,l++,y=l,b.toUpperCase())},">(\\*|[\\w-]+)":function(a,b){var c=y;p=b=="*";var d=bI;d+=c?"children":"childNodes";if(!p&&c)d+=".tags('%3')";d+=";for(i%2=0;(e%2=n%2[i%2]);i%2++){";if(p){d+="if(e%2.nodeType==1){";p=bi}else{if(!c)d+="if(e%2.nodeName=='%3'){"}return i(d,l++,y=l,b.toUpperCase())},"\\+(\\*|[\\w-]+)":function(a,b){var c="";if(p)c+="if(e%1.nodeName!='!'){";p=false;c+="e%1=IE7._3(e%1);if(e%1";if(b!="*")c+="&&e%1.nodeName=='%2'";c+="){";return i(c,l,b.toUpperCase())},"~(\\*|[\\w-]+)":function(a,b){var c="";if(p)c+="if(e%1.nodeName!='!'){";p=false;Y=2;c+="while(e%1=e%1.nextSibling){if(e%1.ie7_adjacent==IE7._1)break;if(";if(b=="*"){c+="e%1.nodeType==1";if(bi)c+="&&e%1.nodeName!='!'"}else c+="e%1.nodeName=='%2'";c+="){e%1.ie7_adjacent=IE7._1;";return i(c,l,b.toUpperCase())},"#([\\w-]+)":function(a,b){p=false;var c="if(e%1.id=='%2'){";if(y)c+=i("i%1=n%1.length;",y);return i(c,l,b)},"\\.([\\w-]+)":function(a,b){p=false;I.push(new RegExp("(^|\\s)"+W(b)+"(\\s|$)"));return i("if(e%1.className&&reg[%2].test(e%1.className)){",l,I.length-1)},"\\[([\\w-]+)\\s*([^=]?=)?\\s*([^\\]]*)\\]":function(a,b,c,d){var f=bG[b]||b;if(c){var g="e%1.getAttribute('%2',2)";if(!cb.test(b)){g="e%1.%3||"+g}b=i("("+g+")",l,b,f)}else{b=i("IE7._f(e%1,'%2')",l,b)}var h=cf[c||""]||"0";if(h&&h.source){I.push(new RegExp(i(h.source,W(E.unescape(d)))));h="reg[%2].test(%1)";d=I.length-1}return"if("+i(h,b,d)+"){"},":+([\\w-]+)(\\(([^)]+)\\))?":function(a,b,c,d){b=bH[b];return"if("+(b?i(b,l,d||""):"0")+"){"}});var ck=/a(#[\w-]+)?(\.[\w-]+)?:(hover|active)/i;var cl=/\s*\{\s*/,cm=/\s*\}\s*/,cn=/\s*\,\s*/;var co=/(.*)(:first-(line|letter))/;var z=document.styleSheets;IE7.CSS=new(bZ.extend({parser:new bU,screen:"",print:"",styles:[],rules:[],pseudoClasses:m<7?"first\\-child":"",dynamicPseudoClasses:{toString:function(){var a=[];for(var b in this)a.push(b);return a.join("|")}},init:function(){var a="^\x01$";var b="\\[class=?[^\\]]*\\]";var c=[];if(this.pseudoClasses)c.push(this.pseudoClasses);var d=this.dynamicPseudoClasses.toString();if(d)c.push(d);c=c.join("|");var f=m<7?["[>+~[(]|([:.])\\w+\\1"]:[b];if(c)f.push(":("+c+")");this.UNKNOWN=new RegExp(f.join("|")||a,"i");var g=m<7?["\\[[^\\]]+\\]|[^\\s(\\[]+\\s*[+~]"]:[b];var h=g.concat();if(c)h.push(":("+c+")");o.COMPLEX=new RegExp(h.join("|")||a,"ig");if(this.pseudoClasses)g.push(":("+this.pseudoClasses+")");O.COMPLEX=new RegExp(g.join("|")||a,"i");O.MATCH=new RegExp(d?"(.*):("+d+")(.*)":a,"i");this.createStyleSheet();this.refresh()},addEventHandler:function(){v.apply(null,arguments)},addFix:function(a,b){this.parser.add(a,b)},addRecalc:function(c,d,f,g){d=new RegExp("([{;\\s])"+c+"\\s*:\\s*"+d+"[^;}]*");var h=this.recalcs.length;if(g)g=c+":"+g;this.addFix(d,function(a,b){return(g?b+g:a)+";ie7-"+a.slice(1)+";ie7_recalc"+h+":1"});this.recalcs.push(arguments);return h},apply:function(){this.getInlineStyles();new bJ("screen");this.trash()},createStyleSheet:function(){this.styleSheet=document.createStyleSheet();this.styleSheet.ie7=true;this.styleSheet.owningElement.ie7=true;this.styleSheet.cssText=J},getInlineStyles:function(){var a=document.getElementsByTagName("style"),b;for(var c=a.length-1;(b=a[c]);c--){if(!b.disabled&&!b.ie7){this.styles.push(b.innerHTML)}}},getText:function(a,b){try{var c=a.cssText}catch(e){c=""}if(K)c=cD(a.href,b)||c;return c},recalc:function(){this.screen.recalc();var a=/ie7_recalc\d+/g;var b=J.match(/[{,]/g).length;var c=b+(this.screen.cssText.match(/\{/g)||"").length;var d=this.styleSheet.rules,f;var g,h,j,q,r,k,u,n;for(r=b;r<c;r++){f=d[r];var s=f.style.cssText;if(f&&(g=s.match(a))){j=x(f.selectorText);if(j.length)for(k=0;k<g.length;k++){n=g[k];h=IE7.CSS.recalcs[n.slice(10)][2];for(u=0;(q=j[u]);u++){if(q.currentStyle[n])h(q,s)}}}}},refresh:function(){this.styleSheet.cssText=J+this.screen+this.print},trash:function(){for(var a=0;a<z.length;a++){if(!z[a].ie7){try{var b=z[a].cssText}catch(e){b=""}if(b)z[a].cssText=""}}}}));var bJ=B.extend({constructor:function(a){this.media=a;this.load();IE7.CSS[a]=this;IE7.CSS.refresh()},createRule:function(a,b){if(IE7.CSS.UNKNOWN.test(a)){var c;if(F&&(c=a.match(F.MATCH))){return new F(c[1],c[2],b)}else if(c=a.match(O.MATCH)){if(!ck.test(c[0])||O.COMPLEX.test(c[0])){return new O(a,c[1],c[2],c[3],b)}}else return new o(a,b)}return a+" {"+b+"}"},getText:function(){var h=[].concat(IE7.CSS.styles);var j=/@media\s+([^{]*)\{([^@]+\})\s*\}/gi;var q=/\ball\b|^$/i,r=/\bscreen\b/i,k=/\bprint\b/i;function u(a,b){n.value=b;return a.replace(j,n)};function n(a,b,c){b=s(b);switch(b){case"screen":case"print":if(b!=n.value)return"";case"all":return c}return""};function s(a){if(q.test(a))return"all";else if(r.test(a))return(k.test(a))?"all":"screen";else if(k.test(a))return"print"};var R=this;function S(a,b,c,d){var f="";if(!d){c=s(a.media);d=0}if(c=="all"||c==R.media){if(d<3){for(var g=0;g<a.imports.length;g++){f+=S(a.imports[g],by(a.href,b),c,d+1)}}f+=cS(a.href?cy(a,b):h.pop()||"");f=u(f,R.media)}return f};var bw={};function cy(a,b){var c=bc(a.href,b);if(bw[c])return"";bw[c]=(a.disabled)?"":cA(IE7.CSS.getText(a,b),by(a.href,b));return bw[c]};var cz=/(url\s*\(\s*['"]?)([\w\.]+[^:\)]*['"]?\))/gi;function cA(a,b){return a.replace(cz,"$1"+b.slice(0,b.lastIndexOf("/")+1)+"$2")};for(var T=0;T<z.length;T++){if(!z[T].disabled&&!z[T].ie7){this.cssText+=S(z[T])}}},load:function(){this.cssText="";this.getText();this.parse();this.cssText=bg(this.cssText);bd={}},parse:function(){this.cssText=IE7.CSS.parser.exec(this.cssText);var a=IE7.CSS.rules.length;var b=this.cssText.split(cm),c;var d,f,g,h;for(g=0;g<b.length;g++){c=b[g].split(cl);d=c[0].split(cn);f=c[1];for(h=0;h<d.length;h++){d[h]=f?this.createRule(d[h],f):""}b[g]=d.join("\n")}this.cssText=b.join("\n");this.rules=IE7.CSS.rules.slice(a)},recalc:function(){var a,b;for(b=0;(a=this.rules[b]);b++)a.recalc()},toString:function(){return"@media "+this.media+"{"+this.cssText+"}"}});var F;var o=IE7.Rule=B.extend({constructor:function(a,b){this.id=IE7.CSS.rules.length;this.className=o.PREFIX+this.id;a=a.match(co)||a||"*";this.selector=a[1]||a;this.selectorText=this.parse(this.selector)+(a[2]||"");this.cssText=b;this.MATCH=new RegExp("\\s"+this.className+"(\\s|$)","g");IE7.CSS.rules.push(this);this.init()},init:U,add:function(a){a.className+=" "+this.className},recalc:function(){var a=x(this.selector);for(var b=0;b<a.length;b++)this.add(a[b])},parse:function(a){var b=a.replace(o.CHILD," ").replace(o.COMPLEX,"");if(m<7)b=b.replace(o.MULTI,"");var c=L(b,o.TAGS).length-L(a,o.TAGS).length;var d=L(b,o.CLASSES).length-L(a,o.CLASSES).length+1;while(d>0&&o.CLASS.test(b)){b=b.replace(o.CLASS,"");d--}while(c>0&&o.TAG.test(b)){b=b.replace(o.TAG,"$1*");c--}b+="."+this.className;d=Math.min(d,2);c=Math.min(c,2);var f=-10*d-c;if(f>0){b=b+","+o.MAP[f]+" "+b}return b},remove:function(a){a.className=a.className.replace(this.MATCH,"$1")},toString:function(){return i("%1 {%2}",this.selectorText,this.cssText)}},{CHILD:/>/g,CLASS:/\.[\w-]+/,CLASSES:/[.:\[]/g,MULTI:/(\.[\w-]+)+/g,PREFIX:"ie7_class",TAG:/^\w+|([\s>+~])\w+/,TAGS:/^\w|[\s>+~]\w/g,MAP:{1:"html",2:"html body",10:".ie7_html",11:"html.ie7_html",12:"html.ie7_html body",20:".ie7_html .ie7_body",21:"html.ie7_html .ie7_body",22:"html.ie7_html body.ie7_body"}});var O=o.extend({constructor:function(a,b,c,d,f){this.attach=b||"*";this.dynamicPseudoClass=IE7.CSS.dynamicPseudoClasses[c];this.target=d;this.base(a,f)},recalc:function(){var a=x(this.attach),b;for(var c=0;b=a[c];c++){var d=this.target?x(this.target,b):[b];if(d.length)this.dynamicPseudoClass.apply(b,d,this)}}});var A=B.extend({constructor:function(a,b){this.name=a;this.apply=b;this.instances={};IE7.CSS.dynamicPseudoClasses[a]=this},register:function(a){var b=a[2];a.id=b.id+a[0].uniqueID;if(!this.instances[a.id]){var c=a[1],d;for(d=0;d<c.length;d++)b.add(c[d]);this.instances[a.id]=a}},unregister:function(a){if(this.instances[a.id]){var b=a[2];var c=a[1],d;for(d=0;d<c.length;d++)b.remove(c[d]);delete this.instances[a.id]}}});if(m<7){var Z=new A("hover",function(a){var b=arguments;IE7.CSS.addEventHandler(a,m<5.5?"onmouseover":"onmouseenter",function(){Z.register(b)});IE7.CSS.addEventHandler(a,m<5.5?"onmouseout":"onmouseleave",function(){Z.unregister(b)})});v(document,"onmouseup",function(){var a=Z.instances;for(var b in a)if(!a[b][0].contains(event.srcElement))Z.unregister(a[b])})}IE7.CSS.addRecalc("[\\w-]+","inherit",function(c,d){var f=d.match(/[\w-]+\s*:\s*inherit/g);for(var g=0;g<f.length;g++){var h=f[g].replace(/ie7\-|\s*:\s*inherit/g,"").replace(/\-([a-z])/g,function(a,b){return b.toUpperCase()});c.runtimeStyle[h]=c.parentElement.currentStyle[h]}});IE7.HTML=new(bZ.extend({fixed:{},init:U,addFix:function(){this.fixes.push(arguments)},apply:function(){for(var a=0;a<this.fixes.length;a++){var b=x(this.fixes[a][0]);var c=this.fixes[a][1];for(var d=0;d<b.length;d++)c(b[d])}},addRecalc:function(){this.recalcs.push(arguments)},recalc:function(){for(var a=0;a<this.recalcs.length;a++){var b=x(this.recalcs[a][0]);var c=this.recalcs[a][1],d;var f=Math.pow(2,a);for(var g=0;(d=b[g]);g++){var h=d.uniqueID;if((this.fixed[h]&f)==0){d=c(d)||d;this.fixed[h]|=f}}}}}));if(m<7){document.createElement("abbr");IE7.HTML.addRecalc("label",function(a){if(!a.htmlFor){var b=x("input,textarea",a,true);if(b){v(a,"onclick",function(){b.click()})}}})}var P="[.\\d]";new function(_){var layout=IE7.Layout=this;J+="*{boxSizing:content-box}";IE7.hasLayout=m<5.5?function(a){return a.clientWidth}:function(a){return a.currentStyle.hasLayout};layout.boxSizing=function(a){if(!IE7.hasLayout(a)){a.style.height="0cm";if(a.currentStyle.verticalAlign=="auto")a.runtimeStyle.verticalAlign="top";collapseMargins(a)}};function collapseMargins(a){if(a!=t&&a.currentStyle.position!="absolute"){collapseMargin(a,"marginTop");collapseMargin(a,"marginBottom")}};function collapseMargin(a,b){if(!a.runtimeStyle[b]){var c=a.parentElement;if(c&&IE7.hasLayout(c)&&!IE7[b=="marginTop"?"_4":"_3"](a))return;var d=x(">*:"+(b=="marginTop"?"first":"last")+"-child",a,true);if(d&&d.currentStyle.styleFloat=="none"&&IE7.hasLayout(d)){collapseMargin(d,b);margin=_b(a,a.currentStyle[b]);childMargin=_b(d,d.currentStyle[b]);if(margin<0||childMargin<0){a.runtimeStyle[b]=margin+childMargin}else{a.runtimeStyle[b]=Math.max(childMargin,margin)}d.runtimeStyle[b]="0px"}}};function _b(a,b){return b=="auto"?0:D(a,b)};var UNIT=/^[.\d][\w%]*$/,AUTO=/^(auto|0cm)$/;var applyWidth,applyHeight;IE7.Layout.borderBox=function(a){applyWidth(a);applyHeight(a)};var fixWidth=function(g){applyWidth=function(a){if(!M.test(a.currentStyle.width))h(a);collapseMargins(a)};function h(a,b){if(!a.runtimeStyle.fixedWidth){if(!b)b=a.currentStyle.width;a.runtimeStyle.fixedWidth=(UNIT.test(b))?Math.max(0,r(a,b)):b;N(a,"width",a.runtimeStyle.fixedWidth)}};function j(a){if(!bh(a)){var b=a.offsetParent;while(b&&!IE7.hasLayout(b))b=b.offsetParent}return(b||t).clientWidth};function q(a,b){if(M.test(b))return parseInt(parseFloat(b)/100*j(a));return D(a,b)};var r=function(a,b){var c=a.currentStyle["box-sizing"]=="border-box";var d=0;if(G&&!c)d+=k(a)+u(a,"padding");else if(!G&&c)d-=k(a)+u(a,"padding");return q(a,b)+d};function k(a){return a.offsetWidth-a.clientWidth};function u(a,b){return q(a,a.currentStyle[b+"Left"])+q(a,a.currentStyle[b+"Right"])};J+="*{minWidth:none;maxWidth:none;min-width:none;max-width:none}";layout.minWidth=function(a){if(a.currentStyle["min-width"]!=null){a.style.minWidth=a.currentStyle["min-width"]}if(X(arguments.callee,a,a.currentStyle.minWidth!="none")){layout.boxSizing(a);h(a);n(a)}};eval("IE7.Layout.maxWidth="+String(layout.minWidth).replace(/min/g,"max"));function n(a){var b=a.getBoundingClientRect();var c=b.right-b.left;if(a.currentStyle.minWidth!="none"&&c<=r(a,a.currentStyle.minWidth)){a.runtimeStyle.width=a.currentStyle.minWidth}else if(a.currentStyle.maxWidth!="none"&&c>=r(a,a.currentStyle.maxWidth)){a.runtimeStyle.width=a.currentStyle.maxWidth}else{a.runtimeStyle.width=a.runtimeStyle.fixedWidth}};function s(a){if(X(s,a,/^(fixed|absolute)$/.test(a.currentStyle.position)&&bF(a,"left")!="auto"&&bF(a,"right")!="auto"&&AUTO.test(bF(a,"width")))){R(a);IE7.Layout.boxSizing(a)}};IE7.Layout.fixRight=s;function R(a){var b=q(a,a.runtimeStyle._c||a.currentStyle.left);var c=j(a)-q(a,a.currentStyle.right)-b-u(a,"margin");if(parseInt(a.runtimeStyle.width)==c)return;a.runtimeStyle.width="";if(bh(a)||g||a.offsetWidth<c){if(!G)c-=k(a)+u(a,"padding");if(c<0)c=0;a.runtimeStyle.fixedWidth=c;N(a,"width",c)}};var S=0;bC(function(){if(!t)return;var a,b=(S<t.clientWidth);S=t.clientWidth;var c=layout.minWidth.elements;for(a in c){var d=c[a];var f=(parseInt(d.runtimeStyle.width)==r(d,d.currentStyle.minWidth));if(b&&f)d.runtimeStyle.width="";if(b==f)n(d)}var c=layout.maxWidth.elements;for(a in c){var d=c[a];var f=(parseInt(d.runtimeStyle.width)==r(d,d.currentStyle.maxWidth));if(!b&&f)d.runtimeStyle.width="";if(b!=f)n(d)}for(a in s.elements)R(s.elements[a])});if(G){IE7.CSS.addRecalc("width",P,applyWidth)}if(m<7){IE7.CSS.addRecalc("min-width",P,layout.minWidth);IE7.CSS.addRecalc("max-width",P,layout.maxWidth);IE7.CSS.addRecalc("right",P,s)}};eval("var fixHeight="+C(fixWidth));fixWidth();fixHeight(true)};var bk=bc("blank.gif",cC);var bl="DXImageTransform.Microsoft.AlphaImageLoader";var bK="progid:"+bl+"(src='%1',sizingMethod='%2')";var bm;var Q=[];function bL(a){if(bm.test(a.src)){var b=new Image(a.width,a.height);b.onload=function(){a.width=b.width;a.height=b.height;b=null};b.src=a.src;a.pngSrc=a.src;bo(a)}};if(m>=5.5&&m<7){IE7.CSS.addFix(/background(-image)?\s*:\s*([^};]*)?url\(([^\)]+)\)([^;}]*)?/,function(a,b,c,d,f){d=bB(d);return bm.test(d)?"filter:"+i(bK,d,"crop")+";zoom:1;background"+(b||"")+":"+(c||"")+"none"+(f||""):a});IE7.HTML.addRecalc("img,input",function(a){if(a.tagName=="INPUT"&&a.type!="image")return;bL(a);v(a,"onpropertychange",function(){if(!bn&&event.propertyName=="src"&&a.src.indexOf(bk)==-1)bL(a)})});var bn=false;v(window,"onbeforeprint",function(){bn=true;for(var a=0;a<Q.length;a++)cp(Q[a])});v(window,"onafterprint",function(){for(var a=0;a<Q.length;a++)bo(Q[a]);bn=false})}function bo(a,b){var c=a.filters[bl];if(c){c.src=a.src;c.enabled=true}else{a.runtimeStyle.filter=i(bK,a.src,b||"scale");Q.push(a)}a.src=bk};function cp(a){a.src=a.pngSrc;a.filters[bl].enabled=false};new function(_){if(m>=7)return;IE7.CSS.addRecalc("position","fixed",_8,"absolute");IE7.CSS.addRecalc("background(-attachment)?","[^};]*fixed",_5);var $viewport=G?"body":"documentElement";function _6(){if(w.currentStyle.backgroundAttachment!="fixed"){if(w.currentStyle.backgroundImage=="none"){w.runtimeStyle.backgroundRepeat="no-repeat";w.runtimeStyle.backgroundImage="url("+bk+")"}w.runtimeStyle.backgroundAttachment="fixed"}_6=U};var _0=ca("img");function _2(a){return a?bh(a)||_2(a.parentElement):false};function _d(a,b,c){setTimeout("document.all."+a.uniqueID+".runtimeStyle.setExpression('"+b+"','"+c+"')",0)};function _5(a){if(X(_5,a,a.currentStyle.backgroundAttachment=="fixed"&&!a.contains(w))){_6();bgLeft(a);bgTop(a);_a(a)}};function _a(a){_0.src=a.currentStyle.backgroundImage.slice(5,-2);var b=a.canHaveChildren?a:a.parentElement;b.appendChild(_0);setOffsetLeft(a);setOffsetTop(a);b.removeChild(_0)};function bgLeft(a){a.style.backgroundPositionX=a.currentStyle.backgroundPositionX;if(!_2(a)){_d(a,"backgroundPositionX","(parseInt(runtimeStyle.offsetLeft)+document."+$viewport+".scrollLeft)||0")}};eval(C(bgLeft));function setOffsetLeft(a){var b=_2(a)?"backgroundPositionX":"offsetLeft";a.runtimeStyle[b]=getOffsetLeft(a,a.style.backgroundPositionX)-a.getBoundingClientRect().left-a.clientLeft+2};eval(C(setOffsetLeft));function getOffsetLeft(a,b){switch(b){case"left":case"top":return 0;case"right":case"bottom":return t.clientWidth-_0.offsetWidth;case"center":return(t.clientWidth-_0.offsetWidth)/2;default:if(M.test(b)){return parseInt((t.clientWidth-_0.offsetWidth)*parseFloat(b)/100)}_0.style.left=b;return _0.offsetLeft}};eval(C(getOffsetLeft));function _8(a){if(X(_8,a,bh(a))){N(a,"position","absolute");N(a,"left",a.currentStyle.left);N(a,"top",a.currentStyle.top);_6();IE7.Layout.fixRight(a);_7(a)}};function _7(a,b){positionTop(a,b);positionLeft(a,b,true);if(!a.runtimeStyle.autoLeft&&a.currentStyle.marginLeft=="auto"&&a.currentStyle.right!="auto"){var c=t.clientWidth-getPixelWidth(a,a.currentStyle.right)-getPixelWidth(a,a.runtimeStyle._c)-a.clientWidth;if(a.currentStyle.marginRight=="auto")c=parseInt(c/2);if(_2(a.offsetParent))a.runtimeStyle.pixelLeft+=c;else a.runtimeStyle.shiftLeft=c}clipWidth(a);clipHeight(a)};function clipWidth(a){var b=a.runtimeStyle.fixWidth;a.runtimeStyle.borderRightWidth="";a.runtimeStyle.width=b?getPixelWidth(a,b):"";if(a.currentStyle.width!="auto"){var c=a.getBoundingClientRect();var d=a.offsetWidth-t.clientWidth+c.left-2;if(d>=0){a.runtimeStyle.borderRightWidth="0px";d=Math.max(D(a,a.currentStyle.width)-d,0);N(a,"width",d);return d}}};eval(C(clipWidth));function positionLeft(a,b){if(!b&&M.test(a.currentStyle.width)){a.runtimeStyle.fixWidth=a.currentStyle.width}if(a.runtimeStyle.fixWidth){a.runtimeStyle.width=getPixelWidth(a,a.runtimeStyle.fixWidth)}a.runtimeStyle.shiftLeft=0;a.runtimeStyle._c=a.currentStyle.left;a.runtimeStyle.autoLeft=a.currentStyle.right!="auto"&&a.currentStyle.left=="auto";a.runtimeStyle.left="";a.runtimeStyle.screenLeft=getScreenLeft(a);a.runtimeStyle.pixelLeft=a.runtimeStyle.screenLeft;if(!b&&!_2(a.offsetParent)){_d(a,"pixelLeft","runtimeStyle.screenLeft+runtimeStyle.shiftLeft+document."+$viewport+".scrollLeft")}};eval(C(positionLeft));function getScreenLeft(a){var b=a.offsetLeft,c=1;if(a.runtimeStyle.autoLeft){b=t.clientWidth-a.offsetWidth-getPixelWidth(a,a.currentStyle.right)}if(a.currentStyle.marginLeft!="auto"){b-=getPixelWidth(a,a.currentStyle.marginLeft)}while(a=a.offsetParent){if(a.currentStyle.position!="static")c=-1;b+=a.offsetLeft*c}return b};eval(C(getScreenLeft));function getPixelWidth(a,b){return M.test(b)?parseInt(parseFloat(b)/100*t.clientWidth):D(a,b)};eval(C(getPixelWidth));function _j(){var a=_5.elements;for(var b in a)_a(a[b]);a=_8.elements;for(b in a){_7(a[b],true);_7(a[b],true)}_9=0};var _9;bC(function(){if(!_9)_9=setTimeout(_j,0)})};var bp={backgroundColor:"transparent",backgroundImage:"none",backgroundPositionX:null,backgroundPositionY:null,backgroundRepeat:null,borderTopWidth:0,borderRightWidth:0,borderBottomWidth:0,borderLeftStyle:"none",borderTopStyle:"none",borderRightStyle:"none",borderBottomStyle:"none",borderLeftWidth:0,height:null,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,width:"100%"};IE7.CSS.addRecalc("overflow","visible",function(a){if(a.parentNode.ie7_wrapped)return;if(IE7.Layout&&a.currentStyle["max-height"]!="auto"){IE7.Layout.maxHeight(a)}if(a.currentStyle.marginLeft=="auto")a.style.marginLeft=0;if(a.currentStyle.marginRight=="auto")a.style.marginRight=0;var b=document.createElement(bN);b.ie7_wrapped=a;for(var c in bp){b.style[c]=a.currentStyle[c];if(bp[c]!=null){a.runtimeStyle[c]=bp[c]}}b.style.display="block";b.style.position="relative";a.runtimeStyle.position="absolute";a.parentNode.insertBefore(b,a);b.appendChild(a)});function cq(){var f="xx-small,x-small,small,medium,large,x-large,xx-large".split(",");for(var g=0;g<f.length;g++){f[f[g]]=f[g-1]||"0.67em"}IE7.CSS.addFix(/(font(-size)?\s*:\s*)([\w.-]+)/,function(a,b,c,d){return b+(f[d]||d)});if(m<6){var h=/^\-/,j=/(em|ex)$/i;var q=/em$/i,r=/ex$/i;D=function(a,b){if(bY.test(b))return parseInt(b)||0;var c=h.test(b)?-1:1;if(j.test(b))c*=u(a);k.style.width=(c<0)?b.slice(1):b;w.appendChild(k);b=c*k.offsetWidth;k.removeNode();return parseInt(b)};var k=ca();function u(a){var b=1;k.style.fontFamily=a.currentStyle.fontFamily;k.style.lineHeight=a.currentStyle.lineHeight;while(a!=w){var c=a.currentStyle["ie7-font-size"];if(c){if(q.test(c))b*=parseFloat(c);else if(M.test(c))b*=(parseFloat(c)/100);else if(r.test(c))b*=(parseFloat(c)/2);else{k.style.fontSize=c;return 1}}a=a.parentElement}return b};IE7.CSS.addFix(/cursor\s*:\s*pointer/,"cursor:hand");IE7.CSS.addFix(/display\s*:\s*list-item/,"display:block")}function n(a){if(m<5.5)IE7.Layout.boxSizing(a.parentElement);var b=a.parentElement;var c=b.offsetWidth-a.offsetWidth-s(b);var d=(a.currentStyle["ie7-margin"]&&a.currentStyle.marginRight=="auto")||a.currentStyle["ie7-margin-right"]=="auto";switch(b.currentStyle.textAlign){case"right":c=d?parseInt(c/2):0;a.runtimeStyle.marginRight=c+"px";break;case"center":if(d)c=0;default:if(d)c/=2;a.runtimeStyle.marginLeft=parseInt(c)+"px"}};function s(a){return D(a,a.currentStyle.paddingLeft)+D(a,a.currentStyle.paddingRight)};IE7.CSS.addRecalc("margin(-left|-right)?","[^};]*auto",function(a){if(X(n,a,a.parentElement&&a.currentStyle.display=="block"&&a.currentStyle.marginLeft=="auto"&&a.currentStyle.position!="absolute")){n(a)}});bC(function(){for(var a in n.elements){var b=n.elements[a];b.runtimeStyle.marginLeft=b.runtimeStyle.marginRight="";n(b)}})};IE7._g=function(a){a=a.firstChild;while(a){if(a.nodeType==3||(a.nodeType==1&&a.nodeName!="!"))return false;a=a.nextSibling}return true};IE7._h=function(a,b){while(a&&!a.getAttribute("lang"))a=a.parentNode;return a&&new RegExp("^"+W(b),"i").test(a.getAttribute("lang"))};function cr(a,b,c,d){d=/last/i.test(a)?d+"+1-":"";if(!isNaN(b))b="0n+"+b;else if(b=="even")b="2n";else if(b=="odd")b="2n+1";b=b.split("n");var f=b[0]?(b[0]=="-")?-1:parseInt(b[0]):1;var g=parseInt(b[1])||0;var h=f<0;if(h){f=-f;if(f==1)g++}var j=i(f==0?"%3%7"+(d+g):"(%4%3-%2)%6%1%70%5%4%3>=%2",f,g,c,d,"&&","%","==");if(h)j="!("+j+")";return j};bH={"link":"e%1.currentStyle['ie7-link']=='link'","visited":"e%1.currentStyle['ie7-link']=='visited'","checked":"e%1.checked","contains":"e%1.innerText.indexOf('%2')!=-1","disabled":"e%1.isDisabled","empty":"IE7._g(e%1)","enabled":"e%1.disabled===false","first-child":"!IE7._4(e%1)","lang":"IE7._h(e%1,'%2')","last-child":"!IE7._3(e%1)","only-child":"!IE7._4(e%1)&&!IE7._3(e%1)","target":"e%1.id==location.hash.slice(1)","indeterminate":"e%1.indeterminate"};IE7._i=function(a){if(a.rows){a.ie7_length=a.rows.length;a.ie7_lookup="rowIndex"}else if(a.cells){a.ie7_length=a.cells.length;a.ie7_lookup="cellIndex"}else if(a.ie7_indexed!=IE7._1){var b=0;var c=a.firstChild;while(c){if(c.nodeType==1&&c.nodeName!="!"){c.ie7_index=++b}c=c.nextSibling}a.ie7_length=b;a.ie7_lookup="ie7_index"}a.ie7_indexed=IE7._1;return a};var ba=E[V];var cs=ba[ba.length-1];ba.length--;E.merge({":not\\((\\*|[\\w-]+)?([^)]*)\\)":function(a,b,c){var d=(b&&b!="*")?i("if(e%1.nodeName=='%2'){",l,b.toUpperCase()):"";d+=E.exec(c);return"if(!"+d.slice(2,-1).replace(/\)\{if\(/g,"&&")+"){"},":nth(-last)?-child\\(([^)]+)\\)":function(a,b,c){p=false;b=i("e%1.parentNode.ie7_length",l);var d="if(p%1!==e%1.parentNode)p%1=IE7._i(e%1.parentNode);";d+="var i=e%1[p%1.ie7_lookup];if(p%1.ie7_lookup!='ie7_index')i++;if(";return i(d,l)+cr(a,c,"i",b)+"){"}});ba.push(cs);var bM="\\([^)]*\\)";if(IE7.CSS.pseudoClasses)IE7.CSS.pseudoClasses+="|";IE7.CSS.pseudoClasses+="before|after|last\\-child|only\\-child|empty|root|"+"not|nth\\-child|nth\\-last\\-child|contains|lang".split("|").join(bM+"|")+bM;bV.add(/::/,":");var bb=new A("focus",function(a){var b=arguments;IE7.CSS.addEventHandler(a,"onfocus",function(){bb.unregister(b);bb.register(b)});IE7.CSS.addEventHandler(a,"onblur",function(){bb.unregister(b)});if(a==document.activeElement){bb.register(b)}});var bq=new A("active",function(a){var b=arguments;IE7.CSS.addEventHandler(a,"onmousedown",function(){bq.register(b)})});v(document,"onmouseup",function(){var a=bq.instances;for(var b in a)bq.unregister(a[b])});var br=new A("checked",function(a){if(typeof a.checked!="boolean")return;var b=arguments;IE7.CSS.addEventHandler(a,"onpropertychange",function(){if(event.propertyName=="checked"){if(a.checked)br.register(b);else br.unregister(b)}});if(a.checked)br.register(b)});var bs=new A("enabled",function(a){if(typeof a.disabled!="boolean")return;var b=arguments;IE7.CSS.addEventHandler(a,"onpropertychange",function(){if(event.propertyName=="disabled"){if(!a.isDisabled)bs.register(b);else bs.unregister(b)}});if(!a.isDisabled)bs.register(b)});var bt=new A("disabled",function(a){if(typeof a.disabled!="boolean")return;var b=arguments;IE7.CSS.addEventHandler(a,"onpropertychange",function(){if(event.propertyName=="disabled"){if(a.isDisabled)bt.register(b);else bt.unregister(b)}});if(a.isDisabled)bt.register(b)});var bu=new A("indeterminate",function(a){if(typeof a.indeterminate!="boolean")return;var b=arguments;IE7.CSS.addEventHandler(a,"onpropertychange",function(){if(event.propertyName=="indeterminate"){if(a.indeterminate)bu.register(b);else bu.unregister(b)}});IE7.CSS.addEventHandler(a,"onclick",function(){bu.unregister(b)})});var bv=new A("target",function(a){var b=arguments;if(!a.tabIndex)a.tabIndex=0;IE7.CSS.addEventHandler(document,"onpropertychange",function(){if(event.propertyName=="activeElement"){if(a.id&&a.id==location.hash.slice(1))bv.register(b);else bv.unregister(b)}});if(a.id&&a.id==location.hash.slice(1))bv.register(b)});var ct=/^attr/;var cu=/^url\s*\(\s*([^)]*)\)$/;var cv={before0:"beforeBegin",before1:"afterBegin",after0:"afterEnd",after1:"beforeEnd"};var F=IE7.PseudoElement=o.extend({constructor:function(a,b,c){this.position=b;var d=c.match(F.CONTENT),f,g;if(d){d=d[1];f=d.split(/\s+/);for(var h=0;(g=f[h]);h++){f[h]=ct.test(g)?{attr:g.slice(5,-1)}:(g.charAt(0)=="'")?bB(g):bg(g)}d=f}this.content=d;this.base(a,bg(c))},init:function(){this.match=x(this.selector);for(var a=0;a<this.match.length;a++){var b=this.match[a].runtimeStyle;if(!b[this.position])b[this.position]={cssText:""};b[this.position].cssText+=";"+this.cssText;if(this.content!=null)b[this.position].content=this.content}},create:function(a){var b=a.runtimeStyle[this.position];if(b){var c=[].concat(b.content||"");for(var d=0;d<c.length;d++){if(typeof c[d]=="object"){c[d]=a.getAttribute(c[d].attr)}}c=c.join("");var f=c.match(cu);var g="overflow:hidden;"+b.cssText.replace(/'/g,'"');if(a.currentStyle.styleFloat!="none"){}var h=cv[this.position+Number(a.canHaveChildren)];var j='ie7_pseudo'+F.count++;a.insertAdjacentHTML(h,i(F.ANON,this.className,j,g,f?"":c));if(f){var q=document.getElementById(j);q.src=bB(f[1]);bo(q,"crop")}a.runtimeStyle[this.position]=null}},recalc:function(){if(this.content==null)return;for(var a=0;a<this.match.length;a++){this.create(this.match[a])}},toString:function(){return"."+this.className+"{display:inline}"}},{CONTENT:/content\s*:\s*([^;]*)(;|$)/,ANON:"<ie7:! class='ie7_anon %1' id=%2 style='%3'>%4</ie7:!>",MATCH:/(.*):(before|after).*/,count:0});var cw=/^(submit|reset|button)$/;IE7.HTML.addRecalc("button,input",function(a){if(a.tagName=="BUTTON"){var b=a.outerHTML.match(/ value="([^"]*)"/i);a.runtimeStyle.value=(b)?b[1]:""}if(a.type=="submit"){v(a,"onclick",function(){a.runtimeStyle.clicked=true;setTimeout("document.all."+a.uniqueID+".runtimeStyle.clicked=false",1)})}});IE7.HTML.addRecalc("form",function(c){v(c,"onsubmit",function(){for(var a,b=0;a=c[b];b++){if(cw.test(a.type)&&!a.disabled&&!a.runtimeStyle.clicked){a.disabled=true;setTimeout("document.all."+a.uniqueID+".disabled=false",1)}else if(a.tagName=="BUTTON"&&a.type=="submit"){setTimeout("document.all."+a.uniqueID+".value='"+a.value+"'",1);a.value=a.runtimeStyle.value}}})});IE7.HTML.addRecalc("img",function(a){if(a.alt&&!a.title)a.title=""});IE7.CSS.addRecalc("border-spacing",P,function(a){if(a.currentStyle.borderCollapse!="collapse"){a.cellSpacing=D(a,a.currentStyle["border-spacing"])}});IE7.CSS.addRecalc("box-sizing","content-box",IE7.Layout.boxSizing);IE7.CSS.addRecalc("box-sizing","border-box",IE7.Layout.borderBox);IE7.CSS.addFix(/opacity\s*:\s*([\d.]+)/,function(a,b){return"zoom:1;filter:Alpha(opacity="+((b*100)||1)+")"});var cx=/^image/i;IE7.HTML.addRecalc("object",function(a){if(cx.test(a.type)){a.body.style.cssText="margin:0;padding:0;border:none;overflow:hidden";return a}});IE7.loaded=true;(function(){try{bx.doScroll("left")}catch(e){setTimeout(arguments.callee,1);return}try{eval(bO.innerHTML)}catch(e){}bm=new RegExp(W(typeof IE7_PNG_SUFFIX=="string"?IE7_PNG_SUFFIX:"-trans.png")+"$","i");w=document.body;t=G?w:bx;w.className+=" ie7_body";bx.className+=" ie7_html";if(G)cq();IE7.CSS.init();IE7.HTML.init();IE7.HTML.apply();IE7.CSS.apply();IE7.recalc()})()})(); \ No newline at end of file diff --git a/public/stylesheets/ie.css b/public/stylesheets/ie.css index bb59a79..1fcdd58 100644 --- a/public/stylesheets/ie.css +++ b/public/stylesheets/ie.css @@ -1,22 +1,27 @@ /* ----------------------------------------------------------------------- Blueprint CSS Framework 0.7.1 http://blueprintcss.googlecode.com * Copyright (c) 2007-2008. See LICENSE for more info. * See README for instructions on how to use Blueprint. * For credits and origins, see AUTHORS. * This is a compressed file. See the sources in the 'src' directory. ----------------------------------------------------------------------- */ /* ie.css */ body {text-align:center;} .container {text-align:left;} * html .column {overflow-x:hidden;} * html legend {margin:-18px -8px 16px 0;padding:0;} ol {margin-left:2em;} sup {vertical-align:text-top;} sub {vertical-align:text-bottom;} html>body p code {*white-space:normal;} -hr {margin:-8px auto 11px;} \ No newline at end of file +hr {margin:-8px auto 11px;} + +#content { + position: relative; + top: -20px; +} \ No newline at end of file diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index 1feb768..9108cf8 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,260 +1,286 @@ /* layout */ body { background-color: #7C6255; font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; font-size: 11pt; } h1 { + margin-top: 5px; border-bottom: 1px solid #CCC; } h2 { margin: 0; } #content { background-color: #FFF; padding: 10px; margin-top: -10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; + padding-top: 5px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; - border-left: 1px solid #FFF; - border-top: 1px solid #FFF; + border-left: 2px solid #FFF; + border-top: 2px solid #FFF; border-right: 1px solid #FFF; background-color: #222; background-image: -webkit-gradient(linear, left top, left bottom, from(#666), to(#222)); padding: 5px; padding-top: 60px; margin-left: -1px; } #header-title ul li a { color: #fff; } #header-title ul li:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#444)); background-color: #444; } .menu-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#FFF)) !important; background-color: #FFF !important; } .menu-current a { color: #000 !important; } .menu-backstage { background-image: -webkit-gradient(linear, left top, left bottom, from(#C30017), to(#73000E)) !important; background-color: #73000E !important; } .menu-backstage:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#B20014)) !important; background-color: #920011 !important; } .menu-backstage-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#FFF), color-stop(0.8, #FFF)) !important; background-color: #FFF !important; } .menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; color: #FFF; word-spacing: 4px; font-family: Helvetica; } /* admin css */ .admin-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#C17436), to(#A9652F)); background-color: #C17436; color: #FFF; font-size: 2em; border-top: 1px solid #000; border-left: 1px solid #000; border-right: 1px solid #000; } .admin-menu { margin: 0; padding: 0; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; font-size: 1.75em; } .admin-menu a { display: block; padding: 2px; } .admin-menu .arrow { float: right; + display: none; } .admin-menu a:hover { display: block; background-image: -webkit-gradient(linear, left top, left bottom, from(#0000FF), to(#000099)) !important; background-color: #000099; color: #FFF; text-decoration: none; } .table { font-size: 1.25em; border-bottom: 1px solid #000; } .table .thead { border-top: 1px solid #000; font-size: 1.25em; border-bottom: 1px dashed #000; } .table .tbody { border-top: 1px dashed #000; margin-top: -1px; } .table .tbody .container div { line-height: 30px; } .table .tbody .container p.clearfix { margin: 0px; } .table .tbody .container a.button { margin-top: 2px; } form input { font-size: 22pt; } form input[type="file"] { font-size: 1em !important; } form textarea { font-size: 18pt; } /* blog front */ .blog-date { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#444), to(#000)); background-color: #000; color: #FFF; letter-spacing: 0.3em; } .blog-title { font-size: 2em; color: rgb(99, 60, 17); margin: 0px; } .blog-content { margin-left: 10px; text-indent: 2em; } /* sidebar */ #sidebar { width: 230px; height: 600px; background: url('../images/bkg_blackboard.jpg') repeat-y; color: white; padding: 10px; padding-right: 35px; margin-left: -10px; -webkit-box-shadow: 0px 3px 5px black; -moz-box-shadow: 0px 3px 5px black; position: relative; float: left; } #sidebar { /* Damn IE fix */ height: auto; min-height: 600px; } #sidebar #metal_holder { width: 68px; height: 213px; background: url('../images/img_blackboard_holder.png') no-repeat; position: absolute; top: 200px; left: 240px; } #sidebar h1 { color: #FFF; border: none; } /* pagination */ .pagination { margin: 5px; font-size: 1.2em; } .pagination * { padding: 2px; } .pagination a { border: 1px solid #00F; } .pagination a:hover { border: 1px solid #00F; background-color: #00A; color: #FFF; } .pagination span.current { border: 1px solid #00E; background-color: #00F; color: #FFF; } + +/* filter css */ +.filter-title { + display: block; + margin: 0; + padding: 2px; + background-image: -webkit-gradient(linear, left top, left bottom, from(#0D0099), to(#3D4C99)); + background-color: #C17436; + color: #FFF; + font-size: 1.3em; + border: 3px solid #333; +} + +.filter-title input { + font-size: 1.2em; +} + +/* book admin */ +.book-cover img { + margin: 2px; + border: 1px solid #000; + width: 80px; +} \ No newline at end of file diff --git a/public/webuikit-css/webuikit.css b/public/webuikit-css/webuikit.css index 37d7cb5..edc4835 100644 --- a/public/webuikit-css/webuikit.css +++ b/public/webuikit-css/webuikit.css @@ -1,232 +1,236 @@ /* Web UI Kit 1.0 Leo Lin | http://jiwostudio.com Copyright (c) 2008. All rights Reserved. Based on http://www.oscaralexander.com/tutorials/how-to-make-sexy-buttons-with-css.html */ /* @group General */ a { outline: none; border: none; } .clearfix { width: 100%; clear: both; overflow: visible; } /* iepngfix http://www.twinhelix.com/ */ -img { behavior: url(/webuikit-css/iepngfix.htc) } +img, #metal_holder { behavior: url(/webuikit-css/iepngfix.htc) } /* @end */ /* @group Buttons */ /* normal */ a.button { float: left; height: 24px; background: url(../webuikit-img/buttons/normal_right.png) no-repeat right top; padding-right: 11px; text-decoration: none; } a.button span { display: block; padding-left: 11px; background: url(../webuikit-img/buttons/normal_left.png) no-repeat left top; z-index: 1; } a.button span span { font-size: 12px; line-height: 24px; text-shadow: none; color: white; display: block; background-position: -100px top; cursor: pointer; padding-right: 3px; padding-left: 3px; z-index: 2; } a.button:active { background-position: right bottom; } a.button:active span { background-position: left bottom; } a.button:active span span { background-position: -11px bottom; } /* alt */ a.button.alt { background-image: url(../webuikit-img/buttons/alt_right.png); } a.button.alt span { background-image: url(../webuikit-img/buttons/alt_left.png); } /*pink*/ a.button.pink { background-image: url(../webuikit-img/buttons/pink_right.png); } a.button.pink span { background-image: url(../webuikit-img/buttons/pink_left.png); } /*green*/ a.button.green { background-image: url(../webuikit-img/buttons/green_right.png); } a.button.green span { background-image: url(../webuikit-img/buttons/green_left.png); } /*purple*/ a.button.purple { background-image: url(../webuikit-img/buttons/purple_right.png); } a.button.purple span { background-image: url(../webuikit-img/buttons/purple_left.png); } /*dark*/ a.button.dark { background-image: url(../webuikit-img/buttons/dark_right.png); } a.button.dark span { background-image: url(../webuikit-img/buttons/dark_left.png); } /*milk*/ a.button.milk { background-image: url(../webuikit-img/buttons/milk_right.png); } a.button.milk span { background-image: url(../webuikit-img/buttons/milk_left.png); } /* @end */ /* @group Glyphs + text */ a.button.back span span, a.button.back:active span span { background: url(../webuikit-img/glyphs/back.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.check span span, a.button.check:active span span { background: url(../webuikit-img/glyphs/check.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.left span span, a.button.left:active span span { background: url(../webuikit-img/glyphs/left.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.right span span, a.button.right:active span span { background: url(../webuikit-img/glyphs/right.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.up span span, a.button.up:active span span { background: url(../webuikit-img/glyphs/up.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.down span span, a.button.down:active span span { background: url(../webuikit-img/glyphs/down.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.plus span span, a.button.plus:active span span { background: url(../webuikit-img/glyphs/plus.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.minus span span, a.button.minus:active span span { background: url(../webuikit-img/glyphs/minus.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.heart span span, a.button.heart:active span span { background: url(../webuikit-img/glyphs/heart.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.star span span, a.button.star:active span span { background: url(../webuikit-img/glyphs/star.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.x span span, a.button.x:active span span { background: url(../webuikit-img/glyphs/x.png) no-repeat; padding-left: 20px; padding-right: 3px; } a.button.thumb span span, a.button.thumb:active span span { background: url(../webuikit-img/glyphs/thumb.png) no-repeat; padding-left: 20px; padding-right: 3px; } - +a.button.pencil span span, a.button.pencil:active span span { + background: url(../webuikit-img/glyphs/pencil.png) no-repeat; + padding-left: 20px; + padding-right: 3px; +} /* @end */ /* @group Glyphs without text */ a.button.no-text span span { font-size: 0; padding-right: 8px; padding-left: 8px; } a.button.no-text:active span span { padding-right: 8px; padding-left: 8px; } /* @end */ \ No newline at end of file diff --git a/public/webuikit-img/glyphs/pencil.png b/public/webuikit-img/glyphs/pencil.png new file mode 100644 index 0000000..384d90e Binary files /dev/null and b/public/webuikit-img/glyphs/pencil.png differ diff --git a/test/fixtures/books.yml b/test/fixtures/books.yml new file mode 100644 index 0000000..c004b20 --- /dev/null +++ b/test/fixtures/books.yml @@ -0,0 +1,28 @@ +# == Schema Information +# Schema version: 20080929055605 +# +# Table name: books +# +# id :integer not null, primary key +# cover :string(255) +# author :string(255) +# title :string(255) +# publisher :string(255) +# published_at :string(255) +# content :text +# toc :text +# problems :text +# state :string(255) +# note :string(255) +# isbn :string(255) +# created_at :datetime +# updated_at :datetime +# + +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/functional/books_controller_test.rb b/test/functional/books_controller_test.rb new file mode 100644 index 0000000..eedf6a5 --- /dev/null +++ b/test/functional/books_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class BooksControllerTest < ActionController::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/test/unit/book_test.rb b/test/unit/book_test.rb new file mode 100644 index 0000000..d46a612 --- /dev/null +++ b/test/unit/book_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class BookTest < ActiveSupport::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/acts_as_state_machine/CHANGELOG b/vendor/plugins/acts_as_state_machine/CHANGELOG new file mode 100644 index 0000000..b97ad74 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/CHANGELOG @@ -0,0 +1,13 @@ +* trunk * + break with true value [Kaspar Schiess] + +* 2.1 * + After actions [Saimon Moore] + +* 2.0 * (2006-01-20 15:26:28 -0500) + Enter / Exit actions + Transition guards + Guards and actions can be a symbol pointing to a method or a Proc + +* 1.0 * (2006-01-15 12:16:55 -0500) + Initial Release diff --git a/vendor/plugins/acts_as_state_machine/MIT-LICENSE b/vendor/plugins/acts_as_state_machine/MIT-LICENSE new file mode 100644 index 0000000..3189ba6 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2006 Scott Barron + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/acts_as_state_machine/README b/vendor/plugins/acts_as_state_machine/README new file mode 100644 index 0000000..2bbcced --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/README @@ -0,0 +1,33 @@ += Acts As State Machine + +This act gives an Active Record model the ability to act as a finite state +machine (FSM). + +Acquire via subversion at: + +http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk + +If prompted, use the user/pass anonymous/anonymous. + +== Example + + class Order < ActiveRecord::Base + acts_as_state_machine :initial => :opened + + state :opened + state :closed, :enter => Proc.new {|o| Mailer.send_notice(o)} + state :returned + + event :close do + transitions :to => :closed, :from => :opened + end + + event :return do + transitions :to => :returned, :from => :closed + end + end + + o = Order.create + o.close! # notice is sent by mailer + o.return! + diff --git a/vendor/plugins/acts_as_state_machine/Rakefile b/vendor/plugins/acts_as_state_machine/Rakefile new file mode 100644 index 0000000..101fdde --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/Rakefile @@ -0,0 +1,28 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => [:clean_db, :test] + +desc 'Remove the stale db file' +task :clean_db do + `rm -f #{File.dirname(__FILE__)}/test/state_machine.sqlite.db` +end + +desc 'Test the acts as state machine plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the acts as state machine plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'Acts As State Machine' + rdoc.options << '--line-numbers --inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('TODO') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/vendor/plugins/acts_as_state_machine/TODO b/vendor/plugins/acts_as_state_machine/TODO new file mode 100644 index 0000000..8d5d706 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/TODO @@ -0,0 +1,11 @@ +* Currently invalid events are ignored, create an option so that they can be + ignored or raise an exception. + +* Query for a list of possible next states. + +* Make listing states optional since they can be inferred from the events. + Only required to list a state if you want to define a transition block for it. + +* Real transition actions + +* Default states diff --git a/vendor/plugins/acts_as_state_machine/init.rb b/vendor/plugins/acts_as_state_machine/init.rb new file mode 100644 index 0000000..dd1b4cd --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/init.rb @@ -0,0 +1,5 @@ +require 'acts_as_state_machine' + +ActiveRecord::Base.class_eval do + include ScottBarron::Acts::StateMachine +end diff --git a/vendor/plugins/acts_as_state_machine/lib/acts_as_state_machine.rb b/vendor/plugins/acts_as_state_machine/lib/acts_as_state_machine.rb new file mode 100644 index 0000000..50d0439 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/lib/acts_as_state_machine.rb @@ -0,0 +1,268 @@ +module ScottBarron #:nodoc: + module Acts #:nodoc: + module StateMachine #:nodoc: + class InvalidState < Exception #:nodoc: + end + class NoInitialState < Exception #:nodoc: + end + + def self.included(base) #:nodoc: + base.extend ActMacro + end + + module SupportingClasses + class State + attr_reader :name + + def initialize(name, opts) + @name, @opts = name, opts + end + + def entering(record) + enteract = @opts[:enter] + record.send(:run_transition_action, enteract) if enteract + end + + def entered(record) + afteractions = @opts[:after] + return unless afteractions + Array(afteractions).each do |afteract| + record.send(:run_transition_action, afteract) + end + end + + def exited(record) + exitact = @opts[:exit] + record.send(:run_transition_action, exitact) if exitact + end + end + + class StateTransition + attr_reader :from, :to, :opts + + def initialize(opts) + @from, @to, @guard = opts[:from], opts[:to], opts[:guard] + @opts = opts + end + + def guard(obj) + @guard ? obj.send(:run_transition_action, @guard) : true + end + + def perform(record) + return false unless guard(record) + loopback = record.current_state == to + states = record.class.read_inheritable_attribute(:states) + next_state = states[to] + old_state = states[record.current_state] + + next_state.entering(record) unless loopback + + record.update_attribute(record.class.state_column, to.to_s) + + next_state.entered(record) unless loopback + old_state.exited(record) unless loopback + true + end + + def ==(obj) + @from == obj.from && @to == obj.to + end + end + + class Event + attr_reader :name + attr_reader :transitions + attr_reader :opts + + def initialize(name, opts, transition_table, &block) + @name = name.to_sym + @transitions = transition_table[@name] = [] + instance_eval(&block) if block + @opts = opts + @opts.freeze + @transitions.freeze + freeze + end + + def next_states(record) + @transitions.select { |t| t.from == record.current_state } + end + + def fire(record) + next_states(record).each do |transition| + break true if transition.perform(record) + end + end + + def transitions(trans_opts) + Array(trans_opts[:from]).each do |s| + @transitions << SupportingClasses::StateTransition.new(trans_opts.merge({:from => s.to_sym})) + end + end + end + end + + module ActMacro + # Configuration options are + # + # * +column+ - specifies the column name to use for keeping the state (default: state) + # * +initial+ - specifies an initial state for newly created objects (required) + def acts_as_state_machine(opts) + self.extend(ClassMethods) + raise NoInitialState unless opts[:initial] + + write_inheritable_attribute :states, {} + write_inheritable_attribute :initial_state, opts[:initial] + write_inheritable_attribute :transition_table, {} + write_inheritable_attribute :event_table, {} + write_inheritable_attribute :state_column, opts[:column] || 'state' + + class_inheritable_reader :initial_state + class_inheritable_reader :state_column + class_inheritable_reader :transition_table + class_inheritable_reader :event_table + + self.send(:include, ScottBarron::Acts::StateMachine::InstanceMethods) + + before_create :set_initial_state + after_create :run_initial_state_actions + end + end + + module InstanceMethods + def set_initial_state #:nodoc: + write_attribute self.class.state_column, self.class.initial_state.to_s + end + + def run_initial_state_actions + initial = self.class.read_inheritable_attribute(:states)[self.class.initial_state.to_sym] + initial.entering(self) + initial.entered(self) + end + + # Returns the current state the object is in, as a Ruby symbol. + def current_state + self.send(self.class.state_column).to_sym + end + + # Returns what the next state for a given event would be, as a Ruby symbol. + def next_state_for_event(event) + ns = next_states_for_event(event) + ns.empty? ? nil : ns.first.to + end + + def next_states_for_event(event) + self.class.read_inheritable_attribute(:transition_table)[event.to_sym].select do |s| + s.from == current_state + end + end + + def run_transition_action(action) + Symbol === action ? self.method(action).call : action.call(self) + end + private :run_transition_action + end + + module ClassMethods + # Returns an array of all known states. + def states + read_inheritable_attribute(:states).keys + end + + # Define an event. This takes a block which describes all valid transitions + # for this event. + # + # Example: + # + # class Order < ActiveRecord::Base + # acts_as_state_machine :initial => :open + # + # state :open + # state :closed + # + # event :close_order do + # transitions :to => :closed, :from => :open + # end + # end + # + # +transitions+ takes a hash where <tt>:to</tt> is the state to transition + # to and <tt>:from</tt> is a state (or Array of states) from which this + # event can be fired. + # + # This creates an instance method used for firing the event. The method + # created is the name of the event followed by an exclamation point (!). + # Example: <tt>order.close_order!</tt>. + def event(event, opts={}, &block) + tt = read_inheritable_attribute(:transition_table) + + et = read_inheritable_attribute(:event_table) + e = et[event.to_sym] = SupportingClasses::Event.new(event, opts, tt, &block) + define_method("#{event.to_s}!") { e.fire(self) } + end + + # Define a state of the system. +state+ can take an optional Proc object + # which will be executed every time the system transitions into that + # state. The proc will be passed the current object. + # + # Example: + # + # class Order < ActiveRecord::Base + # acts_as_state_machine :initial => :open + # + # state :open + # state :closed, Proc.new { |o| Mailer.send_notice(o) } + # end + def state(name, opts={}) + state = SupportingClasses::State.new(name.to_sym, opts) + read_inheritable_attribute(:states)[name.to_sym] = state + + define_method("#{state.name}?") { current_state == state.name } + end + + # Wraps ActiveRecord::Base.find to conveniently find all records in + # a given state. Options: + # + # * +number+ - This is just :first or :all from ActiveRecord +find+ + # * +state+ - The state to find + # * +args+ - The rest of the args are passed down to ActiveRecord +find+ + def find_in_state(number, state, *args) + with_state_scope state do + find(number, *args) + end + end + + # Wraps ActiveRecord::Base.count to conveniently count all records in + # a given state. Options: + # + # * +state+ - The state to find + # * +args+ - The rest of the args are passed down to ActiveRecord +find+ + def count_in_state(state, *args) + with_state_scope state do + count(*args) + end + end + + # Wraps ActiveRecord::Base.calculate to conveniently calculate all records in + # a given state. Options: + # + # * +state+ - The state to find + # * +args+ - The rest of the args are passed down to ActiveRecord +calculate+ + def calculate_in_state(state, *args) + with_state_scope state do + calculate(*args) + end + end + + protected + def with_state_scope(state) + raise InvalidState unless states.include?(state) + + with_scope :find => {:conditions => ["#{table_name}.#{state_column} = ?", state.to_s]} do + yield if block_given? + end + end + end + end + end +end \ No newline at end of file diff --git a/vendor/plugins/acts_as_state_machine/test/acts_as_state_machine_test.rb b/vendor/plugins/acts_as_state_machine/test/acts_as_state_machine_test.rb new file mode 100644 index 0000000..e113515 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/acts_as_state_machine_test.rb @@ -0,0 +1,224 @@ +require File.dirname(__FILE__) + '/test_helper' + +include ScottBarron::Acts::StateMachine + +class ActsAsStateMachineTest < Test::Unit::TestCase + fixtures :conversations + + def test_no_initial_value_raises_exception + assert_raise(NoInitialState) { + Person.acts_as_state_machine({}) + } + end + + def test_initial_state_value + assert_equal :needs_attention, Conversation.initial_state + end + + def test_column_was_set + assert_equal 'state_machine', Conversation.state_column + end + + def test_initial_state + c = Conversation.create + assert_equal :needs_attention, c.current_state + assert c.needs_attention? + end + + def test_states_were_set + [:needs_attention, :read, :closed, :awaiting_response, :junk].each do |s| + assert Conversation.states.include?(s) + end + end + + def test_event_methods_created + c = Conversation.create + %w(new_message! view! reply! close! junk! unjunk!).each do |event| + assert c.respond_to?(event) + end + end + + def test_query_methods_created + c = Conversation.create + %w(needs_attention? read? closed? awaiting_response? junk?).each do |event| + assert c.respond_to?(event) + end + end + + def test_transition_table + tt = Conversation.transition_table + + assert tt[:new_message].include?(SupportingClasses::StateTransition.new(:from => :read, :to => :needs_attention)) + assert tt[:new_message].include?(SupportingClasses::StateTransition.new(:from => :closed, :to => :needs_attention)) + assert tt[:new_message].include?(SupportingClasses::StateTransition.new(:from => :awaiting_response, :to => :needs_attention)) + end + + def test_next_state_for_event + c = Conversation.create + assert_equal :read, c.next_state_for_event(:view) + end + + def test_change_state + c = Conversation.create + c.view! + assert c.read? + end + + def test_can_go_from_read_to_closed_because_guard_passes + c = Conversation.create + c.can_close = true + c.view! + c.reply! + c.close! + assert_equal :closed, c.current_state + end + + def test_cannot_go_from_read_to_closed_because_of_guard + c = Conversation.create + c.can_close = false + c.view! + c.reply! + c.close! + assert_equal :read, c.current_state + end + + def test_ignore_invalid_events + c = Conversation.create + c.view! + c.junk! + + # This is the invalid event + c.new_message! + assert_equal :junk, c.current_state + end + + def test_entry_action_executed + c = Conversation.create + c.read_enter = false + c.view! + assert c.read_enter + end + + def test_after_actions_executed + c = Conversation.create + + c.read_after_first = false + c.read_after_second = false + c.closed_after = false + + c.view! + assert c.read_after_first + assert c.read_after_second + + c.can_close = true + c.close! + + assert c.closed_after + assert_equal :closed, c.current_state + end + + def test_after_actions_not_run_on_loopback_transition + c = Conversation.create + + c.view! + c.read_after_first = false + c.read_after_second = false + c.view! + + assert !c.read_after_first + assert !c.read_after_second + + c.can_close = true + + c.close! + c.closed_after = false + c.close! + + assert !c.closed_after + end + + def test_exit_action_executed + c = Conversation.create + c.read_exit = false + c.view! + c.junk! + assert c.read_exit + end + + def test_entry_and_exit_not_run_on_loopback_transition + c = Conversation.create + c.view! + c.read_enter = false + c.read_exit = false + c.view! + assert !c.read_enter + assert !c.read_exit + end + + def test_entry_and_after_actions_called_for_initial_state + c = Conversation.create + assert c.needs_attention_enter + assert c.needs_attention_after + end + + def test_run_transition_action_is_private + c = Conversation.create + assert_raise(NoMethodError) { c.run_transition_action :foo } + end + + def test_find_all_in_state + cs = Conversation.find_in_state(:all, :read) + + assert_equal 2, cs.size + end + + def test_find_first_in_state + c = Conversation.find_in_state(:first, :read) + + assert_equal conversations(:first).id, c.id + end + + def test_find_all_in_state_with_conditions + cs = Conversation.find_in_state(:all, :read, :conditions => ['subject = ?', conversations(:second).subject]) + + assert_equal 1, cs.size + assert_equal conversations(:second).id, cs.first.id + end + + def test_find_first_in_state_with_conditions + c = Conversation.find_in_state(:first, :read, :conditions => ['subject = ?', conversations(:second).subject]) + assert_equal conversations(:second).id, c.id + end + + def test_count_in_state + cnt0 = Conversation.count(['state_machine = ?', 'read']) + cnt = Conversation.count_in_state(:read) + + assert_equal cnt0, cnt + end + + def test_count_in_state_with_conditions + cnt0 = Conversation.count(['state_machine = ? AND subject = ?', 'read', 'Foo']) + cnt = Conversation.count_in_state(:read, ['subject = ?', 'Foo']) + + assert_equal cnt0, cnt + end + + def test_find_in_invalid_state_raises_exception + assert_raise(InvalidState) { + Conversation.find_in_state(:all, :dead) + } + end + + def test_count_in_invalid_state_raises_exception + assert_raise(InvalidState) { + Conversation.count_in_state(:dead) + } + end + + def test_can_access_events_via_event_table + event = Conversation.event_table[:junk] + assert_equal :junk, event.name + assert_equal "finished", event.opts[:note] + end +end diff --git a/vendor/plugins/acts_as_state_machine/test/database.yml b/vendor/plugins/acts_as_state_machine/test/database.yml new file mode 100644 index 0000000..f012c25 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/database.yml @@ -0,0 +1,18 @@ +sqlite: + :adapter: sqlite + :dbfile: state_machine.sqlite.db +sqlite3: + :adapter: sqlite3 + :dbfile: state_machine.sqlite3.db +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: state_machine_test + :min_messages: ERROR +mysql: + :adapter: mysql + :host: localhost + :username: rails + :password: + :database: state_machine_test \ No newline at end of file diff --git a/vendor/plugins/acts_as_state_machine/test/fixtures/conversation.rb b/vendor/plugins/acts_as_state_machine/test/fixtures/conversation.rb new file mode 100644 index 0000000..8b41432 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/fixtures/conversation.rb @@ -0,0 +1,67 @@ +class Conversation < ActiveRecord::Base + attr_writer :can_close + attr_accessor :read_enter, :read_exit, :read_after_first, :read_after_second, + :closed_after, :needs_attention_enter, :needs_attention_after + + acts_as_state_machine :initial => :needs_attention, :column => 'state_machine' + + state :needs_attention, :enter => Proc.new { |o| o.needs_attention_enter = true }, + :after => Proc.new { |o| o.needs_attention_after = true } + + state :read, :enter => :read_enter_action, + :exit => Proc.new { |o| o.read_exit = true }, + :after => [:read_after_first_action, :read_after_second_action] + + state :closed, :after => :closed_after_action + state :awaiting_response + state :junk + + event :new_message do + transitions :to => :needs_attention, :from => [:read, :closed, :awaiting_response] + end + + event :view do + transitions :to => :read, :from => [:needs_attention, :read] + end + + event :reply do + transitions :to => :awaiting_response, :from => [:read, :closed] + end + + event :close do + transitions :to => :closed, :from => [:read, :awaiting_response], :guard => Proc.new {|o| o.can_close?} + transitions :to => :read, :from => [:read, :awaiting_response], :guard => :always_true + end + + event :junk, :note => "finished" do + transitions :to => :junk, :from => [:read, :closed, :awaiting_response] + end + + event :unjunk do + transitions :to => :closed, :from => :junk + end + + def can_close? + @can_close + end + + def read_enter_action + self.read_enter = true + end + + def always_true + true + end + + def read_after_first_action + self.read_after_first = true + end + + def read_after_second_action + self.read_after_second = true + end + + def closed_after_action + self.closed_after = true + end +end diff --git a/vendor/plugins/acts_as_state_machine/test/fixtures/conversations.yml b/vendor/plugins/acts_as_state_machine/test/fixtures/conversations.yml new file mode 100644 index 0000000..572e0ee --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/fixtures/conversations.yml @@ -0,0 +1,11 @@ +first: + id: 1 + state_machine: read + subject: This is a test + closed: false + +second: + id: 2 + state_machine: read + subject: Foo + closed: false diff --git a/vendor/plugins/acts_as_state_machine/test/fixtures/person.rb b/vendor/plugins/acts_as_state_machine/test/fixtures/person.rb new file mode 100644 index 0000000..e64a826 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/fixtures/person.rb @@ -0,0 +1,2 @@ +class Person < ActiveRecord::Base +end \ No newline at end of file diff --git a/vendor/plugins/acts_as_state_machine/test/schema.rb b/vendor/plugins/acts_as_state_machine/test/schema.rb new file mode 100644 index 0000000..5012899 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/schema.rb @@ -0,0 +1,11 @@ +ActiveRecord::Schema.define(:version => 1) do + create_table :conversations, :force => true do |t| + t.column :state_machine, :string + t.column :subject, :string + t.column :closed, :boolean + end + + create_table :people, :force => true do |t| + t.column :name, :string + end +end diff --git a/vendor/plugins/acts_as_state_machine/test/test_helper.rb b/vendor/plugins/acts_as_state_machine/test/test_helper.rb new file mode 100644 index 0000000..95331d0 --- /dev/null +++ b/vendor/plugins/acts_as_state_machine/test/test_helper.rb @@ -0,0 +1,38 @@ +$:.unshift(File.dirname(__FILE__) + '/../lib') +RAILS_ROOT = File.dirname(__FILE__) + +require 'rubygems' +require 'test/unit' +require 'active_record' +require 'active_record/fixtures' +require 'active_support/binding_of_caller' +require 'active_support/breakpoint' +require "#{File.dirname(__FILE__)}/../init" + + +config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) +ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") +ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite']) + +load(File.dirname(__FILE__) + "/schema.rb") if File.exist?(File.dirname(__FILE__) + "/schema.rb") + +Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/" +$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path) + +class Test::Unit::TestCase #:nodoc: + def create_fixtures(*table_names) + if block_given? + Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield } + else + Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) + end + end + + # Turn off transactional fixtures if you're working with MyISAM tables in MySQL + self.use_transactional_fixtures = true + + # Instantiated fixtures are slow, but give you @david where you otherwise would need people(:david) + self.use_instantiated_fixtures = false + + # Add more helper methods to be used by all tests here... +end \ No newline at end of file diff --git a/vendor/plugins/file_column/CHANGELOG b/vendor/plugins/file_column/CHANGELOG new file mode 100644 index 0000000..bb4e5c6 --- /dev/null +++ b/vendor/plugins/file_column/CHANGELOG @@ -0,0 +1,69 @@ +*svn* + * allow for directories in file_column dirs as well + * use subdirs for versions instead of fiddling with filename + * url_for_image_column_helper for dynamic resizing of images from views + * new "crop" feature [Sean Treadway] + * url_for_file_column helper: do not require model objects to be stored in + instance variables + * allow more fined-grained control over :store_dir via callback + methods [Gerret Apelt] + * allow assignment of regular file objects + * validation of file format and file size [Kyle Maxwell] + * validation of image dimensions [Lee O'Mara] + * file permissions can be set via :permissions option + * fixed bug that prevents deleting of file via assigning nil if + column is declared as NON NULL on some databases + * don't expand absolute paths. This is necessary for file_column to work + when your rails app is deployed into a sub-directory via a symbolic link + * url_for_*_column will no longer return absolute URLs! Instead, although the + generated URL starts with a slash, it will be relative to your application's + root URL. This is so, because rails' image_tag helper will automatically + convert it to an absolute URL. If you need an absolute URL (e.g., to pass + it to link_to) use url_for_file_column's :absolute => true option. + * added support for file_column enabled unit tests [Manuel Holtgrewe] + * support for custom transformation of images [Frederik Fix] + * allow setting of image attributes (e.g., quality) [Frederik Fix] + * :magick columns can optionally ignore non-images (i.e., do not try to + resize them) + +0.3.1 + * make object with file_columns serializable + * use normal require for RMagick, so that it works with gem + and custom install as well + +0.3 + * fixed bug where empty file uploads were not recognized with some browsers + * fixed bug on windows when "file" utility is not present + * added option to disable automatic file extension correction + * Only allow one attribute per call to file_column, so that options only + apply to one argument + * try to detect when people forget to set the form encoding to + 'multipart/form-data' + * converted to rails plugin + * easy integration with RMagick + +0.2 + * complete rewrite using state pattern + * fixed sanitize filename [Michael Raidel] + * fixed bug when no file was uploaded [Michael Raidel] + * try to fix filename extensions [Michael Raidel] + * Feed absolute paths through File.expand_path to make them as simple as possible + * Make file_column_field helper work with auto-ids (e.g., "event[]") + +0.1.3 + * test cases with more than 1 file_column + * fixed bug when file_column was called with several arguments + * treat empty ("") file_columns as nil + * support for binary files on windows + +0.1.2 + * better rails integration, so that you do not have to include the modules yourself. You + just have to "require 'rails_file_column'" in your "config/environment.rb" + * Rakefile for testing and packaging + +0.1.1 (2005-08-11) + * fixed nasty bug in url_for_file_column that made it unusable on Apache + * prepared for public release + +0.1 (2005-08-10) + * initial release diff --git a/vendor/plugins/file_column/README b/vendor/plugins/file_column/README new file mode 100644 index 0000000..07a6e96 --- /dev/null +++ b/vendor/plugins/file_column/README @@ -0,0 +1,54 @@ +FEATURES +======== + +Let's assume an model class named Entry, where we want to define the "image" column +as a "file_upload" column. + +class Entry < ActiveRecord::Base + file_column :image +end + +* every entry can have one uploaded file, the filename will be stored in the "image" column + +* files will be stored in "public/entry/image/<entry.id>/filename.ext" + +* Newly uploaded files will be stored in "public/entry/tmp/<random>/filename.ext" so that + they can be reused in form redisplays (due to validation etc.) + +* in a view, "<%= file_column_field 'entry', 'image' %> will create a file upload field as well + as a hidden field to recover files uploaded before in a case of a form redisplay + +* in a view, "<%= url_for_file_column 'entry', 'image' %> will create an URL to access the + uploaded file. Note that you need an Entry object in the instance variable @entry for this + to work. + +* easy integration with RMagick to resize images and/or create thumb-nails. + +USAGE +===== + +Just drop the whole directory into your application's "vendor/plugins" directory. Starting +with version 1.0rc of rails, it will be automatically picked for you by rails plugin +mechanism. + +DOCUMENTATION +============= + +Please look at the rdoc-generated documentation in the "doc" directory. + +RUNNING UNITTESTS +================= + +There are extensive unittests in the "test" directory. Currently, only MySQL is supported, but +you should be able to easily fix this by looking at "connection.rb". You have to create a +database for the tests and put the connection information into "connection.rb". The schema +for MySQL can be found in "test/fixtures/mysql.sql". + +You can run the tests by starting the "*_test.rb" in the directory "test" + +BUGS & FEEDBACK +=============== + +Bug reports (as well as patches) and feedback are very welcome. Please send it to [email protected] + diff --git a/vendor/plugins/file_column/Rakefile b/vendor/plugins/file_column/Rakefile new file mode 100644 index 0000000..0a24682 --- /dev/null +++ b/vendor/plugins/file_column/Rakefile @@ -0,0 +1,36 @@ +task :default => [:test] + +PKG_NAME = "file-column" +PKG_VERSION = "0.3.1" + +PKG_DIR = "release/#{PKG_NAME}-#{PKG_VERSION}" + +task :clean do + rm_rf "release" +end + +task :setup_directories do + mkpath "release" +end + + +task :checkout_release => :setup_directories do + rm_rf PKG_DIR + revision = ENV["REVISION"] || "HEAD" + sh "svn export -r #{revision} . #{PKG_DIR}" +end + +task :release_docs => :checkout_release do + sh "cd #{PKG_DIR}; rdoc lib" +end + +task :package => [:checkout_release, :release_docs] do + sh "cd release; tar czf #{PKG_NAME}-#{PKG_VERSION}.tar.gz #{PKG_NAME}-#{PKG_VERSION}" +end + +task :test do + sh "cd test; ruby file_column_test.rb" + sh "cd test; ruby file_column_helper_test.rb" + sh "cd test; ruby magick_test.rb" + sh "cd test; ruby magick_view_only_test.rb" +end diff --git a/vendor/plugins/file_column/TODO b/vendor/plugins/file_column/TODO new file mode 100644 index 0000000..d46e9fa --- /dev/null +++ b/vendor/plugins/file_column/TODO @@ -0,0 +1,6 @@ +* document configuration options better +* support setting of permissions +* validation methods for file format/size +* delete stale files from tmp directories + +* ensure valid URLs are created even when deployed at sub-path (compute_public_url?) diff --git a/vendor/plugins/file_column/init.rb b/vendor/plugins/file_column/init.rb new file mode 100644 index 0000000..d31ef1b --- /dev/null +++ b/vendor/plugins/file_column/init.rb @@ -0,0 +1,13 @@ +# plugin init file for rails +# this file will be picked up by rails automatically and +# add the file_column extensions to rails + +require 'file_column' +require 'file_compat' +require 'file_column_helper' +require 'validations' +require 'test_case' + +ActiveRecord::Base.send(:include, FileColumn) +ActionView::Base.send(:include, FileColumnHelper) +ActiveRecord::Base.send(:include, FileColumn::Validations) \ No newline at end of file diff --git a/vendor/plugins/file_column/lib/file_column.rb b/vendor/plugins/file_column/lib/file_column.rb new file mode 100644 index 0000000..6e65998 --- /dev/null +++ b/vendor/plugins/file_column/lib/file_column.rb @@ -0,0 +1,720 @@ +require 'fileutils' +require 'tempfile' +require 'magick_file_column' + +module FileColumn # :nodoc: + def self.append_features(base) + super + base.extend(ClassMethods) + end + + def self.create_state(instance,attr) + filename = instance[attr] + if filename.nil? or filename.empty? + NoUploadedFile.new(instance,attr) + else + PermanentUploadedFile.new(instance,attr) + end + end + + def self.init_options(defaults, model, attr) + options = defaults.dup + options[:store_dir] ||= File.join(options[:root_path], model, attr) + unless options[:store_dir].is_a?(Symbol) + options[:tmp_base_dir] ||= File.join(options[:store_dir], "tmp") + end + options[:base_url] ||= options[:web_root] + File.join(model, attr) + + [:store_dir, :tmp_base_dir].each do |dir_sym| + if options[dir_sym].is_a?(String) and !File.exists?(options[dir_sym]) + FileUtils.mkpath(options[dir_sym]) + end + end + + options + end + + class BaseUploadedFile # :nodoc: + + def initialize(instance,attr) + @instance, @attr = instance, attr + @options_method = "#{attr}_options".to_sym + end + + + def assign(file) + if file.is_a? File + # this did not come in via a CGI request. However, + # assigning files directly may be useful, so we + # make just this file object similar enough to an uploaded + # file that we can handle it. + file.extend FileColumn::FileCompat + end + + if file.nil? + delete + else + if file.size == 0 + # user did not submit a file, so we + # can simply ignore this + self + else + if file.is_a?(String) + # if file is a non-empty string it is most probably + # the filename and the user forgot to set the encoding + # to multipart/form-data. Since we would raise an exception + # because of the missing "original_filename" method anyways, + # we raise a more meaningful exception rightaway. + raise TypeError.new("Do not know how to handle a string with value '#{file}' that was passed to a file_column. Check if the form's encoding has been set to 'multipart/form-data'.") + end + upload(file) + end + end + end + + def just_uploaded? + @just_uploaded + end + + def on_save(&blk) + @on_save ||= [] + @on_save << Proc.new + end + + # the following methods are overriden by sub-classes if needed + + def temp_path + nil + end + + def absolute_dir + if absolute_path then File.dirname(absolute_path) else nil end + end + + def relative_dir + if relative_path then File.dirname(relative_path) else nil end + end + + def after_save + @on_save.each { |blk| blk.call } if @on_save + self + end + + def after_destroy + end + + def options + @instance.send(@options_method) + end + + private + + def store_dir + if options[:store_dir].is_a? Symbol + raise ArgumentError.new("'#{options[:store_dir]}' is not an instance method of class #{@instance.class.name}") unless @instance.respond_to?(options[:store_dir]) + + dir = File.join(options[:root_path], @instance.send(options[:store_dir])) + FileUtils.mkpath(dir) unless File.exists?(dir) + dir + else + options[:store_dir] + end + end + + def tmp_base_dir + if options[:tmp_base_dir] + options[:tmp_base_dir] + else + dir = File.join(store_dir, "tmp") + FileUtils.mkpath(dir) unless File.exists?(dir) + dir + end + end + + def clone_as(klass) + klass.new(@instance, @attr) + end + + end + + + class NoUploadedFile < BaseUploadedFile # :nodoc: + def delete + # we do not have a file so deleting is easy + self + end + + def upload(file) + # replace ourselves with a TempUploadedFile + temp = clone_as TempUploadedFile + temp.store_upload(file) + temp + end + + def absolute_path(subdir=nil) + nil + end + + + def relative_path(subdir=nil) + nil + end + + def assign_temp(temp_path) + return self if temp_path.nil? or temp_path.empty? + temp = clone_as TempUploadedFile + temp.parse_temp_path temp_path + temp + end + end + + class RealUploadedFile < BaseUploadedFile # :nodoc: + def absolute_path(subdir=nil) + if subdir + File.join(@dir, subdir, @filename) + else + File.join(@dir, @filename) + end + end + + def relative_path(subdir=nil) + if subdir + File.join(relative_path_prefix, subdir, @filename) + else + File.join(relative_path_prefix, @filename) + end + end + + private + + # regular expressions to try for identifying extensions + EXT_REGEXPS = [ + /^(.+)\.([^.]+\.[^.]+)$/, # matches "something.tar.gz" + /^(.+)\.([^.]+)$/ # matches "something.jpg" + ] + + def split_extension(filename,fallback=nil) + EXT_REGEXPS.each do |regexp| + if filename =~ regexp + base,ext = $1, $2 + return [base, ext] if options[:extensions].include?(ext.downcase) + end + end + if fallback and filename =~ EXT_REGEXPS.last + return [$1, $2] + end + [filename, ""] + end + + end + + class TempUploadedFile < RealUploadedFile # :nodoc: + + def store_upload(file) + @tmp_dir = FileColumn.generate_temp_name + @dir = File.join(tmp_base_dir, @tmp_dir) + FileUtils.mkdir(@dir) + + @filename = FileColumn::sanitize_filename(file.original_filename) + local_file_path = File.join(tmp_base_dir,@tmp_dir,@filename) + + # stored uploaded file into local_file_path + # If it was a Tempfile object, the temporary file will be + # cleaned up automatically, so we do not have to care for this + if file.respond_to?(:local_path) and file.local_path and File.exists?(file.local_path) + FileUtils.copy_file(file.local_path, local_file_path) + elsif file.respond_to?(:read) + File.open(local_file_path, "wb") { |f| f.write(file.read) } + else + raise ArgumentError.new("Do not know how to handle #{file.inspect}") + end + File.chmod(options[:permissions], local_file_path) + + if options[:fix_file_extensions] + # try to determine correct file extension and fix + # if necessary + content_type = get_content_type((file.content_type.chomp if file.content_type)) + if content_type and options[:mime_extensions][content_type] + @filename = correct_extension(@filename,options[:mime_extensions][content_type]) + end + + new_local_file_path = File.join(tmp_base_dir,@tmp_dir,@filename) + File.rename(local_file_path, new_local_file_path) unless new_local_file_path == local_file_path + local_file_path = new_local_file_path + end + + @instance[@attr] = @filename + @just_uploaded = true + end + + + # tries to identify and strip the extension of filename + # if an regular expresion from EXT_REGEXPS matches and the + # downcased extension is a known extension (in options[:extensions]) + # we'll strip this extension + def strip_extension(filename) + split_extension(filename).first + end + + def correct_extension(filename, ext) + strip_extension(filename) << ".#{ext}" + end + + def parse_temp_path(temp_path, instance_options=nil) + raise ArgumentError.new("invalid format of '#{temp_path}'") unless temp_path =~ %r{^((\d+\.)+\d+)/([^/].+)$} + @tmp_dir, @filename = $1, FileColumn.sanitize_filename($3) + @dir = File.join(tmp_base_dir, @tmp_dir) + + @instance[@attr] = @filename unless instance_options == :ignore_instance + end + + def upload(file) + # store new file + temp = clone_as TempUploadedFile + temp.store_upload(file) + + # delete old copy + delete_files + + # and return new TempUploadedFile object + temp + end + + def delete + delete_files + @instance[@attr] = "" + clone_as NoUploadedFile + end + + def assign_temp(temp_path) + return self if temp_path.nil? or temp_path.empty? + # we can ignore this since we've already received a newly uploaded file + + # however, we delete the old temporary files + temp = clone_as TempUploadedFile + temp.parse_temp_path(temp_path, :ignore_instance) + temp.delete_files + + self + end + + def temp_path + File.join(@tmp_dir, @filename) + end + + def after_save + super + + # we have a newly uploaded image, move it to the correct location + file = clone_as PermanentUploadedFile + file.move_from(File.join(tmp_base_dir, @tmp_dir), @just_uploaded) + + # delete temporary files + delete_files + + # replace with the new PermanentUploadedFile object + file + end + + def delete_files + FileUtils.rm_rf(File.join(tmp_base_dir, @tmp_dir)) + end + + def get_content_type(fallback=nil) + if options[:file_exec] + begin + content_type = `#{options[:file_exec]} -bi "#{File.join(@dir,@filename)}"`.chomp + content_type = fallback unless $?.success? + content_type.gsub!(/;.+$/,"") if content_type + content_type + rescue + fallback + end + else + fallback + end + end + + private + + def relative_path_prefix + File.join("tmp", @tmp_dir) + end + end + + + class PermanentUploadedFile < RealUploadedFile # :nodoc: + def initialize(*args) + super *args + @dir = File.join(store_dir, relative_path_prefix) + @filename = @instance[@attr] + @filename = nil if @filename.empty? + end + + def move_from(local_dir, just_uploaded) + # remove old permament dir first + # this creates a short moment, where neither the old nor + # the new files exist but we can't do much about this as + # filesystems aren't transactional. + FileUtils.rm_rf @dir + + FileUtils.mv local_dir, @dir + + @just_uploaded = just_uploaded + end + + def upload(file) + temp = clone_as TempUploadedFile + temp.store_upload(file) + temp + end + + def delete + file = clone_as NoUploadedFile + @instance[@attr] = "" + file.on_save { delete_files } + file + end + + def assign_temp(temp_path) + return nil if temp_path.nil? or temp_path.empty? + + temp = clone_as TempUploadedFile + temp.parse_temp_path(temp_path) + temp + end + + def after_destroy + delete_files + end + + def delete_files + FileUtils.rm_rf @dir + end + + private + + def relative_path_prefix + raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.id.to_s.empty? + @instance.id.to_s + end + end + + # The FileColumn module allows you to easily handle file uploads. You can designate + # one or more columns of your model's table as "file columns" like this: + # + # class Entry < ActiveRecord::Base + # + # file_column :image + # end + # + # Now, by default, an uploaded file "test.png" for an entry object with primary key 42 will + # be stored in in "public/entry/image/42/test.png". The filename "test.png" will be stored + # in the record's "image" column. The "entries" table should have a +VARCHAR+ column + # named "image". + # + # The methods of this module are automatically included into <tt>ActiveRecord::Base</tt> + # as class methods, so that you can use them in your models. + # + # == Generated Methods + # + # After calling "<tt>file_column :image</tt>" as in the example above, a number of instance methods + # will automatically be generated, all prefixed by "image": + # + # * <tt>Entry#image=(uploaded_file)</tt>: this will handle a newly uploaded file + # (see below). Note that + # you can simply call your upload field "entry[image]" in your view (or use the + # helper). + # * <tt>Entry#image(subdir=nil)</tt>: This will return an absolute path (as a + # string) to the currently uploaded file + # or nil if no file has been uploaded + # * <tt>Entry#image_relative_path(subdir=nil)</tt>: This will return a path relative to + # this file column's base directory + # as a string or nil if no file has been uploaded. This would be "42/test.png" in the example. + # * <tt>Entry#image_just_uploaded?</tt>: Returns true if a new file has been uploaded to this instance. + # You can use this in your code to perform certain actions (e. g., validation, + # custom post-processing) only on newly uploaded files. + # + # You can access the raw value of the "image" column (which will contain the filename) via the + # <tt>ActiveRecord::Base#attributes</tt> or <tt>ActiveRecord::Base#[]</tt> methods like this: + # + # entry['image'] # e.g."test.png" + # + # == Storage of uploaded files + # + # For a model class +Entry+ and a column +image+, all files will be stored under + # "public/entry/image". A sub-directory named after the primary key of the object will + # be created, so that files can be stored using their real filename. For example, a file + # "test.png" stored in an Entry object with id 42 will be stored in + # + # public/entry/image/42/test.png + # + # Files will be moved to this location in an +after_save+ callback. They will be stored in + # a temporary location previously as explained in the next section. + # + # By default, files will be created with unix permissions of <tt>0644</tt> (i. e., owner has + # read/write access, group and others only have read access). You can customize + # this by passing the desired mode as a <tt>:permissions</tt> options. The value + # you give here is passed directly to <tt>File::chmod</tt>, so on Unix you should + # give some octal value like 0644, for example. + # + # == Handling of form redisplay + # + # Suppose you have a form for creating a new object where the user can upload an image. The form may + # have to be re-displayed because of validation errors. The uploaded file has to be stored somewhere so + # that the user does not have to upload it again. FileColumn will store these in a temporary directory + # (called "tmp" and located under the column's base directory by default) so that it can be moved to + # the final location if the object is successfully created. If the form is never completed, though, you + # can easily remove all the images in this "tmp" directory once per day or so. + # + # So in the example above, the image "test.png" would first be stored in + # "public/entry/image/tmp/<some_random_key>/test.png" and be moved to + # "public/entry/image/<primary_key>/test.png". + # + # This temporary location of newly uploaded files has another advantage when updating objects. If the + # update fails for some reasons (e.g. due to validations), the existing image will not be overwritten, so + # it has a kind of "transactional behaviour". + # + # == Additional Files and Directories + # + # FileColumn allows you to keep more than one file in a directory and will move/delete + # all the files and directories it finds in a model object's directory when necessary. + # + # As a convenience you can access files stored in sub-directories via the +subdir+ + # parameter if they have the same filename. + # + # Suppose your uploaded file is named "vancouver.jpg" and you want to create a + # thumb-nail and store it in the "thumb" directory. If you call + # <tt>image("thumb")</tt>, you + # will receive an absolute path for the file "thumb/vancouver.jpg" in the same + # directory "vancouver.jpg" is stored. Look at the documentation of FileColumn::Magick + # for more examples and how to create these thumb-nails automatically. + # + # == File Extensions + # + # FileColumn will try to fix the file extension of uploaded files, so that + # the files are served with the correct mime-type by your web-server. Most + # web-servers are setting the mime-type based on the file's extension. You + # can disable this behaviour by passing the <tt>:fix_file_extensions</tt> option + # with a value of +nil+ to +file_column+. + # + # In order to set the correct extension, FileColumn tries to determine + # the files mime-type first. It then uses the +MIME_EXTENSIONS+ hash to + # choose the corresponding file extension. You can override this hash + # by passing in a <tt>:mime_extensions</tt> option to +file_column+. + # + # The mime-type of the uploaded file is determined with the following steps: + # + # 1. Run the external "file" utility. You can specify the full path to + # the executable in the <tt>:file_exec</tt> option or set this option + # to +nil+ to disable this step + # + # 2. If the file utility couldn't determine the mime-type or the utility was not + # present, the content-type provided by the user's browser is used + # as a fallback. + # + # == Custom Storage Directories + # + # FileColumn's storage location is determined in the following way. All + # files are saved below the so-called "root_path" directory, which defaults to + # "RAILS_ROOT/public". For every file_column, you can set a separte "store_dir" + # option. It defaults to "model_name/attribute_name". + # + # Files will always be stored in sub-directories of the store_dir path. The + # subdirectory is named after the instance's +id+ attribute for a saved model, + # or "tmp/<randomkey>" for unsaved models. + # + # You can specify a custom root_path by setting the <tt>:root_path</tt> option. + # + # You can specify a custom storage_dir by setting the <tt>:storage_dir</tt> option. + # + # For setting a static storage_dir that doesn't change with respect to a particular + # instance, you assign <tt>:storage_dir</tt> a String representing a directory + # as an absolute path. + # + # If you need more fine-grained control over the storage directory, you + # can use the name of a callback-method as a symbol for the + # <tt>:store_dir</tt> option. This method has to be defined as an + # instance method in your model. It will be called without any arguments + # whenever the storage directory for an uploaded file is needed. It should return + # a String representing a directory relativeo to root_path. + # + # Uploaded files for unsaved models objects will be stored in a temporary + # directory. By default this directory will be a "tmp" directory in + # your <tt>:store_dir</tt>. You can override this via the + # <tt>:tmp_base_dir</tt> option. + module ClassMethods + + # default mapping of mime-types to file extensions. FileColumn will try to + # rename a file to the correct extension if it detects a known mime-type + MIME_EXTENSIONS = { + "image/gif" => "gif", + "image/jpeg" => "jpg", + "image/pjpeg" => "jpg", + "image/x-png" => "png", + "image/jpg" => "jpg", + "image/png" => "png", + "application/x-shockwave-flash" => "swf", + "application/pdf" => "pdf", + "application/pgp-signature" => "sig", + "application/futuresplash" => "spl", + "application/msword" => "doc", + "application/postscript" => "ps", + "application/x-bittorrent" => "torrent", + "application/x-dvi" => "dvi", + "application/x-gzip" => "gz", + "application/x-ns-proxy-autoconfig" => "pac", + "application/x-shockwave-flash" => "swf", + "application/x-tgz" => "tar.gz", + "application/x-tar" => "tar", + "application/zip" => "zip", + "audio/mpeg" => "mp3", + "audio/x-mpegurl" => "m3u", + "audio/x-ms-wma" => "wma", + "audio/x-ms-wax" => "wax", + "audio/x-wav" => "wav", + "image/x-xbitmap" => "xbm", + "image/x-xpixmap" => "xpm", + "image/x-xwindowdump" => "xwd", + "text/css" => "css", + "text/html" => "html", + "text/javascript" => "js", + "text/plain" => "txt", + "text/xml" => "xml", + "video/mpeg" => "mpeg", + "video/quicktime" => "mov", + "video/x-msvideo" => "avi", + "video/x-ms-asf" => "asf", + "video/x-ms-wmv" => "wmv" + } + + EXTENSIONS = Set.new MIME_EXTENSIONS.values + EXTENSIONS.merge %w(jpeg) + + # default options. You can override these with +file_column+'s +options+ parameter + DEFAULT_OPTIONS = { + :root_path => File.join(RAILS_ROOT, "public"), + :web_root => "", + :mime_extensions => MIME_EXTENSIONS, + :extensions => EXTENSIONS, + :fix_file_extensions => true, + :permissions => 0644, + + # path to the unix "file" executbale for + # guessing the content-type of files + :file_exec => "file" + } + + # handle the +attr+ attribute as a "file-upload" column, generating additional methods as explained + # above. You should pass the attribute's name as a symbol, like this: + # + # file_column :image + # + # You can pass in an options hash that overrides the options + # in +DEFAULT_OPTIONS+. + def file_column(attr, options={}) + options = DEFAULT_OPTIONS.merge(options) if options + + my_options = FileColumn::init_options(options, + Inflector.underscore(self.name).to_s, + attr.to_s) + + state_attr = "@#{attr}_state".to_sym + state_method = "#{attr}_state".to_sym + + define_method state_method do + result = instance_variable_get state_attr + if result.nil? + result = FileColumn::create_state(self, attr.to_s) + instance_variable_set state_attr, result + end + result + end + + private state_method + + define_method attr do |*args| + send(state_method).absolute_path *args + end + + define_method "#{attr}_relative_path" do |*args| + send(state_method).relative_path *args + end + + define_method "#{attr}_dir" do + send(state_method).absolute_dir + end + + define_method "#{attr}_relative_dir" do + send(state_method).relative_dir + end + + define_method "#{attr}=" do |file| + state = send(state_method).assign(file) + instance_variable_set state_attr, state + if state.options[:after_upload] and state.just_uploaded? + state.options[:after_upload].each do |sym| + self.send sym + end + end + end + + define_method "#{attr}_temp" do + send(state_method).temp_path + end + + define_method "#{attr}_temp=" do |temp_path| + instance_variable_set state_attr, send(state_method).assign_temp(temp_path) + end + + after_save_method = "#{attr}_after_save".to_sym + + define_method after_save_method do + instance_variable_set state_attr, send(state_method).after_save + end + + after_save after_save_method + + after_destroy_method = "#{attr}_after_destroy".to_sym + + define_method after_destroy_method do + send(state_method).after_destroy + end + after_destroy after_destroy_method + + define_method "#{attr}_just_uploaded?" do + send(state_method).just_uploaded? + end + + # this creates a closure keeping a reference to my_options + # right now that's the only way we store the options. We + # might use a class attribute as well + define_method "#{attr}_options" do + my_options + end + + private after_save_method, after_destroy_method + + FileColumn::MagickExtension::file_column(self, attr, my_options) if options[:magick] + end + + end + + private + + def self.generate_temp_name + now = Time.now + "#{now.to_i}.#{now.usec}.#{Process.pid}" + end + + def self.sanitize_filename(filename) + filename = File.basename(filename.gsub("\\", "/")) # work-around for IE + filename.gsub!(/[^a-zA-Z0-9\.\-\+_]/,"_") + filename = "_#{filename}" if filename =~ /^\.+$/ + filename = "unnamed" if filename.size == 0 + filename + end + +end + + diff --git a/vendor/plugins/file_column/lib/file_column_helper.rb b/vendor/plugins/file_column/lib/file_column_helper.rb new file mode 100644 index 0000000..f4ebe38 --- /dev/null +++ b/vendor/plugins/file_column/lib/file_column_helper.rb @@ -0,0 +1,150 @@ +# This module contains helper methods for displaying and uploading files +# for attributes created by +FileColumn+'s +file_column+ method. It will be +# automatically included into ActionView::Base, thereby making this module's +# methods available in all your views. +module FileColumnHelper + + # Use this helper to create an upload field for a file_column attribute. This will generate + # an additional hidden field to keep uploaded files during form-redisplays. For example, + # when called with + # + # <%= file_column_field("entry", "image") %> + # + # the following HTML will be generated (assuming the form is redisplayed and something has + # already been uploaded): + # + # <input type="hidden" name="entry[image_temp]" value="..." /> + # <input type="file" name="entry[image]" /> + # + # You can use the +option+ argument to pass additional options to the file-field tag. + # + # Be sure to set the enclosing form's encoding to 'multipart/form-data', by + # using something like this: + # + # <%= form_tag {:action => "create", ...}, :multipart => true %> + def file_column_field(object, method, options={}) + result = ActionView::Helpers::InstanceTag.new(object.dup, method.to_s+"_temp", self).to_input_field_tag("hidden", {}) + result << ActionView::Helpers::InstanceTag.new(object.dup, method, self).to_input_field_tag("file", options) + end + + # Creates an URL where an uploaded file can be accessed. When called for an Entry object with + # id 42 (stored in <tt>@entry</tt>) like this + # + # <%= url_for_file_column(@entry, "image") + # + # the following URL will be produced, assuming the file "test.png" has been stored in + # the "image"-column of an Entry object stored in <tt>@entry</tt>: + # + # /entry/image/42/test.png + # + # This will produce a valid URL even for temporary uploaded files, e.g. files where the object + # they are belonging to has not been saved in the database yet. + # + # The URL produces, although starting with a slash, will be relative + # to your app's root. If you pass it to one rails' +image_tag+ + # helper, rails will properly convert it to an absolute + # URL. However, this will not be the case, if you create a link with + # the +link_to+ helper. In this case, you can pass <tt>:absolute => + # true</tt> to +options+, which will make sure, the generated URL is + # absolute on your server. Examples: + # + # <%= image_tag url_for_file_column(@entry, "image") %> + # <%= link_to "Download", url_for_file_column(@entry, "image", :absolute => true) %> + # + # If there is currently no uploaded file stored in the object's column this method will + # return +nil+. + def url_for_file_column(object, method, options=nil) + case object + when String, Symbol + object = instance_variable_get("@#{object.to_s}") + end + + # parse options + subdir = nil + absolute = false + if options + case options + when Hash + subdir = options[:subdir] + absolute = options[:absolute] + when String, Symbol + subdir = options + end + end + + relative_path = object.send("#{method}_relative_path", subdir) + return nil unless relative_path + + url = "" + url << request.relative_url_root.to_s if absolute + url << "/" + url << object.send("#{method}_options")[:base_url] << "/" + url << relative_path + end + + # Same as +url_for_file_colum+ but allows you to access different versions + # of the image that have been processed by RMagick. + # + # If your +options+ parameter is non-nil this will + # access a different version of an image that will be produced by + # RMagick. You can use the following types for +options+: + # + # * a <tt>:symbol</tt> will select a version defined in the model + # via FileColumn::Magick's <tt>:versions</tt> feature. + # * a <tt>geometry_string</tt> will dynamically create an + # image resized as specified by <tt>geometry_string</tt>. The image will + # be stored so that it does not have to be recomputed the next time the + # same version string is used. + # * <tt>some_hash</tt> will dynamically create an image + # that is created according to the options in <tt>some_hash</tt>. This + # accepts exactly the same options as Magick's version feature. + # + # The version produced by RMagick will be stored in a special sub-directory. + # The directory's name will be derived from the options you specified + # (via a hash function) but if you want + # to set it yourself, you can use the <tt>:name => name</tt> option. + # + # Examples: + # + # <%= url_for_image_column @entry, "image", "640x480" %> + # + # will produce an URL like this + # + # /entry/image/42/bdn19n/filename.jpg + # # "640x480".hash.abs.to_s(36) == "bdn19n" + # + # and + # + # <%= url_for_image_column @entry, "image", + # :size => "50x50", :crop => "1:1", :name => "thumb" %> + # + # will produce something like this: + # + # /entry/image/42/thumb/filename.jpg + # + # Hint: If you are using the same geometry string / options hash multiple times, you should + # define it in a helper to stay with DRY. Another option is to define it in the model via + # FileColumn::Magick's <tt>:versions</tt> feature and then refer to it via a symbol. + # + # The URL produced by this method is relative to your application's root URL, + # although it will start with a slash. + # If you pass this URL to rails' +image_tag+ helper, it will be converted to an + # absolute URL automatically. + # If there is currently no image uploaded, or there is a problem while loading + # the image this method will return +nil+. + def url_for_image_column(object, method, options=nil) + case object + when String, Symbol + object = instance_variable_get("@#{object.to_s}") + end + subdir = nil + if options + subdir = object.send("#{method}_state").create_magick_version_if_needed(options) + end + if subdir.nil? + nil + else + url_for_file_column(object, method, subdir) + end + end +end diff --git a/vendor/plugins/file_column/lib/file_compat.rb b/vendor/plugins/file_column/lib/file_compat.rb new file mode 100644 index 0000000..f284410 --- /dev/null +++ b/vendor/plugins/file_column/lib/file_compat.rb @@ -0,0 +1,28 @@ +module FileColumn + + # This bit of code allows you to pass regular old files to + # file_column. file_column depends on a few extra methods that the + # CGI uploaded file class adds. We will add the equivalent methods + # to file objects if necessary by extending them with this module. This + # avoids opening up the standard File class which might result in + # naming conflicts. + + module FileCompat # :nodoc: + def original_filename + File.basename(path) + end + + def size + File.size(path) + end + + def local_path + path + end + + def content_type + nil + end + end +end + diff --git a/vendor/plugins/file_column/lib/magick_file_column.rb b/vendor/plugins/file_column/lib/magick_file_column.rb new file mode 100644 index 0000000..c4dc06f --- /dev/null +++ b/vendor/plugins/file_column/lib/magick_file_column.rb @@ -0,0 +1,260 @@ +module FileColumn # :nodoc: + + class BaseUploadedFile # :nodoc: + def transform_with_magick + if needs_transform? + begin + img = ::Magick::Image::read(absolute_path).first + rescue ::Magick::ImageMagickError + if options[:magick][:image_required] + @magick_errors ||= [] + @magick_errors << "invalid image" + end + return + end + + if options[:magick][:versions] + options[:magick][:versions].each_pair do |version, version_options| + next if version_options[:lazy] + dirname = version_options[:name] + FileUtils.mkdir File.join(@dir, dirname) + transform_image(img, version_options, absolute_path(dirname)) + end + end + if options[:magick][:size] or options[:magick][:crop] or options[:magick][:transformation] or options[:magick][:attributes] + transform_image(img, options[:magick], absolute_path) + end + + GC.start + end + end + + def create_magick_version_if_needed(version) + # RMagick might not have been loaded so far. + # We do not want to require it on every call of this method + # as this might be fairly expensive, so we just try if ::Magick + # exists and require it if not. + begin + ::Magick + rescue NameError + require 'RMagick' + end + + if version.is_a?(Symbol) + version_options = options[:magick][:versions][version] + else + version_options = MagickExtension::process_options(version) + end + + unless File.exists?(absolute_path(version_options[:name])) + begin + img = ::Magick::Image::read(absolute_path).first + rescue ::Magick::ImageMagickError + # we might be called directly from the view here + # so we just return nil if we cannot load the image + return nil + end + dirname = version_options[:name] + FileUtils.mkdir File.join(@dir, dirname) + transform_image(img, version_options, absolute_path(dirname)) + end + + version_options[:name] + end + + attr_reader :magick_errors + + def has_magick_errors? + @magick_errors and !@magick_errors.empty? + end + + private + + def needs_transform? + options[:magick] and just_uploaded? and + (options[:magick][:size] or options[:magick][:versions] or options[:magick][:transformation] or options[:magick][:attributes]) + end + + def transform_image(img, img_options, dest_path) + begin + if img_options[:transformation] + if img_options[:transformation].is_a?(Symbol) + img = @instance.send(img_options[:transformation], img) + else + img = img_options[:transformation].call(img) + end + end + if img_options[:crop] + dx, dy = img_options[:crop].split(':').map { |x| x.to_f } + w, h = (img.rows * dx / dy), (img.columns * dy / dx) + img = img.crop(::Magick::CenterGravity, [img.columns, w].min, + [img.rows, h].min, true) + end + + if img_options[:size] + img = img.change_geometry(img_options[:size]) do |c, r, i| + i.resize(c, r) + end + end + ensure + img.write(dest_path) do + if img_options[:attributes] + img_options[:attributes].each_pair do |property, value| + self.send "#{property}=", value + end + end + end + File.chmod options[:permissions], dest_path + end + end + end + + # If you are using file_column to upload images, you can + # directly process the images with RMagick, + # a ruby extension + # for accessing the popular imagemagick libraries. You can find + # more information about RMagick at http://rmagick.rubyforge.org. + # + # You can control what to do by adding a <tt>:magick</tt> option + # to your options hash. All operations are performed immediately + # after a new file is assigned to the file_column attribute (i.e., + # when a new file has been uploaded). + # + # == Resizing images + # + # To resize the uploaded image according to an imagemagick geometry + # string, just use the <tt>:size</tt> option: + # + # file_column :image, :magick => {:size => "800x600>"} + # + # If the uploaded file cannot be loaded by RMagick, file_column will + # signal a validation error for the corresponding attribute. If you + # want to allow non-image files to be uploaded in a column that uses + # the <tt>:magick</tt> option, you can set the <tt>:image_required</tt> + # attribute to +false+: + # + # file_column :image, :magick => {:size => "800x600>", + # :image_required => false } + # + # == Multiple versions + # + # You can also create additional versions of your image, for example + # thumb-nails, like this: + # file_column :image, :magick => {:versions => { + # :thumb => {:size => "50x50"}, + # :medium => {:size => "640x480>"} + # } + # + # These versions will be stored in separate sub-directories, named like the + # symbol you used to identify the version. So in the previous example, the + # image versions will be stored in "thumb", "screen" and "widescreen" + # directories, resp. + # A name different from the symbol can be set via the <tt>:name</tt> option. + # + # These versions can be accessed via FileColumnHelper's +url_for_image_column+ + # method like this: + # + # <%= url_for_image_column "entry", "image", :thumb %> + # + # == Cropping images + # + # If you wish to crop your images with a size ratio before scaling + # them according to your version geometry, you can use the :crop directive. + # file_column :image, :magick => {:versions => { + # :square => {:crop => "1:1", :size => "50x50", :name => "thumb"}, + # :screen => {:crop => "4:3", :size => "640x480>"}, + # :widescreen => {:crop => "16:9", :size => "640x360!"}, + # } + # } + # + # == Custom attributes + # + # To change some of the image properties like compression level before they + # are saved you can set the <tt>:attributes</tt> option. + # For a list of available attributes go to http://www.simplesystems.org/RMagick/doc/info.html + # + # file_column :image, :magick => { :attributes => { :quality => 30 } } + # + # == Custom transformations + # + # To perform custom transformations on uploaded images, you can pass a + # callback to file_column: + # file_column :image, :magick => + # Proc.new { |image| image.quantize(256, Magick::GRAYColorspace) } + # + # The callback you give, receives one argument, which is an instance + # of Magick::Image, the RMagick image class. It should return a transformed + # image. Instead of passing a <tt>Proc</tt> object, you can also give a + # <tt>Symbol</tt>, the name of an instance method of your model. + # + # Custom transformations can be combined via the standard :size and :crop + # features, by using the :transformation option: + # file_column :image, :magick => { + # :transformation => Proc.new { |image| ... }, + # :size => "640x480" + # } + # + # In this case, the standard resizing operations will be performed after the + # custom transformation. + # + # Of course, custom transformations can be used in versions, as well. + # + # <b>Note:</b> You'll need the + # RMagick extension being installed in order to use file_column's + # imagemagick integration. + module MagickExtension + + def self.file_column(klass, attr, options) # :nodoc: + require 'RMagick' + options[:magick] = process_options(options[:magick],false) if options[:magick] + if options[:magick][:versions] + options[:magick][:versions].each_pair do |name, value| + options[:magick][:versions][name] = process_options(value, name.to_s) + end + end + state_method = "#{attr}_state".to_sym + after_assign_method = "#{attr}_magick_after_assign".to_sym + + klass.send(:define_method, after_assign_method) do + self.send(state_method).transform_with_magick + end + + options[:after_upload] ||= [] + options[:after_upload] << after_assign_method + + klass.validate do |record| + state = record.send(state_method) + if state.has_magick_errors? + state.magick_errors.each do |error| + record.errors.add attr, error + end + end + end + end + + + def self.process_options(options,create_name=true) + case options + when String then options = {:size => options} + when Proc, Symbol then options = {:transformation => options } + end + if options[:geometry] + options[:size] = options.delete(:geometry) + end + options[:image_required] = true unless options.key?(:image_required) + if options[:name].nil? and create_name + if create_name == true + hash = 0 + for key in [:size, :crop] + hash = hash ^ options[key].hash if options[key] + end + options[:name] = hash.abs.to_s(36) + else + options[:name] = create_name + end + end + options + end + + end +end diff --git a/vendor/plugins/file_column/lib/rails_file_column.rb b/vendor/plugins/file_column/lib/rails_file_column.rb new file mode 100644 index 0000000..af8c95a --- /dev/null +++ b/vendor/plugins/file_column/lib/rails_file_column.rb @@ -0,0 +1,19 @@ +# require this file from your "config/environment.rb" (after rails has been loaded) +# to integrate the file_column extension into rails. + +require 'file_column' +require 'file_column_helper' + + +module ActiveRecord # :nodoc: + class Base # :nodoc: + # make file_column method available in all active record decendants + include FileColumn + end +end + +module ActionView # :nodoc: + class Base # :nodoc: + include FileColumnHelper + end +end diff --git a/vendor/plugins/file_column/lib/test_case.rb b/vendor/plugins/file_column/lib/test_case.rb new file mode 100644 index 0000000..1416a1e --- /dev/null +++ b/vendor/plugins/file_column/lib/test_case.rb @@ -0,0 +1,124 @@ +require 'test/unit' + +# Add the methods +upload+, the <tt>setup_file_fixtures</tt> and +# <tt>teardown_file_fixtures</tt> to the class Test::Unit::TestCase. +class Test::Unit::TestCase + # Returns a +Tempfile+ object as it would have been generated on file upload. + # Use this method to create the parameters when emulating form posts with + # file fields. + # + # === Example: + # + # def test_file_column_post + # entry = { :title => 'foo', :file => upload('/tmp/foo.txt')} + # post :upload, :entry => entry + # + # # ... + # end + # + # === Parameters + # + # * <tt>path</tt> The path to the file to upload. + # * <tt>content_type</tt> The MIME type of the file. If it is <tt>:guess</tt>, + # the method will try to guess it. + def upload(path, content_type=:guess, type=:tempfile) + if content_type == :guess + case path + when /\.jpg$/ then content_type = "image/jpeg" + when /\.png$/ then content_type = "image/png" + else content_type = nil + end + end + uploaded_file(path, content_type, File.basename(path), type) + end + + # Copies the fixture files from "RAILS_ROOT/test/fixtures/file_column" into + # the temporary storage directory used for testing + # ("RAILS_ROOT/test/tmp/file_column"). Call this method in your + # <tt>setup</tt> methods to get the file fixtures (images, for example) into + # the directory used by file_column in testing. + # + # Note that the files and directories in the "fixtures/file_column" directory + # must have the same structure as you would expect in your "/public" directory + # after uploading with FileColumn. + # + # For example, the directory structure could look like this: + # + # test/fixtures/file_column/ + # `-- container + # |-- first_image + # | |-- 1 + # | | `-- image1.jpg + # | `-- tmp + # `-- second_image + # |-- 1 + # | `-- image2.jpg + # `-- tmp + # + # Your fixture file for this one "container" class fixture could look like this: + # + # first: + # id: 1 + # first_image: image1.jpg + # second_image: image1.jpg + # + # A usage example: + # + # def setup + # setup_fixture_files + # + # # ... + # end + def setup_fixture_files + tmp_path = File.join(RAILS_ROOT, "test", "tmp", "file_column") + file_fixtures = Dir.glob File.join(RAILS_ROOT, "test", "fixtures", "file_column", "*") + + FileUtils.mkdir_p tmp_path unless File.exists?(tmp_path) + FileUtils.cp_r file_fixtures, tmp_path + end + + # Removes the directory "RAILS_ROOT/test/tmp/file_column/" so the files + # copied on test startup are removed. Call this in your unit test's +teardown+ + # method. + # + # A usage example: + # + # def teardown + # teardown_fixture_files + # + # # ... + # end + def teardown_fixture_files + FileUtils.rm_rf File.join(RAILS_ROOT, "test", "tmp", "file_column") + end + + private + + def uploaded_file(path, content_type, filename, type=:tempfile) # :nodoc: + if type == :tempfile + t = Tempfile.new(File.basename(filename)) + FileUtils.copy_file(path, t.path) + else + if path + t = StringIO.new(IO.read(path)) + else + t = StringIO.new + end + end + (class << t; self; end).class_eval do + alias local_path path if type == :tempfile + define_method(:local_path) { "" } if type == :stringio + define_method(:original_filename) {filename} + define_method(:content_type) {content_type} + end + return t + end +end + +# If we are running in the "test" environment, we overwrite the default +# settings for FileColumn so that files are not uploaded into "/public/" +# in tests but rather into the directory "/test/tmp/file_column". +if RAILS_ENV == "test" + FileColumn::ClassMethods::DEFAULT_OPTIONS[:root_path] = + File.join(RAILS_ROOT, "test", "tmp", "file_column") +end diff --git a/vendor/plugins/file_column/lib/validations.rb b/vendor/plugins/file_column/lib/validations.rb new file mode 100644 index 0000000..5b961eb --- /dev/null +++ b/vendor/plugins/file_column/lib/validations.rb @@ -0,0 +1,112 @@ +module FileColumn + module Validations #:nodoc: + + def self.append_features(base) + super + base.extend(ClassMethods) + end + + # This module contains methods to create validations of uploaded files. All methods + # in this module will be included as class methods into <tt>ActiveRecord::Base</tt> + # so that you can use them in your models like this: + # + # class Entry < ActiveRecord::Base + # file_column :image + # validates_filesize_of :image, :in => 0..1.megabyte + # end + module ClassMethods + EXT_REGEXP = /\.([A-z0-9]+)$/ + + # This validates the file type of one or more file_columns. A list of file columns + # should be given followed by an options hash. + # + # Required options: + # * <tt>:in</tt> => list of extensions or mime types. If mime types are used they + # will be mapped into an extension via FileColumn::ClassMethods::MIME_EXTENSIONS. + # + # Examples: + # validates_file_format_of :field, :in => ["gif", "png", "jpg"] + # validates_file_format_of :field, :in => ["image/jpeg"] + def validates_file_format_of(*attrs) + + options = attrs.pop if attrs.last.is_a?Hash + raise ArgumentError, "Please include the :in option." if !options || !options[:in] + options[:in] = [options[:in]] if options[:in].is_a?String + raise ArgumentError, "Invalid value for option :in" unless options[:in].is_a?Array + + validates_each(attrs, options) do |record, attr, value| + unless value.blank? + mime_extensions = record.send("#{attr}_options")[:mime_extensions] + extensions = options[:in].map{|o| mime_extensions[o] || o } + record.errors.add attr, "is not a valid format." unless extensions.include?(value.scan(EXT_REGEXP).flatten.first) + end + end + + end + + # This validates the file size of one or more file_columns. A list of file columns + # should be given followed by an options hash. + # + # Required options: + # * <tt>:in</tt> => A size range. Note that you can use ActiveSupport's + # numeric extensions for kilobytes, etc. + # + # Examples: + # validates_filesize_of :field, :in => 0..100.megabytes + # validates_filesize_of :field, :in => 15.kilobytes..1.megabyte + def validates_filesize_of(*attrs) + + options = attrs.pop if attrs.last.is_a?Hash + raise ArgumentError, "Please include the :in option." if !options || !options[:in] + raise ArgumentError, "Invalid value for option :in" unless options[:in].is_a?Range + + validates_each(attrs, options) do |record, attr, value| + unless value.blank? + size = File.size(value) + record.errors.add attr, "is smaller than the allowed size range." if size < options[:in].first + record.errors.add attr, "is larger than the allowed size range." if size > options[:in].last + end + end + + end + + IMAGE_SIZE_REGEXP = /^(\d+)x(\d+)$/ + + # Validates the image size of one or more file_columns. A list of file columns + # should be given followed by an options hash. The validation will pass + # if both image dimensions (rows and columns) are at least as big as + # given in the <tt>:min</tt> option. + # + # Required options: + # * <tt>:min</tt> => minimum image dimension string, in the format NNxNN + # (columns x rows). + # + # Example: + # validates_image_size :field, :min => "1200x1800" + # + # This validation requires RMagick to be installed on your system + # to check the image's size. + def validates_image_size(*attrs) + options = attrs.pop if attrs.last.is_a?Hash + raise ArgumentError, "Please include a :min option." if !options || !options[:min] + minimums = options[:min].scan(IMAGE_SIZE_REGEXP).first.collect{|n| n.to_i} rescue [] + raise ArgumentError, "Invalid value for option :min (should be 'XXxYY')" unless minimums.size == 2 + + require 'RMagick' + + validates_each(attrs, options) do |record, attr, value| + unless value.blank? + begin + img = ::Magick::Image::read(value).first + record.errors.add('image', "is too small, must be at least #{minimums[0]}x#{minimums[1]}") if ( img.rows < minimums[1] || img.columns < minimums[0] ) + rescue ::Magick::ImageMagickError + record.errors.add('image', "invalid image") + end + img = nil + GC.start + end + end + end + end + end +end diff --git a/vendor/plugins/file_column/test/abstract_unit.rb b/vendor/plugins/file_column/test/abstract_unit.rb new file mode 100644 index 0000000..22bc53b --- /dev/null +++ b/vendor/plugins/file_column/test/abstract_unit.rb @@ -0,0 +1,63 @@ +require 'test/unit' +require 'rubygems' +require 'active_support' +require 'active_record' +require 'action_view' +require File.dirname(__FILE__) + '/connection' +require 'stringio' + +RAILS_ROOT = File.dirname(__FILE__) +RAILS_ENV = "" + +$: << "../lib" + +require 'file_column' +require 'file_compat' +require 'validations' +require 'test_case' + +# do not use the file executable normally in our tests as +# it may not be present on the machine we are running on +FileColumn::ClassMethods::DEFAULT_OPTIONS = + FileColumn::ClassMethods::DEFAULT_OPTIONS.merge({:file_exec => nil}) + +class ActiveRecord::Base + include FileColumn + include FileColumn::Validations +end + + +class RequestMock + attr_accessor :relative_url_root + + def initialize + @relative_url_root = "" + end +end + +class Test::Unit::TestCase + + def assert_equal_paths(expected_path, path) + assert_equal normalize_path(expected_path), normalize_path(path) + end + + + private + + def normalize_path(path) + Pathname.new(path).realpath + end + + def clear_validations + [:validate, :validate_on_create, :validate_on_update].each do |attr| + Entry.write_inheritable_attribute attr, [] + Movie.write_inheritable_attribute attr, [] + end + end + + def file_path(filename) + File.expand_path("#{File.dirname(__FILE__)}/fixtures/#{filename}") + end + + alias_method :f, :file_path +end diff --git a/vendor/plugins/file_column/test/connection.rb b/vendor/plugins/file_column/test/connection.rb new file mode 100644 index 0000000..a2f28ba --- /dev/null +++ b/vendor/plugins/file_column/test/connection.rb @@ -0,0 +1,17 @@ +print "Using native MySQL\n" +require 'logger' + +ActiveRecord::Base.logger = Logger.new("debug.log") + +db = 'file_column_test' + +ActiveRecord::Base.establish_connection( + :adapter => "mysql", + :host => "localhost", + :username => "rails", + :password => "", + :database => db, + :socket => "/var/run/mysqld/mysqld.sock" +) + +load File.dirname(__FILE__) + "/fixtures/schema.rb" diff --git a/vendor/plugins/file_column/test/file_column_helper_test.rb b/vendor/plugins/file_column/test/file_column_helper_test.rb new file mode 100644 index 0000000..ffb2c43 --- /dev/null +++ b/vendor/plugins/file_column/test/file_column_helper_test.rb @@ -0,0 +1,97 @@ +require File.dirname(__FILE__) + '/abstract_unit' +require File.dirname(__FILE__) + '/fixtures/entry' + +class UrlForFileColumnTest < Test::Unit::TestCase + include FileColumnHelper + + def setup + Entry.file_column :image + @request = RequestMock.new + end + + def test_url_for_file_column_with_temp_entry + @e = Entry.new(:image => upload(f("skanthak.png"))) + url = url_for_file_column("e", "image") + assert_match %r{^/entry/image/tmp/\d+(\.\d+)+/skanthak.png$}, url + end + + def test_url_for_file_column_with_saved_entry + @e = Entry.new(:image => upload(f("skanthak.png"))) + assert @e.save + + url = url_for_file_column("e", "image") + assert_equal "/entry/image/#{@e.id}/skanthak.png", url + end + + def test_url_for_file_column_works_with_symbol + @e = Entry.new(:image => upload(f("skanthak.png"))) + assert @e.save + + url = url_for_file_column(:e, :image) + assert_equal "/entry/image/#{@e.id}/skanthak.png", url + end + + def test_url_for_file_column_works_with_object + e = Entry.new(:image => upload(f("skanthak.png"))) + assert e.save + + url = url_for_file_column(e, "image") + assert_equal "/entry/image/#{e.id}/skanthak.png", url + end + + def test_url_for_file_column_should_return_nil_on_no_uploaded_file + e = Entry.new + assert_nil url_for_file_column(e, "image") + end + + def test_url_for_file_column_without_extension + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "something/unknown", "local_filename") + assert e.save + assert_equal "/entry/image/#{e.id}/local_filename", url_for_file_column(e, "image") + end +end + +class UrlForFileColumnTest < Test::Unit::TestCase + include FileColumnHelper + include ActionView::Helpers::AssetTagHelper + include ActionView::Helpers::TagHelper + include ActionView::Helpers::UrlHelper + + def setup + Entry.file_column :image + + # mock up some request data structures for AssetTagHelper + @request = RequestMock.new + @request.relative_url_root = "/foo/bar" + @controller = self + end + + def request + @request + end + + IMAGE_URL = %r{^/foo/bar/entry/image/.+/skanthak.png$} + def test_with_image_tag + e = Entry.new(:image => upload(f("skanthak.png"))) + html = image_tag url_for_file_column(e, "image") + url = html.scan(/src=\"(.+)\"/).first.first + + assert_match IMAGE_URL, url + end + + def test_with_link_to_tag + e = Entry.new(:image => upload(f("skanthak.png"))) + html = link_to "Download", url_for_file_column(e, "image", :absolute => true) + url = html.scan(/href=\"(.+)\"/).first.first + + assert_match IMAGE_URL, url + end + + def test_relative_url_root_not_modified + e = Entry.new(:image => upload(f("skanthak.png"))) + url_for_file_column(e, "image", :absolute => true) + + assert_equal "/foo/bar", @request.relative_url_root + end +end diff --git a/vendor/plugins/file_column/test/file_column_test.rb b/vendor/plugins/file_column/test/file_column_test.rb new file mode 100644 index 0000000..452b781 --- /dev/null +++ b/vendor/plugins/file_column/test/file_column_test.rb @@ -0,0 +1,650 @@ +require File.dirname(__FILE__) + '/abstract_unit' + +require File.dirname(__FILE__) + '/fixtures/entry' + +class Movie < ActiveRecord::Base +end + + +class FileColumnTest < Test::Unit::TestCase + + def setup + # we define the file_columns here so that we can change + # settings easily in a single test + + Entry.file_column :image + Entry.file_column :file + Movie.file_column :movie + + clear_validations + end + + def teardown + FileUtils.rm_rf File.dirname(__FILE__)+"/public/entry/" + FileUtils.rm_rf File.dirname(__FILE__)+"/public/movie/" + FileUtils.rm_rf File.dirname(__FILE__)+"/public/my_store_dir/" + end + + def test_column_write_method + assert Entry.new.respond_to?("image=") + end + + def test_column_read_method + assert Entry.new.respond_to?("image") + end + + def test_sanitize_filename + assert_equal "test.jpg", FileColumn::sanitize_filename("test.jpg") + assert FileColumn::sanitize_filename("../../very_tricky/foo.bar") !~ /[\\\/]/, "slashes not removed" + assert_equal "__foo", FileColumn::sanitize_filename('`*foo') + assert_equal "foo.txt", FileColumn::sanitize_filename('c:\temp\foo.txt') + assert_equal "_.", FileColumn::sanitize_filename(".") + end + + def test_default_options + e = Entry.new + assert_match %r{/public/entry/image}, e.image_options[:store_dir] + assert_match %r{/public/entry/image/tmp}, e.image_options[:tmp_base_dir] + end + + def test_assign_without_save_with_tempfile + do_test_assign_without_save(:tempfile) + end + + def test_assign_without_save_with_stringio + do_test_assign_without_save(:stringio) + end + + def do_test_assign_without_save(upload_type) + e = Entry.new + e.image = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png", upload_type) + assert e.image.is_a?(String), "#{e.image.inspect} is not a String" + assert File.exists?(e.image) + assert FileUtils.identical?(e.image, file_path("skanthak.png")) + end + + def test_filename_preserved + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "local_filename.jpg") + assert_equal "local_filename.jpg", File.basename(e.image) + end + + def test_filename_stored_in_attribute + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + assert_equal "kerb.jpg", e["image"] + end + + def test_extension_added + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "local_filename") + assert_equal "local_filename.jpg", File.basename(e.image) + assert_equal "local_filename.jpg", e["image"] + end + + def test_no_extension_without_content_type + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "something/unknown", "local_filename") + assert_equal "local_filename", File.basename(e.image) + assert_equal "local_filename", e["image"] + end + + def test_extension_unknown_type + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "not/known", "local_filename") + assert_equal "local_filename", File.basename(e.image) + assert_equal "local_filename", e["image"] + end + + def test_extension_unknown_type_with_extension + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "not/known", "local_filename.abc") + assert_equal "local_filename.abc", File.basename(e.image) + assert_equal "local_filename.abc", e["image"] + end + + def test_extension_corrected + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "local_filename.jpeg") + assert_equal "local_filename.jpg", File.basename(e.image) + assert_equal "local_filename.jpg", e["image"] + end + + def test_double_extension + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "application/x-tgz", "local_filename.tar.gz") + assert_equal "local_filename.tar.gz", File.basename(e.image) + assert_equal "local_filename.tar.gz", e["image"] + end + + FILE_UTILITY = "/usr/bin/file" + + def test_get_content_type_with_file + Entry.file_column :image, :file_exec => FILE_UTILITY + + # run this test only if the machine we are running on + # has the file utility installed + if File.executable?(FILE_UTILITY) + e = Entry.new + file = FileColumn::TempUploadedFile.new(e, "image") + file.instance_variable_set :@dir, File.dirname(file_path("kerb.jpg")) + file.instance_variable_set :@filename, File.basename(file_path("kerb.jpg")) + + assert_equal "image/jpeg", file.get_content_type + else + puts "Warning: Skipping test_get_content_type_with_file test as '#{options[:file_exec]}' does not exist" + end + end + + def test_fix_extension_with_file + Entry.file_column :image, :file_exec => FILE_UTILITY + + # run this test only if the machine we are running on + # has the file utility installed + if File.executable?(FILE_UTILITY) + e = Entry.new(:image => uploaded_file(file_path("skanthak.png"), "", "skanthak.jpg")) + + assert_equal "skanthak.png", File.basename(e.image) + else + puts "Warning: Skipping test_fix_extension_with_file test as '#{options[:file_exec]}' does not exist" + end + end + + def test_do_not_fix_file_extensions + Entry.file_column :image, :fix_file_extensions => false + + e = Entry.new(:image => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb")) + + assert_equal "kerb", File.basename(e.image) + end + + def test_correct_extension + e = Entry.new + file = FileColumn::TempUploadedFile.new(e, "image") + + assert_equal "filename.jpg", file.correct_extension("filename.jpeg","jpg") + assert_equal "filename.tar.gz", file.correct_extension("filename.jpg","tar.gz") + assert_equal "filename.jpg", file.correct_extension("filename.tar.gz","jpg") + assert_equal "Protokoll_01.09.2005.doc", file.correct_extension("Protokoll_01.09.2005","doc") + assert_equal "strange.filenames.exist.jpg", file.correct_extension("strange.filenames.exist","jpg") + assert_equal "another.strange.one.jpg", file.correct_extension("another.strange.one.png","jpg") + end + + def test_assign_with_save + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg") + tmp_file_path = e.image + assert e.save + assert File.exists?(e.image) + assert FileUtils.identical?(e.image, file_path("kerb.jpg")) + assert_equal "#{e.id}/kerb.jpg", e.image_relative_path + assert !File.exists?(tmp_file_path), "temporary file '#{tmp_file_path}' not removed" + assert !File.exists?(File.dirname(tmp_file_path)), "temporary directory '#{File.dirname(tmp_file_path)}' not removed" + + local_path = e.image + e = Entry.find(e.id) + assert_equal local_path, e.image + end + + def test_dir_methods + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg") + e.save + + assert_equal_paths File.join(RAILS_ROOT, "public", "entry", "image", e.id.to_s), e.image_dir + assert_equal File.join(e.id.to_s), e.image_relative_dir + end + + def test_store_dir_callback + Entry.file_column :image, {:store_dir => :my_store_dir} + e = Entry.new + + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg") + assert e.save + + assert_equal_paths File.join(RAILS_ROOT, "public", "my_store_dir", e.id), e.image_dir + end + + def test_tmp_dir_with_store_dir_callback + Entry.file_column :image, {:store_dir => :my_store_dir} + e = Entry.new + e.image = upload(f("kerb.jpg")) + + assert_equal File.expand_path(File.join(RAILS_ROOT, "public", "my_store_dir", "tmp")), File.expand_path(File.join(e.image_dir,"..")) + end + + def test_invalid_store_dir_callback + Entry.file_column :image, {:store_dir => :my_store_dir_doesnt_exit} + e = Entry.new + assert_raise(ArgumentError) { + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg") + e.save + } + end + + def test_subdir_parameter + e = Entry.new + assert_nil e.image("thumb") + assert_nil e.image_relative_path("thumb") + assert_nil e.image(nil) + + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg") + + assert_equal "kerb.jpg", File.basename(e.image("thumb")) + assert_equal "kerb.jpg", File.basename(e.image_relative_path("thumb")) + + assert_equal File.join(e.image_dir,"thumb","kerb.jpg"), e.image("thumb") + assert_match %r{/thumb/kerb\.jpg$}, e.image_relative_path("thumb") + + assert_equal e.image, e.image(nil) + assert_equal e.image_relative_path, e.image_relative_path(nil) + end + + def test_cleanup_after_destroy + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + assert e.save + local_path = e.image + assert File.exists?(local_path) + assert e.destroy + assert !File.exists?(local_path), "'#{local_path}' still exists although entry was destroyed" + assert !File.exists?(File.dirname(local_path)) + end + + def test_keep_tmp_image + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + e.validation_should_fail = true + assert !e.save, "e should not save due to validation errors" + assert File.exists?(local_path = e.image) + image_temp = e.image_temp + e = Entry.new("image_temp" => image_temp) + assert_equal local_path, e.image + assert e.save + assert FileUtils.identical?(e.image, file_path("kerb.jpg")) + end + + def test_keep_tmp_image_with_existing_image + e = Entry.new("image" =>uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + assert e.save + assert File.exists?(local_path = e.image) + e = Entry.find(e.id) + e.image = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png") + e.validation_should_fail = true + assert !e.save + temp_path = e.image_temp + e = Entry.find(e.id) + e.image_temp = temp_path + assert e.save + + assert FileUtils.identical?(e.image, file_path("skanthak.png")) + assert !File.exists?(local_path), "old image has not been deleted" + end + + def test_replace_tmp_image_temp_first + do_test_replace_tmp_image([:image_temp, :image]) + end + + def test_replace_tmp_image_temp_last + do_test_replace_tmp_image([:image, :image_temp]) + end + + def do_test_replace_tmp_image(order) + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + e.validation_should_fail = true + assert !e.save + image_temp = e.image_temp + temp_path = e.image + new_img = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png") + e = Entry.new + for method in order + case method + when :image_temp then e.image_temp = image_temp + when :image then e.image = new_img + end + end + assert e.save + assert FileUtils.identical?(e.image, file_path("skanthak.png")), "'#{e.image}' is not the expected 'skanthak.png'" + assert !File.exists?(temp_path), "temporary file '#{temp_path}' is not cleaned up" + assert !File.exists?(File.dirname(temp_path)), "temporary directory not cleaned up" + assert e.image_just_uploaded? + end + + def test_replace_image_on_saved_object + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + assert e.save + old_file = e.image + e = Entry.find(e.id) + e.image = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png") + assert e.save + assert FileUtils.identical?(file_path("skanthak.png"), e.image) + assert old_file != e.image + assert !File.exists?(old_file), "'#{old_file}' has not been cleaned up" + end + + def test_edit_without_touching_image + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + assert e.save + e = Entry.find(e.id) + assert e.save + assert FileUtils.identical?(file_path("kerb.jpg"), e.image) + end + + def test_save_without_image + e = Entry.new + assert e.save + e.reload + assert_nil e.image + end + + def test_delete_saved_image + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + assert e.save + local_path = e.image + e.image = nil + assert_nil e.image + assert File.exists?(local_path), "file '#{local_path}' should not be deleted until transaction is saved" + assert e.save + assert_nil e.image + assert !File.exists?(local_path) + e.reload + assert e["image"].blank? + e = Entry.find(e.id) + assert_nil e.image + end + + def test_delete_tmp_image + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + local_path = e.image + e.image = nil + assert_nil e.image + assert e["image"].blank? + assert !File.exists?(local_path) + end + + def test_delete_nonexistant_image + e = Entry.new + e.image = nil + assert e.save + assert_nil e.image + end + + def test_delete_image_on_non_null_column + e = Entry.new("file" => upload(f("skanthak.png"))) + assert e.save + + local_path = e.file + assert File.exists?(local_path) + e.file = nil + assert e.save + assert !File.exists?(local_path) + end + + def test_ie_filename + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", 'c:\images\kerb.jpg')) + assert e.image_relative_path =~ /^tmp\/[\d\.]+\/kerb\.jpg$/, "relative path '#{e.image_relative_path}' was not as expected" + assert File.exists?(e.image) + end + + def test_just_uploaded? + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", 'c:\images\kerb.jpg')) + assert e.image_just_uploaded? + assert e.save + assert e.image_just_uploaded? + + e = Entry.new("image" => uploaded_file(file_path("kerb.jpg"), "image/jpeg", 'kerb.jpg')) + temp_path = e.image_temp + e = Entry.new("image_temp" => temp_path) + assert !e.image_just_uploaded? + assert e.save + assert !e.image_just_uploaded? + end + + def test_empty_tmp + e = Entry.new + e.image_temp = "" + assert_nil e.image + end + + def test_empty_tmp_with_image + e = Entry.new + e.image_temp = "" + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", 'c:\images\kerb.jpg') + local_path = e.image + assert File.exists?(local_path) + e.image_temp = "" + assert local_path, e.image + end + + def test_empty_filename + e = Entry.new + assert_equal "", e["file"] + assert_nil e.file + assert_nil e["image"] + assert_nil e.image + end + + def test_with_two_file_columns + e = Entry.new + e.image = uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg") + e.file = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png") + assert e.save + assert_match %{/entry/image/}, e.image + assert_match %{/entry/file/}, e.file + assert FileUtils.identical?(e.image, file_path("kerb.jpg")) + assert FileUtils.identical?(e.file, file_path("skanthak.png")) + end + + def test_with_two_models + e = Entry.new(:image => uploaded_file(file_path("kerb.jpg"), "image/jpeg", "kerb.jpg")) + m = Movie.new(:movie => uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png")) + assert e.save + assert m.save + assert_match %{/entry/image/}, e.image + assert_match %{/movie/movie/}, m.movie + assert FileUtils.identical?(e.image, file_path("kerb.jpg")) + assert FileUtils.identical?(m.movie, file_path("skanthak.png")) + end + + def test_no_file_uploaded + e = Entry.new + assert_nothing_raised { e.image = + uploaded_file(nil, "application/octet-stream", "", :stringio) } + assert_equal nil, e.image + end + + # when safari submits a form where no file has been + # selected, it does not transmit a content-type and + # the result is an empty string "" + def test_no_file_uploaded_with_safari + e = Entry.new + assert_nothing_raised { e.image = "" } + assert_equal nil, e.image + end + + def test_detect_wrong_encoding + e = Entry.new + assert_raise(TypeError) { e.image ="img42.jpg" } + end + + def test_serializable_before_save + e = Entry.new + e.image = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png") + assert_nothing_raised { + flash = Marshal.dump(e) + e = Marshal.load(flash) + } + assert File.exists?(e.image) + end + + def test_should_call_after_upload_on_new_upload + Entry.file_column :image, :after_upload => [:after_assign] + e = Entry.new + e.image = upload(f("skanthak.png")) + assert e.after_assign_called? + end + + def test_should_call_user_after_save_on_save + e = Entry.new(:image => upload(f("skanthak.png"))) + assert e.save + + assert_kind_of FileColumn::PermanentUploadedFile, e.send(:image_state) + assert e.after_save_called? + end + + + def test_assign_standard_files + e = Entry.new + e.image = File.new(file_path('skanthak.png')) + + assert_equal 'skanthak.png', File.basename(e.image) + assert FileUtils.identical?(file_path('skanthak.png'), e.image) + + assert e.save + end + + + def test_validates_filesize + Entry.validates_filesize_of :image, :in => 50.kilobytes..100.kilobytes + + e = Entry.new(:image => upload(f("kerb.jpg"))) + assert e.save + + e.image = upload(f("skanthak.png")) + assert !e.save + assert e.errors.invalid?("image") + end + + def test_validates_file_format_simple + e = Entry.new(:image => upload(f("skanthak.png"))) + assert e.save + + Entry.validates_file_format_of :image, :in => ["jpg"] + + e.image = upload(f("kerb.jpg")) + assert e.save + + e.image = upload(f("mysql.sql")) + assert !e.save + assert e.errors.invalid?("image") + + end + + def test_validates_image_size + Entry.validates_image_size :image, :min => "640x480" + + e = Entry.new(:image => upload(f("kerb.jpg"))) + assert e.save + + e = Entry.new(:image => upload(f("skanthak.png"))) + assert !e.save + assert e.errors.invalid?("image") + end + + def do_permission_test(uploaded_file, permissions=0641) + Entry.file_column :image, :permissions => permissions + + e = Entry.new(:image => uploaded_file) + assert e.save + + assert_equal permissions, (File.stat(e.image).mode & 0777) + end + + def test_permissions_with_small_file + do_permission_test upload(f("skanthak.png"), :guess, :stringio) + end + + def test_permission_with_big_file + do_permission_test upload(f("kerb.jpg")) + end + + def test_permission_that_overrides_umask + do_permission_test upload(f("skanthak.png"), :guess, :stringio), 0666 + do_permission_test upload(f("kerb.jpg")), 0666 + end + + def test_access_with_empty_id + # an empty id might happen after a clone or through some other + # strange event. Since we would create a path that contains nothing + # where the id would have been, we should fail fast with an exception + # in this case + + e = Entry.new(:image => upload(f("skanthak.png"))) + assert e.save + id = e.id + + e = Entry.find(id) + + e["id"] = "" + assert_raise(RuntimeError) { e.image } + + e = Entry.find(id) + e["id"] = nil + assert_raise(RuntimeError) { e.image } + end +end + +# Tests for moving temp dir to permanent dir +class FileColumnMoveTest < Test::Unit::TestCase + + def setup + # we define the file_columns here so that we can change + # settings easily in a single test + + Entry.file_column :image + + end + + def teardown + FileUtils.rm_rf File.dirname(__FILE__)+"/public/entry/" + end + + def test_should_move_additional_files_from_tmp + e = Entry.new + e.image = uploaded_file(file_path("skanthak.png"), "image/png", "skanthak.png") + FileUtils.cp file_path("kerb.jpg"), File.dirname(e.image) + assert e.save + dir = File.dirname(e.image) + assert File.exists?(File.join(dir, "skanthak.png")) + assert File.exists?(File.join(dir, "kerb.jpg")) + end + + def test_should_move_direcotries_on_save + e = Entry.new(:image => upload(f("skanthak.png"))) + + FileUtils.mkdir( e.image_dir+"/foo" ) + FileUtils.cp file_path("kerb.jpg"), e.image_dir+"/foo/kerb.jpg" + + assert e.save + + assert File.exists?(e.image) + assert File.exists?(File.dirname(e.image)+"/foo/kerb.jpg") + end + + def test_should_overwrite_dirs_with_files_on_reupload + e = Entry.new(:image => upload(f("skanthak.png"))) + + FileUtils.mkdir( e.image_dir+"/kerb.jpg") + FileUtils.cp file_path("kerb.jpg"), e.image_dir+"/kerb.jpg/" + assert e.save + + e.image = upload(f("kerb.jpg")) + assert e.save + + assert File.file?(e.image_dir+"/kerb.jpg") + end + + def test_should_overwrite_files_with_dirs_on_reupload + e = Entry.new(:image => upload(f("skanthak.png"))) + + assert e.save + assert File.file?(e.image_dir+"/skanthak.png") + + e.image = upload(f("kerb.jpg")) + FileUtils.mkdir(e.image_dir+"/skanthak.png") + + assert e.save + assert File.file?(e.image_dir+"/kerb.jpg") + assert !File.file?(e.image_dir+"/skanthak.png") + assert File.directory?(e.image_dir+"/skanthak.png") + end + +end + diff --git a/vendor/plugins/file_column/test/fixtures/entry.rb b/vendor/plugins/file_column/test/fixtures/entry.rb new file mode 100644 index 0000000..b9f7c95 --- /dev/null +++ b/vendor/plugins/file_column/test/fixtures/entry.rb @@ -0,0 +1,32 @@ +class Entry < ActiveRecord::Base + attr_accessor :validation_should_fail + + def validate + errors.add("image","some stupid error") if @validation_should_fail + end + + def after_assign + @after_assign_called = true + end + + def after_assign_called? + @after_assign_called + end + + def after_save + @after_save_called = true + end + + def after_save_called? + @after_save_called + end + + def my_store_dir + # not really dynamic but at least it could be... + "my_store_dir" + end + + def load_image_with_rmagick(path) + Magick::Image::read(path).first + end +end diff --git a/vendor/plugins/file_column/test/fixtures/invalid-image.jpg b/vendor/plugins/file_column/test/fixtures/invalid-image.jpg new file mode 100644 index 0000000..bd4933b --- /dev/null +++ b/vendor/plugins/file_column/test/fixtures/invalid-image.jpg @@ -0,0 +1 @@ +this is certainly not a JPEG image diff --git a/vendor/plugins/file_column/test/fixtures/kerb.jpg b/vendor/plugins/file_column/test/fixtures/kerb.jpg new file mode 100644 index 0000000..083138e Binary files /dev/null and b/vendor/plugins/file_column/test/fixtures/kerb.jpg differ diff --git a/vendor/plugins/file_column/test/fixtures/mysql.sql b/vendor/plugins/file_column/test/fixtures/mysql.sql new file mode 100644 index 0000000..55143f2 --- /dev/null +++ b/vendor/plugins/file_column/test/fixtures/mysql.sql @@ -0,0 +1,25 @@ +-- MySQL dump 9.11 +-- +-- Host: localhost Database: file_column_test +-- ------------------------------------------------------ +-- Server version 4.0.24 + +-- +-- Table structure for table `entries` +-- + +DROP TABLE IF EXISTS entries; +CREATE TABLE entries ( + id int(11) NOT NULL auto_increment, + image varchar(200) default NULL, + file varchar(200) NOT NULL, + PRIMARY KEY (id) +) TYPE=MyISAM; + +DROP TABLE IF EXISTS movies; +CREATE TABLE movies ( + id int(11) NOT NULL auto_increment, + movie varchar(200) default NULL, + PRIMARY KEY (id) +) TYPE=MyISAM; + diff --git a/vendor/plugins/file_column/test/fixtures/schema.rb b/vendor/plugins/file_column/test/fixtures/schema.rb new file mode 100644 index 0000000..49b5ddb --- /dev/null +++ b/vendor/plugins/file_column/test/fixtures/schema.rb @@ -0,0 +1,10 @@ +ActiveRecord::Schema.define do + create_table :entries, :force => true do |t| + t.column :image, :string, :null => true + t.column :file, :string, :null => false + end + + create_table :movies, :force => true do |t| + t.column :movie, :string + end +end diff --git a/vendor/plugins/file_column/test/fixtures/skanthak.png b/vendor/plugins/file_column/test/fixtures/skanthak.png new file mode 100644 index 0000000..7415eb6 Binary files /dev/null and b/vendor/plugins/file_column/test/fixtures/skanthak.png differ diff --git a/vendor/plugins/file_column/test/magick_test.rb b/vendor/plugins/file_column/test/magick_test.rb new file mode 100644 index 0000000..0362719 --- /dev/null +++ b/vendor/plugins/file_column/test/magick_test.rb @@ -0,0 +1,380 @@ +require File.dirname(__FILE__) + '/abstract_unit' +require 'RMagick' +require File.dirname(__FILE__) + '/fixtures/entry' + + +class AbstractRMagickTest < Test::Unit::TestCase + def teardown + FileUtils.rm_rf File.dirname(__FILE__)+"/public/entry/" + end + + def test_truth + assert true + end + + private + + def read_image(path) + Magick::Image::read(path).first + end + + def assert_max_image_size(img, s) + assert img.columns <= s, "img has #{img.columns} columns, expected: #{s}" + assert img.rows <= s, "img has #{img.rows} rows, expected: #{s}" + assert_equal s, [img.columns, img.rows].max + end +end + +class RMagickSimpleTest < AbstractRMagickTest + def setup + Entry.file_column :image, :magick => { :geometry => "100x100" } + end + + def test_simple_resize_without_save + e = Entry.new + e.image = upload(f("kerb.jpg")) + + img = read_image(e.image) + assert_max_image_size img, 100 + end + + def test_simple_resize_with_save + e = Entry.new + e.image = upload(f("kerb.jpg")) + assert e.save + e.reload + + img = read_image(e.image) + assert_max_image_size img, 100 + end + + def test_resize_on_saved_image + Entry.file_column :image, :magick => { :geometry => "100x100" } + + e = Entry.new + e.image = upload(f("skanthak.png")) + assert e.save + e.reload + old_path = e.image + + e.image = upload(f("kerb.jpg")) + assert e.save + assert "kerb.jpg", File.basename(e.image) + assert !File.exists?(old_path), "old image '#{old_path}' still exists" + + img = read_image(e.image) + assert_max_image_size img, 100 + end + + def test_invalid_image + e = Entry.new + assert_nothing_raised { e.image = upload(f("invalid-image.jpg")) } + assert !e.valid? + end + + def test_serializable + e = Entry.new + e.image = upload(f("skanthak.png")) + assert_nothing_raised { + flash = Marshal.dump(e) + e = Marshal.load(flash) + } + assert File.exists?(e.image) + end + + def test_imagemagick_still_usable + e = Entry.new + assert_nothing_raised { + img = e.load_image_with_rmagick(file_path("skanthak.png")) + assert img.kind_of?(Magick::Image) + } + end +end + +class RMagickRequiresImageTest < AbstractRMagickTest + def setup + Entry.file_column :image, :magick => { + :size => "100x100>", + :image_required => false, + :versions => { + :thumb => "80x80>", + :large => {:size => "200x200>", :lazy => true} + } + } + end + + def test_image_required_with_image + e = Entry.new(:image => upload(f("skanthak.png"))) + assert_max_image_size read_image(e.image), 100 + assert e.valid? + end + + def test_image_required_with_invalid_image + e = Entry.new(:image => upload(f("invalid-image.jpg"))) + assert e.valid?, "did not ignore invalid image" + assert FileUtils.identical?(e.image, f("invalid-image.jpg")), "uploaded file has not been left alone" + end + + def test_versions_with_invalid_image + e = Entry.new(:image => upload(f("invalid-image.jpg"))) + assert e.valid? + + image_state = e.send(:image_state) + assert_nil image_state.create_magick_version_if_needed(:thumb) + assert_nil image_state.create_magick_version_if_needed(:large) + assert_nil image_state.create_magick_version_if_needed("300x300>") + end +end + +class RMagickCustomAttributesTest < AbstractRMagickTest + def assert_image_property(img, property, value, text = nil) + assert File.exists?(img), "the image does not exist" + assert_equal value, read_image(img).send(property), text + end + + def test_simple_attributes + Entry.file_column :image, :magick => { :attributes => { :quality => 20 } } + e = Entry.new("image" => upload(f("kerb.jpg"))) + assert_image_property e.image, :quality, 20, "the quality was not set" + end + + def test_version_attributes + Entry.file_column :image, :magick => { + :versions => { + :thumb => { :attributes => { :quality => 20 } } + } + } + e = Entry.new("image" => upload(f("kerb.jpg"))) + assert_image_property e.image("thumb"), :quality, 20, "the quality was not set" + end + + def test_lazy_attributes + Entry.file_column :image, :magick => { + :versions => { + :thumb => { :attributes => { :quality => 20 }, :lazy => true } + } + } + e = Entry.new("image" => upload(f("kerb.jpg"))) + e.send(:image_state).create_magick_version_if_needed(:thumb) + assert_image_property e.image("thumb"), :quality, 20, "the quality was not set" + end +end + +class RMagickVersionsTest < AbstractRMagickTest + def setup + Entry.file_column :image, :magick => {:geometry => "200x200", + :versions => { + :thumb => "50x50", + :medium => {:geometry => "100x100", :name => "100_100"}, + :large => {:geometry => "150x150", :lazy => true} + } + } + end + + + def test_should_create_thumb + e = Entry.new("image" => upload(f("skanthak.png"))) + + assert File.exists?(e.image("thumb")), "thumb-nail not created" + + assert_max_image_size read_image(e.image("thumb")), 50 + end + + def test_version_name_can_be_different_from_key + e = Entry.new("image" => upload(f("skanthak.png"))) + + assert File.exists?(e.image("100_100")) + assert !File.exists?(e.image("medium")) + end + + def test_should_not_create_lazy_versions + e = Entry.new("image" => upload(f("skanthak.png"))) + assert !File.exists?(e.image("large")), "lazy versions should not be created unless needed" + end + + def test_should_create_lazy_version_on_demand + e = Entry.new("image" => upload(f("skanthak.png"))) + + e.send(:image_state).create_magick_version_if_needed(:large) + + assert File.exists?(e.image("large")), "lazy version should be created on demand" + + assert_max_image_size read_image(e.image("large")), 150 + end + + def test_generated_name_should_not_change + e = Entry.new("image" => upload(f("skanthak.png"))) + + name1 = e.send(:image_state).create_magick_version_if_needed("50x50") + name2 = e.send(:image_state).create_magick_version_if_needed("50x50") + name3 = e.send(:image_state).create_magick_version_if_needed(:geometry => "50x50") + assert_equal name1, name2, "hash value has changed" + assert_equal name1, name3, "hash value has changed" + end + + def test_should_create_version_with_string + e = Entry.new("image" => upload(f("skanthak.png"))) + + name = e.send(:image_state).create_magick_version_if_needed("32x32") + + assert File.exists?(e.image(name)) + + assert_max_image_size read_image(e.image(name)), 32 + end + + def test_should_create_safe_auto_id + e = Entry.new("image" => upload(f("skanthak.png"))) + + name = e.send(:image_state).create_magick_version_if_needed("32x32") + + assert_match /^[a-zA-Z0-9]+$/, name + end +end + +class RMagickCroppingTest < AbstractRMagickTest + def setup + Entry.file_column :image, :magick => {:geometry => "200x200", + :versions => { + :thumb => {:crop => "1:1", :geometry => "50x50"} + } + } + end + + def test_should_crop_image_on_upload + e = Entry.new("image" => upload(f("skanthak.png"))) + + img = read_image(e.image("thumb")) + + assert_equal 50, img.rows + assert_equal 50, img.columns + end + +end + +class UrlForImageColumnTest < AbstractRMagickTest + include FileColumnHelper + + def setup + Entry.file_column :image, :magick => { + :versions => {:thumb => "50x50"} + } + @request = RequestMock.new + end + + def test_should_use_version_on_symbol_option + e = Entry.new(:image => upload(f("skanthak.png"))) + + url = url_for_image_column(e, "image", :thumb) + assert_match %r{^/entry/image/tmp/.+/thumb/skanthak.png$}, url + end + + def test_should_use_string_as_size + e = Entry.new(:image => upload(f("skanthak.png"))) + + url = url_for_image_column(e, "image", "50x50") + + assert_match %r{^/entry/image/tmp/.+/.+/skanthak.png$}, url + + url =~ /\/([^\/]+)\/skanthak.png$/ + dirname = $1 + + assert_max_image_size read_image(e.image(dirname)), 50 + end + + def test_should_accept_version_hash + e = Entry.new(:image => upload(f("skanthak.png"))) + + url = url_for_image_column(e, "image", :size => "50x50", :crop => "1:1", :name => "small") + + assert_match %r{^/entry/image/tmp/.+/small/skanthak.png$}, url + + img = read_image(e.image("small")) + assert_equal 50, img.rows + assert_equal 50, img.columns + end +end + +class RMagickPermissionsTest < AbstractRMagickTest + def setup + Entry.file_column :image, :magick => {:geometry => "200x200", + :versions => { + :thumb => {:crop => "1:1", :geometry => "50x50"} + } + }, :permissions => 0616 + end + + def check_permissions(e) + assert_equal 0616, (File.stat(e.image).mode & 0777) + assert_equal 0616, (File.stat(e.image("thumb")).mode & 0777) + end + + def test_permissions_with_rmagick + e = Entry.new(:image => upload(f("skanthak.png"))) + + check_permissions e + + assert e.save + + check_permissions e + end +end + +class Entry + def transform_grey(img) + img.quantize(256, Magick::GRAYColorspace) + end +end + +class RMagickTransformationTest < AbstractRMagickTest + def assert_transformed(image) + assert File.exists?(image), "the image does not exist" + assert 256 > read_image(image).number_colors, "the number of colors was not changed" + end + + def test_simple_transformation + Entry.file_column :image, :magick => { :transformation => Proc.new { |image| image.quantize(256, Magick::GRAYColorspace) } } + e = Entry.new("image" => upload(f("skanthak.png"))) + assert_transformed(e.image) + end + + def test_simple_version_transformation + Entry.file_column :image, :magick => { + :versions => { :thumb => Proc.new { |image| image.quantize(256, Magick::GRAYColorspace) } } + } + e = Entry.new("image" => upload(f("skanthak.png"))) + assert_transformed(e.image("thumb")) + end + + def test_complex_version_transformation + Entry.file_column :image, :magick => { + :versions => { + :thumb => { :transformation => Proc.new { |image| image.quantize(256, Magick::GRAYColorspace) } } + } + } + e = Entry.new("image" => upload(f("skanthak.png"))) + assert_transformed(e.image("thumb")) + end + + def test_lazy_transformation + Entry.file_column :image, :magick => { + :versions => { + :thumb => { :transformation => Proc.new { |image| image.quantize(256, Magick::GRAYColorspace) }, :lazy => true } + } + } + e = Entry.new("image" => upload(f("skanthak.png"))) + e.send(:image_state).create_magick_version_if_needed(:thumb) + assert_transformed(e.image("thumb")) + end + + def test_simple_callback_transformation + Entry.file_column :image, :magick => :transform_grey + e = Entry.new(:image => upload(f("skanthak.png"))) + assert_transformed(e.image) + end + + def test_complex_callback_transformation + Entry.file_column :image, :magick => { :transformation => :transform_grey } + e = Entry.new(:image => upload(f("skanthak.png"))) + assert_transformed(e.image) + end +end diff --git a/vendor/plugins/file_column/test/magick_view_only_test.rb b/vendor/plugins/file_column/test/magick_view_only_test.rb new file mode 100644 index 0000000..a7daa61 --- /dev/null +++ b/vendor/plugins/file_column/test/magick_view_only_test.rb @@ -0,0 +1,21 @@ +require File.dirname(__FILE__) + '/abstract_unit' +require File.dirname(__FILE__) + '/fixtures/entry' + +class RMagickViewOnlyTest < Test::Unit::TestCase + include FileColumnHelper + + def setup + Entry.file_column :image + @request = RequestMock.new + end + + def teardown + FileUtils.rm_rf File.dirname(__FILE__)+"/public/entry/" + end + + def test_url_for_image_column_without_model_versions + e = Entry.new(:image => upload(f("skanthak.png"))) + + assert_nothing_raised { url_for_image_column e, "image", "50x50" } + end +end
itszero/eLib2
ffbf6a5980c62b17ad001fb021936d060eb20458
staff done, and with autocomplete
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 02b86cf..93a897a 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,125 +1,188 @@ require 'csv' class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem layout 'service' - before_filter :super_required, :only => [:staff] - before_filter :admin_required, :except => [:index, :edit, :bulk_add] + before_filter :super_required, :only => [:staff, :demote, :promote] + before_filter :admin_required, :except => [:index, :edit, :bulk_add, :demote, :promote] before_filter :login_required, :only => [:edit] def index redirect_to '/' end def admin @in_admin_function = true if !params[:id] @user = User.paginate :page => params[:page] else @u = User.find(params[:id]) render :partial => 'user_list_item' end end def staff - @super_user = User.find(:all, :conditions => 'permission = 2') - @staff_user = User.find(:all, :conditions => 'permission = 1') + @user = User.find(:all, :conditions => 'permission > 0', :order => 'permission DESC, id ASC') + end + + def promote + @user = User.find(params[:id]) + + if !@user + error_stickie "找不到使用者 ##{params[:id]}" + redirect_to :action => :staff + return + end + + @user.permission+=1 if @user.permission < 2 + @user.save + + notice_stickie "使用者 「#{@user.name}」 已提昇權限" + redirect_to :action => :staff + end + + def demote + @user = User.find(params[:id]) + + if !@user + error_stickie "找不到使用者 ##{params[:id]}" + redirect_to :action => :staff + return + end + + @user.permission-=1 if @user.permission > 1 + @user.save + + notice_stickie "使用者 「#{@user.name}」 已降低權限" + redirect_to :action => :staff + end + + def set_permission + suppress(ActiveRecord::RecordNotFound) do + @user = User.find(params[:id]) + end + + suppress(ActiveRecord::RecordNotFound) do + @user = User.find_by_login(params[:id]) if !@user + end + + if !@user + error_stickie "找不到使用者 ##{params[:id]}" + redirect_to :action => :staff + return + end + + @user.permission = params[:permission] + if params[:permission].to_i == 0 + notice_stickie "使用者 「#{@user.name}」 的權限已取消。" + elsif params[:permission].to_i > 0 + notice_stickie "使用者 「#{@user.name}」 已經設定為工作人員。" + end + @user.save + + redirect_to :action => :staff + end + + def uid_autocomplete + @users = User.find(:all, :conditions => "login LIKE '%#{params[:q]}%'") + + render :text => (@users.map &:login).join("\n") end def bulk_add @in_admin_function = true if request.post? csv = CSV.parse(params[:csv].read) header = csv.shift # check reader expect_header = ['login', 'email', 'password', 'name', 'student_id', 'student_class'] pass = true expect_header.each do |h| pass = false if !header.include? h end if !pass error_stickie "匯入的欄位有缺失,請檢查CSV檔案!" redirect_to :action => :bulk_add return end # read it result = [] csv.each do |row| result << Hash[*header.zip(row.to_a).flatten] end errors = [] # add it result.each do |r| u = User.new(r) u.password_confirmation = u.password if !u.save errors << "使用者 #{r["login"]} 無法新增,請檢查資料。" end end if errors != [] error_stickie errors.join("<br/>") end notice_stickie("收到 #{result.size} 筆資料,成功新增 #{result.size - errors.size} 筆,失敗 #{errors.size} 筆。") redirect_to :action => :bulk_add end end def create @user = User.new @user.login = params[:login] @user.password = params[:password] @user.password_confirmation = params[:password_confirmation] @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] if @user.save notice_stickie "使用者 #{params[:login]} 建立成功" else error_stickie "無法建立使用者 #{params[:login]}<br/>#{@user.errors.inspect}" end redirect_to :action => 'admin' end def delete User.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? if @current_user.permission == 2 || @current_user.id == params[:id] @user = User.find(params[:id]) @user.student_id = params[:student_id] @user.student_class = params[:student_class] @user.name = params[:name] @user.email = params[:email] @user.nickname = params[:nickname] if params[:nickname] @user.save end if @current_user.permission > 0 redirect_to '/users/admin' else redirect_to '/users/edit' end else if @current_user.permission == 0 @u = User.find(@current_user.id) else @u = User.find(params[:id]) render :layout => false end end end end diff --git a/app/views/news/admin.html.erb b/app/views/news/admin.html.erb index ecbdfad..f9c8812 100644 --- a/app/views/news/admin.html.erb +++ b/app/views/news/admin.html.erb @@ -1,56 +1,56 @@ <h1>公告管理</h1> <p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#news-add').toggle('blind'); $('#news-add-form input[type=\'text\'], #news-add-form textarea').val(''); this.blur();"><span><span>新增公告</span></span></a><a href="/news" class="button green right"><span><span>前往圖書館部落格</span></span></a></p> <div id="news-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> <form action="/news/new" method="post" accept-charset="utf-8" id="news-add-form"> <p>公告標題<br/><input type="text" name="title" value="" id="title"></p> <p>公告內容<br/><textarea name="content" rows="8" cols="40"></textarea></p> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <p class="clearfix"><a href="#" class="button dark check" onclick="$('#news-add-form').submit(); this.blur();"><span><span>確定送出</span></span></a></p> </form> </div> -<div id="news-list"> +<div id="news-list" class="table"> <div class="thead"> <div class="container"> <div class="span-3">日期</div> <div class="span-15">公告</div> <div class="span-4 last">行動</div> </div> </div> <% @news.each do |news| @n = news%> <div class="tbody" id="news-<%=news.id%>"> <%=render_partial "news_list_item"%> </div> <% end %> </div> <%=will_paginate @news, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> <script type="text/javascript" charset="utf-8"> function toggle_content(e) { if ($(e).hasClass("down")) { $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); $(e).removeClass("down").addClass("up"); } else { $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); $(e).removeClass("up").addClass("down"); } return false; } function edit_news(id) { $('#btn-edit-' + id).children('span').children('span').html('...'); $.get('/news/edit/' + id, {}, function(data){ $('#news-' + id).html(data); }); } function restore_news(id) { $.get('/news/admin/' + id, {}, function(data){ $('#news-' + id).html(data); }) } </script> \ No newline at end of file diff --git a/app/views/users/admin.html.erb b/app/views/users/admin.html.erb index 56416a4..ad65556 100644 --- a/app/views/users/admin.html.erb +++ b/app/views/users/admin.html.erb @@ -1,55 +1,55 @@ <h1>讀者資料查詢/ç¶­è­·</h1> <p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#user-add').toggle('blind'); $('#user-add-form input[type=\'text\']').val(''); this.blur();"><span><span>新增讀者</span></span></a><a href="/users/bulk_add" class="button dark right"><span><span>大批新增讀者</span></span></a></p> <div id="user-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> <form action="/users/create" method="post" accept-charset="utf-8" id="user-add-form"> <div style="float: left;">登入帳號<br/><input type="text" name="login" id="login"></div> <div style="float: left;">暱稱<br/><input type="text" name="nickname" value=">" id="nickname"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">密碼<br/><input type="password" name="password" id="password"></div> <div style="float: left;">確認密碼<br/><input type="password" name="password_confirmation" id="password_confirmation"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">學生證號<br/><input type="text" name="student_id" value="" id="student_id"></div> <div style="float: left;">班級<br/><input type="text" name="student_class" value="" id="student_class"></div> <div style="clear: both;">&nbsp;</div> <div style="float: left;">姓名<br/><input type="text" name="name" value="" id="name"></div> <div style="float: left;">E-mail<br/><input type="text" name="email" value="" id="email"></div> <div style="clear: both;">&nbsp;</div> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <p class="clearfix"><a href="#" class="button normal plus" onclick="$('#user-add-form').submit(); this.blur(); return false;" style="margin-right: 10px;"><span><span>新增讀者</span></span></a></p> </form> </div> -<div id="user-list"> +<div id="user-list" class="table"> <div class="thead"> <div class="container"> <div class="span-3">學號</div> <div class="span-5">姓名</div> <div class="span-3">班級</div> <div class="span-5">電子郵件</div> <div class="span-8 last">行動</div> </div> </div> <% @user.each do |user| @u = user%> <div class="tbody" id="user-<%=user.id%>"> <%=render_partial "user_list_item"%> </div> <% end %> </div> <%=will_paginate @user, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> <script type="text/javascript" charset="utf-8"> function edit_user(id) { $('#btn-edit-' + id).children('span').children('span').html('...'); $.get('/users/edit/' + id, {}, function(data){ $('#user-' + id).html(data); }); } function restore_user(id) { $.get('/users/admin/' + id, {}, function(data){ $('#user-' + id).html(data); }) } </script> \ No newline at end of file diff --git a/app/views/users/staff.html.erb b/app/views/users/staff.html.erb index 7813b75..555d131 100644 --- a/app/views/users/staff.html.erb +++ b/app/views/users/staff.html.erb @@ -1,25 +1,43 @@ +<link rel="stylesheet" href="/stylesheets/jquery.autocomplete.css" type="text/css" media="screen" charset="utf-8"/> +<script type="text/javascript" charset="utf-8" src="/javascripts/jquery.autocomplete.js"></script> + +<script type="text/javascript" charset="utf-8"> + $(function(){ + $('#uid').autocomplete("/users/uid_autocomplete"); + }); +</script> + <h1>工作人員權限管理</h1> -<div id="staff-add" style="margin: 10px; border: 2px solid #00F; padding: 10px; width: 250px; height: 80px;"> - <p>讀者帳號:<input type="text" name="id" id="id"><br/> +<div id="staff-add" style="margin: 10px; border: 2px solid #AAB; padding: 10px; width: 250px; height: 80px;"> + <form id="staff-add-form" action="/users/set_permission" method="get" accept-charset="utf-8"> + <p>讀者帳號:<input type="text" name="id" id="uid" style="font-size: 1em;" size="14"><br/> 目標權限:<select name="permission"><option value="1">工作人員</option><option value="2">系統管理員</option></select></p> - <p class="clearfix" style="margin-top: -20px;"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#staff-add').toggle('blind'); $('#staff-add input[type=\'text\']').val(''); this.blur();"><span><span>提昇讀者權限為工作人員</span></span></a></p> + <p class="clearfix" style="margin-top: -20px;"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#staff-add-form').submit(); this.blur();"><span><span>提昇讀者權限為工作人員</span></span></a></p> + </form> </div> <h2>工作人員名單</h2> -<div id="staff-list"> +<div id="staff-list" class="table"> <div class="thead"> <div class="container"> - <div class="span-3">學號</div> - <div class="span-5">姓名</div> - <div class="span-3">班級</div> - <div class="span-5">電子郵件</div> - <div class="span-8 last">行動</div> + <div class="span-4">權限</div> + <div class="span-2">帳號</div> + <div class="span-4">姓名</div> + <div class="span-6">電子郵件</div> + <div class="span-7 last">行動</div> </div> </div> <% @user.each do |user| @u = user%> - <div class="tbody" id="user-<%=user.id%>"> - <%=render_partial "user_list_item"%> - </div> + <div class="tbody" id="staff-<%[email protected]%>"> + <div class="container"> + <div class="span-4"><%if @u.permission == 2%><span style="color: red;">系統管理員</span><%end%><%if @u.permission == 1%><span style="color: red;">工作人員</span><%end%></div> + <div class="span-2"><%[email protected]%></div> + <div class="span-4"><%[email protected]%></div> + <div class="span-6"><%[email protected]%></div> + <div class="span-7 last"> + <p class="clearfix"><% if @u.permission < 2 %><a href="/users/promote/<%[email protected]%>" class="button dark plus" style="margin-right: 10px;" onclick="this.blur();return confirm('您確定要將使用者 「<%[email protected]%>」 昇級嗎?');"><span><span>提昇</span></span></a><% end %><% if @u.permission > 1 %><a href="/users/demote/<%[email protected]%>" class="button alt minus" style="margin-right: 10px;" onclick="this.blur(); return confirm('您確定要將使用者 「<%[email protected]%>」 降級嗎?');"><span><span>降級</span></span></a><% end %><a href="/users/set_permission/<%[email protected]%>?permission=0" class="button pink check" onclick="return confirm('確定要取消使用者 「<%[email protected]%>」的管理權限嗎?')"><span><span>刪除權限</span></span></a></p> + </div> + </div> </div> <% end %> </div> diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb index 92a311d..9eb7ccd 100644 --- a/app/views/welcome/index.html.erb +++ b/app/views/welcome/index.html.erb @@ -1,35 +1,35 @@ <div style="text-align: center; border: 1px solid #000; width:900px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="iTunesAlbumArt" align="middle" width="900" height="329"> <param name="allowScriptAccess" value="always"> <param name="allowFullScreen" value="false"> <param name="movie" value="iTunesAlbumArt.swf"> <param name="quality" value="high"> - + <param name="wmode" value="opaque"> <param name="bgcolor" value="#000000"> <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329"> </object> </div> <div class="container" style="margin-top: 5px;"> <div class="span-11" style="padding-right: 5px; border-right: 2px dashed #000;"> <h2>圖書館部落格</h2> <ul style="margin-left: 30px;"> <% @news.each do |news| %> <li id="news-<%=news.id%>"><a href="/news/show/<%=news.id%>"><%=news.title%></a> - <%=news.created_at.strftime("%Y-%m-%d")%></li> <% end %> </ul> <%=link_to '更多消息...', :controller => 'news'%> </div> <div class="span-12 last"> <% if @current_user %> <h2>資訊快遞</h2> <ul style="margin-left: 30px;"> <li>您目前共借閱 5 本書,2 本書即將到期。</li> <li>您還需要繳交 3 篇讀書心得。</li> </ul> <%=link_to '詳細資訊...', :controller => 'reader'%> <% else %> <h2>熱門書籍</h2> <% end %> </div> </div> \ No newline at end of file diff --git a/public/javascripts/jquery.autocomplete.js b/public/javascripts/jquery.autocomplete.js new file mode 100644 index 0000000..76af765 --- /dev/null +++ b/public/javascripts/jquery.autocomplete.js @@ -0,0 +1,502 @@ +jQuery.autocomplete = function(input, options) { + // Create a link to self + var me = this; + + // Create jQuery object for input element + var $input = $(input).attr("autocomplete", "off"); + + // Apply inputClass if necessary + if (options.inputClass) $input.addClass(options.inputClass); + + // Create results + var results = document.createElement("div"); + // Create jQuery object for results + var $results = $(results); + $results.hide().addClass(options.resultsClass).css("position", "absolute"); + if( options.width > 0 ) $results.css("width", options.width); + + // Add to body element + $("body").append(results); + + input.autocompleter = me; + + var timeout = null; + var prev = ""; + var active = -1; + var cache = {}; + var keyb = false; + var hasFocus = false; + var lastKeyPressCode = null; + + // flush cache + function flushCache(){ + cache = {}; + cache.data = {}; + cache.length = 0; + }; + + // flush cache + flushCache(); + + // if there is a data array supplied + if( options.data != null ){ + var sFirstChar = "", stMatchSets = {}, row = []; + + // no url was specified, we need to adjust the cache length to make sure it fits the local data store + if( typeof options.url != "string" ) options.cacheLength = 1; + + // loop through the array and create a lookup structure + for( var i=0; i < options.data.length; i++ ){ + // if row is a string, make an array otherwise just reference the array + row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]); + + // if the length is zero, don't add to list + if( row[0].length > 0 ){ + // get the first character + sFirstChar = row[0].substring(0, 1).toLowerCase(); + // if no lookup array for this character exists, look it up now + if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = []; + // if the match is a string + stMatchSets[sFirstChar].push(row); + } + } + + // add the data items to the cache + for( var k in stMatchSets ){ + // increase the cache size + options.cacheLength++; + // add to the cache + addToCache(k, stMatchSets[k]); + } + } + + $input + .keydown(function(e) { + // track last key pressed + lastKeyPressCode = e.keyCode; + switch(e.keyCode) { + case 38: // up + e.preventDefault(); + moveSelect(-1); + break; + case 40: // down + e.preventDefault(); + moveSelect(1); + break; + case 9: // tab + case 13: // return + if( selectCurrent() ){ + // make sure to blur off the current field + $input.get(0).blur(); + e.preventDefault(); + } + break; + default: + active = -1; + if (timeout) clearTimeout(timeout); + timeout = setTimeout(function(){onChange();}, options.delay); + break; + } + }) + .focus(function(){ + // track whether the field has focus, we shouldn't process any results if the field no longer has focus + hasFocus = true; + }) + .blur(function() { + // track whether the field has focus + hasFocus = false; + hideResults(); + }); + + hideResultsNow(); + + function onChange() { + // ignore if the following keys are pressed: [del] [shift] [capslock] + if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide(); + var v = $input.val(); + if (v == prev) return; + prev = v; + if (v.length >= options.minChars) { + $input.addClass(options.loadingClass); + requestData(v); + } else { + $input.removeClass(options.loadingClass); + $results.hide(); + } + }; + + function moveSelect(step) { + + var lis = $("li", results); + if (!lis) return; + + active += step; + + if (active < 0) { + active = 0; + } else if (active >= lis.size()) { + active = lis.size() - 1; + } + + lis.removeClass("ac_over"); + + $(lis[active]).addClass("ac_over"); + + // Weird behaviour in IE + // if (lis[active] && lis[active].scrollIntoView) { + // lis[active].scrollIntoView(false); + // } + + }; + + function selectCurrent() { + var li = $("li.ac_over", results)[0]; + if (!li) { + var $li = $("li", results); + if (options.selectOnly) { + if ($li.length == 1) li = $li[0]; + } else if (options.selectFirst) { + li = $li[0]; + } + } + if (li) { + selectItem(li); + return true; + } else { + return false; + } + }; + + function selectItem(li) { + if (!li) { + li = document.createElement("li"); + li.extra = []; + li.selectValue = ""; + } + var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML); + input.lastSelected = v; + prev = v; + $results.html(""); + $input.val(v); + hideResultsNow(); + if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1); + }; + + // selects a portion of the input string + function createSelection(start, end){ + // get a reference to the input element + var field = $input.get(0); + if( field.createTextRange ){ + var selRange = field.createTextRange(); + selRange.collapse(true); + selRange.moveStart("character", start); + selRange.moveEnd("character", end); + selRange.select(); + } else if( field.setSelectionRange ){ + field.setSelectionRange(start, end); + } else { + if( field.selectionStart ){ + field.selectionStart = start; + field.selectionEnd = end; + } + } + field.focus(); + }; + + // fills in the input box w/the first match (assumed to be the best match) + function autoFill(sValue){ + // if the last user key pressed was backspace, don't autofill + if( lastKeyPressCode != 8 ){ + // fill in the value (keep the case the user has typed) + $input.val($input.val() + sValue.substring(prev.length)); + // select the portion of the value not typed by the user (so the next character will erase) + createSelection(prev.length, sValue.length); + } + }; + + function showResults() { + // get the position of the input field right now (in case the DOM is shifted) + var pos = findPos(input); + // either use the specified width, or autocalculate based on form element + var iWidth = (options.width > 0) ? options.width : $input.width(); + // reposition + $results.css({ + width: parseInt(iWidth) + "px", + top: (pos.y + input.offsetHeight) + "px", + left: pos.x + "px" + }).show(); + }; + + function hideResults() { + if (timeout) clearTimeout(timeout); + timeout = setTimeout(hideResultsNow, 200); + }; + + function hideResultsNow() { + if (timeout) clearTimeout(timeout); + $input.removeClass(options.loadingClass); + if ($results.is(":visible")) { + $results.hide(); + } + if (options.mustMatch) { + var v = $input.val(); + if (v != input.lastSelected) { + selectItem(null); + } + } + }; + + function receiveData(q, data) { + if (data) { + $input.removeClass(options.loadingClass); + results.innerHTML = ""; + + // if the field no longer has focus or if there are no matches, do not display the drop down + if( !hasFocus || data.length == 0 ) return hideResultsNow(); + + if ($.browser.msie) { + // we put a styled iframe behind the calendar so HTML SELECT elements don't show through + $results.append(document.createElement('iframe')); + } + results.appendChild(dataToDom(data)); + // autofill in the complete box w/the first match as long as the user hasn't entered in more data + if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]); + showResults(); + } else { + hideResultsNow(); + } + }; + + function parseData(data) { + if (!data) return null; + var parsed = []; + var rows = data.split(options.lineSeparator); + for (var i=0; i < rows.length; i++) { + var row = $.trim(rows[i]); + if (row) { + parsed[parsed.length] = row.split(options.cellSeparator); + } + } + return parsed; + }; + + function dataToDom(data) { + var ul = document.createElement("ul"); + var num = data.length; + + // limited results to a max number + if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow; + + for (var i=0; i < num; i++) { + var row = data[i]; + if (!row) continue; + var li = document.createElement("li"); + if (options.formatItem) { + li.innerHTML = options.formatItem(row, i, num); + li.selectValue = row[0]; + } else { + li.innerHTML = row[0]; + li.selectValue = row[0]; + } + var extra = null; + if (row.length > 1) { + extra = []; + for (var j=1; j < row.length; j++) { + extra[extra.length] = row[j]; + } + } + li.extra = extra; + ul.appendChild(li); + $(li).hover( + function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); }, + function() { $(this).removeClass("ac_over"); } + ).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) }); + } + return ul; + }; + + function requestData(q) { + if (!options.matchCase) q = q.toLowerCase(); + var data = options.cacheLength ? loadFromCache(q) : null; + // recieve the cached data + if (data) { + receiveData(q, data); + // if an AJAX url has been supplied, try loading the data now + } else if( (typeof options.url == "string") && (options.url.length > 0) ){ + $.get(makeUrl(q), function(data) { + data = parseData(data); + addToCache(q, data); + receiveData(q, data); + }); + // if there's been no data found, remove the loading class + } else { + $input.removeClass(options.loadingClass); + } + }; + + function makeUrl(q) { + var url = options.url + "?q=" + encodeURI(q); + for (var i in options.extraParams) { + url += "&" + i + "=" + encodeURI(options.extraParams[i]); + } + return url; + }; + + function loadFromCache(q) { + if (!q) return null; + if (cache.data[q]) return cache.data[q]; + if (options.matchSubset) { + for (var i = q.length - 1; i >= options.minChars; i--) { + var qs = q.substr(0, i); + var c = cache.data[qs]; + if (c) { + var csub = []; + for (var j = 0; j < c.length; j++) { + var x = c[j]; + var x0 = x[0]; + if (matchSubset(x0, q)) { + csub[csub.length] = x; + } + } + return csub; + } + } + } + return null; + }; + + function matchSubset(s, sub) { + if (!options.matchCase) s = s.toLowerCase(); + var i = s.indexOf(sub); + if (i == -1) return false; + return i == 0 || options.matchContains; + }; + + this.flushCache = function() { + flushCache(); + }; + + this.setExtraParams = function(p) { + options.extraParams = p; + }; + + this.findValue = function(){ + var q = $input.val(); + + if (!options.matchCase) q = q.toLowerCase(); + var data = options.cacheLength ? loadFromCache(q) : null; + if (data) { + findValueCallback(q, data); + } else if( (typeof options.url == "string") && (options.url.length > 0) ){ + $.get(makeUrl(q), function(data) { + data = parseData(data) + addToCache(q, data); + findValueCallback(q, data); + }); + } else { + // no matches + findValueCallback(q, null); + } + } + + function findValueCallback(q, data){ + if (data) $input.removeClass(options.loadingClass); + + var num = (data) ? data.length : 0; + var li = null; + + for (var i=0; i < num; i++) { + var row = data[i]; + + if( row[0].toLowerCase() == q.toLowerCase() ){ + li = document.createElement("li"); + if (options.formatItem) { + li.innerHTML = options.formatItem(row, i, num); + li.selectValue = row[0]; + } else { + li.innerHTML = row[0]; + li.selectValue = row[0]; + } + var extra = null; + if( row.length > 1 ){ + extra = []; + for (var j=1; j < row.length; j++) { + extra[extra.length] = row[j]; + } + } + li.extra = extra; + } + } + + if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1); + } + + function addToCache(q, data) { + if (!data || !q || !options.cacheLength) return; + if (!cache.length || cache.length > options.cacheLength) { + flushCache(); + cache.length++; + } else if (!cache[q]) { + cache.length++; + } + cache.data[q] = data; + }; + + function findPos(obj) { + var curleft = obj.offsetLeft || 0; + var curtop = obj.offsetTop || 0; + while (obj = obj.offsetParent) { + curleft += obj.offsetLeft + curtop += obj.offsetTop + } + return {x:curleft,y:curtop}; + } +} + +jQuery.fn.autocomplete = function(url, options, data) { + // Make sure options exists + options = options || {}; + // Set url as option + options.url = url; + // set some bulk local data + options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null; + + // Set default values for required options + options.inputClass = options.inputClass || "ac_input"; + options.resultsClass = options.resultsClass || "ac_results"; + options.lineSeparator = options.lineSeparator || "\n"; + options.cellSeparator = options.cellSeparator || "|"; + options.minChars = options.minChars || 1; + options.delay = options.delay || 400; + options.matchCase = options.matchCase || 0; + options.matchSubset = options.matchSubset || 1; + options.matchContains = options.matchContains || 0; + options.cacheLength = options.cacheLength || 1; + options.mustMatch = options.mustMatch || 0; + options.extraParams = options.extraParams || {}; + options.loadingClass = options.loadingClass || "ac_loading"; + options.selectFirst = options.selectFirst || false; + options.selectOnly = options.selectOnly || false; + options.maxItemsToShow = options.maxItemsToShow || -1; + options.autoFill = options.autoFill || false; + options.width = parseInt(options.width, 10) || 0; + + this.each(function() { + var input = this; + new jQuery.autocomplete(input, options); + }); + + // Don't break the chain + return this; +} + +jQuery.fn.autocompleteArray = function(data, options) { + return this.autocomplete(null, options, data); +} + +jQuery.fn.indexOf = function(e){ + for( var i=0; i<this.length; i++ ){ + if( this[i] == e ) return i; + } + return -1; +}; diff --git a/public/stylesheets/jquery.autocomplete.css b/public/stylesheets/jquery.autocomplete.css new file mode 100644 index 0000000..e1a26be --- /dev/null +++ b/public/stylesheets/jquery.autocomplete.css @@ -0,0 +1,46 @@ +.ac_results { + padding: 0px; + border: 1px solid WindowFrame; + background-color: Window; + overflow: hidden; +} + +.ac_results ul { + width: 100%; + list-style-position: outside; + list-style: none; + padding: 0; + margin: 0; +} + +.ac_results iframe { + display:none;/*sorry for IE5*/ + display/**/:block;/*sorry for IE5*/ + position:absolute; + top:0; + left:0; + z-index:-1; + filter:mask(); + width:3000px; + height:3000px; +} + +.ac_results li { + margin: 0px; + padding: 2px 5px; + cursor: pointer; + display: block; + width: 100%; + font: menu; + font-size: 12px; + overflow: hidden; +} + +.ac_loading { + background : Window url('./indicator.gif') right center no-repeat; +} + +.ac_over { + background-color: Highlight; + color: HighlightText; +} diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index e5b2e0a..1feb768 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,261 +1,260 @@ /* layout */ body { background-color: #7C6255; font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; font-size: 11pt; } h1 { border-bottom: 1px solid #CCC; } h2 { margin: 0; } #content { background-color: #FFF; padding: 10px; margin-top: -10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; border-left: 1px solid #FFF; border-top: 1px solid #FFF; border-right: 1px solid #FFF; background-color: #222; background-image: -webkit-gradient(linear, left top, left bottom, from(#666), to(#222)); padding: 5px; padding-top: 60px; margin-left: -1px; } #header-title ul li a { color: #fff; } #header-title ul li:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#444)); background-color: #444; } .menu-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#FFF)) !important; background-color: #FFF !important; } .menu-current a { color: #000 !important; } .menu-backstage { background-image: -webkit-gradient(linear, left top, left bottom, from(#C30017), to(#73000E)) !important; background-color: #73000E !important; } .menu-backstage:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#B20014)) !important; background-color: #920011 !important; } .menu-backstage-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#FFF), color-stop(0.8, #FFF)) !important; background-color: #FFF !important; } .menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; color: #FFF; word-spacing: 4px; font-family: Helvetica; } /* admin css */ .admin-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#C17436), to(#A9652F)); background-color: #C17436; color: #FFF; font-size: 2em; border-top: 1px solid #000; border-left: 1px solid #000; border-right: 1px solid #000; } .admin-menu { margin: 0; padding: 0; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; font-size: 1.75em; } .admin-menu a { display: block; padding: 2px; } .admin-menu .arrow { float: right; } .admin-menu a:hover { display: block; background-image: -webkit-gradient(linear, left top, left bottom, from(#0000FF), to(#000099)) !important; background-color: #000099; color: #FFF; text-decoration: none; } -/* news(blog) css */ -#news-list { +.table { font-size: 1.25em; border-bottom: 1px solid #000; } -#news-list .thead { +.table .thead { border-top: 1px solid #000; font-size: 1.25em; border-bottom: 1px dashed #000; } -#news-list .tbody { +.table .tbody { border-top: 1px dashed #000; margin-top: -1px; } -#news-list .tbody .container div { +.table .tbody .container div { line-height: 30px; } -#news-list .tbody .container p.clearfix { +.table .tbody .container p.clearfix { margin: 0px; } -#news-list .tbody .container a.button { +.table .tbody .container a.button { margin-top: 2px; } form input { font-size: 22pt; } form input[type="file"] { font-size: 1em !important; } form textarea { font-size: 18pt; } /* blog front */ .blog-date { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#444), to(#000)); background-color: #000; color: #FFF; letter-spacing: 0.3em; } .blog-title { font-size: 2em; color: rgb(99, 60, 17); margin: 0px; } .blog-content { margin-left: 10px; text-indent: 2em; } /* sidebar */ #sidebar { width: 230px; height: 600px; background: url('../images/bkg_blackboard.jpg') repeat-y; color: white; padding: 10px; padding-right: 35px; margin-left: -10px; -webkit-box-shadow: 0px 3px 5px black; -moz-box-shadow: 0px 3px 5px black; position: relative; float: left; } #sidebar { /* Damn IE fix */ height: auto; min-height: 600px; } #sidebar #metal_holder { width: 68px; height: 213px; background: url('../images/img_blackboard_holder.png') no-repeat; position: absolute; top: 200px; left: 240px; } #sidebar h1 { color: #FFF; border: none; } /* pagination */ .pagination { margin: 5px; font-size: 1.2em; } .pagination * { padding: 2px; } .pagination a { border: 1px solid #00F; } .pagination a:hover { border: 1px solid #00F; background-color: #00A; color: #FFF; } .pagination span.current { border: 1px solid #00E; background-color: #00F; color: #FFF; }
itszero/eLib2
92e756dd9f90c67fa50f5572a0d30ad70f43054b
user admin ok, staff on the way
diff --git a/app/controllers/news_controller.rb b/app/controllers/news_controller.rb index 63f17de..5fd1f66 100644 --- a/app/controllers/news_controller.rb +++ b/app/controllers/news_controller.rb @@ -1,55 +1,55 @@ class NewsController < ApplicationController layout 'service' before_filter :admin_required, :except => [:index, :show] def index @in_reader_function = true @news = Blog.find(:all, :order => "created_at DESC") end def admin @in_admin_function = true if !params[:id] - @news = Blog.find(:all, :order => "created_at DESC") + @news = Blog.paginate :page => params[:page], :order => 'created_at DESC' else @n = Blog.find(params[:id]) render :partial => 'news_list_item' end end def show @in_reader_function = true @news = Blog.find(params[:id]) warning_stickie "找不到您指定的新聞。" if !@news redirect_to '/news' if !@news end def new @news = Blog.new @news.title = params[:title] @news.content = params[:content] @news.save redirect_to :action => 'admin' end def delete Blog.find(params[:id]).destroy redirect_to :action => 'admin' end def edit if request.post? @news = Blog.find(params[:id]) @news.title = params[:title] @news.content = params[:content] @news.created_at = params[:date] @news.save redirect_to '/news/admin' else @news = Blog.find(params[:id]) render :layout => false end end end \ No newline at end of file diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 02b0f5e..02b86cf 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,28 +1,125 @@ +require 'csv' + class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem + layout 'service' + before_filter :super_required, :only => [:staff] + before_filter :admin_required, :except => [:index, :edit, :bulk_add] + before_filter :login_required, :only => [:edit] + + def index + redirect_to '/' + end + + def admin + @in_admin_function = true + if !params[:id] + @user = User.paginate :page => params[:page] + else + @u = User.find(params[:id]) + render :partial => 'user_list_item' + end + end + def staff + @super_user = User.find(:all, :conditions => 'permission = 2') + @staff_user = User.find(:all, :conditions => 'permission = 1') + end - # render new.rhtml - def new - @user = User.new + def bulk_add + @in_admin_function = true + + if request.post? + csv = CSV.parse(params[:csv].read) + header = csv.shift + + # check reader + expect_header = ['login', 'email', 'password', 'name', 'student_id', 'student_class'] + pass = true + expect_header.each do |h| + pass = false if !header.include? h + end + + if !pass + error_stickie "匯入的欄位有缺失,請檢查CSV檔案!" + redirect_to :action => :bulk_add + return + end + + # read it + result = [] + csv.each do |row| + result << Hash[*header.zip(row.to_a).flatten] + end + + errors = [] + # add it + result.each do |r| + u = User.new(r) + u.password_confirmation = u.password + if !u.save + errors << "使用者 #{r["login"]} 無法新增,請檢查資料。" + end + end + + if errors != [] + error_stickie errors.join("<br/>") + end + notice_stickie("收到 #{result.size} 筆資料,成功新增 #{result.size - errors.size} 筆,失敗 #{errors.size} 筆。") + + redirect_to :action => :bulk_add + end end def create - logout_keeping_session! - @user = User.new(params[:user]) - success = @user && @user.save - if success && @user.errors.empty? - # Protects against session fixation attacks, causes request forgery - # protection if visitor resubmits an earlier form using back - # button. Uncomment if you understand the tradeoffs. - # reset session - self.current_user = @user # !! now logged in - redirect_back_or_default('/') - flash[:notice] = "Thanks for signing up! We're sending you an email with your activation code." + @user = User.new + @user.login = params[:login] + @user.password = params[:password] + @user.password_confirmation = params[:password_confirmation] + @user.student_id = params[:student_id] + @user.student_class = params[:student_class] + @user.name = params[:name] + @user.email = params[:email] + @user.nickname = params[:nickname] if params[:nickname] + if @user.save + notice_stickie "使用者 #{params[:login]} 建立成功" + else + error_stickie "無法建立使用者 #{params[:login]}<br/>#{@user.errors.inspect}" + end + + redirect_to :action => 'admin' + end + + def delete + User.find(params[:id]).destroy + redirect_to :action => 'admin' + end + + def edit + if request.post? + if @current_user.permission == 2 || @current_user.id == params[:id] + @user = User.find(params[:id]) + @user.student_id = params[:student_id] + @user.student_class = params[:student_class] + @user.name = params[:name] + @user.email = params[:email] + @user.nickname = params[:nickname] if params[:nickname] + @user.save + end + + if @current_user.permission > 0 + redirect_to '/users/admin' + else + redirect_to '/users/edit' + end else - flash[:error] = "We couldn't set up that account, sorry. Please try again, or contact an admin (link is above)." - render :action => 'new' + if @current_user.permission == 0 + @u = User.find(@current_user.id) + else + @u = User.find(params[:id]) + render :layout => false + end end end end diff --git a/app/models/blog.rb b/app/models/blog.rb index 0ad9473..c5569eb 100644 --- a/app/models/blog.rb +++ b/app/models/blog.rb @@ -1,2 +1,15 @@ +# == Schema Information +# Schema version: 20080926035923 +# +# Table name: blogs +# +# id :integer not null, primary key +# title :string(255) +# content :string(255) +# user_id :integer +# created_at :datetime +# updated_at :datetime +# + class Blog < ActiveRecord::Base end diff --git a/app/models/user.rb b/app/models/user.rb index 42f98d7..9ad9d01 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,54 +1,75 @@ +# == Schema Information +# Schema version: 20080926035923 +# +# Table name: users +# +# id :integer not null, primary key +# login :string(40) +# name :string(100) default("") +# email :string(100) +# crypted_password :string(40) +# salt :string(40) +# created_at :datetime +# updated_at :datetime +# remember_token :string(40) +# remember_token_expires_at :datetime +# student_class :string(255) +# student_id :string(255) +# nickname :string(255) +# permission :integer +# + require 'digest/sha1' class User < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100 validates_presence_of :email validates_length_of :email, :within => 6..100 #[email protected] validates_uniqueness_of :email validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message # HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. - attr_accessible :login, :email, :name, :password, :password_confirmation + attr_accessible :login, :email, :name, :password, :password_confirmation, :student_id, :student_class, :name # Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find_by_login(login) # need to get the salt u && u.authenticated?(password) ? u : nil end def login=(value) write_attribute :login, (value ? value.downcase : nil) end def email=(value) write_attribute :email, (value ? value.downcase : nil) end protected end diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index a2d18ae..2e5ea7b 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> <li <%='class="menu-current"' if @in_books_function%>><a href="#">搜尋書籍</a></li> <li <%='class="menu-current"' if @in_reader_function%>><a href="#">讀者服務</a></li> <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> <% if @current_user && @current_user.permission == 2%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> - <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">工作人員</span><% end %> + <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">系統管理員</span><% end %><% if @current_user.permission == 1 %><span style="color: red;">工作人員</span><% end %> <% else %> <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", :url => '/login' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> \ No newline at end of file diff --git a/app/views/news/_news_list_item.html.erb b/app/views/news/_news_list_item.html.erb index 3f0ced6..555dbf3 100644 --- a/app/views/news/_news_list_item.html.erb +++ b/app/views/news/_news_list_item.html.erb @@ -1,11 +1,11 @@ <div class="container"> <div class="span-3"><%[email protected]_at.strftime("%Y-%m-%d")%></div> <div class="span-15"><a href="#" id="btn-content-<%[email protected]%>" class="button no-text down" style="margin-right: 10px;" onclick="return toggle_content(this);"><span><span>&nbsp;</span></span></a><%[email protected]%></div> <div class="span-4 last"> - <p class="clearfix"><a href="#" class="button dark right" style="margin-right: 10px;" onclick="edit_news(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/news/delete/<%[email protected]%>" class="button pink minus" onclick="confirm('確定要刪除新聞 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> + <p class="clearfix"><a href="#" class="button dark right" style="margin-right: 10px;" onclick="edit_news(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/news/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除新聞 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> </div> </div> <div class="container" id="content-<%[email protected]%>" style="display: none;"> <div class="span-3">&nbsp;</div> <div class="span-19 last"><%[email protected]("\n", "<br/>")%></div> </div> diff --git a/app/views/news/admin.html.erb b/app/views/news/admin.html.erb index 4263726..ecbdfad 100644 --- a/app/views/news/admin.html.erb +++ b/app/views/news/admin.html.erb @@ -1,55 +1,56 @@ <h1>公告管理</h1> <p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#news-add').toggle('blind'); $('#news-add-form input[type=\'text\'], #news-add-form textarea').val(''); this.blur();"><span><span>新增公告</span></span></a><a href="/news" class="button green right"><span><span>前往圖書館部落格</span></span></a></p> <div id="news-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> <form action="/news/new" method="post" accept-charset="utf-8" id="news-add-form"> <p>公告標題<br/><input type="text" name="title" value="" id="title"></p> <p>公告內容<br/><textarea name="content" rows="8" cols="40"></textarea></p> <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> <p class="clearfix"><a href="#" class="button dark check" onclick="$('#news-add-form').submit(); this.blur();"><span><span>確定送出</span></span></a></p> </form> </div> <div id="news-list"> <div class="thead"> <div class="container"> <div class="span-3">日期</div> <div class="span-15">公告</div> <div class="span-4 last">行動</div> </div> </div> <% @news.each do |news| @n = news%> <div class="tbody" id="news-<%=news.id%>"> <%=render_partial "news_list_item"%> </div> <% end %> </div> +<%=will_paginate @news, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> <script type="text/javascript" charset="utf-8"> function toggle_content(e) { if ($(e).hasClass("down")) { $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); $(e).removeClass("down").addClass("up"); } else { $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); $(e).removeClass("up").addClass("down"); } return false; } function edit_news(id) { $('#btn-edit-' + id).children('span').children('span').html('...'); $.get('/news/edit/' + id, {}, function(data){ $('#news-' + id).html(data); }); } function restore_news(id) { $.get('/news/admin/' + id, {}, function(data){ $('#news-' + id).html(data); }) } </script> \ No newline at end of file diff --git a/app/views/users/_user_list_item.html.erb b/app/views/users/_user_list_item.html.erb new file mode 100644 index 0000000..d92e6de --- /dev/null +++ b/app/views/users/_user_list_item.html.erb @@ -0,0 +1,9 @@ +<div class="container"> + <div class="span-3"><%[email protected]_id%></div> + <div class="span-5"><%[email protected]%> <%if @u.permission == 2%><span style="color: red; font-size: small;">系統管理員</span><%end%><%if @u.permission == 1%><span style="color: red; font-size: small;">工作人員</span><%end%></div> + <div class="span-3"><%[email protected]_class%></div> + <div class="span-5"><%[email protected]%></div> + <div class="span-8 last"> + <p class="clearfix"><a href="#" class="button dark right" style="margin-right: 10px;" onclick="edit_user(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/users/details/<%[email protected]%>" class="button alt star" style="margin-right: 10px;" onclick="this.blur();" id="btn-detail-<%[email protected]%>"><span><span>詳細記錄</span></span></a><a href="/users/delete/<%[email protected]%>" class="button pink minus" onclick="return confirm('確定要刪除使用者 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> + </div> +</div> \ No newline at end of file diff --git a/app/views/users/admin.html.erb b/app/views/users/admin.html.erb new file mode 100644 index 0000000..56416a4 --- /dev/null +++ b/app/views/users/admin.html.erb @@ -0,0 +1,55 @@ +<h1>讀者資料查詢/ç¶­è­·</h1> +<p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#user-add').toggle('blind'); $('#user-add-form input[type=\'text\']').val(''); this.blur();"><span><span>新增讀者</span></span></a><a href="/users/bulk_add" class="button dark right"><span><span>大批新增讀者</span></span></a></p> + +<div id="user-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> + <form action="/users/create" method="post" accept-charset="utf-8" id="user-add-form"> + <div style="float: left;">登入帳號<br/><input type="text" name="login" id="login"></div> + <div style="float: left;">暱稱<br/><input type="text" name="nickname" value=">" id="nickname"></div> + <div style="clear: both;">&nbsp;</div> + <div style="float: left;">密碼<br/><input type="password" name="password" id="password"></div> + <div style="float: left;">確認密碼<br/><input type="password" name="password_confirmation" id="password_confirmation"></div> + <div style="clear: both;">&nbsp;</div> + <div style="float: left;">學生證號<br/><input type="text" name="student_id" value="" id="student_id"></div> + <div style="float: left;">班級<br/><input type="text" name="student_class" value="" id="student_class"></div> + <div style="clear: both;">&nbsp;</div> + <div style="float: left;">姓名<br/><input type="text" name="name" value="" id="name"></div> + <div style="float: left;">E-mail<br/><input type="text" name="email" value="" id="email"></div> + <div style="clear: both;">&nbsp;</div> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + <p class="clearfix"><a href="#" class="button normal plus" onclick="$('#user-add-form').submit(); this.blur(); return false;" style="margin-right: 10px;"><span><span>新增讀者</span></span></a></p> + </form> +</div> +<div id="user-list"> + <div class="thead"> + <div class="container"> + <div class="span-3">學號</div> + <div class="span-5">姓名</div> + <div class="span-3">班級</div> + <div class="span-5">電子郵件</div> + <div class="span-8 last">行動</div> + </div> + </div> + <% @user.each do |user| @u = user%> + <div class="tbody" id="user-<%=user.id%>"> + <%=render_partial "user_list_item"%> + </div> + <% end %> +</div> +<%=will_paginate @user, :previous_label => '&laquo; 上一頁', :next_label => '下一頁 &raquo;'%> + +<script type="text/javascript" charset="utf-8"> + function edit_user(id) + { + $('#btn-edit-' + id).children('span').children('span').html('...'); + $.get('/users/edit/' + id, {}, function(data){ + $('#user-' + id).html(data); + }); + } + + function restore_user(id) + { + $.get('/users/admin/' + id, {}, function(data){ + $('#user-' + id).html(data); + }) + } +</script> \ No newline at end of file diff --git a/app/views/users/bulk_add.html.erb b/app/views/users/bulk_add.html.erb new file mode 100644 index 0000000..949c8ad --- /dev/null +++ b/app/views/users/bulk_add.html.erb @@ -0,0 +1,17 @@ +<h1>大量新增讀者</h1> +您可以使用這個功能匯入CSV資料來快速建立讀者名單。請注意您的CSV資料必須包含以下欄位: +<ul> + <li>login - 帳號</li> + <li>email - 電子郵件地址</li> + <li>password - 密碼(需要六位以上)</li> + <li>name - 姓名</li> + <li>student_id - 學生證號</li> + <li>student_class - 學生系級(班級)</li> +</ul> +<h2>進行匯入</h2> +<form action="/users/bulk_add" method="post" accept-charset="utf-8" enctype="multipart/form-data"> + <p>CSV檔案<br/> + <input type="file" name="csv" id="csv"></p> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + <p><input type="submit" value="開始匯入 &rarr;"></p> +</form> \ No newline at end of file diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 0000000..829541b --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,12 @@ +<form action="/users/edit" method="post" accept-charset="utf-8" id="user-edit-form"> + 登入帳號:<%[email protected]%><br/> + <div style="float: left;">學生證號<br/><input type="text" name="student_id" value="<%[email protected]_id%>" id="student_id"></div> + <div style="float: left;">班級<br/><input type="text" name="student_class" value="<%[email protected]_class%>" id="student_class"></div> + <div style="clear: both;">&nbsp;</div> + <div style="float: left;">姓名<br/><input type="text" name="name" value="<%[email protected]%>" id="name"></div> + <div style="float: left;">E-mail<br/><input type="text" name="email" value="<%[email protected]%>" id="email"></div> + <div style="clear: both;">&nbsp;</div> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + <input type="hidden" name="id" value="<%[email protected]%>" id="id"> + <p class="clearfix"><a href="#" class="button normal check" onclick="$('#user-edit-form').submit(); this.blur(); return false;" style="margin-right: 10px;"><span><span>儲存修改</span></span></a> <a href="#" class="button dark x" onclick="restore_user(<%[email protected]%>); return false;"><span><span>取消</span></span></a></p> +</form> diff --git a/app/views/users/staff.html.erb b/app/views/users/staff.html.erb new file mode 100644 index 0000000..7813b75 --- /dev/null +++ b/app/views/users/staff.html.erb @@ -0,0 +1,25 @@ +<h1>工作人員權限管理</h1> + +<div id="staff-add" style="margin: 10px; border: 2px solid #00F; padding: 10px; width: 250px; height: 80px;"> + <p>讀者帳號:<input type="text" name="id" id="id"><br/> + 目標權限:<select name="permission"><option value="1">工作人員</option><option value="2">系統管理員</option></select></p> + <p class="clearfix" style="margin-top: -20px;"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#staff-add').toggle('blind'); $('#staff-add input[type=\'text\']').val(''); this.blur();"><span><span>提昇讀者權限為工作人員</span></span></a></p> +</div> + +<h2>工作人員名單</h2> +<div id="staff-list"> + <div class="thead"> + <div class="container"> + <div class="span-3">學號</div> + <div class="span-5">姓名</div> + <div class="span-3">班級</div> + <div class="span-5">電子郵件</div> + <div class="span-8 last">行動</div> + </div> + </div> + <% @user.each do |user| @u = user%> + <div class="tbody" id="user-<%=user.id%>"> + <%=render_partial "user_list_item"%> + </div> + <% end %> +</div> diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb index cb09dc7..d12115f 100644 --- a/app/views/welcome/admin.html.erb +++ b/app/views/welcome/admin.html.erb @@ -1,35 +1,35 @@ <div class="bkgwhite"> <div class="container"> <div class="span-11"> <p class="admin-title">圖書管理</p> <div class="admin-menu"> <a href="#">搜尋/維護館藏<span class="arrow">&raquo;</span></a> <a href="#">新增館藏<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">館藏流通</p> <div class="admin-menu"> <a href="#">借閱/還書介面<span class="arrow">&raquo;</span></a> <a href="#">列出逾期書籍<span class="arrow">&raquo;</span></a> </div> </div> </div> <div class="container" style="margin-top: 10px;"> <div class="span-11"> <p class="admin-title">讀者資料</p> <div class="admin-menu"> - <a href="#">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> - <a href="#">(大批)新增讀者<span class="arrow">&raquo;</span></a> + <a href="/users/admin">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> + <a href="/users/bulk_add">大批新增讀者<span class="arrow">&raquo;</span></a> </div> </div> <div class="span-12 last"> <p class="admin-title">公告及其他</p> <div class="admin-menu"> <a href="/news/admin">公告管理<span class="arrow">&raquo;</span></a> - <a href="#">工作人員權限管理<span class="arrow">&raquo;</span></a> + <a href="/users/staff">工作人員權限管理<span class="arrow">&raquo;</span></a> </div> </div> </div> </div> \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index f4c7966..2dea73c 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,67 +1,68 @@ # Be sure to restart your server when you modify this file # Uncomment below to force Rails into production mode when # you don't control web/app server and can't set it the proper way # ENV['RAILS_ENV'] ||= 'production' # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.1.1' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" + config.gem 'mislav-will_paginate', :version => '~> 2.3.4', :lib => 'will_paginate', :source => 'http://gems.github.com' # Only load the plugins named here, in the order given. By default, all plugins # in vendor/plugins are loaded in alphabetical order. # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :session_key => '_2009csc_session', :secret => '0c1f79921db05b13c29c624d9d62f900aca73ce1c3a4c8b8afd5269b1af99ebaaf1aacfc01469d49f6a553f5f8a63ebc022d2f32407e4ec4124a995a8aac7c96' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector end diff --git a/config/routes.rb b/config/routes.rb index 969d17d..dd28539 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,52 +1,51 @@ ActionController::Routing::Routes.draw do |map| map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' - map.resources :users map.resource :session # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. map.admin '/admin', :controller => "welcome", :action => 'admin' map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index e6dfe6f..e5b2e0a 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,231 +1,261 @@ /* layout */ body { background-color: #7C6255; font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; font-size: 11pt; } h1 { border-bottom: 1px solid #CCC; } h2 { margin: 0; } #content { background-color: #FFF; padding: 10px; margin-top: -10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; border-left: 1px solid #FFF; border-top: 1px solid #FFF; border-right: 1px solid #FFF; background-color: #222; background-image: -webkit-gradient(linear, left top, left bottom, from(#666), to(#222)); padding: 5px; padding-top: 60px; margin-left: -1px; } #header-title ul li a { color: #fff; } #header-title ul li:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#444)); background-color: #444; } .menu-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#FFF)) !important; background-color: #FFF !important; } .menu-current a { color: #000 !important; } .menu-backstage { background-image: -webkit-gradient(linear, left top, left bottom, from(#C30017), to(#73000E)) !important; background-color: #73000E !important; } .menu-backstage:hover { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#B20014)) !important; background-color: #920011 !important; } .menu-backstage-current { background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#FFF), color-stop(0.8, #FFF)) !important; background-color: #FFF !important; } .menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; color: #FFF; word-spacing: 4px; font-family: Helvetica; } /* admin css */ .admin-title { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#C17436), to(#A9652F)); background-color: #C17436; color: #FFF; font-size: 2em; border-top: 1px solid #000; border-left: 1px solid #000; border-right: 1px solid #000; } .admin-menu { margin: 0; padding: 0; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; font-size: 1.75em; } .admin-menu a { display: block; padding: 2px; } .admin-menu .arrow { float: right; } .admin-menu a:hover { display: block; background-image: -webkit-gradient(linear, left top, left bottom, from(#0000FF), to(#000099)) !important; background-color: #000099; color: #FFF; text-decoration: none; } /* news(blog) css */ #news-list { font-size: 1.25em; border-bottom: 1px solid #000; } #news-list .thead { border-top: 1px solid #000; font-size: 1.25em; border-bottom: 1px dashed #000; } #news-list .tbody { border-top: 1px dashed #000; margin-top: -1px; } #news-list .tbody .container div { line-height: 30px; } #news-list .tbody .container p.clearfix { margin: 0px; } #news-list .tbody .container a.button { margin-top: 2px; } form input { font-size: 22pt; } +form input[type="file"] { + font-size: 1em !important; +} + form textarea { font-size: 18pt; } /* blog front */ .blog-date { display: block; margin: 0; padding: 2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#444), to(#000)); background-color: #000; color: #FFF; letter-spacing: 0.3em; } .blog-title { font-size: 2em; color: rgb(99, 60, 17); margin: 0px; } .blog-content { margin-left: 10px; text-indent: 2em; } /* sidebar */ #sidebar { width: 230px; height: 600px; background: url('../images/bkg_blackboard.jpg') repeat-y; color: white; padding: 10px; padding-right: 35px; margin-left: -10px; -webkit-box-shadow: 0px 3px 5px black; -moz-box-shadow: 0px 3px 5px black; position: relative; float: left; } #sidebar { /* Damn IE fix */ height: auto; min-height: 600px; } #sidebar #metal_holder { width: 68px; height: 213px; background: url('../images/img_blackboard_holder.png') no-repeat; position: absolute; top: 200px; left: 240px; } #sidebar h1 { color: #FFF; border: none; -} \ No newline at end of file +} + +/* pagination */ +.pagination { + margin: 5px; + font-size: 1.2em; +} + +.pagination * { + padding: 2px; +} + +.pagination a { + border: 1px solid #00F; +} + +.pagination a:hover { + border: 1px solid #00F; + background-color: #00A; + color: #FFF; +} + +.pagination span.current { + border: 1px solid #00E; + background-color: #00F; + color: #FFF; +} diff --git a/sample.csv b/sample.csv new file mode 100644 index 0000000..0127aa2 --- /dev/null +++ b/sample.csv @@ -0,0 +1,3 @@ +login,email,password,name,student_id,student_class +csvuser,[email protected],123456,csv1,123456,TEST02 +csvuser2,[email protected],123,csv2,123456,TEST02 diff --git a/test/fixtures/blogs.yml b/test/fixtures/blogs.yml index 5bf0293..e1f2572 100644 --- a/test/fixtures/blogs.yml +++ b/test/fixtures/blogs.yml @@ -1,7 +1,20 @@ +# == Schema Information +# Schema version: 20080926035923 +# +# Table name: blogs +# +# id :integer not null, primary key +# title :string(255) +# content :string(255) +# user_id :integer +# created_at :datetime +# updated_at :datetime +# + # Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html # one: # column: value # # two: # column: value diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml index f179a32..88dbf00 100644 --- a/test/fixtures/users.yml +++ b/test/fixtures/users.yml @@ -1,31 +1,52 @@ +# == Schema Information +# Schema version: 20080926035923 +# +# Table name: users +# +# id :integer not null, primary key +# login :string(40) +# name :string(100) default("") +# email :string(100) +# crypted_password :string(40) +# salt :string(40) +# created_at :datetime +# updated_at :datetime +# remember_token :string(40) +# remember_token_expires_at :datetime +# student_class :string(255) +# student_id :string(255) +# nickname :string(255) +# permission :integer +# + quentin: id: 1 login: quentin email: [email protected] salt: 356a192b7913b04c54574d18c28d46e6395428ab # SHA1('0') crypted_password: faedaa6fa5d3546428f8b5a7a36bb4795cc242ff # 'monkey' created_at: <%= 5.days.ago.to_s :db %> remember_token_expires_at: <%= 1.days.from_now.to_s %> remember_token: 77de68daecd823babbb58edb1c8e14d7106e83bb aaron: id: 2 login: aaron email: [email protected] salt: da4b9237bacccdf19c0760cab7aec4a8359010b0 # SHA1('1') crypted_password: e10a09b117dc45d9605357f0d5a88517b83e1f72 # 'monkey' created_at: <%= 1.days.ago.to_s :db %> remember_token_expires_at: remember_token: old_password_holder: id: 3 login: old_password_holder email: [email protected] salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test created_at: <%= 1.days.ago.to_s :db %>
itszero/eLib2
3ecc8bd5ee5ce7904cb54f861ee61e2464db8b3c
blog done.
diff --git a/app/controllers/application.rb b/app/controllers/application.rb index 94d3b92..88e1376 100644 --- a/app/controllers/application.rb +++ b/app/controllers/application.rb @@ -1,28 +1,29 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base include FaceboxRender + include AuthenticatedSystem helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details # Uncomment the :secret if you're not using the cookie session store protect_from_forgery # :secret => 'ce44bb469671dfe6809abe1eb0fe97bd' # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters # from your application log (in this case, all fields with names like "password"). # filter_parameter_logging :password before_filter :get_sessions after_filter :set_sessions private def get_sessions @current_user = session[:current_user] end def set_sessions session[:current_user] = @current_user end end diff --git a/app/controllers/news_controller.rb b/app/controllers/news_controller.rb new file mode 100644 index 0000000..63f17de --- /dev/null +++ b/app/controllers/news_controller.rb @@ -0,0 +1,55 @@ +class NewsController < ApplicationController + layout 'service' + before_filter :admin_required, :except => [:index, :show] + + def index + @in_reader_function = true + @news = Blog.find(:all, :order => "created_at DESC") + end + + def admin + @in_admin_function = true + + if !params[:id] + @news = Blog.find(:all, :order => "created_at DESC") + else + @n = Blog.find(params[:id]) + render :partial => 'news_list_item' + end + end + + def show + @in_reader_function = true + @news = Blog.find(params[:id]) + warning_stickie "找不到您指定的新聞。" if !@news + redirect_to '/news' if !@news + end + + def new + @news = Blog.new + @news.title = params[:title] + @news.content = params[:content] + @news.save + + redirect_to :action => 'admin' + end + + def delete + Blog.find(params[:id]).destroy + redirect_to :action => 'admin' + end + + def edit + if request.post? + @news = Blog.find(params[:id]) + @news.title = params[:title] + @news.content = params[:content] + @news.created_at = params[:date] + @news.save + redirect_to '/news/admin' + else + @news = Blog.find(params[:id]) + render :layout => false + end + end +end \ No newline at end of file diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb index 316ca9a..73c8a31 100644 --- a/app/controllers/welcome_controller.rb +++ b/app/controllers/welcome_controller.rb @@ -1,11 +1,13 @@ class WelcomeController < ApplicationController layout 'service' + before_filter :admin_required, :only => :admin def index @in_homepage_function = true + @news = Blog.find(:all, :order => "created_at DESC", :limit => 5) end def admin @in_admin_function = true end end diff --git a/app/helpers/news_helper.rb b/app/helpers/news_helper.rb new file mode 100644 index 0000000..9877c33 --- /dev/null +++ b/app/helpers/news_helper.rb @@ -0,0 +1,2 @@ +module NewsHelper +end diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index 3975eb6..a2d18ae 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,61 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png"/> </div> <div class="span-11 last" id="header-title"> <ul> <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> <li <%='class="menu-current"' if @in_books_function%>><a href="#">搜尋書籍</a></li> <li <%='class="menu-current"' if @in_reader_function%>><a href="#">讀者服務</a></li> <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> <% if @current_user && @current_user.permission == 2%> <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> - 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">工作人員</span> <%end%>: <a href="/logout">登出 <img src="/images/img_power.png" width="20" height="20" align="top"></a> + <a href="/logout"><img src="/images/img_power.png" width="20" height="20">登出</a> 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">工作人員</span><% end %> <% else %> - 使用個人化服務,請先 <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", :url => '/login' %> + <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", :url => '/login' %> 後才能使用使用個人化服務。 <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> \ No newline at end of file diff --git a/app/views/news/_news_list_item.html.erb b/app/views/news/_news_list_item.html.erb new file mode 100644 index 0000000..3f0ced6 --- /dev/null +++ b/app/views/news/_news_list_item.html.erb @@ -0,0 +1,11 @@ +<div class="container"> + <div class="span-3"><%[email protected]_at.strftime("%Y-%m-%d")%></div> + <div class="span-15"><a href="#" id="btn-content-<%[email protected]%>" class="button no-text down" style="margin-right: 10px;" onclick="return toggle_content(this);"><span><span>&nbsp;</span></span></a><%[email protected]%></div> + <div class="span-4 last"> + <p class="clearfix"><a href="#" class="button dark right" style="margin-right: 10px;" onclick="edit_news(<%[email protected]%>); this.blur(); return false;" id="btn-edit-<%[email protected]%>"><span><span>編輯</span></span></a><a href="/news/delete/<%[email protected]%>" class="button pink minus" onclick="confirm('確定要刪除新聞 「<%[email protected]%>」 嗎?')"><span><span>刪除</span></span></a></p> + </div> +</div> +<div class="container" id="content-<%[email protected]%>" style="display: none;"> + <div class="span-3">&nbsp;</div> + <div class="span-19 last"><%[email protected]("\n", "<br/>")%></div> +</div> diff --git a/app/views/news/admin.html.erb b/app/views/news/admin.html.erb new file mode 100644 index 0000000..4263726 --- /dev/null +++ b/app/views/news/admin.html.erb @@ -0,0 +1,55 @@ +<h1>公告管理</h1> +<p class="clearfix"><a href="#" class="button pink plus" style="margin-right: 10px;" onclick="$('#news-add').toggle('blind'); $('#news-add-form input[type=\'text\'], #news-add-form textarea').val(''); this.blur();"><span><span>新增公告</span></span></a><a href="/news" class="button green right"><span><span>前往圖書館部落格</span></span></a></p> +<div id="news-add" style="display: none; border-left: 10px solid #333; margin-left: 5px; padding-left: 5px;"> + <form action="/news/new" method="post" accept-charset="utf-8" id="news-add-form"> + <p>公告標題<br/><input type="text" name="title" value="" id="title"></p> + <p>公告內容<br/><textarea name="content" rows="8" cols="40"></textarea></p> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + <p class="clearfix"><a href="#" class="button dark check" onclick="$('#news-add-form').submit(); this.blur();"><span><span>確定送出</span></span></a></p> + </form> +</div> +<div id="news-list"> + <div class="thead"> + <div class="container"> + <div class="span-3">日期</div> + <div class="span-15">公告</div> + <div class="span-4 last">行動</div> + </div> + </div> + <% @news.each do |news| @n = news%> + <div class="tbody" id="news-<%=news.id%>"> + <%=render_partial "news_list_item"%> + </div> + <% end %> +</div> + +<script type="text/javascript" charset="utf-8"> + function toggle_content(e) + { + if ($(e).hasClass("down")) { + $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); + $(e).removeClass("down").addClass("up"); + } + else + { + $('#' + $(e).attr('id').replace('btn-', '')).toggle('blind'); + $(e).removeClass("up").addClass("down"); + } + return false; + } + + function edit_news(id) + { + $('#btn-edit-' + id).children('span').children('span').html('...'); + $.get('/news/edit/' + id, {}, function(data){ + $('#news-' + id).html(data); + }); + } + + function restore_news(id) + { + $.get('/news/admin/' + id, {}, function(data){ + $('#news-' + id).html(data); + }) + } +</script> \ No newline at end of file diff --git a/app/views/news/edit.html.erb b/app/views/news/edit.html.erb new file mode 100644 index 0000000..85baf51 --- /dev/null +++ b/app/views/news/edit.html.erb @@ -0,0 +1,9 @@ +<form action="/news/edit" method="post" accept-charset="utf-8" id="news-edit-form"> + <div style="float: left;">公告標題<br/><input type="text" name="title" value="<%[email protected]%>" id="title"></div> + <div style="float: left;">公告日期<br/><input type="text" name="date" value="<%[email protected]_at.strftime("%Y-%m-%d")%>" id="date"></div> + <div style="clear: both;">&nbsp;</div> + <p>公告內容<br/><textarea name="content" rows="8"><%[email protected]%></textarea></p> + <input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>" id="authenticity_token"> + <input type="hidden" name="id" value="<%[email protected]%>" id="id"> + <p class="clearfix"><a href="#" class="button normal check" onclick="$('#news-edit-form').submit(); this.blur(); return false;" style="margin-right: 10px;"><span><span>儲存修改</span></span></a> <a href="#" class="button dark x" onclick="restore_news(<%[email protected]%>); return false;"><span><span>取消</span></span></a></p> +</form> diff --git a/app/views/news/index.html.erb b/app/views/news/index.html.erb new file mode 100644 index 0000000..045e591 --- /dev/null +++ b/app/views/news/index.html.erb @@ -0,0 +1,38 @@ +<!-- YUI css --> +<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/calendar/assets/skins/sam/calendar.css"> +<!-- YUI js --> +<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/calendar/calendar-min.js"></script> + +<h1>圖書館部落格</h1> +<div class="container"> + <div class="span-8"> + <div id="sidebar"> + <h1>月曆</h1> + <div id="calendar_panel" class="blog_panel yui-skin-sam"> + <div id="cal1Container"></div> + <span class="clear"></span> + </div> + <div id="metal_holder">&nbsp;</div> + </div> + </div> + <div class="span-15 last"> + <% @news.each do |news| %> + <p class="blog-date"><%=news.created_at.strftime("%Yå¹´%m月%d日")%></p> + <p class="blog-title"><%=news.title%></p> + <p class="blog-content"><%=news.content.gsub("\n", "<br/>")%></p> + <% end %> + </div> +</div> +<script type="text/javascript" charset="utf-8"> + var cal1 = new YAHOO.widget.Calendar("cal1Container"); + cal1.cfg.setProperty("DATE_FIELD_DELIMITER", "."); + cal1.cfg.setProperty("navigator", true); + cal1.cfg.setProperty("MONTHS_SHORT", ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]); + cal1.cfg.setProperty("MONTHS_LONG", ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]); + cal1.cfg.setProperty("WEEKDAYS_1CHAR", ["S", "M", "D", "M", "D", "F", "S"]); + cal1.cfg.setProperty("WEEKDAYS_SHORT", ["日", "一", "二", "三", "四", "五", "六"]); + cal1.cfg.setProperty("WEEKDAYS_MEDIUM",["週日", "週一", "週二", "週三", "週四", "週五", "週六"]); + cal1.cfg.setProperty("WEEKDAYS_LONG", ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]); + + cal1.render(); +</script> \ No newline at end of file diff --git a/app/views/news/show.html.erb b/app/views/news/show.html.erb new file mode 100644 index 0000000..0c27fb6 --- /dev/null +++ b/app/views/news/show.html.erb @@ -0,0 +1,14 @@ +<!-- YUI css --> +<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/calendar/assets/skins/sam/calendar.css"> +<!-- YUI js --> +<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/calendar/calendar-min.js"></script> + +<h1>圖書館部落格</h1> +<div class="container"> + <div class="span-23 last"> + <a href="/news">&larr; 回圖書館部落格</a> + <p class="blog-date"><%[email protected]_at.strftime("%Yå¹´%m月%d日")%></p> + <p class="blog-title"><%[email protected]%></p> + <p class="blog-content"><%[email protected]("\n", "<br/>")%></p> + </div> +</div> diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb index ca07389..cb09dc7 100644 --- a/app/views/welcome/admin.html.erb +++ b/app/views/welcome/admin.html.erb @@ -1,33 +1,35 @@ -<div class="container"> - <div class="span-11"> - <p class="admin-title">圖書管理</p> - <div class="admin-menu"> - <a href="#">搜尋/維護館藏<span class="arrow">&raquo;</span></a> - <a href="#">新增館藏<span class="arrow">&raquo;</span></a> +<div class="bkgwhite"> + <div class="container"> + <div class="span-11"> + <p class="admin-title">圖書管理</p> + <div class="admin-menu"> + <a href="#">搜尋/維護館藏<span class="arrow">&raquo;</span></a> + <a href="#">新增館藏<span class="arrow">&raquo;</span></a> + </div> </div> - </div> - <div class="span-12 last"> - <p class="admin-title">館藏流通</p> - <div class="admin-menu"> - <a href="#">借閱/還書介面<span class="arrow">&raquo;</span></a> - <a href="#">列出愈期書籍<span class="arrow">&raquo;</span></a> + <div class="span-12 last"> + <p class="admin-title">館藏流通</p> + <div class="admin-menu"> + <a href="#">借閱/還書介面<span class="arrow">&raquo;</span></a> + <a href="#">列出逾期書籍<span class="arrow">&raquo;</span></a> + </div> </div> </div> -</div> -<div class="container" style="margin-top: 10px;"> - <div class="span-11"> - <p class="admin-title">讀者資料</p> - <div class="admin-menu"> - <a href="#">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> - <a href="#">(大批)新增讀者<span class="arrow">&raquo;</span></a> + <div class="container" style="margin-top: 10px;"> + <div class="span-11"> + <p class="admin-title">讀者資料</p> + <div class="admin-menu"> + <a href="#">讀者資料查詢/ç¶­è­·<span class="arrow">&raquo;</span></a> + <a href="#">(大批)新增讀者<span class="arrow">&raquo;</span></a> + </div> </div> - </div> - <div class="span-12 last"> - <p class="admin-title">公告及其他</p> - <div class="admin-menu"> - <a href="#">公告維護<span class="arrow">&raquo;</span></a> - <a href="#">工作人員權限管理<span class="arrow">&raquo;</span></a> + <div class="span-12 last"> + <p class="admin-title">公告及其他</p> + <div class="admin-menu"> + <a href="/news/admin">公告管理<span class="arrow">&raquo;</span></a> + <a href="#">工作人員權限管理<span class="arrow">&raquo;</span></a> + </div> </div> </div> </div> \ No newline at end of file diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb index 83638a9..92a311d 100644 --- a/app/views/welcome/index.html.erb +++ b/app/views/welcome/index.html.erb @@ -1,15 +1,35 @@ <div style="text-align: center; border: 1px solid #000; width:900px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="iTunesAlbumArt" align="middle" width="900" height="329"> <param name="allowScriptAccess" value="always"> <param name="allowFullScreen" value="false"> <param name="movie" value="iTunesAlbumArt.swf"> <param name="quality" value="high"> <param name="bgcolor" value="#000000"> <embed sap-type="flash" sap-mode="checked" sap="flash" src="/coverflow/iTunesAlbumArt.swf" quality="high" bgcolor="#000000" name="iTunesAlbumArt" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" width="900" height="329"> </object> </div> + <div class="container" style="margin-top: 5px;"> - <div class="span-11" style="padding: 5px; border-right: 2px dashed #000; height: 300px;"></div> - <div class="span-12 last"></div> + <div class="span-11" style="padding-right: 5px; border-right: 2px dashed #000;"> + <h2>圖書館部落格</h2> + <ul style="margin-left: 30px;"> + <% @news.each do |news| %> + <li id="news-<%=news.id%>"><a href="/news/show/<%=news.id%>"><%=news.title%></a> - <%=news.created_at.strftime("%Y-%m-%d")%></li> + <% end %> + </ul> + <%=link_to '更多消息...', :controller => 'news'%> + </div> + <div class="span-12 last"> + <% if @current_user %> + <h2>資訊快遞</h2> + <ul style="margin-left: 30px;"> + <li>您目前共借閱 5 本書,2 本書即將到期。</li> + <li>您還需要繳交 3 篇讀書心得。</li> + </ul> + <%=link_to '詳細資訊...', :controller => 'reader'%> + <% else %> + <h2>熱門書籍</h2> + <% end %> + </div> </div> \ No newline at end of file diff --git a/lib/authenticated_system.rb b/lib/authenticated_system.rb index 8e43e4c..894bf13 100644 --- a/lib/authenticated_system.rb +++ b/lib/authenticated_system.rb @@ -1,193 +1,201 @@ module AuthenticatedSystem protected # Returns true or false if the user is logged in. # Preloads @current_user with the user model if they're logged in. def logged_in? !!current_user end # Accesses the current user from the session. # Future calls avoid the database because nil is not equal to false. def current_user @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false end # Store the given user id in the session. def current_user=(new_user) session[:user_id] = new_user ? new_user.id : nil @current_user = new_user || false end # Check if the user is authorized # # Override this method in your controllers if you want to restrict access # to only a few actions or if you want to check if the user # has the correct rights. # # Example: # # # only allow nonbobs # def authorized? # current_user.login != "bob" # end # def authorized?(action = action_name, resource = nil) logged_in? end # Filter method to enforce a login requirement. # # To require logins for all actions, use this in your controllers: # # before_filter :login_required # # To require logins for specific actions, use this in your controllers: # # before_filter :login_required, :only => [ :edit, :update ] # # To skip this in a subclassed controller: # # skip_before_filter :login_required # def login_required authorized? || access_denied end + + def admin_required + authorized? && @current_user.permission >= 1 + end + + def super_required + authorized? && @current_user.permission >= 2 + end # Redirect as appropriate when an access request fails. # # The default action is to redirect to the login screen. # # Override this method in your controllers if you want to have special # behavior in case the user is not authorized # to access the requested action. For example, a popup window might # simply close itself. def access_denied respond_to do |format| format.html do store_location redirect_to new_session_path end # format.any doesn't work in rails version < http://dev.rubyonrails.org/changeset/8987 # Add any other API formats here. (Some browsers, notably IE6, send Accept: */* and trigger # the 'format.any' block incorrectly. See http://bit.ly/ie6_borken or http://bit.ly/ie6_borken2 # for a workaround.) format.any(:json, :xml) do request_http_basic_authentication 'Web Password' end end end # Store the URI of the current request in the session. # # We can return to this location by calling #redirect_back_or_default. def store_location session[:return_to] = request.request_uri end # Redirect to the URI stored by the most recent store_location call or # to the passed default. Set an appropriately modified # after_filter :store_location, :only => [:index, :new, :show, :edit] # for any controller you want to be bounce-backable. def redirect_back_or_default(default, facebox=false) if (facebox) redirect_from_facebox(session[:return_to] || default) else redirect_to(session[:return_to] || default) end session[:return_to] = nil end # Inclusion hook to make #current_user and #logged_in? # available as ActionView helper methods. def self.included(base) base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method end # # Login # # Called from #current_user. First attempt to login by the user id stored in the session. def login_from_session self.current_user = User.find_by_id(session[:user_id]) if session[:user_id] end # Called from #current_user. Now, attempt to login by basic authentication information. def login_from_basic_auth authenticate_with_http_basic do |login, password| self.current_user = User.authenticate(login, password) end end # # Logout # # Called from #current_user. Finaly, attempt to login by an expiring token in the cookie. # for the paranoid: we _should_ be storing user_token = hash(cookie_token, request IP) def login_from_cookie user = cookies[:auth_token] && User.find_by_remember_token(cookies[:auth_token]) if user && user.remember_token? self.current_user = user handle_remember_cookie! false # freshen cookie token (keeping date) self.current_user end end # This is ususally what you want; resetting the session willy-nilly wreaks # havoc with forgery protection, and is only strictly necessary on login. # However, **all session state variables should be unset here**. def logout_keeping_session! # Kill server-side auth cookie @current_user.forget_me if @current_user.is_a? User @current_user = false # not logged in, and don't do it for me kill_remember_cookie! # Kill client-side auth cookie session[:user_id] = nil # keeps the session but kill our variable # explicitly kill any other session variables you set end # The session should only be reset at the tail end of a form POST -- # otherwise the request forgery protection fails. It's only really necessary # when you cross quarantine (logged-out to logged-in). def logout_killing_session! logout_keeping_session! reset_session end # # Remember_me Tokens # # Cookies shouldn't be allowed to persist past their freshness date, # and they should be changed at each login # Cookies shouldn't be allowed to persist past their freshness date, # and they should be changed at each login def valid_remember_cookie? return nil unless @current_user (@current_user.remember_token?) && (cookies[:auth_token] == @current_user.remember_token) end # Refresh the cookie auth token if it exists, create it otherwise def handle_remember_cookie!(new_cookie_flag) return unless @current_user case when valid_remember_cookie? then @current_user.refresh_token # keeping same expiry date when new_cookie_flag then @current_user.remember_me else @current_user.forget_me end send_remember_cookie! end def kill_remember_cookie! cookies.delete :auth_token end def send_remember_cookie! cookies[:auth_token] = { :value => @current_user.remember_token, :expires => @current_user.remember_token_expires_at } end end diff --git a/public/albuminfo.xml b/public/albuminfo.xml index a456997..94eca5c 100644 --- a/public/albuminfo.xml +++ b/public/albuminfo.xml @@ -1,9 +1,23 @@ <artworkinfo> <albuminfo> - <artLocation>images/books/test.jpg</artLocation> + <artLocation>images/books/test.png</artLocation> + <artist>fake Steve Jobs</artist> + <albumName>老子賺番了</albumName> + <artistLink>http://www.books.com.tw/exep/activity/activity.php?id=0000015854&amp;sid=0000015854&amp;page=1</artistLink> + <albumLink>http://www.books.com.tw/exep/activity/activity.php?id=0000015854&amp;sid=0000015854&amp;page=1</albumLink> + </albuminfo> + <albuminfo> + <artLocation>images/books/test.png</artLocation> + <artist>fake Steve Jobs</artist> + <albumName>老子賺番了</albumName> + <artistLink>http://www.books.com.tw/exep/activity/activity.php?id=0000015854&amp;sid=0000015854&amp;page=1</artistLink> + <albumLink>http://www.books.com.tw/exep/activity/activity.php?id=0000015854&amp;sid=0000015854&amp;page=1</albumLink> + </albuminfo> + <albuminfo> + <artLocation>images/books/test.png</artLocation> <artist>fake Steve Jobs</artist> <albumName>老子賺番了</albumName> <artistLink>http://www.books.com.tw/exep/activity/activity.php?id=0000015854&amp;sid=0000015854&amp;page=1</artistLink> <albumLink>http://www.books.com.tw/exep/activity/activity.php?id=0000015854&amp;sid=0000015854&amp;page=1</albumLink> </albuminfo> </artworkinfo> diff --git a/public/dispatch.cgi b/public/dispatch.cgi old mode 100755 new mode 100644 diff --git a/public/dispatch.fcgi b/public/dispatch.fcgi old mode 100755 new mode 100644 diff --git a/public/dispatch.rb b/public/dispatch.rb old mode 100755 new mode 100644 diff --git a/public/facebox/closelabel.gif b/public/facebox/closelabel.gif old mode 100755 new mode 100644 diff --git a/public/facebox/loading.gif b/public/facebox/loading.gif old mode 100755 new mode 100644 diff --git a/public/images/bkg_blackboard.jpg b/public/images/bkg_blackboard.jpg new file mode 100644 index 0000000..b88ed03 Binary files /dev/null and b/public/images/bkg_blackboard.jpg differ diff --git a/public/images/bkg_cabinet.png b/public/images/bkg_cabinet.png new file mode 100644 index 0000000..9b8a49b Binary files /dev/null and b/public/images/bkg_cabinet.png differ diff --git a/public/images/books/test.png b/public/images/books/test.png new file mode 100644 index 0000000..13a880e Binary files /dev/null and b/public/images/books/test.png differ diff --git a/public/images/img_blackboard_holder.png b/public/images/img_blackboard_holder.png new file mode 100644 index 0000000..107d389 Binary files /dev/null and b/public/images/img_blackboard_holder.png differ diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index a3ac598..e6dfe6f 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,121 +1,231 @@ /* layout */ body { background-color: #7C6255; font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; + font-size: 11pt; +} + +h1 { + border-bottom: 1px solid #CCC; +} + +h2 { + margin: 0; } #content { background-color: #FFF; - -moz-border-radius: 10px; - -webkit-border-radius: 10px; padding: 10px; margin-top: -10px; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; border-left: 1px solid #FFF; border-top: 1px solid #FFF; border-right: 1px solid #FFF; background-color: #222; + background-image: -webkit-gradient(linear, left top, left bottom, from(#666), to(#222)); padding: 5px; padding-top: 60px; margin-left: -1px; } #header-title ul li a { color: #fff; } #header-title ul li:hover { + background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#444)); background-color: #444; } .menu-current { + background-image: -webkit-gradient(linear, left top, left bottom, from(#AAA), to(#FFF)) !important; background-color: #FFF !important; } .menu-current a { color: #000 !important; } .menu-backstage { + background-image: -webkit-gradient(linear, left top, left bottom, from(#C30017), to(#73000E)) !important; background-color: #73000E !important; } .menu-backstage:hover { + background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#B20014)) !important; background-color: #920011 !important; } .menu-backstage-current { + background-image: -webkit-gradient(linear, left top, left bottom, from(#FF001D), to(#FFF), color-stop(0.8, #FFF)) !important; background-color: #FFF !important; } .menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; color: #FFF; word-spacing: 4px; font-family: Helvetica; } /* admin css */ .admin-title { display: block; margin: 0; padding: 2px; + background-image: -webkit-gradient(linear, left top, left bottom, from(#C17436), to(#A9652F)); background-color: #C17436; color: #FFF; font-size: 2em; border-top: 1px solid #000; border-left: 1px solid #000; border-right: 1px solid #000; } .admin-menu { margin: 0; padding: 0; border-left: 1px solid #000; border-right: 1px solid #000; border-bottom: 1px solid #000; font-size: 1.75em; } .admin-menu a { display: block; padding: 2px; } .admin-menu .arrow { float: right; } .admin-menu a:hover { display: block; + background-image: -webkit-gradient(linear, left top, left bottom, from(#0000FF), to(#000099)) !important; background-color: #000099; color: #FFF; text-decoration: none; +} + +/* news(blog) css */ +#news-list { + font-size: 1.25em; + border-bottom: 1px solid #000; +} + +#news-list .thead { + border-top: 1px solid #000; + font-size: 1.25em; + border-bottom: 1px dashed #000; +} + +#news-list .tbody { + border-top: 1px dashed #000; + margin-top: -1px; +} + +#news-list .tbody .container div { + line-height: 30px; +} + +#news-list .tbody .container p.clearfix { + margin: 0px; +} + +#news-list .tbody .container a.button { + margin-top: 2px; +} + +form input { + font-size: 22pt; +} + +form textarea { + font-size: 18pt; +} + +/* blog front */ +.blog-date { + display: block; + margin: 0; + padding: 2px; + background-image: -webkit-gradient(linear, left top, left bottom, from(#444), to(#000)); + background-color: #000; + color: #FFF; + letter-spacing: 0.3em; +} + +.blog-title { + font-size: 2em; + color: rgb(99, 60, 17); + margin: 0px; +} + +.blog-content { + margin-left: 10px; + text-indent: 2em; +} + +/* sidebar */ +#sidebar { + width: 230px; + height: 600px; + background: url('../images/bkg_blackboard.jpg') repeat-y; + color: white; + padding: 10px; + padding-right: 35px; + margin-left: -10px; + -webkit-box-shadow: 0px 3px 5px black; + -moz-box-shadow: 0px 3px 5px black; + position: relative; + float: left; +} + +#sidebar { /* Damn IE fix */ + height: auto; + min-height: 600px; +} + +#sidebar #metal_holder { + width: 68px; + height: 213px; + background: url('../images/img_blackboard_holder.png') no-repeat; + position: absolute; + top: 200px; + left: 240px; +} + +#sidebar h1 { + color: #FFF; + border: none; } \ No newline at end of file diff --git a/public/stylesheets/screen.css b/public/stylesheets/screen.css index 0fe0799..eb86692 100644 --- a/public/stylesheets/screen.css +++ b/public/stylesheets/screen.css @@ -1,226 +1,226 @@ /* ----------------------------------------------------------------------- Blueprint CSS Framework 0.7.1 http://blueprintcss.googlecode.com * Copyright (c) 2007-2008. See LICENSE for more info. * See README for instructions on how to use Blueprint. * For credits and origins, see AUTHORS. * This is a compressed file. See the sources in the 'src' directory. ----------------------------------------------------------------------- */ /* reset.css */ html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;} body {line-height:1.5;} table {border-collapse:separate;border-spacing:0;} caption, th, td {text-align:left;font-weight:normal;} table, td, th {vertical-align:middle;} blockquote:before, blockquote:after, q:before, q:after {content:"";} blockquote, q {quotes:"" "";} a img {border:none;} /* typography.css */ body {font-size:75%;color:#222;background:#fff;font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;} h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111;} -h1 {font-size:3em;line-height:1;margin-bottom:0.5em;} -h2 {font-size:2em;margin-bottom:0.75em;} +h1 {font-size:2em;line-height:1;margin-bottom:0.5em;} +h2 {font-size:1.75em;margin-bottom:0.75em;} h3 {font-size:1.5em;line-height:1;margin-bottom:1em;} h4 {font-size:1.2em;line-height:1.25;margin-bottom:1.25em;height:1.25em;} h5 {font-size:1em;font-weight:bold;margin-bottom:1.5em;} h6 {font-size:1em;font-weight:bold;} h1 img, h2 img, h3 img, h4 img, h5 img, h6 img {margin:0;} p {margin:0 0 1.5em;} p img {float:left;margin:1.5em 1.5em 1.5em 0;padding:0;} p img.right {float:right;margin:1.5em 0 1.5em 1.5em;} a:focus, a:hover {color:#000; text-decoration: underline;} a {color:#009;text-decoration:none;} blockquote {margin:1.5em;color:#666;font-style:italic;} strong {font-weight:bold;} em, dfn {font-style:italic;} dfn {font-weight:bold;} sup, sub {line-height:0;} abbr, acronym {border-bottom:1px dotted #666;} address {margin:0 0 1.5em;font-style:italic;} del {color:#666;} pre, code {margin:1.5em 0;white-space:pre;} pre, code, tt {font:1em 'andale mono', 'lucida console', monospace;line-height:1.5;} li ul, li ol {margin:0 1.5em;} ul, ol {margin:0 1.5em 1.5em 1.5em;} ul {list-style-type:disc;} ol {list-style-type:decimal;} dl {margin:0 0 1.5em 0;} dl dt {font-weight:bold;} dd {margin-left:1.5em;} table {margin-bottom:1.4em;width:100%;} th {font-weight:bold;background:#C3D9FF;} th, td {padding:4px 10px 4px 5px;} tr.even td {background:#E5ECF9;} tfoot {font-style:italic;} caption {background:#eee;} .small {font-size:.8em;margin-bottom:1.875em;line-height:1.875em;} .large {font-size:1.2em;line-height:2.5em;margin-bottom:1.25em;} .hide {display:none;} .quiet {color:#666;} .loud {color:#000;} .highlight {background:#ff0;} .added {background:#060;color:#fff;} .removed {background:#900;color:#fff;} .first {margin-left:0;padding-left:0;} .last {margin-right:0;padding-right:0;} .top {margin-top:0;padding-top:0;} .bottom {margin-bottom:0;padding-bottom:0;} /* grid.css */ .container {width:950px;margin:0 auto;} .showgrid {background:url(src/grid.png);} body {margin:1.5em 0;} div.span-1, div.span-2, div.span-3, div.span-4, div.span-5, div.span-6, div.span-7, div.span-8, div.span-9, div.span-10, div.span-11, div.span-12, div.span-13, div.span-14, div.span-15, div.span-16, div.span-17, div.span-18, div.span-19, div.span-20, div.span-21, div.span-22, div.span-23, div.span-24 {float:left;margin-right:10px;} div.last {margin-right:0;} .span-1 {width:30px;} .span-2 {width:70px;} .span-3 {width:110px;} .span-4 {width:150px;} .span-5 {width:190px;} .span-6 {width:230px;} .span-7 {width:270px;} .span-8 {width:310px;} .span-9 {width:350px;} .span-10 {width:390px;} .span-11 {width:430px;} .span-12 {width:470px;} .span-13 {width:510px;} .span-14 {width:550px;} .span-15 {width:590px;} .span-16 {width:630px;} .span-17 {width:670px;} .span-18 {width:710px;} .span-19 {width:750px;} .span-20 {width:790px;} .span-21 {width:830px;} .span-22 {width:870px;} .span-23 {width:910px;} .span-24, div.span-24 {width:950px;margin:0;} .append-1 {padding-right:40px;} .append-2 {padding-right:80px;} .append-3 {padding-right:120px;} .append-4 {padding-right:160px;} .append-5 {padding-right:200px;} .append-6 {padding-right:240px;} .append-7 {padding-right:280px;} .append-8 {padding-right:320px;} .append-9 {padding-right:360px;} .append-10 {padding-right:400px;} .append-11 {padding-right:440px;} .append-12 {padding-right:480px;} .append-13 {padding-right:520px;} .append-14 {padding-right:560px;} .append-15 {padding-right:600px;} .append-16 {padding-right:640px;} .append-17 {padding-right:680px;} .append-18 {padding-right:720px;} .append-19 {padding-right:760px;} .append-20 {padding-right:800px;} .append-21 {padding-right:840px;} .append-22 {padding-right:880px;} .append-23 {padding-right:920px;} .prepend-1 {padding-left:40px;} .prepend-2 {padding-left:80px;} .prepend-3 {padding-left:120px;} .prepend-4 {padding-left:160px;} .prepend-5 {padding-left:200px;} .prepend-6 {padding-left:240px;} .prepend-7 {padding-left:280px;} .prepend-8 {padding-left:320px;} .prepend-9 {padding-left:360px;} .prepend-10 {padding-left:400px;} .prepend-11 {padding-left:440px;} .prepend-12 {padding-left:480px;} .prepend-13 {padding-left:520px;} .prepend-14 {padding-left:560px;} .prepend-15 {padding-left:600px;} .prepend-16 {padding-left:640px;} .prepend-17 {padding-left:680px;} .prepend-18 {padding-left:720px;} .prepend-19 {padding-left:760px;} .prepend-20 {padding-left:800px;} .prepend-21 {padding-left:840px;} .prepend-22 {padding-left:880px;} .prepend-23 {padding-left:920px;} div.border {padding-right:4px;margin-right:5px;border-right:1px solid #eee;} div.colborder {padding-right:24px;margin-right:25px;border-right:1px solid #eee;} .pull-1 {margin-left:-40px;} .pull-2 {margin-left:-80px;} .pull-3 {margin-left:-120px;} .pull-4 {margin-left:-160px;} .pull-5 {margin-left:-200px;} .pull-6 {margin-left:-240px;} .pull-7 {margin-left:-280px;} .pull-8 {margin-left:-320px;} .pull-9 {margin-left:-360px;} .pull-10 {margin-left:-400px;} .pull-11 {margin-left:-440px;} .pull-12 {margin-left:-480px;} .pull-13 {margin-left:-520px;} .pull-14 {margin-left:-560px;} .pull-15 {margin-left:-600px;} .pull-16 {margin-left:-640px;} .pull-17 {margin-left:-680px;} .pull-18 {margin-left:-720px;} .pull-19 {margin-left:-760px;} .pull-20 {margin-left:-800px;} .pull-21 {margin-left:-840px;} .pull-22 {margin-left:-880px;} .pull-23 {margin-left:-920px;} .pull-24 {margin-left:-960px;} .pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float:left;position:relative;} .push-1 {margin:0 -40px 1.5em 40px;} .push-2 {margin:0 -80px 1.5em 80px;} .push-3 {margin:0 -120px 1.5em 120px;} .push-4 {margin:0 -160px 1.5em 160px;} .push-5 {margin:0 -200px 1.5em 200px;} .push-6 {margin:0 -240px 1.5em 240px;} .push-7 {margin:0 -280px 1.5em 280px;} .push-8 {margin:0 -320px 1.5em 320px;} .push-9 {margin:0 -360px 1.5em 360px;} .push-10 {margin:0 -400px 1.5em 400px;} .push-11 {margin:0 -440px 1.5em 440px;} .push-12 {margin:0 -480px 1.5em 480px;} .push-13 {margin:0 -520px 1.5em 520px;} .push-14 {margin:0 -560px 1.5em 560px;} .push-15 {margin:0 -600px 1.5em 600px;} .push-16 {margin:0 -640px 1.5em 640px;} .push-17 {margin:0 -680px 1.5em 680px;} .push-18 {margin:0 -720px 1.5em 720px;} .push-19 {margin:0 -760px 1.5em 760px;} .push-20 {margin:0 -800px 1.5em 800px;} .push-21 {margin:0 -840px 1.5em 840px;} .push-22 {margin:0 -880px 1.5em 880px;} .push-23 {margin:0 -920px 1.5em 920px;} .push-24 {margin:0 -960px 1.5em 960px;} .push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float:right;position:relative;} .box {padding:1.5em;margin-bottom:1.5em;background:#E5ECF9;} hr {background:#ddd;color:#ddd;clear:both;float:none;width:100%;height:.1em;margin:0 0 1.45em;border:none;} hr.space {background:#fff;color:#fff;} .clearfix:after, .container:after {content:".";display:block;height:0;clear:both;visibility:hidden;} .clearfix, .container {display:inline-block;} * html .clearfix, * html .container {height:1%;} .clearfix, .container {display:block;} .clear {clear:both;} /* forms.css */ label {font-weight:bold;} fieldset {padding:1.4em;margin:0 0 1.5em 0;border:1px solid #ccc;} legend {font-weight:bold;font-size:1.2em;} input.text, input.title, textarea, select {margin:0.5em 0;border:1px solid #bbb;} input.text:focus, input.title:focus, textarea:focus, select:focus {border:1px solid #666;} input.text, input.title {width:300px;padding:5px;} input.title {font-size:1.5em;} textarea {width:390px;height:250px;padding:5px;} .error, .notice, .success {padding:.8em;margin-bottom:1em;border:2px solid #ddd;} .error {background:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;} .notice {background:#FFF6BF;color:#514721;border-color:#FFD324;} .success {background:#E6EFC2;color:#264409;border-color:#C6D880;} .error a {color:#8a1f11;} .notice a {color:#514721;} .success a {color:#264409;} \ No newline at end of file diff --git a/public/webuikit-css/blank.gif b/public/webuikit-css/blank.gif old mode 100755 new mode 100644 diff --git a/public/webuikit-css/iepngfix.htc b/public/webuikit-css/iepngfix.htc old mode 100755 new mode 100644 diff --git a/public/webuikit-css/iepngfix_tilebg.js b/public/webuikit-css/iepngfix_tilebg.js old mode 100755 new mode 100644 diff --git a/script/performance/benchmarker b/script/performance/benchmarker old mode 100755 new mode 100644 diff --git a/script/performance/profiler b/script/performance/profiler old mode 100755 new mode 100644 diff --git a/script/performance/request b/script/performance/request old mode 100755 new mode 100644 diff --git a/script/process/inspector b/script/process/inspector old mode 100755 new mode 100644 diff --git a/script/process/reaper b/script/process/reaper old mode 100755 new mode 100644 diff --git a/script/process/spawner b/script/process/spawner old mode 100755 new mode 100644 diff --git a/test/functional/news_controller_test.rb b/test/functional/news_controller_test.rb new file mode 100644 index 0000000..b2ee48b --- /dev/null +++ b/test/functional/news_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class NewsControllerTest < ActionController::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end diff --git a/vendor/plugins/restful-authentication/generators/authenticated/templates/stories/rest_auth_stories.rb b/vendor/plugins/restful-authentication/generators/authenticated/templates/stories/rest_auth_stories.rb old mode 100755 new mode 100644
itszero/eLib2
0c6f65ac625284eb88efd103c59ed85809393147
admin interface complete & blog initial
diff --git a/app/controllers/application.rb b/app/controllers/application.rb index c927587..94d3b92 100644 --- a/app/controllers/application.rb +++ b/app/controllers/application.rb @@ -1,28 +1,28 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base include FaceboxRender helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details # Uncomment the :secret if you're not using the cookie session store protect_from_forgery # :secret => 'ce44bb469671dfe6809abe1eb0fe97bd' # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters # from your application log (in this case, all fields with names like "password"). # filter_parameter_logging :password before_filter :get_sessions after_filter :set_sessions private def get_sessions @current_user = session[:current_user] end def set_sessions - session[:current_user] = @currnet_user + session[:current_user] = @current_user end end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index fecf2a0..dba5cb7 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,46 +1,47 @@ # This controller handles the login/logout function of the site. class SessionsController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem # render new.rhtml def new render_to_facebox end def create logout_keeping_session! user = User.authenticate(params[:login], params[:password]) if user # Protects against session fixation attacks, causes request forgery # protection if user resubmits an earlier form using back # button. Uncomment if you understand the tradeoffs. # reset_session self.current_user = user + @current_user = user new_cookie_flag = (params[:remember_me] == "1") handle_remember_cookie! new_cookie_flag notice_stickie('登入完成,歡迎使用本系統!') redirect_back_or_default('/', true) flash[:notice] = "Logged in successfully" else note_failed_signin @login = params[:login] @remember_me = params[:remember_me] render_to_facebox :action => 'new' @current_user = nil end end def destroy logout_killing_session! notice_stickie('登出完成,期待您的再度光臨。') redirect_back_or_default('/') end protected # Track failed login attempts def note_failed_signin warning_stickie("登入失敗,請檢查您的帳號密碼。") logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}" end end diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb index e009fc2..316ca9a 100644 --- a/app/controllers/welcome_controller.rb +++ b/app/controllers/welcome_controller.rb @@ -1,6 +1,11 @@ class WelcomeController < ApplicationController layout 'service' def index + @in_homepage_function = true + end + + def admin + @in_admin_function = true end end diff --git a/app/models/blog.rb b/app/models/blog.rb new file mode 100644 index 0000000..0ad9473 --- /dev/null +++ b/app/models/blog.rb @@ -0,0 +1,2 @@ +class Blog < ActiveRecord::Base +end diff --git a/app/views/layouts/service.html.erb b/app/views/layouts/service.html.erb index 61998b9..3975eb6 100644 --- a/app/views/layouts/service.html.erb +++ b/app/views/layouts/service.html.erb @@ -1,60 +1,61 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/stylesheets/screen.css" type="text/css" media="screen, projection" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/print.css" type="text/css" media="print" charset="utf-8"> <!--[if IE]><link rel="stylesheet" href="/stylesheets/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="/webuikit-css/webuikit.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/stylesheets/main.css" type="text/css" media="screen" charset="utf-8"> <link rel="stylesheet" href="/facebox/facebox.css" type="text/css" media="screen" charset="utf-8"> <%= stylesheet_link_tag('stickies') %> <script type="text/javascript" src="/javascripts/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jquery-ui.js" charset="utf-8"></script> <script type="text/javascript" src="/javascripts/jrails.js" charset="utf-8"></script> <script type="text/javascript" src="/facebox/facebox.js" charset="utf-8"></script> </head> <body> <div class="container" id="header"> <div class="span-13" id="header-img"> <img src="/images/img_sitetitle.png"/> </div> <div class="span-11 last" id="header-title"> <ul> - <li class="menu-current">首頁</li> - <li>搜尋書籍</li> - <li>讀者服務</li> - <li>聯絡我們</li> - <% if @current_user && @current_user.permission == 2 %> - <li class="menu-backstage">後臺區</li> + <li <%='class="menu-current"' if @in_homepage_function%>><a href="/">首頁</a></li> + <li <%='class="menu-current"' if @in_books_function%>><a href="#">搜尋書籍</a></li> + <li <%='class="menu-current"' if @in_reader_function%>><a href="#">讀者服務</a></li> + <li <%='class="menu-current"' if @in_contact_function%>><a href="#">聯絡我們</a></li> + <% if @current_user && @current_user.permission == 2%> + <li class="menu-backstage<%="-current" if @in_admin_function%>"><a href="/admin">後臺區</a></li> <% end %> </ul> </div> </div> <div class="container"> <div class="span-23 last" id="content"> <div class="container"> <div class="span-23 last" id="session_bar"> <% if @current_user %> + 您好,<%=@current_user.nickname || @current_user.name || @current_user.login%>(<%=@current_user.student_id%>) <% if @current_user.permission == 2 %><span style="color: red;">工作人員</span> <%end%>: <a href="/logout">登出 <img src="/images/img_power.png" width="20" height="20" align="top"></a> <% else %> 使用個人化服務,請先 <%= facebox_link_to "登入 <img src=\"/images/img_power.png\" width=\"20\" height=\"20\" align=\"top\" />", :url => '/login' %> <% end %> </div> </div> <div class="container"> <div class="span-23 last"> <%=render_stickies :effect => "blindUp", :close => '關閉'%> </div> </div> <%=yield%> </div> </div> <div class="container"> <div class="span-24 last" id="footer"> eLib<sup>2</sup>, ZZHC 2008. Powered by Ruby on Rails. </div> </div> </body> </html> \ No newline at end of file diff --git a/app/views/welcome/admin.html.erb b/app/views/welcome/admin.html.erb new file mode 100644 index 0000000..ca07389 --- /dev/null +++ b/app/views/welcome/admin.html.erb @@ -0,0 +1,33 @@ +<div class="container"> + <div class="span-11"> + <p class="admin-title">圖書管理</p> + <div class="admin-menu"> + <a href="#">搜尋/維護館藏<span class="arrow">&raquo;</span></a> + <a href="#">新增館藏<span class="arrow">&raquo;</span></a> + </div> + </div> + <div class="span-12 last"> + <p class="admin-title">館藏流通</p> + <div class="admin-menu"> + <a href="#">借閱/還書介面<span class="arrow">&raquo;</span></a> + <a href="#">列出愈期書籍<span class="arrow">&raquo;</span></a> + </div> + </div> +</div> + +<div class="container" style="margin-top: 10px;"> + <div class="span-11"> + <p class="admin-title">讀者資料</p> + <div class="admin-menu"> + <a href="#">讀者資料查詢/維護<span class="arrow">&raquo;</span></a> + <a href="#">(大批)新增讀者<span class="arrow">&raquo;</span></a> + </div> + </div> + <div class="span-12 last"> + <p class="admin-title">公告及其他</p> + <div class="admin-menu"> + <a href="#">公告維護<span class="arrow">&raquo;</span></a> + <a href="#">工作人員權限管理<span class="arrow">&raquo;</span></a> + </div> + </div> +</div> \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 8c0c432..969d17d 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,51 +1,52 @@ ActionController::Routing::Routes.draw do |map| map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.resources :users map.resource :session # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. + map.admin '/admin', :controller => "welcome", :action => 'admin' map.root :controller => "welcome" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing the them or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20080926035923_create_blogs.rb b/db/migrate/20080926035923_create_blogs.rb new file mode 100644 index 0000000..eecaa43 --- /dev/null +++ b/db/migrate/20080926035923_create_blogs.rb @@ -0,0 +1,14 @@ +class CreateBlogs < ActiveRecord::Migration + def self.up + create_table :blogs do |t| + t.string :title + t.string :content + t.integer :user_id + t.timestamps + end + end + + def self.down + drop_table :blogs + end +end \ No newline at end of file diff --git a/db/schema.rb b/db/schema.rb index 2adf40c..0a839a9 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,32 +1,40 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20080926022630) do +ActiveRecord::Schema.define(:version => 20080926035923) do + + create_table "blogs", :force => true do |t| + t.string "title" + t.string "content" + t.integer "user_id" + t.datetime "created_at" + t.datetime "updated_at" + end create_table "users", :force => true do |t| t.string "login", :limit => 40 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" t.string "student_class" t.string "student_id" t.string "nickname" t.integer "permission" end add_index "users", ["login"], :name => "index_users_on_login", :unique => true end diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css index 2c6ea76..a3ac598 100644 --- a/public/stylesheets/main.css +++ b/public/stylesheets/main.css @@ -1,72 +1,121 @@ +/* layout */ body { background-color: #7C6255; + font-family: Helvetica, Verdana, Arial, DFHeiStd-W5, HiraKakuPro-W3, LiHei Pro, Microsoft JhengHei; } #content { background-color: #FFF; -moz-border-radius: 10px; -webkit-border-radius: 10px; padding: 10px; margin-top: -10px; } #session_bar { border-bottom: 1px solid #DDD; padding-bottom: 2px; margin-bottom: 10px; } #header-title { font-size: 18px; } #header-title ul { list-style: none; height: 70px; } #header-title ul li { float: left; border-left: 1px solid #FFF; border-top: 1px solid #FFF; border-right: 1px solid #FFF; background-color: #222; - color: #fff; padding: 5px; padding-top: 60px; margin-left: -1px; } +#header-title ul li a { + color: #fff; +} + #header-title ul li:hover { background-color: #444; } .menu-current { background-color: #FFF !important; +} + +.menu-current a { color: #000 !important; } .menu-backstage { background-color: #73000E !important; } .menu-backstage:hover { background-color: #920011 !important; } .menu-backstage-current { - background-color: #A00 !important; + background-color: #FFF !important; +} + +.menu-backstage-current a { color: #F00 !important; } #header-title ul li a { display: block; } #footer { margin: 5px; text-align: center; - font-weight: bold; color: #FFF; word-spacing: 4px; + font-family: Helvetica; +} + +/* admin css */ +.admin-title { + display: block; + margin: 0; + padding: 2px; + background-color: #C17436; + color: #FFF; + font-size: 2em; + border-top: 1px solid #000; + border-left: 1px solid #000; + border-right: 1px solid #000; +} + +.admin-menu { + margin: 0; + padding: 0; + border-left: 1px solid #000; + border-right: 1px solid #000; + border-bottom: 1px solid #000; + font-size: 1.75em; +} + +.admin-menu a { + display: block; + padding: 2px; +} + +.admin-menu .arrow { + float: right; +} + +.admin-menu a:hover { + display: block; + background-color: #000099; + color: #FFF; + text-decoration: none; } \ No newline at end of file diff --git a/test/fixtures/blogs.yml b/test/fixtures/blogs.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/blogs.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/unit/blog_test.rb b/test/unit/blog_test.rb new file mode 100644 index 0000000..02fedcf --- /dev/null +++ b/test/unit/blog_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class BlogTest < ActiveSupport::TestCase + # Replace this with your real tests. + def test_truth + assert true + end +end
itszero/eLib2
24c2356a5319b6f0fcfd2136c9ca8b8b44188d7c
gitignores
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e802885 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +log/*.log +tmp/**/* +config/database.yml +db/*.sqlite3 diff --git a/log/.gitignore b/log/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/tmp/.gitignore b/tmp/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/.gitignore b/vendor/.gitignore new file mode 100644 index 0000000..e69de29
antlr/antlrcs
b22ff98be0a636d6e21e031fbef3e9e7c4eba58b
Prepare for next development iteration
diff --git a/Directory.Build.props b/Directory.Build.props index ca0e041..46d9d15 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,80 +1,80 @@ <?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> </PropertyGroup> <PropertyGroup> <!-- These properties are used by Directory.Build.props. Make sure they are set early enough for cases where they are not explicitly set during the MSBuild invocation. --> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> </PropertyGroup> <PropertyGroup> <!-- Solution build dependencies are not project dependencies. https://github.com/Microsoft/msbuild/issues/3626 --> <AddSyntheticProjectReferencesForSolutionDependencies>false</AddSyntheticProjectReferencesForSolutionDependencies> </PropertyGroup> <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> - <ANTLRInformationalVersion>3.5.2-rc1</ANTLRInformationalVersion> + <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> - <STInformationalVersion>4.0.9-rc1</STInformationalVersion> + <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> <PropertyGroup> <!-- Default NuGet package properties. Additional items set in Directory.Build.targets. --> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Authors>Sam Harwell, Terence Parr</Authors> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageLicenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</PackageLicenseUrl> <PackageProjectUrl>https://github.com/antlr/antlrcs</PackageProjectUrl> <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl> <PackageReleaseNotes>https://github.com/antlr/antlrcs/releases/$(ANTLRInformationalVersion)</PackageReleaseNotes> <IncludeSymbols>true</IncludeSymbols> <IncludeSource>true</IncludeSource> <PackageOutputPath>$(MSBuildThisFileDirectory)build\prep\nuget\</PackageOutputPath> </PropertyGroup> <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta2" PrivateAssets="all" /> </ItemGroup> <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project> diff --git a/build/Validation/DotnetValidation.csproj b/build/Validation/DotnetValidation.csproj index b38bb3c..809a958 100644 --- a/build/Validation/DotnetValidation.csproj +++ b/build/Validation/DotnetValidation.csproj @@ -1,33 +1,33 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net20;net30;net35;net40;net45;netcoreapp1.1;portable40-net40+sl5+win8+wp8+wpa81</TargetFrameworks> <EnableDefaultNoneItems>False</EnableDefaultNoneItems> <Antlr4UseCSharpGenerator>True</Antlr4UseCSharpGenerator> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'portable40-net40+sl5+win8+wp8+wpa81'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Profile328</TargetFrameworkProfile> <DefineConstants>$(DefineConstants);LEGACY_PCL</DefineConstants> </PropertyGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> </When> </Choose> <ItemGroup> - <PackageReference Include="Antlr3" Version="3.5.2-rc1" /> + <PackageReference Include="Antlr3" Version="3.5.2-dev" /> </ItemGroup> <ItemGroup> <None Include="NuGet.config" /> </ItemGroup> </Project> diff --git a/build/prep/version.ps1 b/build/prep/version.ps1 index 182f347..e8252a8 100644 --- a/build/prep/version.ps1 +++ b/build/prep/version.ps1 @@ -1,2 +1,2 @@ -$AntlrVersion = "3.5.2-rc1" -$STVersion = "4.0.9-rc1" +$AntlrVersion = "3.5.2-dev" +$STVersion = "4.0.9-dev"
antlr/antlrcs
c0d38e7ae64252fdd25710420465ef194cd6693c
Fix file copy during build
diff --git a/build/prep/prepare.ps1 b/build/prep/prepare.ps1 index c386748..0359255 100644 --- a/build/prep/prepare.ps1 +++ b/build/prep/prepare.ps1 @@ -1,253 +1,255 @@ param ( [switch]$Debug, [string]$VisualStudioVersion = '15.0', [string]$Verbosity = 'minimal', [string]$Logger, [switch]$NoValidate ) . .\version.ps1 # build the solution $SolutionPath = "..\..\Antlr3.sln" # make sure the script was run from the expected path if (!(Test-Path $SolutionPath)) { $host.ui.WriteErrorLine("The script was run from an invalid working directory.") exit 1 } If ($Debug) { $BuildConfig = 'Debug' } Else { $BuildConfig = 'Release' } $DebugBuild = $false # clean up from any previous builds $CleanItems = "Runtime", "Tool", "Bootstrap", "ST3", "ST4" $CleanItems | ForEach-Object { if (Test-Path $_) { Remove-Item -Force -Recurse $_ } } # build the project $visualStudio = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7')."$VisualStudioVersion" $msbuild = "$visualStudio\MSBuild\$VisualStudioVersion\Bin\MSBuild.exe" If (-not (Test-Path $msbuild)) { $host.UI.WriteErrorLine("Couldn't find MSBuild.exe") exit 1 } If ($Logger) { $LoggerArgument = "/logger:$Logger" } # Make sure we don't have a stray config file from the bootstrap build If (Test-Path '..\..\NuGet.config') { Remove-Item '..\..\NuGet.config' } # Restore packages .\NuGet.exe update -self .\NuGet.exe restore $SolutionPath -Project2ProjectTimeOut 1200 &$msbuild /nologo /m /nr:false /t:rebuild $LoggerArgument "/verbosity:$Verbosity" /p:Configuration=$BuildConfig $SolutionPath If (-not $?) { $host.ui.WriteErrorLine("Build Failed, Aborting!") exit $LASTEXITCODE } # Build Antlr3.CodeGenerator so we can use it for the boostrap build .\NuGet.exe pack .\Antlr3.CodeGenerator.nuspec -OutputDirectory nuget -Prop Configuration=$BuildConfig -Version $AntlrVersion -Prop ANTLRVersion=$AntlrVersion -Prop STVersion=$STVersion -Symbols If (-not $?) { $host.ui.WriteErrorLine("Failed to create NuGet package prior to bootstrap, Aborting!") exit 1 } # build the project again with the new bootstrap files copy -force '..\..\NuGet.config.bootstrap' '..\..\NuGet.config' .\NuGet.exe restore $SolutionPath -Project2ProjectTimeOut 1200 &$msbuild /nologo /m /nr:false /t:rebuild "/verbosity:$Verbosity" /p:Configuration=$BuildConfig $SolutionPath If (-not $?) { $host.ui.WriteErrorLine("Build Failed, Aborting!") Remove-Item '..\..\NuGet.config' exit 1 } Remove-Item '..\..\NuGet.config' # copy files from the build mkdir Runtime mkdir Tool mkdir Tool\Rules mkdir Bootstrap mkdir ST3 mkdir ST4 copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.dll" ".\Runtime" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.pdb" ".\Runtime" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.xml" ".\Runtime" copy "..\..\LICENSE.txt" ".\Runtime" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.exe" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.exe.config" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.dll" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.Debug.dll" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.dll" ".\Tool" if ($DebugBuild) { copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.Visualizer.dll" ".\Tool" } -copy "..\..\bin\$BuildConfig\net40\Antlr3.props" ".\Tool" -copy "..\..\bin\$BuildConfig\net40\Antlr3.targets" ".\Tool" +copy "..\..\bin\$BuildConfig\net40\Antlr3.CodeGenerator.DefaultItems.props" ".\Tool" +copy "..\..\bin\$BuildConfig\net40\Antlr3.CodeGenerator.DefaultItems.targets" ".\Tool" +copy "..\..\bin\$BuildConfig\net40\Antlr3.CodeGenerator.props" ".\Tool" +copy "..\..\bin\$BuildConfig\net40\Antlr3.CodeGenerator.targets" ".\Tool" copy "..\..\bin\$BuildConfig\net40\AntlrBuildTask.dll" ".\Tool" copy "..\..\bin\$BuildConfig\net40\Rules\Antlr3.ProjectItemsSchema.xml" ".\Tool\Rules" copy "..\..\bin\$BuildConfig\net40\Rules\Antlr3.xml" ".\Tool\Rules" copy "..\..\bin\$BuildConfig\net40\Rules\AntlrAbstractGrammar.xml" ".\Tool\Rules" copy "..\..\bin\$BuildConfig\net40\Rules\AntlrTokens.xml" ".\Tool\Rules" copy "..\..\LICENSE.txt" ".\Tool" copy ".\Tool\*" ".\Bootstrap" # copy ST4 binaries and all symbol files to the full Tool folder copy "..\..\bin\$BuildConfig\net35-client\Antlr3.pdb" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.pdb" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.Debug.pdb" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.pdb" ".\Tool" if ($DebugBuild) { copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.Visualizer.pdb" ".\Tool" } copy "..\..\bin\$BuildConfig\net40\AntlrBuildTask.pdb" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.xml" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.xml" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.Debug.xml" ".\Tool" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.xml" ".\Tool" if ($DebugBuild) { copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.Visualizer.xml" ".\Tool" } copy "..\..\bin\$BuildConfig\net40\AntlrBuildTask.xml" ".\Tool" mkdir "Tool\Codegen" mkdir "Tool\Targets" mkdir "Tool\Tool" copy -r "..\..\bin\$BuildConfig\net35-client\Codegen\*" ".\Tool\Codegen" copy -r "..\..\bin\$BuildConfig\net35-client\Targets\*.dll" ".\Tool\Targets" copy -r "..\..\bin\$BuildConfig\net35-client\Targets\*.pdb" ".\Tool\Targets" copy -r "..\..\bin\$BuildConfig\net35-client\Targets\*.xml" ".\Tool\Targets" copy -r "..\..\bin\$BuildConfig\net35-client\Tool\*" ".\Tool\Tool" mkdir "Bootstrap\Codegen\Templates\CSharp2" mkdir "Bootstrap\Codegen\Templates\CSharp3" mkdir "Bootstrap\Tool" mkdir "Bootstrap\Targets" copy "..\..\bin\$BuildConfig\net35-client\Codegen\Templates\LeftRecursiveRules.stg" ".\Bootstrap\Codegen\Templates" copy "..\..\bin\$BuildConfig\net35-client\Codegen\Templates\CSharp2\*" ".\Bootstrap\Codegen\Templates\CSharp2" copy "..\..\bin\$BuildConfig\net35-client\Codegen\Templates\CSharp3\*" ".\Bootstrap\Codegen\Templates\CSharp3" copy "..\..\bin\$BuildConfig\net35-client\Targets\Antlr3.Targets.CSharp2.dll" ".\Bootstrap\Targets" copy "..\..\bin\$BuildConfig\net35-client\Targets\Antlr3.Targets.CSharp3.dll" ".\Bootstrap\Targets" copy -r "..\..\bin\$BuildConfig\net35-client\Tool\*" ".\Bootstrap\Tool" Remove-Item ".\Bootstrap\Tool\Templates\messages\formats\gnu.stg" # ST3 dist copy "..\..\Antlr3.StringTemplate\bin\$BuildConfig\net35-client\Antlr3.StringTemplate.dll" ".\ST3" copy "..\..\Antlr3.StringTemplate\bin\$BuildConfig\net35-client\Antlr3.Runtime.dll" ".\ST3" copy "..\..\Antlr3.StringTemplate\bin\$BuildConfig\net35-client\Antlr3.StringTemplate.pdb" ".\ST3" copy "..\..\Antlr3.StringTemplate\bin\$BuildConfig\net35-client\Antlr3.Runtime.pdb" ".\ST3" copy "..\..\Antlr3.StringTemplate\bin\$BuildConfig\net35-client\Antlr3.StringTemplate.xml" ".\ST3" copy "..\..\Antlr3.StringTemplate\bin\$BuildConfig\net35-client\Antlr3.Runtime.xml" ".\ST3" copy "..\..\LICENSE.txt" ".\ST3" # ST4 dist copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.dll" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.dll" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.Visualizer.dll" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.pdb" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.pdb" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.Visualizer.pdb" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr3.Runtime.xml" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.xml" ".\ST4" copy "..\..\bin\$BuildConfig\net35-client\Antlr4.StringTemplate.Visualizer.xml" ".\ST4" copy "..\..\LICENSE.txt" ".\ST4" # compress the distributable packages $ArchivePath = ".\dist\antlr-dotnet-csharpbootstrap-" + $AntlrVersion + ".7z" .\7z.exe a -r -mx9 $ArchivePath ".\Bootstrap\*" $ArchivePath = ".\dist\antlr-dotnet-csharpruntime-" + $AntlrVersion + ".7z" .\7z.exe a -r -mx9 $ArchivePath ".\Runtime\*" $ArchivePath = ".\dist\antlr-dotnet-tool-" + $AntlrVersion + ".7z" .\7z.exe a -r -mx9 $ArchivePath ".\Tool\*" $ArchivePath = ".\dist\antlr-dotnet-st3-" + $AntlrVersion + ".7z" .\7z.exe a -r -mx9 $ArchivePath ".\ST3\*" $ArchivePath = ".\dist\antlr-dotnet-st4-" + $STVersion + ".7z" .\7z.exe a -r -mx9 $ArchivePath ".\ST4\*" # Build the NuGet packages .\NuGet.exe pack .\Antlr3.CodeGenerator.nuspec -OutputDirectory nuget -Prop Configuration=$BuildConfig -Version $AntlrVersion -Prop ANTLRVersion=$AntlrVersion -Prop STVersion=$STVersion -Symbols If (-not $?) { $host.ui.WriteErrorLine("Failed to create NuGet package, Aborting!") exit 1 } .\NuGet.exe pack .\Antlr3.nuspec -OutputDirectory nuget -Prop Configuration=$BuildConfig -Version $AntlrVersion -Prop ANTLRVersion=$AntlrVersion -Prop STVersion=$STVersion -Symbols If (-not $?) { $host.ui.WriteErrorLine("Failed to create NuGet package, Aborting!") exit 1 } # Validate the build If (-not $NoValidate) { git 'clean' '-dxf' '..\Validation' dotnet 'run' '--project' '..\Validation\DotnetValidation.csproj' '--framework' 'netcoreapp1.1' if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit $LASTEXITCODE } git 'clean' '-dxf' '..\Validation' .\NuGet.exe 'restore' '..\Validation' &$msbuild '/nologo' '/m' '/nr:false' '/t:Rebuild' $LoggerArgument "/verbosity:$Verbosity" "/p:Configuration=$BuildConfig" '..\Validation\DotnetValidation.sln' if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } "..\Validation\bin\$BuildConfig\net20\DotnetValidation.exe" if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } "..\Validation\bin\$BuildConfig\net30\DotnetValidation.exe" if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } "..\Validation\bin\$BuildConfig\net35\DotnetValidation.exe" if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } "..\Validation\bin\$BuildConfig\net40\DotnetValidation.exe" if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } "..\Validation\bin\$BuildConfig\portable40-net40+sl5+win8+wp8+wpa81\DotnetValidation.exe" if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } "..\Validation\bin\$BuildConfig\net45\DotnetValidation.exe" if (-not $?) { $host.ui.WriteErrorLine('Build failed, aborting!') Exit 1 } }
antlr/antlrcs
7a4aa96dc140b3499960dad4870ee3493ddb2b88
Set the default XML namespace for imported build props/targets
diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props index 1f9f3f0..103ff21 100644 --- a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props +++ b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props @@ -1,14 +1,14 @@ <?xml version="1.0" encoding="utf-8"?> -<Project> +<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- Note: In this file, only items may be conditioned on the Antlr4IsSdkProject property. The EnableDefaultAntlrItems is defined unconditionally, but it is simply unused outside of SDK projects. --> <ItemGroup Condition="'$(AntlrIsSdkProject)' == 'True' AND '$(EnableDefaultItems)' == 'True'"> <Antlr3 Include="**/*.g" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <Antlr3 Include="**/*.g3" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <AntlrTokens Include="**/*.tokens" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> </ItemGroup> </Project> diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets index 5d39d2b..512310c 100644 --- a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets +++ b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets @@ -1,21 +1,21 @@ <?xml version="1.0" encoding="utf-8"?> -<Project> +<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <EnableDefaultAntlrItems Condition="'$(EnableDefaultAntlrItems)' == ''">True</EnableDefaultAntlrItems> </PropertyGroup> <ItemGroup Condition="'$(EnableDefaultItems)' == 'True' AND '$(EnableDefaultNoneItems)' == 'True'"> <None Remove="**/*.g" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <None Remove="**/*.g3" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <None Remove="**/*.tokens" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> </ItemGroup> <!-- Modify the CustomToolNamespace based on the directory location of the grammar --> <ItemGroup> <Antlr3 Update="@(Antlr3)" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault(%(RelativeDir), '').Replace('\', '.').Replace('/', '.').TrimEnd('.'))" /> <Antlr3 Update="@(Antlr3)" Condition="'$(RootNamespace)' != ''" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault('$(RootNamespace).%(DefaultCustomToolNamespace)', '').TrimEnd('.'))" /> <Antlr3 Update="@(Antlr3)" CustomToolNamespace="$([MSBuild]::ValueOrDefault(%(CustomToolNamespace), %(DefaultCustomToolNamespace)))" /> </ItemGroup> </Project>
antlr/antlrcs
78df3ee3de6d00b2e497c78f8da778bb65e640bc
Add default items before the project file
diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props new file mode 100644 index 0000000..1f9f3f0 --- /dev/null +++ b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.props @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project> + + <!-- + Note: In this file, only items may be conditioned on the Antlr4IsSdkProject property. The EnableDefaultAntlrItems + is defined unconditionally, but it is simply unused outside of SDK projects. + --> + <ItemGroup Condition="'$(AntlrIsSdkProject)' == 'True' AND '$(EnableDefaultItems)' == 'True'"> + <Antlr3 Include="**/*.g" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + <Antlr3 Include="**/*.g3" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + <AntlrTokens Include="**/*.tokens" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + </ItemGroup> + +</Project> diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets index 4bfe8b3..5d39d2b 100644 --- a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets +++ b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets @@ -1,27 +1,21 @@ <?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <EnableDefaultAntlrItems Condition="'$(EnableDefaultAntlrItems)' == ''">True</EnableDefaultAntlrItems> </PropertyGroup> - <ItemGroup Condition="'$(EnableDefaultItems)' == 'True'"> - <Antlr3 Include="**/*.g" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - <Antlr3 Include="**/*.g3" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - <AntlrTokens Include="**/*.tokens" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - </ItemGroup> - <ItemGroup Condition="'$(EnableDefaultItems)' == 'True' AND '$(EnableDefaultNoneItems)' == 'True'"> <None Remove="**/*.g" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <None Remove="**/*.g3" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <None Remove="**/*.tokens" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> </ItemGroup> <!-- Modify the CustomToolNamespace based on the directory location of the grammar --> <ItemGroup> <Antlr3 Update="@(Antlr3)" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault(%(RelativeDir), '').Replace('\', '.').Replace('/', '.').TrimEnd('.'))" /> <Antlr3 Update="@(Antlr3)" Condition="'$(RootNamespace)' != ''" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault('$(RootNamespace).%(DefaultCustomToolNamespace)', '').TrimEnd('.'))" /> <Antlr3 Update="@(Antlr3)" CustomToolNamespace="$([MSBuild]::ValueOrDefault(%(CustomToolNamespace), %(DefaultCustomToolNamespace)))" /> </ItemGroup> </Project> diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.props b/AntlrBuildTask/Antlr3.CodeGenerator.props index a921e65..6e3b20b 100644 --- a/AntlrBuildTask/Antlr3.CodeGenerator.props +++ b/AntlrBuildTask/Antlr3.CodeGenerator.props @@ -1,15 +1,17 @@ <?xml version="1.0" encoding="utf-8" ?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> </PropertyGroup> <PropertyGroup> <!-- Folder containing AntlrBuildTask.dll --> <AntlrBuildTaskPath Condition="'$(MSBuildRuntimeType)' != 'Core'">$(MSBuildThisFileDirectory)..\tools\net40</AntlrBuildTaskPath> <AntlrBuildTaskPath Condition="'$(MSBuildRuntimeType)' == 'Core'">$(MSBuildThisFileDirectory)..\tools\netstandard</AntlrBuildTaskPath> <!-- Path to the ANTLR tool itself --> <AntlrToolPath Condition="'$(MSBuildRuntimeType)' != 'Core'">$(AntlrBuildTaskPath)\Antlr3.exe</AntlrToolPath> <AntlrToolPath Condition="'$(MSBuildRuntimeType)' == 'Core'">$(AntlrBuildTaskPath)\Antlr3.dll</AntlrToolPath> </PropertyGroup> + + <Import Project="Antlr3.CodeGenerator.DefaultItems.props" /> </Project> diff --git a/AntlrBuildTask/AntlrBuildTask.csproj b/AntlrBuildTask/AntlrBuildTask.csproj index 48c8e39..164b68f 100644 --- a/AntlrBuildTask/AntlrBuildTask.csproj +++ b/AntlrBuildTask/AntlrBuildTask.csproj @@ -1,53 +1,56 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net40</TargetFrameworks> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <OutputPath>..\bin\$(Configuration)\</OutputPath> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="14.3" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="14.3" /> </ItemGroup> <PropertyGroup> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40'"> <ItemGroup> <Reference Include="Microsoft.Build.Framework" /> <Reference Include="Microsoft.Build.Tasks.v4.0" /> <Reference Include="Microsoft.Build.Utilities.v4.0" /> </ItemGroup> </When> </Choose> <ItemGroup> + <None Update="Antlr3.CodeGenerator.DefaultItems.props"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> <None Update="Antlr3.CodeGenerator.DefaultItems.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="Antlr3.CodeGenerator.props"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="Antlr3.CodeGenerator.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <None Update="Rules\*.xml" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/build/prep/Antlr3.CodeGenerator.nuspec b/build/prep/Antlr3.CodeGenerator.nuspec index a85be8b..02d5414 100644 --- a/build/prep/Antlr3.CodeGenerator.nuspec +++ b/build/prep/Antlr3.CodeGenerator.nuspec @@ -1,74 +1,75 @@ <?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata minClientVersion="2.5"> <id>Antlr3.CodeGenerator</id> <version>0.0.0</version> <authors>Sam Harwell, Terence Parr</authors> <owners>Sam Harwell</owners> <description>The C# target of the ANTLR 3 parser generator. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2010 or newer.</description> <language>en-us</language> <projectUrl>https://github.com/antlr/antlrcs</projectUrl> <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> <copyright>Copyright © Sam Harwell 2013</copyright> <releaseNotes>https://github.com/antlr/antlrcs/releases/$version$</releaseNotes> <requireLicenseAcceptance>true</requireLicenseAcceptance> <tags>antlr antlr3 parsing</tags> <title>ANTLR 3</title> <summary>The C# target of the ANTLR 3 parser generator.</summary> <developmentDependency>true</developmentDependency> </metadata> <files> <!-- Tools --> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.exe" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.exe.config" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr4.StringTemplate.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr4.StringTemplate.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\*.stg" target="tools\net40\Codegen\Templates"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\CSharp2\*.stg" target="tools\net40\Codegen\Templates\CSharp2"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\CSharp3\*.stg" target="tools\net40\Codegen\Templates\CSharp3"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp2.dll" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp2.pdb" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp3.dll" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp3.pdb" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Tool\Templates\**\*.stg" target="tools\net40\Tool\Templates"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.dll.config" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.Debug.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.Debug.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr4.StringTemplate.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr4.StringTemplate.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\*.stg" target="tools\netstandard\Codegen\Templates"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\CSharp2\*.stg" target="tools\netstandard\Codegen\Templates\CSharp2"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\CSharp3\*.stg" target="tools\netstandard\Codegen\Templates\CSharp3"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp2.dll" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp2.pdb" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp3.dll" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp3.pdb" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Tool\Templates\**\*.stg" target="tools\netstandard\Tool\Templates"/> <!-- Build Configuration --> + <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.DefaultItems.props" target="build" /> <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.DefaultItems.targets" target="build" /> <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.props" target="build" /> <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.targets" target="build" /> <file src="..\..\bin\$Configuration$\net40\AntlrBuildTask.dll" target="tools\net40" /> <file src="..\..\bin\$Configuration$\net40\AntlrBuildTask.pdb" target="tools\net40" /> <file src="..\..\bin\$Configuration$\netstandard2.0\AntlrBuildTask.dll" target="tools\netstandard" /> <file src="..\..\bin\$Configuration$\netstandard2.0\AntlrBuildTask.pdb" target="tools\netstandard" /> <file src="..\..\bin\$Configuration$\net40\Rules\Antlr3.ProjectItemsSchema.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\Antlr3.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\AntlrAbstractGrammar.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\AntlrTokens.xml" target="build\Rules" /> </files> </package>
antlr/antlrcs
6f96be47d1a633c0c8a2adb7697235ddcaf0181b
Move ANTLR default items to separate files
diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets new file mode 100644 index 0000000..4bfe8b3 --- /dev/null +++ b/AntlrBuildTask/Antlr3.CodeGenerator.DefaultItems.targets @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project> + + <PropertyGroup> + <EnableDefaultAntlrItems Condition="'$(EnableDefaultAntlrItems)' == ''">True</EnableDefaultAntlrItems> + </PropertyGroup> + + <ItemGroup Condition="'$(EnableDefaultItems)' == 'True'"> + <Antlr3 Include="**/*.g" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + <Antlr3 Include="**/*.g3" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + <AntlrTokens Include="**/*.tokens" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + </ItemGroup> + + <ItemGroup Condition="'$(EnableDefaultItems)' == 'True' AND '$(EnableDefaultNoneItems)' == 'True'"> + <None Remove="**/*.g" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + <None Remove="**/*.g3" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + <None Remove="**/*.tokens" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> + </ItemGroup> + + <!-- Modify the CustomToolNamespace based on the directory location of the grammar --> + <ItemGroup> + <Antlr3 Update="@(Antlr3)" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault(%(RelativeDir), '').Replace('\', '.').Replace('/', '.').TrimEnd('.'))" /> + <Antlr3 Update="@(Antlr3)" Condition="'$(RootNamespace)' != ''" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault('$(RootNamespace).%(DefaultCustomToolNamespace)', '').TrimEnd('.'))" /> + <Antlr3 Update="@(Antlr3)" CustomToolNamespace="$([MSBuild]::ValueOrDefault(%(CustomToolNamespace), %(DefaultCustomToolNamespace)))" /> + </ItemGroup> + +</Project> diff --git a/AntlrBuildTask/Antlr3.CodeGenerator.targets b/AntlrBuildTask/Antlr3.CodeGenerator.targets index ba00cb9..e65b81e 100644 --- a/AntlrBuildTask/Antlr3.CodeGenerator.targets +++ b/AntlrBuildTask/Antlr3.CodeGenerator.targets @@ -1,230 +1,210 @@ <!-- [The "BSD licence"] Copyright (c) 2011 Sam Harwell All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> </PropertyGroup> <PropertyGroup Condition="'$(AntlrIsSdkProject)' == ''"> <AntlrIsSdkProject>False</AntlrIsSdkProject> <AntlrIsSdkProject Condition="'$(TargetFramework)' != '' OR '$(TargetFrameworks)' != ''">True</AntlrIsSdkProject> </PropertyGroup> <PropertyGroup> <BuildSystem>MSBuild</BuildSystem> <TaskVersion>3.5.0.2</TaskVersion> <TaskKeyToken>eb42632606e9261f</TaskKeyToken> <AntlrBuildTaskAssemblyName Condition="'$(AntlrBuildTaskAssemblyName)'==''">AntlrBuildTask, Version=$(TaskVersion), Culture=neutral, PublicKeyToken=$(TaskKeyToken)</AntlrBuildTaskAssemblyName> </PropertyGroup> <PropertyGroup> <LoadTimeSensitiveTargets> $(LoadTimeSensitiveTargets); AntlrCompile; </LoadTimeSensitiveTargets> <LoadTimeSensitiveProperties> $(LoadTimeSensitiveProperties); AntlrCompileDependsOn; </LoadTimeSensitiveProperties> </PropertyGroup> <PropertyGroup> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'==''">$(MSBuildBinPath)</AntlrBuildTaskLocation> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'!=''">$(AntlrBuildTaskPath)</AntlrBuildTaskLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'==''">$(MSBuildBinPath)\Antlr3\Antlr3.exe</AntlrToolLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'!=''">$(AntlrToolPath)</AntlrToolLocation> </PropertyGroup> <PropertyGroup> <AntlrGenCodeFileNames Condition="'$(AntlrGenCodeFileNames)'==''">$(MSBuildProjectFile).AntlrGeneratedCodeFileListAbsolute.txt</AntlrGenCodeFileNames> </PropertyGroup> <UsingTask Condition="'$(AntlrBuildTaskPath)'==''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyName="$(AntlrBuildTaskAssemblyName)" /> <UsingTask Condition="'$(AntlrBuildTaskPath)'!=''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyFile="$(AntlrBuildTaskPath)\AntlrBuildTask.dll" /> <PropertyGroup> <PrepareResourcesDependsOn> AntlrCompile; AntlrCompileAddFilesGenerated; $(PrepareResourcesDependsOn) </PrepareResourcesDependsOn> <SourceFilesProjectOutputGroupDependsOn> AntlrCompile; AntlrCompileAddFilesGenerated; $(SourceFilesProjectOutputGroupDependsOn) </SourceFilesProjectOutputGroupDependsOn> </PropertyGroup> <PropertyGroup> <AntlrCompileDependsOn> AntlrCompileReadGeneratedFileList </AntlrCompileDependsOn> </PropertyGroup> <ItemGroup Condition="'$(BuildingInsideVisualStudio)'=='true'"> <AvailableItemName Include="Antlr3" /> <AvailableItemName Include="AntlrTokens" /> <AvailableItemName Include="AntlrAbstractGrammar" /> </ItemGroup> <ItemDefinitionGroup> <Antlr3> <Generator>MSBuild:Compile</Generator> <CustomToolNamespace Condition="'$(AntlrIsSdkProject)' != 'True'">$(RootNamespace)</CustomToolNamespace> <TargetLanguage/> <DebugGrammar>false</DebugGrammar> <ProfileGrammar>false</ProfileGrammar> </Antlr3> </ItemDefinitionGroup> <Target Name="AntlrCompileReadGeneratedFileList"> <ReadLinesFromFile File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)"> <Output TaskParameter="Lines" ItemName="AntlrOutputCodeFilesList"/> </ReadLinesFromFile> </Target> <PropertyGroup> <!-- Add grammar compilation to the CoreCompileDependsOn so that the IDE inproc compilers (particularly VB) can "see" the generated source files. --> <CoreCompileDependsOn Condition="'$(BuildingInsideVisualStudio)' == 'true' "> DesignTimeGrammarCompilation; $(CoreCompileDependsOn) </CoreCompileDependsOn> </PropertyGroup> <Target Name="DesignTimeGrammarCompilation"> <PropertyGroup> <AntlrDesignTimeBuild Condition="'$(DesignTimeBuild)' == 'true' OR '$(BuildingProject)' != 'true'">true</AntlrDesignTimeBuild> </PropertyGroup> <!-- Only if we are not actually performing a compile i.e. we are in design mode --> <CallTarget Condition="'$(AntlrDesignTimeBuild)' == 'true'" Targets="AntlrCompile" /> </Target> <Target Name="AntlrCompile" DependsOnTargets="$(AntlrCompileDependsOn)" Condition="'@(Antlr3)' != ''" Inputs="@(Antlr3);@(AntlrTokens);@(AntlrAbstractGrammar)" Outputs="@(AntlrOutputCodeFilesList); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);"> <ItemGroup> <AntlrGeneratedCodeFiles Remove="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> <PropertyGroup> <AntlrDesignTimeBuild>false</AntlrDesignTimeBuild> <AntlrDesignTimeBuild Condition="'$(DesignTimeBuild)' == 'true' OR '$(BuildingProject)' != 'true'">true</AntlrDesignTimeBuild> </PropertyGroup> <AntlrClassGenerationTask AntlrToolPath="$(AntlrToolLocation)" BuildTaskPath="$(AntlrBuildTaskLocation)" OutputPath="$(IntermediateOutputPath)" TargetLanguage="%(Antlr3.TargetLanguage)" SourceCodeFiles="@(Antlr3)" ContinueOnError="$(AntlrDesignTimeBuild)" TokensFiles="@(AntlrTokens)" AbstractGrammarFiles="@(AntlrAbstractGrammar)" LanguageSourceExtensions="$(DefaultLanguageSourceExtension)" DebugGrammar="%(Antlr3.DebugGrammar)" ProfileGrammar="%(Antlr3.ProfileGrammar)"> <Output ItemName="AntlrGeneratedCodeFiles" TaskParameter="GeneratedCodeFiles" /> </AntlrClassGenerationTask> <WriteLinesToFile Condition="'$(AntlrDesignTimeBuild)' != 'true'" File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)" Lines="@(AntlrGeneratedCodeFiles)" Overwrite="true"/> </Target> <Target Name="AntlrCompileAddFilesGenerated" AfterTargets="AntlrCompile" Condition="'@(Antlr3)' != ''"> <ItemGroup> <AntlrGeneratedCodeFiles Condition="'@(AntlrGeneratedCodeFiles)' == ''" Include="@(AntlrOutputCodeFilesList)" /> </ItemGroup> <ItemGroup> <FileWrites Include="@(AntlrGeneratedCodeFiles); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);" /> </ItemGroup> <ItemGroup> <Compile Include="@(AntlrGeneratedCodeFiles)" /> <!-- The WinFX "GenerateTemporaryTargetAssembly" target requires generated code files be added here. --> <_GeneratedCodeFiles Include="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> </Target> <Choose> <When Condition="'$(AntlrIsSdkProject)' == 'True'"> - <PropertyGroup> - <EnableDefaultAntlrItems Condition="'$(EnableDefaultAntlrItems)' == ''">True</EnableDefaultAntlrItems> - </PropertyGroup> - - <ItemGroup Condition="'$(EnableDefaultItems)' == 'True'"> - <Antlr3 Include="**/*.g" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - <Antlr3 Include="**/*.g3" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - <AntlrTokens Include="**/*.tokens" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - </ItemGroup> - <ItemGroup Condition="'$(EnableDefaultItems)' == 'True' AND '$(EnableDefaultNoneItems)' == 'True'"> - <None Remove="**/*.g" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - <None Remove="**/*.g3" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - <None Remove="**/*.tokens" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> - </ItemGroup> - <ItemGroup> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\Antlr3.ProjectItemsSchema.xml"> <Context>Project</Context> </PropertyPageSchema> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\Antlr3.xml"> <Context>File;BrowseObject</Context> </PropertyPageSchema> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\AntlrAbstractGrammar.xml"> <Context>File;BrowseObject</Context> </PropertyPageSchema> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\AntlrTokens.xml"> <Context>File;BrowseObject</Context> </PropertyPageSchema> </ItemGroup> - - <!-- Modify the CustomToolNamespace based on the directory location of the grammar --> - <ItemGroup> - <Antlr3 Update="@(Antlr3)" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault(%(RelativeDir), '').Replace('\', '.').Replace('/', '.').TrimEnd('.'))" /> - <Antlr3 Update="@(Antlr3)" Condition="'$(RootNamespace)' != ''" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault('$(RootNamespace).%(DefaultCustomToolNamespace)', '').TrimEnd('.'))" /> - <Antlr3 Update="@(Antlr3)" CustomToolNamespace="$([MSBuild]::ValueOrDefault(%(CustomToolNamespace), %(DefaultCustomToolNamespace)))" /> - </ItemGroup> </When> </Choose> + + <Import Condition="'$(AntlrIsSdkProject)' == 'True'" Project="Antlr3.CodeGenerator.DefaultItems.targets" /> </Project> diff --git a/AntlrBuildTask/AntlrBuildTask.csproj b/AntlrBuildTask/AntlrBuildTask.csproj index cbbf616..48c8e39 100644 --- a/AntlrBuildTask/AntlrBuildTask.csproj +++ b/AntlrBuildTask/AntlrBuildTask.csproj @@ -1,50 +1,53 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net40</TargetFrameworks> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <OutputPath>..\bin\$(Configuration)\</OutputPath> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="14.3" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="14.3" /> </ItemGroup> <PropertyGroup> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40'"> <ItemGroup> <Reference Include="Microsoft.Build.Framework" /> <Reference Include="Microsoft.Build.Tasks.v4.0" /> <Reference Include="Microsoft.Build.Utilities.v4.0" /> </ItemGroup> </When> </Choose> <ItemGroup> + <None Update="Antlr3.CodeGenerator.DefaultItems.targets"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> <None Update="Antlr3.CodeGenerator.props"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="Antlr3.CodeGenerator.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <None Update="Rules\*.xml" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/build/prep/Antlr3.CodeGenerator.nuspec b/build/prep/Antlr3.CodeGenerator.nuspec index fdb423d..a85be8b 100644 --- a/build/prep/Antlr3.CodeGenerator.nuspec +++ b/build/prep/Antlr3.CodeGenerator.nuspec @@ -1,73 +1,74 @@ <?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata minClientVersion="2.5"> <id>Antlr3.CodeGenerator</id> <version>0.0.0</version> <authors>Sam Harwell, Terence Parr</authors> <owners>Sam Harwell</owners> <description>The C# target of the ANTLR 3 parser generator. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2010 or newer.</description> <language>en-us</language> <projectUrl>https://github.com/antlr/antlrcs</projectUrl> <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> <copyright>Copyright © Sam Harwell 2013</copyright> <releaseNotes>https://github.com/antlr/antlrcs/releases/$version$</releaseNotes> <requireLicenseAcceptance>true</requireLicenseAcceptance> <tags>antlr antlr3 parsing</tags> <title>ANTLR 3</title> <summary>The C# target of the ANTLR 3 parser generator.</summary> <developmentDependency>true</developmentDependency> </metadata> <files> <!-- Tools --> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.exe" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.exe.config" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr4.StringTemplate.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr4.StringTemplate.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\*.stg" target="tools\net40\Codegen\Templates"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\CSharp2\*.stg" target="tools\net40\Codegen\Templates\CSharp2"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\CSharp3\*.stg" target="tools\net40\Codegen\Templates\CSharp3"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp2.dll" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp2.pdb" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp3.dll" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp3.pdb" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Tool\Templates\**\*.stg" target="tools\net40\Tool\Templates"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.dll.config" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.Debug.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.Debug.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr4.StringTemplate.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr4.StringTemplate.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\*.stg" target="tools\netstandard\Codegen\Templates"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\CSharp2\*.stg" target="tools\netstandard\Codegen\Templates\CSharp2"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\CSharp3\*.stg" target="tools\netstandard\Codegen\Templates\CSharp3"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp2.dll" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp2.pdb" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp3.dll" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp3.pdb" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Tool\Templates\**\*.stg" target="tools\netstandard\Tool\Templates"/> <!-- Build Configuration --> + <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.DefaultItems.targets" target="build" /> <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.props" target="build" /> <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.targets" target="build" /> <file src="..\..\bin\$Configuration$\net40\AntlrBuildTask.dll" target="tools\net40" /> <file src="..\..\bin\$Configuration$\net40\AntlrBuildTask.pdb" target="tools\net40" /> <file src="..\..\bin\$Configuration$\netstandard2.0\AntlrBuildTask.dll" target="tools\netstandard" /> <file src="..\..\bin\$Configuration$\netstandard2.0\AntlrBuildTask.pdb" target="tools\netstandard" /> <file src="..\..\bin\$Configuration$\net40\Rules\Antlr3.ProjectItemsSchema.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\Antlr3.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\AntlrAbstractGrammar.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\AntlrTokens.xml" target="build\Rules" /> </files> </package>
antlr/antlrcs
74559200b01367928dabb38f33c0fb7a30e9861f
Rename build extensions to match package name
diff --git a/AntlrBuildTask/Antlr3.props b/AntlrBuildTask/Antlr3.CodeGenerator.props similarity index 100% rename from AntlrBuildTask/Antlr3.props rename to AntlrBuildTask/Antlr3.CodeGenerator.props diff --git a/AntlrBuildTask/Antlr3.targets b/AntlrBuildTask/Antlr3.CodeGenerator.targets similarity index 100% rename from AntlrBuildTask/Antlr3.targets rename to AntlrBuildTask/Antlr3.CodeGenerator.targets diff --git a/AntlrBuildTask/AntlrBuildTask.csproj b/AntlrBuildTask/AntlrBuildTask.csproj index e894da6..cbbf616 100644 --- a/AntlrBuildTask/AntlrBuildTask.csproj +++ b/AntlrBuildTask/AntlrBuildTask.csproj @@ -1,50 +1,50 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net40</TargetFrameworks> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <OutputPath>..\bin\$(Configuration)\</OutputPath> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="14.3" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="14.3" /> </ItemGroup> <PropertyGroup> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40'"> <ItemGroup> <Reference Include="Microsoft.Build.Framework" /> <Reference Include="Microsoft.Build.Tasks.v4.0" /> <Reference Include="Microsoft.Build.Utilities.v4.0" /> </ItemGroup> </When> </Choose> <ItemGroup> - <None Update="Antlr3.props"> + <None Update="Antlr3.CodeGenerator.props"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> - <None Update="Antlr3.targets"> + <None Update="Antlr3.CodeGenerator.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <None Update="Rules\*.xml" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/build/prep/Antlr3.CodeGenerator.nuspec b/build/prep/Antlr3.CodeGenerator.nuspec index d2bcc0a..fdb423d 100644 --- a/build/prep/Antlr3.CodeGenerator.nuspec +++ b/build/prep/Antlr3.CodeGenerator.nuspec @@ -1,73 +1,73 @@ <?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata minClientVersion="2.5"> <id>Antlr3.CodeGenerator</id> <version>0.0.0</version> <authors>Sam Harwell, Terence Parr</authors> <owners>Sam Harwell</owners> <description>The C# target of the ANTLR 3 parser generator. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2010 or newer.</description> <language>en-us</language> <projectUrl>https://github.com/antlr/antlrcs</projectUrl> <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> <copyright>Copyright © Sam Harwell 2013</copyright> <releaseNotes>https://github.com/antlr/antlrcs/releases/$version$</releaseNotes> <requireLicenseAcceptance>true</requireLicenseAcceptance> <tags>antlr antlr3 parsing</tags> <title>ANTLR 3</title> <summary>The C# target of the ANTLR 3 parser generator.</summary> <developmentDependency>true</developmentDependency> </metadata> <files> <!-- Tools --> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.exe" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.exe.config" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr3.Runtime.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr4.StringTemplate.dll" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Antlr4.StringTemplate.pdb" target="tools\net40"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\*.stg" target="tools\net40\Codegen\Templates"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\CSharp2\*.stg" target="tools\net40\Codegen\Templates\CSharp2"/> <file src="..\..\bin\$Configuration$\net40-client\Codegen\Templates\CSharp3\*.stg" target="tools\net40\Codegen\Templates\CSharp3"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp2.dll" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp2.pdb" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp3.dll" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Targets\Antlr3.Targets.CSharp3.pdb" target="tools\net40\Targets"/> <file src="..\..\bin\$Configuration$\net40-client\Tool\Templates\**\*.stg" target="tools\net40\Tool\Templates"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.dll.config" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.Debug.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.Debug.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr3.Runtime.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr4.StringTemplate.dll" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Antlr4.StringTemplate.pdb" target="tools\netstandard"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\*.stg" target="tools\netstandard\Codegen\Templates"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\CSharp2\*.stg" target="tools\netstandard\Codegen\Templates\CSharp2"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Codegen\Templates\CSharp3\*.stg" target="tools\netstandard\Codegen\Templates\CSharp3"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp2.dll" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp2.pdb" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp3.dll" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Targets\Antlr3.Targets.CSharp3.pdb" target="tools\netstandard\Targets"/> <file src="..\..\bin\$Configuration$\netstandard2.0\Tool\Templates\**\*.stg" target="tools\netstandard\Tool\Templates"/> <!-- Build Configuration --> - <file src="..\..\bin\$Configuration$\net40\Antlr3.props" target="build\Antlr3.CodeGenerator.props" /> - <file src="..\..\bin\$Configuration$\net40\Antlr3.targets" target="build\Antlr3.CodeGenerator.targets" /> + <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.props" target="build" /> + <file src="..\..\bin\$Configuration$\net40\Antlr3.CodeGenerator.targets" target="build" /> <file src="..\..\bin\$Configuration$\net40\AntlrBuildTask.dll" target="tools\net40" /> <file src="..\..\bin\$Configuration$\net40\AntlrBuildTask.pdb" target="tools\net40" /> <file src="..\..\bin\$Configuration$\netstandard2.0\AntlrBuildTask.dll" target="tools\netstandard" /> <file src="..\..\bin\$Configuration$\netstandard2.0\AntlrBuildTask.pdb" target="tools\netstandard" /> <file src="..\..\bin\$Configuration$\net40\Rules\Antlr3.ProjectItemsSchema.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\Antlr3.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\AntlrAbstractGrammar.xml" target="build\Rules" /> <file src="..\..\bin\$Configuration$\net40\Rules\AntlrTokens.xml" target="build\Rules" /> </files> </package>
antlr/antlrcs
8e7b2cb7a979b609652bc0e736da3fe267c5f039
Remove duplicate None items
diff --git a/AntlrBuildTask/AntlrBuildTask.csproj b/AntlrBuildTask/AntlrBuildTask.csproj index da24b93..e894da6 100644 --- a/AntlrBuildTask/AntlrBuildTask.csproj +++ b/AntlrBuildTask/AntlrBuildTask.csproj @@ -1,51 +1,50 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net40</TargetFrameworks> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <OutputPath>..\bin\$(Configuration)\</OutputPath> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="14.3" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="14.3" /> </ItemGroup> <PropertyGroup> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40'"> <ItemGroup> <Reference Include="Microsoft.Build.Framework" /> <Reference Include="Microsoft.Build.Tasks.v4.0" /> <Reference Include="Microsoft.Build.Utilities.v4.0" /> </ItemGroup> </When> </Choose> <ItemGroup> - <None Include="Antlr3.Java.targets" /> - <None Include="Antlr3.props"> + <None Update="Antlr3.props"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> - <None Include="Antlr3.targets"> + <None Update="Antlr3.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <None Update="Rules\*.xml" CopyToOutputDirectory="PreserveNewest" /> </ItemGroup> </Project> \ No newline at end of file
antlr/antlrcs
1b451a16ad9b7232abd4c1692a016c391e5ac680
Simplify YAML syntax in appveyor.yml
diff --git a/appveyor.yml b/appveyor.yml index c8fc1d1..1eabe2f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,24 +1,22 @@ version: 1.0.{build} os: Visual Studio 2017 configuration: Release init: -- cmd: >- +- cmd: | git config --global core.autocrlf true - mkdir ..\..\..\keys\antlr - "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sn.exe" -k ..\..\..\keys\antlr\Key.snk install: - git submodule update --init --recursive build_script: - cd build\prep - powershell -Command .\prepare.ps1 -Logger "${env:ProgramFiles}\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" - cd ..\.. test_script: - vstest.console /logger:Appveyor /TestCaseFilter:"TestCategory!=SkipOnCI" "C:\projects\antlrcs\Antlr3.Test\bin\%CONFIGURATION%\net45\AntlrUnitTests.dll" - vstest.console /logger:Appveyor /TestCaseFilter:"TestCategory!=Visualizer" "C:\projects\antlrcs\Antlr4.Test.StringTemplate\bin\%CONFIGURATION%\net45\Antlr4.Test.StringTemplate.dll" - dotnet vstest /Framework:".NETCoreApp,Version=v2.0" /TestCaseFilter:"TestCategory!=SkipOnCI" "C:\projects\antlrcs\Antlr3.Test\bin\%CONFIGURATION%\netcoreapp2.0\AntlrUnitTests.dll" - dotnet vstest /Framework:".NETCoreApp,Version=v2.0" /TestCaseFilter:"TestCategory!=Visualizer" "C:\projects\antlrcs\Antlr4.Test.StringTemplate\bin\%CONFIGURATION%\netcoreapp2.0\Antlr4.Test.StringTemplate.dll" artifacts: - path: build\prep\nuget\*.nupkg - path: build\prep\dist\*.7z
antlr/antlrcs
eeda54c1b95461dafb826adc8045db35acd69941
Simplify the .gitattributes to auto-detect text files
diff --git a/.gitattributes b/.gitattributes index 14c7e3f..29dbbfe 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,36 +1,2 @@ -# Source code files -*.cs text -*.vsixmanifest text -*.config text -*.resx text -*.vstemplate text -*.nuspec text -*.md text -*.txt text -*.ps1 text -*.stg text -*.xml text -LICENSE text - -# SHFB Content Files -*.aml text -*.content text -*.tokens text - -# Projects and solutions -*.sln text -*.csproj text -*.shfbproj text -*.targets text -*.props text - -# Certainly binary files -*.exe binary -*.dll binary -*.pdb binary - -*.docx binary - -*.png binary -*.ico binary -*.snk binary +# Auto-detect text files +* text=auto
antlr/antlrcs
262f2eba311b33a5fd7744fb84accacb7a4c6f4b
Disable synthetic project references for solution dependencies
diff --git a/Directory.Build.props b/Directory.Build.props index f0ab6aa..46d9d15 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,75 +1,80 @@ <?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> </PropertyGroup> <PropertyGroup> <!-- These properties are used by Directory.Build.props. Make sure they are set early enough for cases where they are not explicitly set during the MSBuild invocation. --> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> </PropertyGroup> + <PropertyGroup> + <!-- Solution build dependencies are not project dependencies. https://github.com/Microsoft/msbuild/issues/3626 --> + <AddSyntheticProjectReferencesForSolutionDependencies>false</AddSyntheticProjectReferencesForSolutionDependencies> + </PropertyGroup> + <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> <PropertyGroup> <!-- Default NuGet package properties. Additional items set in Directory.Build.targets. --> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Authors>Sam Harwell, Terence Parr</Authors> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageLicenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</PackageLicenseUrl> <PackageProjectUrl>https://github.com/antlr/antlrcs</PackageProjectUrl> <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl> <PackageReleaseNotes>https://github.com/antlr/antlrcs/releases/$(ANTLRInformationalVersion)</PackageReleaseNotes> <IncludeSymbols>true</IncludeSymbols> <IncludeSource>true</IncludeSource> <PackageOutputPath>$(MSBuildThisFileDirectory)build\prep\nuget\</PackageOutputPath> </PropertyGroup> <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta2" PrivateAssets="all" /> </ItemGroup> <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project>
antlr/antlrcs
821a790af64b660bb391b4d07c706dae03b2fb5f
Prepare for next development iteration
diff --git a/Directory.Build.props b/Directory.Build.props index d22da6c..37ad5af 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,81 +1,81 @@ <?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> </PropertyGroup> <PropertyGroup> <!-- These properties are used by Directory.Build.props. Make sure they are set early enough for cases where they are not explicitly set during the MSBuild invocation. --> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> </PropertyGroup> <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> - <ANTLRInformationalVersion>3.5.2-beta2</ANTLRInformationalVersion> + <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> - <STInformationalVersion>4.0.9-beta2</STInformationalVersion> + <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> <PropertyGroup> <!-- Default NuGet package properties. Additional items set in Directory.Build.targets. --> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Authors>Sam Harwell, Terence Parr</Authors> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageLicenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</PackageLicenseUrl> <PackageProjectUrl>https://github.com/antlr/antlrcs</PackageProjectUrl> <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl> <PackageReleaseNotes>https://github.com/antlr/antlrcs/releases/$(ANTLRInformationalVersion)</PackageReleaseNotes> <IncludeSymbols>true</IncludeSymbols> <IncludeSource>true</IncludeSource> <PackageOutputPath>$(MSBuildThisFileDirectory)build\prep\nuget\</PackageOutputPath> </PropertyGroup> <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta1" PrivateAssets="all" /> </ItemGroup> <!-- Workaround to ensure generated ANTLR parsers are included in NuGet source package. --> <Target Name="AntlrBeforeSourceFiles" Condition="'$(BootstrapBuild)' != 'true'" BeforeTargets="SourceFilesProjectOutputGroup" DependsOnTargets="AntlrCompile;AntlrCompileAddFilesGenerated" /> <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project> diff --git a/build/Validation/DotnetValidation.csproj b/build/Validation/DotnetValidation.csproj index 8b7070e..809a958 100644 --- a/build/Validation/DotnetValidation.csproj +++ b/build/Validation/DotnetValidation.csproj @@ -1,33 +1,33 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>net20;net30;net35;net40;net45;netcoreapp1.1;portable40-net40+sl5+win8+wp8+wpa81</TargetFrameworks> <EnableDefaultNoneItems>False</EnableDefaultNoneItems> <Antlr4UseCSharpGenerator>True</Antlr4UseCSharpGenerator> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'portable40-net40+sl5+win8+wp8+wpa81'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Profile328</TargetFrameworkProfile> <DefineConstants>$(DefineConstants);LEGACY_PCL</DefineConstants> </PropertyGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> </When> </Choose> <ItemGroup> - <PackageReference Include="Antlr3" Version="3.5.2-beta2" /> + <PackageReference Include="Antlr3" Version="3.5.2-dev" /> </ItemGroup> <ItemGroup> <None Include="NuGet.config" /> </ItemGroup> </Project> diff --git a/build/prep/version.ps1 b/build/prep/version.ps1 index 6625cbb..e8252a8 100644 --- a/build/prep/version.ps1 +++ b/build/prep/version.ps1 @@ -1,2 +1,2 @@ -$AntlrVersion = "3.5.2-beta2" -$STVersion = "4.0.9-beta2" +$AntlrVersion = "3.5.2-dev" +$STVersion = "4.0.9-dev"
antlr/antlrcs
7e09581831200d3ba06a1a5e5165d2a3887e3933
Add Travis CI build status badge
diff --git a/README.md b/README.md index 435ca19..701a2e4 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,28 @@ # ANTLR 3 C# Target [![Join the chat at https://gitter.im/antlr/antlrcs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/antlr/antlrcs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Build status](https://ci.appveyor.com/api/projects/status/x21gyx4ikxsa9n3t/branch/master?svg=true)](https://ci.appveyor.com/project/sharwell/antlrcs/branch/master) +| Platform | Build Status | +| --- | --- | +| Windows | [![Build status](https://ci.appveyor.com/api/projects/status/x21gyx4ikxsa9n3t/branch/master?svg=true)](https://ci.appveyor.com/project/sharwell/antlrcs/branch/master) | +| Linux | [![Build status](https://travis-ci.org/antlr/antlrcs.svg?branch=master)](https://travis-ci.org/antlr/antlrcs) | This repository contains C# versions of 3 major projects, some of which have multiple build artifacts: * ANTLR 3 * [Antlr3](https://www.nuget.org/packages/Antlr3): Code generator for ANTLR 3 * [Antlr3.Runtime](https://www.nuget.org/packages/Antlr3.Runtime): Runtime library for ANTLR 3 * [Antlr3.Runtime.Debug](https://www.nuget.org/packages/Antlr3.Runtime.Debug): Runtime library debugging tools for ANTLR 3 * StringTemplate 3 * [StringTemplate3](https://www.nuget.org/packages/StringTemplate3): Runtime library * StringTemplate 4 * [StringTemplate4](https://www.nuget.org/packages/StringTemplate4): Runtime library * [StringTemplate4.Visualizer](https://www.nuget.org/packages/StringTemplate4.Visualizer): WPF visualizer for rendering StringTemplate 4 templates ## Documentation The following pages provide documentation for this project: * [Visual Studio and the ANTLR C# Target](doc/README.md) * [ANTLR v3 Home](http://www.antlr3.org) * [StringTemplate Home](http://www.stringtemplate.org/)
antlr/antlrcs
ffa85b94cbe32a96fdea6a156f4522eea64ce066
Make sure NuGet pack includes generated source files
diff --git a/AntlrBuildTask/Antlr3.targets b/AntlrBuildTask/Antlr3.targets index e67b491..ba00cb9 100644 --- a/AntlrBuildTask/Antlr3.targets +++ b/AntlrBuildTask/Antlr3.targets @@ -1,225 +1,230 @@ <!-- [The "BSD licence"] Copyright (c) 2011 Sam Harwell All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> </PropertyGroup> <PropertyGroup Condition="'$(AntlrIsSdkProject)' == ''"> <AntlrIsSdkProject>False</AntlrIsSdkProject> <AntlrIsSdkProject Condition="'$(TargetFramework)' != '' OR '$(TargetFrameworks)' != ''">True</AntlrIsSdkProject> </PropertyGroup> <PropertyGroup> <BuildSystem>MSBuild</BuildSystem> <TaskVersion>3.5.0.2</TaskVersion> <TaskKeyToken>eb42632606e9261f</TaskKeyToken> <AntlrBuildTaskAssemblyName Condition="'$(AntlrBuildTaskAssemblyName)'==''">AntlrBuildTask, Version=$(TaskVersion), Culture=neutral, PublicKeyToken=$(TaskKeyToken)</AntlrBuildTaskAssemblyName> </PropertyGroup> <PropertyGroup> <LoadTimeSensitiveTargets> $(LoadTimeSensitiveTargets); AntlrCompile; </LoadTimeSensitiveTargets> <LoadTimeSensitiveProperties> $(LoadTimeSensitiveProperties); AntlrCompileDependsOn; </LoadTimeSensitiveProperties> </PropertyGroup> <PropertyGroup> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'==''">$(MSBuildBinPath)</AntlrBuildTaskLocation> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'!=''">$(AntlrBuildTaskPath)</AntlrBuildTaskLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'==''">$(MSBuildBinPath)\Antlr3\Antlr3.exe</AntlrToolLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'!=''">$(AntlrToolPath)</AntlrToolLocation> </PropertyGroup> <PropertyGroup> <AntlrGenCodeFileNames Condition="'$(AntlrGenCodeFileNames)'==''">$(MSBuildProjectFile).AntlrGeneratedCodeFileListAbsolute.txt</AntlrGenCodeFileNames> </PropertyGroup> <UsingTask Condition="'$(AntlrBuildTaskPath)'==''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyName="$(AntlrBuildTaskAssemblyName)" /> <UsingTask Condition="'$(AntlrBuildTaskPath)'!=''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyFile="$(AntlrBuildTaskPath)\AntlrBuildTask.dll" /> <PropertyGroup> <PrepareResourcesDependsOn> AntlrCompile; AntlrCompileAddFilesGenerated; $(PrepareResourcesDependsOn) </PrepareResourcesDependsOn> + <SourceFilesProjectOutputGroupDependsOn> + AntlrCompile; + AntlrCompileAddFilesGenerated; + $(SourceFilesProjectOutputGroupDependsOn) + </SourceFilesProjectOutputGroupDependsOn> </PropertyGroup> <PropertyGroup> <AntlrCompileDependsOn> AntlrCompileReadGeneratedFileList </AntlrCompileDependsOn> </PropertyGroup> <ItemGroup Condition="'$(BuildingInsideVisualStudio)'=='true'"> <AvailableItemName Include="Antlr3" /> <AvailableItemName Include="AntlrTokens" /> <AvailableItemName Include="AntlrAbstractGrammar" /> </ItemGroup> <ItemDefinitionGroup> <Antlr3> <Generator>MSBuild:Compile</Generator> <CustomToolNamespace Condition="'$(AntlrIsSdkProject)' != 'True'">$(RootNamespace)</CustomToolNamespace> <TargetLanguage/> <DebugGrammar>false</DebugGrammar> <ProfileGrammar>false</ProfileGrammar> </Antlr3> </ItemDefinitionGroup> <Target Name="AntlrCompileReadGeneratedFileList"> <ReadLinesFromFile File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)"> <Output TaskParameter="Lines" ItemName="AntlrOutputCodeFilesList"/> </ReadLinesFromFile> </Target> <PropertyGroup> <!-- Add grammar compilation to the CoreCompileDependsOn so that the IDE inproc compilers (particularly VB) can "see" the generated source files. --> <CoreCompileDependsOn Condition="'$(BuildingInsideVisualStudio)' == 'true' "> DesignTimeGrammarCompilation; $(CoreCompileDependsOn) </CoreCompileDependsOn> </PropertyGroup> <Target Name="DesignTimeGrammarCompilation"> <PropertyGroup> <AntlrDesignTimeBuild Condition="'$(DesignTimeBuild)' == 'true' OR '$(BuildingProject)' != 'true'">true</AntlrDesignTimeBuild> </PropertyGroup> <!-- Only if we are not actually performing a compile i.e. we are in design mode --> <CallTarget Condition="'$(AntlrDesignTimeBuild)' == 'true'" Targets="AntlrCompile" /> </Target> <Target Name="AntlrCompile" DependsOnTargets="$(AntlrCompileDependsOn)" Condition="'@(Antlr3)' != ''" Inputs="@(Antlr3);@(AntlrTokens);@(AntlrAbstractGrammar)" Outputs="@(AntlrOutputCodeFilesList); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);"> <ItemGroup> <AntlrGeneratedCodeFiles Remove="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> <PropertyGroup> <AntlrDesignTimeBuild>false</AntlrDesignTimeBuild> <AntlrDesignTimeBuild Condition="'$(DesignTimeBuild)' == 'true' OR '$(BuildingProject)' != 'true'">true</AntlrDesignTimeBuild> </PropertyGroup> <AntlrClassGenerationTask AntlrToolPath="$(AntlrToolLocation)" BuildTaskPath="$(AntlrBuildTaskLocation)" OutputPath="$(IntermediateOutputPath)" TargetLanguage="%(Antlr3.TargetLanguage)" SourceCodeFiles="@(Antlr3)" ContinueOnError="$(AntlrDesignTimeBuild)" TokensFiles="@(AntlrTokens)" AbstractGrammarFiles="@(AntlrAbstractGrammar)" LanguageSourceExtensions="$(DefaultLanguageSourceExtension)" DebugGrammar="%(Antlr3.DebugGrammar)" ProfileGrammar="%(Antlr3.ProfileGrammar)"> <Output ItemName="AntlrGeneratedCodeFiles" TaskParameter="GeneratedCodeFiles" /> </AntlrClassGenerationTask> <WriteLinesToFile Condition="'$(AntlrDesignTimeBuild)' != 'true'" File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)" Lines="@(AntlrGeneratedCodeFiles)" Overwrite="true"/> </Target> <Target Name="AntlrCompileAddFilesGenerated" AfterTargets="AntlrCompile" Condition="'@(Antlr3)' != ''"> <ItemGroup> <AntlrGeneratedCodeFiles Condition="'@(AntlrGeneratedCodeFiles)' == ''" Include="@(AntlrOutputCodeFilesList)" /> </ItemGroup> <ItemGroup> <FileWrites Include="@(AntlrGeneratedCodeFiles); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);" /> </ItemGroup> <ItemGroup> <Compile Include="@(AntlrGeneratedCodeFiles)" /> <!-- The WinFX "GenerateTemporaryTargetAssembly" target requires generated code files be added here. --> <_GeneratedCodeFiles Include="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> </Target> <Choose> <When Condition="'$(AntlrIsSdkProject)' == 'True'"> <PropertyGroup> <EnableDefaultAntlrItems Condition="'$(EnableDefaultAntlrItems)' == ''">True</EnableDefaultAntlrItems> </PropertyGroup> <ItemGroup Condition="'$(EnableDefaultItems)' == 'True'"> <Antlr3 Include="**/*.g" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <Antlr3 Include="**/*.g3" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <AntlrTokens Include="**/*.tokens" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> </ItemGroup> <ItemGroup Condition="'$(EnableDefaultItems)' == 'True' AND '$(EnableDefaultNoneItems)' == 'True'"> <None Remove="**/*.g" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <None Remove="**/*.g3" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> <None Remove="**/*.tokens" Condition="'$(EnableDefaultAntlrItems)' == 'True'" /> </ItemGroup> <ItemGroup> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\Antlr3.ProjectItemsSchema.xml"> <Context>Project</Context> </PropertyPageSchema> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\Antlr3.xml"> <Context>File;BrowseObject</Context> </PropertyPageSchema> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\AntlrAbstractGrammar.xml"> <Context>File;BrowseObject</Context> </PropertyPageSchema> <PropertyPageSchema Include="$(MSBuildThisFileDirectory)Rules\AntlrTokens.xml"> <Context>File;BrowseObject</Context> </PropertyPageSchema> </ItemGroup> <!-- Modify the CustomToolNamespace based on the directory location of the grammar --> <ItemGroup> <Antlr3 Update="@(Antlr3)" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault(%(RelativeDir), '').Replace('\', '.').Replace('/', '.').TrimEnd('.'))" /> <Antlr3 Update="@(Antlr3)" Condition="'$(RootNamespace)' != ''" DefaultCustomToolNamespace="$([MSBuild]::ValueOrDefault('$(RootNamespace).%(DefaultCustomToolNamespace)', '').TrimEnd('.'))" /> <Antlr3 Update="@(Antlr3)" CustomToolNamespace="$([MSBuild]::ValueOrDefault(%(CustomToolNamespace), %(DefaultCustomToolNamespace)))" /> </ItemGroup> </When> </Choose> </Project>
antlr/antlrcs
63103348733e4c1ec12dd5a53ab6c6104cad0eba
Add a net40-client target for StringTemplate 3
diff --git a/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj b/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj index dec48ef..f07bb41 100644 --- a/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj +++ b/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj @@ -1,87 +1,87 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>net35-client;netstandard2.0</TargetFrameworks> + <TargetFrameworks>net35-client;net40-client;netstandard2.0</TargetFrameworks> <RootNamespace>Antlr.ST</RootNamespace> <Description>The C# port of StringTemplate 3.</Description> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <Title>StringTemplate 3</Title> <PackageId>StringTemplate3</PackageId> <PackageTags>stringtemplate st3 stringtemplate3 template</PackageTags> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <ItemGroup> <PackageReference Include="MSBuild.Sdk.Extras" Version="1.2.1" PrivateAssets="All" /> </ItemGroup> <Target Name="DisableCrazyPackageDeletion" BeforeTargets="Clean"> <PropertyGroup> <GeneratePackageValue>$(GeneratePackageOnBuild)</GeneratePackageValue> <GeneratePackageOnBuild>false</GeneratePackageOnBuild> </PropertyGroup> </Target> <Target Name="EnablePackageGeneration" Condition="'$(GeneratePackageValue)' != ''" BeforeTargets="Build"> <PropertyGroup> <GeneratePackageOnBuild>$(GeneratePackageValue)</GeneratePackageOnBuild> </PropertyGroup> </Target> <Choose> <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> <ItemGroup> <PackageReference Include="System.Reflection.Emit.ILGeneration" Version="4.3.0" /> <PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" /> </ItemGroup> </When> </Choose> <PropertyGroup> <DefineConstants>$(DefineConstants);COMPILE_EXPRESSIONS;CACHE_FUNCTORS</DefineConstants> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> <ItemGroup> <Compile Update="Language\AngleBracketTemplateLexerHelper.cs"> <DependentUpon>AngleBracketTemplateLexer.g3</DependentUpon> </Compile> <Compile Update="Language\TemplateLexerHelper.cs"> <DependentUpon>Template.g3</DependentUpon> </Compile> <Compile Update="Language\TemplateParserHelper.cs"> <DependentUpon>Template.g3</DependentUpon> </Compile> <Compile Update="Language\InterfaceLexerHelper.cs"> <DependentUpon>Interface.g3</DependentUpon> </Compile> <Compile Update="Language\InterfaceParserHelper.cs"> <DependentUpon>Interface.g3</DependentUpon> </Compile> <Compile Update="Language\GroupLexerHelper.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Language\GroupParserHelper.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Language\ActionLexerHelper.cs"> <DependentUpon>Action.g3</DependentUpon> </Compile> <Compile Update="Language\ActionParserHelper.cs"> <DependentUpon>Action.g3</DependentUpon> </Compile> <Compile Update="Language\ActionEvaluatorHelper.cs"> <DependentUpon>ActionEvaluator.g3</DependentUpon> </Compile> </ItemGroup> <Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" /> </Project> \ No newline at end of file
antlr/antlrcs
f82dcb07e0be4ce0d223ca1430bb0fedf47b44b7
Include build customization in MSBuildAllProjects
diff --git a/Antlr3.Targets/Directory.Build.props b/Antlr3.Targets/Directory.Build.props index d24481d..9c8b2d0 100644 --- a/Antlr3.Targets/Directory.Build.props +++ b/Antlr3.Targets/Directory.Build.props @@ -1,53 +1,57 @@ <?xml version="1.0" encoding="utf-8"?> <Project> + <PropertyGroup> + <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> + </PropertyGroup> + <Import Project="../Directory.Build.props" /> <PropertyGroup> <RootNamespace>Antlr3.Targets</RootNamespace> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <IntermediateOutputPath Condition="'$(TargetFramework)' != ''">obj\$(TargetFramework)\$(Configuration)\</IntermediateOutputPath> <OutputPath Condition="'$(TargetFramework)' != ''">$(MSBuildThisFileDirectory)..\bin\$(Configuration)\$(TargetFramework)\Targets\</OutputPath> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'net35-client'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40-client'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> </PropertyGroup> </When> </Choose> <ItemGroup> <ProjectReference Include="$(MSBuildThisFileDirectory)..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj"> <Private>false</Private> </ProjectReference> <ProjectReference Include="$(MSBuildThisFileDirectory)..\Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj"> <Private>false</Private> </ProjectReference> <ProjectReference Include="$(MSBuildThisFileDirectory)..\Antlr3\Antlr3.csproj"> <Private>false</Private> </ProjectReference> <ProjectReference Include="$(MSBuildThisFileDirectory)..\Antlr4.StringTemplate\Antlr4.StringTemplate.csproj"> <Private>false</Private> </ProjectReference> </ItemGroup> </Project> diff --git a/Antlr3.Targets/Directory.Build.targets b/Antlr3.Targets/Directory.Build.targets index af33e64..6eda817 100644 --- a/Antlr3.Targets/Directory.Build.targets +++ b/Antlr3.Targets/Directory.Build.targets @@ -1,12 +1,16 @@ <?xml version="1.0" encoding="utf-8"?> <Project> + <PropertyGroup> + <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> + </PropertyGroup> + <Target Name="RemoveTransitiveProjectReferences" AfterTargets="IncludeTransitiveProjectReferences"> <ItemGroup> <ProjectReference Remove="@(_TransitiveProjectReferences)" /> </ItemGroup> </Target> <Import Project="../Directory.Build.targets" /> </Project> diff --git a/Directory.Build.props b/Directory.Build.props index 756b359..37ad5af 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,77 +1,81 @@ <?xml version="1.0" encoding="utf-8"?> <Project> + <PropertyGroup> + <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> + </PropertyGroup> + <PropertyGroup> <!-- These properties are used by Directory.Build.props. Make sure they are set early enough for cases where they are not explicitly set during the MSBuild invocation. --> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> </PropertyGroup> <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> <PropertyGroup> <!-- Default NuGet package properties. Additional items set in Directory.Build.targets. --> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Authors>Sam Harwell, Terence Parr</Authors> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageLicenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</PackageLicenseUrl> <PackageProjectUrl>https://github.com/antlr/antlrcs</PackageProjectUrl> <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl> <PackageReleaseNotes>https://github.com/antlr/antlrcs/releases/$(ANTLRInformationalVersion)</PackageReleaseNotes> <IncludeSymbols>true</IncludeSymbols> <IncludeSource>true</IncludeSource> <PackageOutputPath>$(MSBuildThisFileDirectory)build\prep\nuget\</PackageOutputPath> </PropertyGroup> <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta1" PrivateAssets="all" /> </ItemGroup> <!-- Workaround to ensure generated ANTLR parsers are included in NuGet source package. --> <Target Name="AntlrBeforeSourceFiles" Condition="'$(BootstrapBuild)' != 'true'" BeforeTargets="SourceFilesProjectOutputGroup" DependsOnTargets="AntlrCompile;AntlrCompileAddFilesGenerated" /> <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project> diff --git a/Directory.Build.targets b/Directory.Build.targets index 4071059..04d3a9f 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,18 +1,22 @@ <?xml version="1.0" encoding="utf-8"?> <Project> + <PropertyGroup> + <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> + </PropertyGroup> + <PropertyGroup> <!-- Default NuGet package properties. Additional items set in Directory.Build.props. --> <PackageVersion Condition="'$(PackageVersion)' == ''">$(InformationalVersion)</PackageVersion> </PropertyGroup> <ItemGroup> <None Condition="'$(SignAssembly)' == 'true'" Include="$(AssemblyOriginatorKeyFile)" Link="%(Filename)%(Extension)" /> </ItemGroup> <ItemGroup Condition="'$(GeneratePackageOnBuild)' == 'true'"> <!-- Workaround for https://github.com/NuGet/Home/issues/6582 --> <UpToDateCheckInput Condition="'$(NuspecFile)' != ''" Include="$(NuspecFile)" /> </ItemGroup> </Project>
antlr/antlrcs
6223de2d8d881c5051516c8dedf15581dcbcc3bb
Make sure the Configuration and Platform properties are set early enough to use
diff --git a/Directory.Build.props b/Directory.Build.props index 9f241f4..756b359 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,68 +1,77 @@ <?xml version="1.0" encoding="utf-8"?> <Project> + <PropertyGroup> + <!-- + These properties are used by Directory.Build.props. Make sure they are set early enough for cases where they are + not explicitly set during the MSBuild invocation. + --> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + </PropertyGroup> + <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> <PropertyGroup> <!-- Default NuGet package properties. Additional items set in Directory.Build.targets. --> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Authors>Sam Harwell, Terence Parr</Authors> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageLicenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</PackageLicenseUrl> <PackageProjectUrl>https://github.com/antlr/antlrcs</PackageProjectUrl> <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl> <PackageReleaseNotes>https://github.com/antlr/antlrcs/releases/$(ANTLRInformationalVersion)</PackageReleaseNotes> <IncludeSymbols>true</IncludeSymbols> <IncludeSource>true</IncludeSource> <PackageOutputPath>$(MSBuildThisFileDirectory)build\prep\nuget\</PackageOutputPath> </PropertyGroup> <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta1" PrivateAssets="all" /> </ItemGroup> <!-- Workaround to ensure generated ANTLR parsers are included in NuGet source package. --> <Target Name="AntlrBeforeSourceFiles" Condition="'$(BootstrapBuild)' != 'true'" BeforeTargets="SourceFilesProjectOutputGroup" DependsOnTargets="AntlrCompile;AntlrCompileAddFilesGenerated" /> <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project>
antlr/antlrcs
44516f4265d54635177cdc07bdb60bfc560f494c
Make sure the CSharp3 target gets built by the Antlr3.Test project
diff --git a/Antlr3.Test/Antlr3.Test.csproj b/Antlr3.Test/Antlr3.Test.csproj index 940b097..8bacad3 100644 --- a/Antlr3.Test/Antlr3.Test.csproj +++ b/Antlr3.Test/Antlr3.Test.csproj @@ -1,55 +1,56 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net45;netcoreapp2.0</TargetFrameworks> <RootNamespace>AntlrUnitTests</RootNamespace> <AssemblyName>AntlrUnitTests</AssemblyName> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> </PropertyGroup> <ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.0'"> <PackageReference Include="Microsoft.Win32.Registry" Version="4.3.0" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" /> <PackageReference Include="MSTest.TestAdapter" Version="1.1.18" /> <PackageReference Include="MSTest.TestFramework" Version="1.1.18" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="body.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="method.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="page.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="row.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="users_list.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> <ProjectReference Include="..\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj" /> <ProjectReference Include="..\Antlr3\Antlr3.csproj" /> <ProjectReference Include="..\Antlr4.StringTemplate\Antlr4.StringTemplate.csproj" /> + <ProjectReference Include="..\Antlr3.Targets\Antlr3.Targets.CSharp3\Antlr3.Targets.CSharp3.csproj" /> <ProjectReference Include="..\Antlr3.Targets\Antlr3.Targets.Java\Antlr3.Targets.Java.csproj" /> </ItemGroup> </Project> \ No newline at end of file
antlr/antlrcs
a19e82b9fb55b3902787722ea2e06828ec414022
Fix handling of paths with invalid characters
diff --git a/Antlr3/AntlrTool.cs b/Antlr3/AntlrTool.cs index 6d8fad8..ccc6ed3 100644 --- a/Antlr3/AntlrTool.cs +++ b/Antlr3/AntlrTool.cs @@ -584,1016 +584,1026 @@ namespace Antlr3 // Have to be tricky here when Maven or build tools call in and must new Tool() // before setting options. The banner won't display that way! if ( Verbose && showBanner ) { ErrorManager.Info( "ANTLR Parser Generator Version " + AssemblyInformationalVersion ); showBanner = false; } try { SortGrammarFiles(); // update grammarFileNames } catch ( Exception e ) { ErrorManager.Error( ErrorManager.MSG_INTERNAL_ERROR, e ); } foreach ( string grammarFileName in GrammarFileNames ) { // If we are in make mode (to support build tools like Maven) and the // file is already up to date, then we do not build it (and in verbose mode // we will say so). if ( Make ) { try { if ( !BuildRequired( grammarFileName ) ) continue; } catch ( Exception e ) { ErrorManager.Error( ErrorManager.MSG_INTERNAL_ERROR, e ); } } if ( Verbose && !Depend ) { Console.Out.WriteLine( grammarFileName ); } try { if ( Depend ) { BuildDependencyGenerator dep = new BuildDependencyGenerator( this, grammarFileName ); #if false IList<string> outputFiles = dep.getGeneratedFileList(); IList<string> dependents = dep.getDependenciesFileList(); Console.Out.WriteLine( "output: " + outputFiles ); Console.Out.WriteLine( "dependents: " + dependents ); #endif Console.Out.WriteLine( dep.GetDependencies().Render() ); continue; } Grammar rootGrammar = GetRootGrammar( grammarFileName ); // we now have all grammars read in as ASTs // (i.e., root and all delegates) rootGrammar.composite.AssignTokenTypes(); //rootGrammar.composite.TranslateLeftRecursiveRules(); rootGrammar.AddRulesForSyntacticPredicates(); rootGrammar.composite.DefineGrammarSymbols(); rootGrammar.composite.CreateNFAs(); GenerateRecognizer( rootGrammar ); if ( PrintGrammar ) { rootGrammar.PrintGrammar( Console.Out ); } if (Report) { GrammarReport2 greport = new GrammarReport2(rootGrammar); Console.WriteLine(greport.ToString()); } if ( Profile ) { GrammarReport report = new GrammarReport(rootGrammar); Stats.WriteReport( GrammarReport.GRAMMAR_STATS_FILENAME, report.ToNotifyString() ); } // now handle the lexer if one was created for a merged spec string lexerGrammarStr = rootGrammar.GetLexerGrammar(); //[email protected]("lexer grammar:\n"+lexerGrammarStr); if ( rootGrammar.type == GrammarType.Combined && lexerGrammarStr != null ) { lexerGrammarFileName = rootGrammar.ImplicitlyGeneratedLexerFileName; try { TextWriter w = GetOutputFile( rootGrammar, lexerGrammarFileName ); w.Write( lexerGrammarStr ); w.Close(); } catch (IOException) { // emit different error message when creating the implicit lexer fails // due to write permission error exceptionWhenWritingLexerFile = true; throw; } try { StringReader sr = new StringReader( lexerGrammarStr ); Grammar lexerGrammar = new Grammar(this); lexerGrammar.composite.WatchNFAConversion = internalOption_watchNFAConversion; lexerGrammar.implicitLexer = true; if ( TestMode ) lexerGrammar.DefaultRuleModifier = "public"; FileInfo lexerGrammarFullFile = new FileInfo( System.IO.Path.Combine( GetFileDirectory( lexerGrammarFileName ), lexerGrammarFileName ) ); lexerGrammar.FileName = lexerGrammarFullFile.ToString(); lexerGrammar.ImportTokenVocabulary( rootGrammar ); lexerGrammar.ParseAndBuildAST( sr ); sr.Close(); lexerGrammar.composite.AssignTokenTypes(); lexerGrammar.AddRulesForSyntacticPredicates(); lexerGrammar.composite.DefineGrammarSymbols(); lexerGrammar.composite.CreateNFAs(); GenerateRecognizer( lexerGrammar ); } finally { // make sure we clean up if ( deleteTempLexer ) { System.IO.DirectoryInfo outputDir = GetOutputDirectory( lexerGrammarFileName ); FileInfo outputFile = new FileInfo( System.IO.Path.Combine( outputDir.FullName, lexerGrammarFileName ) ); outputFile.Delete(); } } } } catch ( IOException e ) { if ( exceptionWhenWritingLexerFile ) { ErrorManager.Error( ErrorManager.MSG_CANNOT_WRITE_FILE, e ); } else { ErrorManager.Error( ErrorManager.MSG_CANNOT_OPEN_FILE, grammarFileName, e ); } } catch ( Exception e ) { ErrorManager.Error( ErrorManager.MSG_INTERNAL_ERROR, grammarFileName, e ); } #if false finally { Console.Out.WriteLine( "creates=" + Interval.creates ); Console.Out.WriteLine( "hits=" + Interval.hits ); Console.Out.WriteLine( "misses=" + Interval.misses ); Console.Out.WriteLine( "outOfRange=" + Interval.outOfRange ); } #endif } if (_showTimer) { Console.WriteLine("Total parse time: {0}ms", timer.ElapsedMilliseconds); } } public virtual void SortGrammarFiles() { //Console.Out.WriteLine( "Grammar names " + GrammarFileNames ); Graph<string> g = new Graph<string>(); foreach ( string gfile in GrammarFileNames ) { GrammarSpelunker grammar = new GrammarSpelunker( inputDirectory, gfile ); grammar.Parse(); string vocabName = grammar.TokenVocab; string grammarName = grammar.GrammarName; // Make all grammars depend on any tokenVocab options if ( vocabName != null ) g.AddEdge( gfile, vocabName + CodeGenerator.VocabFileExtension ); // Make all generated tokens files depend on their grammars g.AddEdge( grammarName + CodeGenerator.VocabFileExtension, gfile ); } List<string> sorted = g.Sort(); //Console.Out.WriteLine( "sorted=" + sorted ); GrammarFileNames.Clear(); // wipe so we can give new ordered list for ( int i = 0; i < sorted.Count; i++ ) { string f = (string)sorted[i]; if ( GrammarExtensions.Any( ext => f.EndsWith( ext, StringComparison.OrdinalIgnoreCase ) ) ) AddGrammarFile( f ); } //Console.Out.WriteLine( "new grammars=" + grammarFileNames ); } /** Get a grammar mentioned on the command-line and any delegates */ public virtual Grammar GetRootGrammar( string grammarFileName ) { //StringTemplate.setLintMode(true); // grammars mentioned on command line are either roots or single grammars. // create the necessary composite in case it's got delegates; even // single grammar needs it to get token types. CompositeGrammar composite = new CompositeGrammar(); Grammar grammar = new Grammar( this, grammarFileName, composite ); if ( TestMode ) grammar.DefaultRuleModifier = "public"; composite.SetDelegationRoot( grammar ); string f = null; if ( haveInputDir ) { f = Path.Combine( inputDirectory, grammarFileName ); } else { f = grammarFileName; } // Store the location of this grammar as if we import files, we can then // search for imports in the same location as the original grammar as well as in // the lib directory. // parentGrammarDirectory = Path.GetDirectoryName( f ); if ( grammarFileName.LastIndexOfAny( new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar } ) == -1 ) { grammarOutputDirectory = "."; } else { grammarOutputDirectory = grammarFileName.Substring( 0, grammarFileName.LastIndexOfAny( new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar } ) ); } StringReader reader = new StringReader( System.IO.File.ReadAllText( f ) ); grammar.ParseAndBuildAST( reader ); composite.WatchNFAConversion = internalOption_watchNFAConversion; return grammar; } /** Create NFA, DFA and generate code for grammar. * Create NFA for any delegates first. Once all NFA are created, * it's ok to create DFA, which must check for left-recursion. That check * is done by walking the full NFA, which therefore must be complete. * After all NFA, comes DFA conversion for root grammar then code gen for * root grammar. DFA and code gen for delegates comes next. */ protected virtual void GenerateRecognizer( Grammar grammar ) { string language = (string)grammar.GetOption( "language" ); if ( language != null ) { CodeGenerator generator = new CodeGenerator( this, grammar, language ); grammar.CodeGenerator = generator; generator.Debug = Debug; generator.Profile = Profile; generator.Trace = Trace; // generate NFA early in case of crash later (for debugging) if ( Generate_NFA_dot ) { GenerateNFAs( grammar ); } // GENERATE CODE generator.GenRecognizer(); if ( Generate_DFA_dot ) { GenerateDFAs( grammar ); } IList<Grammar> delegates = grammar.GetDirectDelegates(); for ( int i = 0; delegates != null && i < delegates.Count; i++ ) { Grammar @delegate = (Grammar)delegates[i]; if ( @delegate != grammar ) { // already processing this one GenerateRecognizer( @delegate ); } } } } public virtual void GenerateDFAs( Grammar g ) { for ( int d = 1; d <= g.NumberOfDecisions; d++ ) { DFA dfa = g.GetLookaheadDFA( d ); if ( dfa == null ) { continue; // not there for some reason, ignore } IGraphGenerator generator; if (GenerateDgmlGraphs) { generator = new DgmlGenerator(g); } else { generator = new DOTGenerator(g); } string graph = generator.GenerateGraph( dfa.StartState ); string graphFileName = g.name + "." + "dec-" + d; if ( g.implicitLexer ) { graphFileName = g.name + Grammar.grammarTypeToFileNameSuffix[(int)g.type] + "." + "dec-" + d; } try { WriteGraphFile( g, graphFileName, graph, generator.FileExtension ); } catch ( IOException ioe ) { ErrorManager.Error( ErrorManager.MSG_CANNOT_GEN_DOT_FILE, graphFileName, ioe ); } } } protected virtual void GenerateNFAs( Grammar g ) { IGraphGenerator generator = GenerateDgmlGraphs ? (IGraphGenerator)new DgmlGenerator(g) : new DOTGenerator(g); HashSet<Rule> rules = g.GetAllImportedRules(); rules.UnionWith( g.Rules ); foreach ( Rule r in rules ) { try { string dot = generator.GenerateGraph( r.StartState ); if ( dot != null ) { WriteGraphFile( g, r, dot, generator.FileExtension ); } } catch ( IOException ioe ) { ErrorManager.Error( ErrorManager.MSG_CANNOT_WRITE_FILE, ioe ); } } } protected virtual void WriteGraphFile( Grammar g, Rule r, string graph, string formatExtension ) { WriteGraphFile( g, r.Grammar.name + "." + r.Name, graph, formatExtension ); } protected virtual void WriteGraphFile( Grammar g, string name, string graph, string formatExtension ) { TextWriter fw = GetOutputFile( g, name + formatExtension ); fw.Write( graph ); fw.Close(); } private static void Version() { ErrorManager.Info( "ANTLR Parser Generator Version " + AntlrTool.AssemblyInformationalVersion ); } private static void Help() { Version(); Console.Error.WriteLine( "usage: java org.antlr.Tool [args] file.g [file2.g file3.g ...]" ); Console.Error.WriteLine( " -o outputDir specify output directory where all output is generated" ); Console.Error.WriteLine( " -fo outputDir same as -o but force even files with relative paths to dir" ); Console.Error.WriteLine( " -lib dir specify location of token files" ); Console.Error.WriteLine( " -depend generate file dependencies" ); Console.Error.WriteLine( " -verbose generate ANTLR version and other information" ); Console.Error.WriteLine( " -report print out a report about the grammar(s) processed" ); Console.Error.WriteLine( " -print print out the grammar without actions" ); Console.Error.WriteLine( " -debug generate a parser that emits debugging events" ); Console.Error.WriteLine( " -trace generate a recognizer that traces rule entry/exit" ); Console.Error.WriteLine( " -profile generate a parser that computes profiling information" ); Console.Error.WriteLine( " -nfa generate an NFA for each rule" ); Console.Error.WriteLine( " -dfa generate a DFA for each decision point" ); Console.Error.WriteLine( " -dgml generate graphs in DGML format." ); Console.Error.WriteLine( " -message-format name specify output style for messages" ); Console.Error.WriteLine( " -verbose generate ANTLR version and other information" ); Console.Error.WriteLine( " -make only build if generated files older than grammar" ); Console.Error.WriteLine( " -version print the version of ANTLR and exit." ); Console.Error.WriteLine( " -language L override language grammar option; generate L" ); Console.Error.WriteLine( " -X display extended argument list" ); } private static void ExtendedHelp() { Version(); Console.Error.WriteLine(" -Xgrtree print the grammar AST"); Console.Error.WriteLine(" -Xdfa print DFA as text "); Console.Error.WriteLine(" -Xnoprune test lookahead against EBNF block exit branches"); Console.Error.WriteLine(" -Xnocollapse collapse incident edges into DFA states"); Console.Error.WriteLine(" -Xdbgconversion dump lots of info during NFA conversion"); Console.Error.WriteLine(" -Xmultithreaded run the analysis in 2 threads"); Console.Error.WriteLine(" -Xnomergestopstates do not merge stop states"); Console.Error.WriteLine(" -Xdfaverbose generate DFA states in DOT with NFA configs"); Console.Error.WriteLine(" -Xwatchconversion print a message for each NFA before converting"); #if DEBUG Console.Error.WriteLine(" -XdbgST put tags at start/stop of all templates in output"); #endif Console.Error.WriteLine(" -Xnfastates for nondeterminisms, list NFA states for each path"); Console.Error.WriteLine(" -Xm m max number of rule invocations during conversion [" + NFAContext.MAX_SAME_RULE_INVOCATIONS_PER_NFA_CONFIG_STACK + "]"); Console.Error.WriteLine(" -Xmaxdfaedges m max \"comfortable\" number of edges for single DFA state [" + DFA.MAX_STATE_TRANSITIONS_FOR_TABLE + "]"); Console.Error.WriteLine(" -Xmaxinlinedfastates m max DFA states before table used rather than inlining [" + CodeGenerator.DefaultMaxSwitchCaseLabels + "]"); Console.Error.WriteLine(" -Xmaxswitchcaselabels m don't generate switch() statements for dfas bigger than m [" + CodeGenerator.DefaultMaxSwitchCaseLabels + "]"); Console.Error.WriteLine(" -Xminswitchalts m don't generate switch() statements for dfas smaller than m [" + CodeGenerator.DefaultMinSwitchAlts + "]"); Console.Error.WriteLine(" -Xsavelexer don't delete temporary lexers generated from combined grammars"); } /// <summary> /// Set the location (base directory) where output files should be produced by the ANTLR tool. /// </summary> /// <param name="outputDirectory"></param> public virtual void SetOutputDirectory( string outputDirectory ) { haveOutputDir = true; this.outputDirectory = outputDirectory; } /** * Used by build tools to force the output files to always be * relative to the base output directory, even though the tool * had to set the output directory to an absolute path as it * cannot rely on the workign directory like command line invocation * can. * * @param forceRelativeOutput true if output files hould always be relative to base output directory */ public virtual void SetForceRelativeOutput( bool forceRelativeOutput ) { this.forceRelativeOutput = forceRelativeOutput; } /** * Set the base location of input files. Normally (when the tool is * invoked from the command line), the inputDirectory is not set, but * for build tools such as Maven, we need to be able to locate the input * files relative to the base, as the working directory could be anywhere and * changing workig directories is not a valid concept for JVMs because of threading and * so on. Setting the directory just means that the getFileDirectory() method will * try to open files relative to this input directory. * * @param inputDirectory Input source base directory */ public virtual void SetInputDirectory( string inputDirectory ) { this.inputDirectory = inputDirectory; haveInputDir = true; } public virtual TextWriter GetOutputFile( Grammar g, string fileName ) { if ( OutputDirectory == null ) return new StringWriter(); // output directory is a function of where the grammar file lives // for subdir/T.g, you get subdir here. Well, depends on -o etc... // But, if this is a .tokens file, then we force the output to // be the base output directory (or current directory if there is not a -o) // #if false System.IO.DirectoryInfo outputDir; if ( fileName.EndsWith( CodeGenerator.VOCAB_FILE_EXTENSION ) ) { if ( haveOutputDir ) { outputDir = new System.IO.DirectoryInfo( OutputDirectory ); } else { outputDir = new System.IO.DirectoryInfo( "." ); } } else { outputDir = getOutputDirectory( g.FileName ); } #else System.IO.DirectoryInfo outputDir = GetOutputDirectory( g.FileName ); #endif FileInfo outputFile = new FileInfo( System.IO.Path.Combine( outputDir.FullName, fileName ) ); if ( !outputDir.Exists ) outputDir.Create(); if ( outputFile.Exists ) outputFile.Delete(); GeneratedFiles.Add(outputFile.FullName); return new System.IO.StreamWriter( new System.IO.BufferedStream( outputFile.OpenWrite() ) ); } /** * Return the location where ANTLR will generate output files for a given file. This is a * base directory and output files will be relative to here in some cases * such as when -o option is used and input files are given relative * to the input directory. * * @param fileNameWithPath path to input source * @return */ public virtual System.IO.DirectoryInfo GetOutputDirectory( string fileNameWithPath ) { string outputDir = OutputDirectory; - if ( fileNameWithPath.IndexOfAny( System.IO.Path.GetInvalidPathChars() ) >= 0 ) + if (IsInvalidFileNameWithPath(fileNameWithPath) ) return new System.IO.DirectoryInfo( outputDir ); if ( !System.IO.Path.IsPathRooted( fileNameWithPath ) ) fileNameWithPath = System.IO.Path.GetFullPath( fileNameWithPath ); string fileDirectory; // Some files are given to us without a PATH but should should // still be written to the output directory in the relative path of // the output directory. The file directory is either the set of sub directories // or just or the relative path recorded for the parent grammar. This means // that when we write the tokens files, or the .java files for imported grammars // taht we will write them in the correct place. // if ( fileNameWithPath.IndexOfAny( new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar } ) == -1 ) { // No path is included in the file name, so make the file // directory the same as the parent grammar (which might sitll be just "" // but when it is not, we will write the file in the correct place. // fileDirectory = grammarOutputDirectory; } else { fileDirectory = fileNameWithPath.Substring( 0, fileNameWithPath.LastIndexOfAny( new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar } ) ); } if ( haveOutputDir ) { // -o /tmp /var/lib/t.g => /tmp/T.java // -o subdir/output /usr/lib/t.g => subdir/output/T.java // -o . /usr/lib/t.g => ./T.java if ( ( fileDirectory != null && !forceRelativeOutput ) && ( System.IO.Path.IsPathRooted( fileDirectory ) || fileDirectory.StartsWith( "~" ) ) || // isAbsolute doesn't count this :( ForceAllFilesToOutputDir ) { // somebody set the dir, it takes precendence; write new file there outputDir = OutputDirectory; } else { // -o /tmp subdir/t.g => /tmp/subdir/t.g if ( fileDirectory != null ) { outputDir = System.IO.Path.Combine( OutputDirectory, fileDirectory ); } else { outputDir = OutputDirectory; } } } else { // they didn't specify a -o dir so just write to location // where grammar is, absolute or relative, this will only happen // with command line invocation as build tools will always // supply an output directory. // outputDir = fileDirectory; } return new System.IO.DirectoryInfo( outputDir ); } + private static bool IsInvalidFileNameWithPath(string fileNameWithPath) + { + if (fileNameWithPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0) + return true; + + // On some platforms, GetInvalidFileNameChars is not simply equal to GetInvalidPathChars plus the directory separators + string[] segments = fileNameWithPath.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); + return segments.Any(segment => segment.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0); + } + /** * Name a file from the -lib dir. Imported grammars and .tokens files * * If we do not locate the file in the library directory, then we try * the location of the originating grammar. * * @param fileName input name we are looking for * @return Path to file that we think shuold be the import file * * @throws java.io.IOException */ public virtual string GetLibraryFile( string fileName ) { // First, see if we can find the file in the library directory // string f = Path.Combine( LibraryDirectory, fileName ); if ( File.Exists( f ) ) { // Found in the library directory // return Path.GetFullPath( f ); } // Need to assume it is in the same location as the input file. Note that // this is only relevant for external build tools and when the input grammar // was specified relative to the source directory (working directory if using // the command line. // return Path.Combine( parentGrammarDirectory, fileName ); } /** Return the directory containing the grammar file for this grammar. * normally this is a relative path from current directory. People will * often do "java org.antlr.Tool grammars/*.g3" So the file will be * "grammars/foo.g3" etc... This method returns "grammars". * * If we have been given a specific input directory as a base, then * we must find the directory relative to this directory, unless the * file name is given to us in absolute terms. */ public virtual string GetFileDirectory( string fileName ) { string f; if ( haveInputDir && !( fileName.StartsWith( Path.DirectorySeparatorChar.ToString() ) || fileName.StartsWith( Path.AltDirectorySeparatorChar.ToString() ) ) ) { f = Path.Combine( inputDirectory, fileName ); } else { f = fileName; } // And ask .NET what the base directory of this location is // return Path.GetDirectoryName( f ); } /** Return a File descriptor for vocab file. Look in library or * in -o output path. antlr -o foo T.g U.g where U needs T.tokens * won't work unless we look in foo too. If we do not find the * file in the lib directory then must assume that the .tokens file * is going to be generated as part of this build and we have defined * .tokens files so that they ALWAYS are generated in the base output * directory, which means the current directory for the command line tool if there * was no output directory specified. */ public virtual string GetImportedVocabFile( string vocabName ) { // first look at files we're generating string path = (from file in GeneratedFiles where Path.GetFileName(file).Equals(vocabName + CodeGenerator.VocabFileExtension) && File.Exists(file) select file) .FirstOrDefault(); if (path != null) return path; path = Path.Combine( LibraryDirectory, vocabName + CodeGenerator.VocabFileExtension ); if ( File.Exists( path ) ) return path; // We did not find the vocab file in the lib directory, so we need // to look for it in the output directory which is where .tokens // files are generated (in the base, not relative to the input // location.) // if ( haveOutputDir ) { path = Path.Combine( OutputDirectory, vocabName + CodeGenerator.VocabFileExtension ); } else { path = vocabName + CodeGenerator.VocabFileExtension; } return path; } /** If the tool needs to panic/exit, how do we do that? */ public virtual void Panic() { throw new Exception( "ANTLR panic" ); } /// <summary> /// Return a time stamp string accurate to sec: yyyy-mm-dd hh:mm:ss /// </summary> public static string GetCurrentTimeStamp() { return DateTime.Now.ToString( "yyyy\\-MM\\-dd HH\\:mm\\:ss" ); } /** * Provide the List of all grammar file names that the ANTLR tool will * process or has processed. * * @return the grammarFileNames */ public virtual IList<string> GrammarFileNames { get { return grammarFileNames; } } public IList<string> GeneratedFiles { get { return generatedFiles; } } /** * Indicates whether ANTLR has gnerated or will generate a description of * all the NFAs in <a href="http://www.graphviz.org">Dot format</a> * * @return the generate_NFA_dot */ public virtual bool Generate_NFA_dot { get { return generate_NFA_dot; } set { this.generate_NFA_dot = value; } } /** * Indicates whether ANTLR has generated or will generate a description of * all the NFAs in <a href="http://www.graphviz.org">Dot format</a> * * @return the generate_DFA_dot */ public virtual bool Generate_DFA_dot { get { return generate_DFA_dot; } set { this.generate_DFA_dot = value; } } public virtual bool GenerateDgmlGraphs { get { return _generateDgmlGraphs; } set { _generateDgmlGraphs = value; } } /** * Return the Path to the base output directory, where ANTLR * will generate all the output files for the current language target as * well as any ancillary files such as .tokens vocab files. * * @return the output Directory */ public virtual string OutputDirectory { get { return outputDirectory; } } /** * Return the Path to the directory in which ANTLR will search for ancillary * files such as .tokens vocab files and imported grammar files. * * @return the lib Directory */ public virtual string LibraryDirectory { get { return libDirectory; } set { this.libDirectory = value; } } /** * Indicate if ANTLR has generated, or will generate a debug version of the * recognizer. Debug versions of a parser communicate with a debugger such * as that contained in ANTLRWorks and at start up will 'hang' waiting for * a connection on an IP port (49100 by default). * * @return the debug flag */ public virtual bool Debug { get { return debug; } set { debug = value; } } /** * Indicate whether ANTLR has generated, or will generate a version of the * recognizer that prints trace messages on entry and exit of each rule. * * @return the trace flag */ public virtual bool Trace { get { return trace; } set { trace = value; } } /** * Indicates whether ANTLR has generated or will generate a version of the * recognizer that gathers statistics about its execution, which it prints when * it terminates. * * @return the profile */ public virtual bool Profile { get { return profile; } set { profile = value; } } /** * Indicates whether ANTLR has generated or will generate a report of various * elements of the grammar analysis, once it it has finished analyzing a grammar * file. * * @return the report flag */ public virtual bool Report { get { return report; } set { report = value; } } /** * Indicates whether ANTLR has printed, or will print, a version of the input grammar * file(s) that is stripped of any action code embedded within. * * @return the printGrammar flag */ public virtual bool PrintGrammar { get { return printGrammar; } set { printGrammar = value; } } /** * Indicates whether ANTLR has supplied, or will supply, a list of all the things * that the input grammar depends upon and all the things that will be generated * when that grammar is successfully analyzed. * * @return the depend flag */ public virtual bool Depend { get { return depend; } set { depend = value; } } public virtual bool TestMode { get { return testMode; } set { testMode = value; } } /** * Indicates whether ANTLR will force all files to the output directory, even * if the input files have relative paths from the input directory. * * @return the forceAllFilesToOutputDir flag */ public virtual bool ForceAllFilesToOutputDir { get { return forceAllFilesToOutputDir; } set { forceAllFilesToOutputDir = value; } } /** * Indicates whether ANTLR will be verbose when analyzing grammar files, such as * displaying the names of the files it is generating and similar information. * * @return the verbose flag */ public virtual bool Verbose { get { return verbose; } set { verbose = value; } } /** * Gets or sets the current setting of the message format descriptor. */ public virtual string MessageFormat { get { return ErrorManager.GetMessageFormat().ToString(); } set { ErrorManager.SetFormat( value ); } } /** * Returns the number of errors that the analysis/processing threw up. * @return Error count */ public virtual int NumErrors { get { return ErrorManager.GetNumErrors(); } } /** * Indicate whether the tool will analyze the dependencies of the provided grammar * file list and ensure that grammars with dependencies are built * after any of the other gramamrs in the list that they are dependent on. Setting * this option also has the side effect that any grammars that are includes for other * grammars in the list are excluded from individual analysis, which allows the caller * to invoke the tool via org.antlr.tool -make *.g and not worry about the inclusion * of grammars that are just includes for other grammars or what order the grammars * appear on the command line. * * This option was coded to make life easier for tool integration (such as Maven) but * may also be useful at the command line. * * @return true if the tool is currently configured to analyze and sort grammar files. */ public virtual bool Make { get { return make; } set { make = value; } } public virtual void AddGrammarFile( string grammarFileName ) { if ( !GrammarFileNames.Contains( grammarFileName ) ) GrammarFileNames.Add( grammarFileName ); } } }
antlr/antlrcs
995f84e724c1254737ab6c4687d972713c9bcc69
Fix ToolPathRoot for dotnet testing without asset deployment
diff --git a/Antlr3.Test/BaseTest.cs b/Antlr3.Test/BaseTest.cs index ca9efc1..fe95ae3 100644 --- a/Antlr3.Test/BaseTest.cs +++ b/Antlr3.Test/BaseTest.cs @@ -1,630 +1,630 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using System; using System.Collections.Generic; using System.Linq; using Antlr.Runtime; using Antlr.Runtime.JavaExtensions; using Antlr3.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using BindingFlags = System.Reflection.BindingFlags; using CultureInfo = System.Globalization.CultureInfo; using Debugger = System.Diagnostics.Debugger; using Directory = System.IO.Directory; using ErrorManager = Antlr3.Tool.ErrorManager; using FieldInfo = System.Reflection.FieldInfo; using GrammarSemanticsMessage = Antlr3.Tool.GrammarSemanticsMessage; using IANTLRErrorListener = Antlr3.Tool.IANTLRErrorListener; using IList = System.Collections.IList; using IOException = System.IO.IOException; using Label = Antlr3.Analysis.Label; using Message = Antlr3.Tool.Message; using Path = System.IO.Path; using Registry = Microsoft.Win32.Registry; using RegistryKey = Microsoft.Win32.RegistryKey; using RegistryValueOptions = Microsoft.Win32.RegistryValueOptions; using StringBuilder = System.Text.StringBuilder; using StringTemplate = Antlr4.StringTemplate.Template; using StringTemplateGroup = Antlr4.StringTemplate.TemplateGroup; [TestClass] [DeploymentItem(@"Codegen\", "Codegen")] [DeploymentItem(@"Antlr3.Targets.Java.dll", "Targets")] [DeploymentItem(@"Antlr3.Targets.Java.pdb", "Targets")] [DeploymentItem(@"Tool\", "Tool")] public abstract class BaseTest { public readonly string jikes = null; public static readonly string pathSep = System.IO.Path.PathSeparator.ToString(); public readonly string RuntimeJar = Path.Combine( Environment.CurrentDirectory, @"..\..\antlr-runtime-3.3.jar" ); public readonly string Runtime2Jar = Path.Combine( Environment.CurrentDirectory, @"..\..\antlr-2.7.7.jar" ); public readonly string StringTemplateJar = Path.Combine( Environment.CurrentDirectory, @"..\..\stringtemplate-3.2.1.jar" ); private static string javaHome; public string tmpdir; public TestContext TestContext { get; set; } /** If error during parser execution, store stderr here; can't return * stdout and stderr. This doesn't trap errors from running antlr. */ protected string stderrDuringParse; public static readonly string NewLine = Environment.NewLine; [ClassInitialize] public void ClassSetUp( TestContext testContext ) { TestContext = testContext; } public static long currentTimeMillis() { return DateTime.Now.ToFileTime() / 10000; } [TestInitialize] public void setUp() { #if DEBUG string configuration = "Debug"; #else string configuration = "Release"; #endif System.IO.DirectoryInfo currentAssemblyDirectory = new System.IO.FileInfo(typeof(BaseTest).Assembly.Location).Directory; #if NET45 AntlrTool.ToolPathRoot = Path.Combine(currentAssemblyDirectory.Parent.Parent.Parent.FullName, "bin", configuration, "net40-client"); #else - AntlrTool.ToolPathRoot = Path.Combine(currentAssemblyDirectory.Parent.Parent.Parent.FullName, "bin", configuration, "netstandard2.0"); + AntlrTool.ToolPathRoot = Path.Combine(currentAssemblyDirectory.Parent.Parent.Parent.Parent.FullName, "bin", configuration, "netstandard2.0"); #endif // new output dir for each test tmpdir = Path.GetFullPath( Path.Combine( Path.GetTempPath(), "antlr-" + currentTimeMillis() ) ); ErrorManager.SetLocale(CultureInfo.GetCultureInfo("en-us")); ErrorManager.SetFormat("antlr"); ErrorManager.ResetErrorState(); StringTemplateGroup.DefaultGroup = new StringTemplateGroup(); // verify token constants in StringTemplate VerifyImportedTokens( typeof( Antlr3.ST.Language.ActionParser ), typeof( Antlr3.ST.Language.ActionLexer ) ); VerifyImportedTokens( typeof( Antlr3.ST.Language.ActionParser ), typeof( Antlr3.ST.Language.ActionEvaluator ) ); VerifyImportedTokens( typeof( Antlr3.ST.Language.TemplateParser ), typeof( Antlr3.ST.Language.TemplateLexer ) ); VerifyImportedTokens( typeof( Antlr3.ST.Language.TemplateParser ), typeof( Antlr3.ST.Language.AngleBracketTemplateLexer ) ); // verify token constants in the ANTLR Tool VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.ANTLRLexer ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.ANTLRTreePrinter ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.AssignTokenTypesWalker ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.CodeGenTreeWalker ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.DefineGrammarItemsWalker ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.TreeToNFAConverter ) ); } [TestCleanup] public void tearDown() { // remove tmpdir if no error. how? if ( TestContext != null && TestContext.CurrentTestOutcome == UnitTestOutcome.Passed ) eraseTempDir(); } private void VerifyImportedTokens( Type source, Type target ) { FieldInfo namesField = source.GetField( "tokenNames", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public ); FieldInfo targetNamesField = target.GetField( "tokenNames", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public ); Assert.IsNotNull( namesField, string.Format( "No tokenNames field was found in grammar {0}.", source.Name ) ); string[] sourceNames = namesField.GetValue( null ) as string[]; string[] targetNames = ( targetNamesField != null ) ? targetNamesField.GetValue( null ) as string[] : null; Assert.IsNotNull( sourceNames, string.Format( "The tokenNames field in grammar {0} was null.", source.Name ) ); for ( int i = 0; i < sourceNames.Length; i++ ) { string tokenName = sourceNames[i]; if ( string.IsNullOrEmpty( tokenName ) || tokenName[0] == '<' ) continue; if ( tokenName[0] == '\'' ) { if ( targetNames != null && targetNames.Length > i ) { // make sure implicit tokens like 'new' that show up in code as T__45 refer to the same token Assert.AreEqual( sourceNames[i], targetNames[i], string.Format( "Implicit token {0} in grammar {1} doesn't match {2} in grammar {3}.", sourceNames[i], source.Name, targetNames[i], target.Name ) ); continue; } else { tokenName = "T__" + i.ToString(); } } FieldInfo sourceToken = source.GetField( tokenName ); FieldInfo targetToken = target.GetField( tokenName ); if ( source != null && target != null ) { int sourceValue = (int)sourceToken.GetValue( null ); int targetValue = (int)targetToken.GetValue( null ); Assert.AreEqual( sourceValue, targetValue, string.Format( "Token {0} with value {1} grammar {2} doesn't match value {3} in grammar {4}.", tokenName, sourceValue, source.Name, targetValue, target.Name ) ); } } } protected AntlrTool newTool(params string[] args) { AntlrTool tool = (args == null || args.Length == 0) ? new AntlrTool() : new AntlrTool(args); tool.SetOutputDirectory( tmpdir ); tool.TestMode = true; return tool; } protected static string JavaHome { get { string home = javaHome; bool debugger = Debugger.IsAttached; if (home == null || debugger) { home = Environment.GetEnvironmentVariable("JAVA_HOME"); if (string.IsNullOrEmpty(home) || !Directory.Exists(home)) { home = CheckForJavaHome(Registry.CurrentUser); if (home == null) home = CheckForJavaHome(Registry.LocalMachine); } if (home != null && !Directory.Exists(home)) home = null; if (!debugger) { javaHome = home; } } return home; } } protected static string CheckForJavaHome(RegistryKey key) { using (RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\JavaSoft\Java Development Kit")) { if (subkey == null) return null; object value = subkey.GetValue("CurrentVersion", null, RegistryValueOptions.None); if (value != null) { using (RegistryKey currentHomeKey = subkey.OpenSubKey(value.ToString())) { if (currentHomeKey == null) return null; value = currentHomeKey.GetValue("JavaHome", null, RegistryValueOptions.None); if (value != null) return value.ToString(); } } } return null; } protected string ClassPath { get { return Path.GetFullPath( RuntimeJar ) + Path.PathSeparator + Path.GetFullPath( Runtime2Jar ) + Path.PathSeparator + Path.GetFullPath( StringTemplateJar ); } } protected string Compiler { get { return Path.Combine( Path.Combine( JavaHome, "bin" ), "javac.exe" ); } } protected string Jvm { get { return Path.Combine( Path.Combine( JavaHome, "bin" ), "java.exe" ); } } protected bool compile( string fileName ) { //String compiler = "javac"; string compiler = Compiler; string classpathOption = "-classpath"; if ( jikes != null ) { compiler = jikes; classpathOption = "-bootclasspath"; } string inputFile = Path.Combine(tmpdir, fileName); string[] args = new string[] { /*compiler,*/ "-d", tmpdir, classpathOption, tmpdir+pathSep+ClassPath, inputFile }; string cmdLine = compiler + " -d " + tmpdir + " " + classpathOption + " " + '"'+tmpdir + pathSep + ClassPath+'"' + " " + fileName; //System.out.println("compile: "+cmdLine); //File outputDir = new File( tmpdir ); try { System.Diagnostics.Process process = System.Diagnostics.Process.Start( new System.Diagnostics.ProcessStartInfo( compiler, '"' + string.Join( "\" \"", args ) + '"' ) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = tmpdir } ); //Process process = // Runtime.getRuntime().exec( args, null, outputDir ); StreamVacuum stdout = new StreamVacuum( process.StandardOutput, inputFile ); StreamVacuum stderr = new StreamVacuum( process.StandardError, inputFile ); stdout.start(); stderr.start(); process.WaitForExit(); if ( stdout.ToString().Length > 0 ) { Console.Error.WriteLine( "compile stdout from: " + cmdLine ); Console.Error.WriteLine( stdout ); } if ( stderr.ToString().Length > 0 ) { Console.Error.WriteLine( "compile stderr from: " + cmdLine ); Console.Error.WriteLine( stderr ); } int ret = process.ExitCode; return ret == 0; } catch ( Exception e ) { Console.Error.WriteLine( "can't exec compilation" ); e.PrintStackTrace( Console.Error ); return false; } } /** Return true if all is ok, no errors */ protected bool antlr( string fileName, string grammarFileName, string grammarStr, bool debug ) { bool allIsWell = true; mkdir( tmpdir ); writeFile( tmpdir, fileName, grammarStr ); try { List<string> options = new List<string>(); options.Add( "-testmode" ); if ( debug ) { options.Add( "-debug" ); } options.Add( "-o" ); options.Add( tmpdir ); options.Add( "-lib" ); options.Add( tmpdir ); options.Add( Path.Combine( tmpdir, grammarFileName ) ); options.Add("-language"); options.Add("Java"); //String[] optionsA = new String[options.size()]; //options.toArray( optionsA ); string[] optionsA = options.ToArray(); /* final ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); */ AntlrTool antlr = new AntlrTool( optionsA ); antlr.Process(); IANTLRErrorListener listener = ErrorManager.GetErrorListener(); if ( listener is ErrorQueue ) { ErrorQueue equeue = (ErrorQueue)listener; if ( equeue.errors.Count > 0 ) { allIsWell = false; Console.Error.WriteLine( "antlr reports errors from [" + string.Join(", ", options) + ']' ); for ( int i = 0; i < equeue.errors.Count; i++ ) { Message msg = (Message)equeue.errors[i]; Console.Error.WriteLine( msg ); } Console.Out.WriteLine( "!!!\ngrammar:" ); Console.Out.WriteLine( grammarStr ); Console.Out.WriteLine( "###" ); } } } catch ( Exception e ) { allIsWell = false; Console.Error.WriteLine( "problems building grammar: " + e ); e.PrintStackTrace( Console.Error ); } return allIsWell; } protected string execLexer( string grammarFileName, string grammarStr, string lexerName, string input, bool debug ) { bool compiled = rawGenerateAndBuildRecognizer( grammarFileName, grammarStr, null, lexerName, debug ); Assert.IsTrue(compiled); writeFile(tmpdir, "input", input); return rawExecRecognizer( null, null, lexerName, null, null, false, false, false, debug ); } protected string execParser( string grammarFileName, string grammarStr, string parserName, string lexerName, string startRuleName, string input, bool debug ) { bool compiled = rawGenerateAndBuildRecognizer( grammarFileName, grammarStr, parserName, lexerName, debug ); Assert.IsTrue(compiled); writeFile(tmpdir, "input", input); bool parserBuildsTrees = grammarStr.IndexOf( "output=AST" ) >= 0 || grammarStr.IndexOf( "output = AST" ) >= 0; bool parserBuildsTemplate = grammarStr.IndexOf( "output=template" ) >= 0 || grammarStr.IndexOf( "output = template" ) >= 0; return rawExecRecognizer( parserName, null, lexerName, startRuleName, null, parserBuildsTrees, parserBuildsTemplate, false, debug ); } protected string execTreeParser( string parserGrammarFileName, string parserGrammarStr, string parserName, string treeParserGrammarFileName, string treeParserGrammarStr, string treeParserName, string lexerName, string parserStartRuleName, string treeParserStartRuleName, string input ) { return execTreeParser( parserGrammarFileName, parserGrammarStr, parserName, treeParserGrammarFileName, treeParserGrammarStr, treeParserName, lexerName, parserStartRuleName, treeParserStartRuleName, input, false ); } protected string execTreeParser( string parserGrammarFileName, string parserGrammarStr, string parserName, string treeParserGrammarFileName, string treeParserGrammarStr, string treeParserName, string lexerName, string parserStartRuleName, string treeParserStartRuleName, string input, bool debug ) { // build the parser bool compiled = rawGenerateAndBuildRecognizer( parserGrammarFileName, parserGrammarStr, parserName, lexerName, debug ); Assert.IsTrue(compiled); // build the tree parser compiled = rawGenerateAndBuildRecognizer( treeParserGrammarFileName, treeParserGrammarStr, treeParserName, lexerName, debug ); Assert.IsTrue(compiled); writeFile( tmpdir, "input", input ); bool parserBuildsTrees = parserGrammarStr.IndexOf( "output=AST" ) >= 0 || parserGrammarStr.IndexOf( "output = AST" ) >= 0; bool treeParserBuildsTrees = treeParserGrammarStr.IndexOf( "output=AST" ) >= 0 || treeParserGrammarStr.IndexOf( "output = AST" ) >= 0; bool parserBuildsTemplate = parserGrammarStr.IndexOf( "output=template" ) >= 0 || parserGrammarStr.IndexOf( "output = template" ) >= 0; return rawExecRecognizer( parserName, treeParserName, lexerName, parserStartRuleName, treeParserStartRuleName, parserBuildsTrees, parserBuildsTemplate, treeParserBuildsTrees, debug ); } /** Return true if all is well */ protected bool rawGenerateAndBuildRecognizer( string grammarFileName, string grammarStr, string parserName, string lexerName, bool debug ) { bool allIsWell = antlr( grammarFileName, grammarFileName, grammarStr, debug ); if (!allIsWell) return false; if ( lexerName != null ) { bool ok; if ( parserName != null ) { ok = compile( parserName + ".java" ); if ( !ok ) { allIsWell = false; } } ok = compile( lexerName + ".java" ); if ( !ok ) { allIsWell = false; } } else { bool ok = compile( parserName + ".java" ); if ( !ok ) { allIsWell = false; } } return allIsWell; } protected string rawExecRecognizer( string parserName, string treeParserName, string lexerName, string parserStartRuleName, string treeParserStartRuleName, bool parserBuildsTrees, bool parserBuildsTemplate, bool treeParserBuildsTrees, bool debug ) { stderrDuringParse = null; WriteRecognizerAndCompile(parserName, treeParserName, lexerName, parserStartRuleName, treeParserStartRuleName, parserBuildsTrees, parserBuildsTemplate, treeParserBuildsTrees, debug); return execRecognizer(); } public string execRecognizer() { try { string inputFile = Path.GetFullPath(Path.Combine(tmpdir, "input")); string[] args = new string[] { /*"java",*/ "-classpath", tmpdir+pathSep+ClassPath, "Test", inputFile }; //String cmdLine = "java -classpath " + CLASSPATH + pathSep + tmpdir + " Test " + Path.GetFullPath( Path.Combine( tmpdir, "input" ) ); //System.out.println("execParser: "+cmdLine); System.Diagnostics.Process process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Jvm, '"' + string.Join("\" \"", args) + '"') { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = tmpdir }); //Process process = // Runtime.getRuntime().exec( args, null, new File( tmpdir ) ); StreamVacuum stdoutVacuum = new StreamVacuum(process.StandardOutput, inputFile); StreamVacuum stderrVacuum = new StreamVacuum(process.StandardError, inputFile); stdoutVacuum.start(); stderrVacuum.start(); process.WaitForExit(); stdoutVacuum.join(); stderrVacuum.join();
antlr/antlrcs
6a80bbc4d99663351a4194c9acc4f182c6b13f49
Mark tests that require Java compilation as SkipOnCI
diff --git a/Antlr3.Test/TestAttributes.cs b/Antlr3.Test/TestAttributes.cs index 47bb099..0e1cde2 100644 --- a/Antlr3.Test/TestAttributes.cs +++ b/Antlr3.Test/TestAttributes.cs @@ -1749,1040 +1749,1042 @@ namespace AntlrUnitTests string expecting2 = "(INT2!=null?INT2.getText():null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ID {" + action + "}\n" + " | INT {" + action2 + "}\n" + " ;\n" + "ID : 'a';\n" + "INT : '0';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action2 ), 2 ); found = translator.Translate(); Assert.AreEqual( expecting2, found ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleLabelFromMultipleAlts() /*throws Exception*/ { string action = "$b.text;"; // must be qualified string action2 = "$c.text;"; // must be qualified string expecting = "(b1!=null?input.toString(b1.start,b1.stop):null);"; string expecting2 = "(c2!=null?input.toString(c2.start,c2.stop):null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : b {###" + action + "!!!}\n" + " | c {^^^" + action2 + "&&&}\n" + " ;\n" + "b : 'a';\n" + "c : '0';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates StringTemplate codeST = generator.RecognizerST; string code = codeST.Render(); string found = code.Substring(code.IndexOf("###") + 3, code.IndexOf("!!!") - code.IndexOf("###") - 3); Assert.AreEqual(expecting, found); found = code.Substring(code.IndexOf("^^^") + 3, code.IndexOf("&&&") - code.IndexOf("^^^") - 3); Assert.AreEqual(expecting2, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUnknownDynamicAttribute() /*throws Exception*/ { string action = "$a::x"; string expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a\n" + "scope {\n" + " int n;\n" + "} : {" + action + "}\n" + " ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE_ATTRIBUTE; object expectedArg = "a"; object expectedArg2 = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUnknownGlobalDynamicAttribute() /*throws Exception*/ { string action = "$Symbols::x"; string expecting = action; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "scope Symbols {\n" + " int n;\n" + "}\n" + "a : {'+action+'}\n" + " ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_DYNAMIC_SCOPE_ATTRIBUTE; object expectedArg = "Symbols"; object expectedArg2 = "x"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUnqualifiedRuleScopeAttribute() /*throws Exception*/ { string action = "$n;"; // must be qualified string expecting = "$n;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a\n" + "scope {\n" + " int n;\n" + "} : b\n" + " ;\n" + "b : {'+action+'}\n" + " ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); ActionTranslator translator = new ActionTranslator( generator, "b", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); int expectedMsgID = ErrorManager.MSG_UNKNOWN_SIMPLE_ATTRIBUTE; object expectedArg = "n"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleAndTokenLabelTypeMismatch() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : id='foo' id=b\n" + " ;\n" + "b : ;\n" ); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; object expectedArg = "id"; object expectedArg2 = "rule!=token"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestListAndTokenLabelTypeMismatch() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ids+='a' ids='b'\n" + " ;\n" + "b : ;\n" ); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; object expectedArg = "ids"; object expectedArg2 = "token!=token-list"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestListAndRuleLabelTypeMismatch() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "options {output=AST;}\n" + "a : bs+=b bs=b\n" + " ;\n" + "b : 'b';\n" ); int expectedMsgID = ErrorManager.MSG_LABEL_TYPE_CONFLICT; object expectedArg = "bs"; object expectedArg2 = "rule!=rule-list"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestArgReturnValueMismatch() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a[int i] returns [int x, int i]\n" + " : \n" + " ;\n" + "b : ;\n" ); int expectedMsgID = ErrorManager.MSG_ARG_RETVAL_CONFLICT; object expectedArg = "i"; object expectedArg2 = "a"; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimplePlusEqualLabel() /*throws Exception*/ { string action = "$ids.size();"; // must be qualified string expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "parser grammar t;\n" + "a : ids+=ID ( COMMA ids+=ID {" + action + "})* ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPlusEqualStringLabel() /*throws Exception*/ { string action = "$ids.size();"; // must be qualified string expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ids+='if' ( ',' ids+=ID {" + action + "})* ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPlusEqualSetLabel() /*throws Exception*/ { string action = "$ids.size();"; // must be qualified string expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ids+=('a'|'b') ( ',' ids+=ID {" + action + "})* ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPlusEqualWildcardLabel() /*throws Exception*/ { string action = "$ids.size();"; // must be qualified string expecting = "list_ids.size();"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ids+=. ( ',' ids+=ID {" + action + "})* ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImplicitTokenLabel() /*throws Exception*/ { string action = "$ID; $ID.text; $ID.getText()"; string expecting = "ID1; (ID1!=null?ID1.getText():null); ID1.getText()"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ID {" + action + "} ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImplicitRuleLabel() /*throws Exception*/ { string action = "$r.start;"; string expecting = "(r1!=null?(r1.start):null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r {###" + action + "!!!} ;" + "r : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); StringTemplate codeST = generator.RecognizerST; string code = codeST.Render(); int startIndex = code.IndexOf("###") + 3; int endIndex = code.IndexOf("!!!"); string found = code.Substring(startIndex, endIndex - startIndex); Assert.AreEqual( expecting, found ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReuseExistingLabelWithImplicitRuleLabel() /*throws Exception*/ { string action = "$r.start;"; string expecting = "(x!=null?(x.start):null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : x=r {###" + action + "!!!} ;" + "r : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); StringTemplate codeST = generator.RecognizerST; string code = codeST.Render(); int startIndex = code.IndexOf("###") + 3; int endIndex = code.IndexOf("!!!"); string found = code.Substring(startIndex, endIndex - startIndex); Assert.AreEqual( expecting, found ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReuseExistingListLabelWithImplicitRuleLabel() /*throws Exception*/ { string action = "$r.start;"; string expecting = "(x!=null?(x.start):null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "options {output=AST;}\n" + "a : x+=r {###" + action + "!!!} ;" + "r : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); StringTemplate codeST = generator.RecognizerST; string code = codeST.Render(); int startIndex = code.IndexOf("###") + 3; int endIndex = code.IndexOf("!!!"); string found = code.Substring(startIndex, endIndex - startIndex); Assert.AreEqual( expecting, found ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReuseExistingLabelWithImplicitTokenLabel() /*throws Exception*/ { string action = "$ID.text;"; string expecting = "(x!=null?x.getText():null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : x=ID {" + action + "} ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReuseExistingListLabelWithImplicitTokenLabel() /*throws Exception*/ { string action = "$ID.text;"; string expecting = "(x!=null?x.getText():null);"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : x+=ID {" + action + "} ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleLabelWithoutOutputOption() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar T;\n" + "s : x+=a ;" + "a : 'a';\n" + "b : 'b';\n" + "WS : ' '|'\n';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_LIST_LABEL_INVALID_UNLESS_RETVAL_STRUCT; object expectedArg = "x"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] + [TestCategory(TestCategories.SkipOnCI)] public void TestRuleLabelOnTwoDifferentRulesAST() /*throws Exception*/ { //Assert.Inconclusive( "I broke this test while trying to fix return values on another test..." ); string grammar = "grammar T;\n" + "options {output=AST;}\n" + "s : x+=a x+=b {System.out.println($x);} ;" + "a : 'a';\n" + "b : 'b';\n" + "WS : (' '|'\\n') {skip();};\n"; string expecting = "[a, b]" + NewLine + "a b" + NewLine; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "a b", false ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] + [TestCategory(TestCategories.SkipOnCI)] public void TestRuleLabelOnTwoDifferentRulesTemplate() /*throws Exception*/ { //Assert.Inconclusive( "I broke this test while trying to fix return values on another test..." ); string grammar = "grammar T;\n" + "options {output=template;}\n" + "s : x+=a x+=b {System.out.println($x);} ;" + "a : 'a' -> {%{\"hi\"}} ;\n" + "b : 'b' -> {%{\"mom\"}} ;\n" + "WS : (' '|'\\n') {skip();};\n"; string expecting = "[hi, mom]" + NewLine; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "a b", false ); Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMissingArgs() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r ;" + "r[int i] : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; object expectedArg = "r"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestArgsWhenNoneDefined() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r[32,34] ;" + "r : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; object expectedArg = "r"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReturnInitValue() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r ;\n" + "r returns [int x=0] : 'a' {$x = 4;} ;\n" ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); Rule r = g.GetRule( "r" ); AttributeScope retScope = r.ReturnScope; var parameters = retScope.Attributes; Assert.IsNotNull(parameters, "missing return action"); Assert.AreEqual( 1, parameters.Count ); string found = parameters.ElementAt( 0 ).ToString(); string expecting = "int x=0"; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMultipleReturnInitValue() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r ;\n" + "r returns [int x=0, int y, String s=new String(\"foo\")] : 'a' {$x = 4;} ;\n" ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); Rule r = g.GetRule( "r" ); AttributeScope retScope = r.ReturnScope; var parameters = retScope.Attributes; Assert.IsNotNull(parameters, "missing return action"); Assert.AreEqual( 3, parameters.Count ); Assert.AreEqual( "int x=0", parameters.ElementAt( 0 ).ToString() ); Assert.AreEqual( "int y", parameters.ElementAt( 1 ).ToString() ); Assert.AreEqual( "String s=new String(\"foo\")", parameters.ElementAt( 2 ).ToString() ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCStyleReturnInitValue() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r ;\n" + "r returns [int (*x)()=NULL] : 'a' ;\n" ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); Rule r = g.GetRule( "r" ); AttributeScope retScope = r.ReturnScope; var parameters = retScope.Attributes; Assert.IsNotNull(parameters, "missing return action"); Assert.AreEqual( 1, parameters.Count ); string found = parameters.ElementAt( 0 ).ToString(); string expecting = "int (*)() x=NULL"; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestArgsWithInitValues() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : r[32,34] ;" + "r[int x, int y=3] : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_ARG_INIT_VALUES_ILLEGAL; object expectedArg = "y"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestArgsOnToken() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : ID[32,34] ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_ARGS_ON_TOKEN_REF; object expectedArg = "ID"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestArgsOnTokenInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : 'z' ID[32,34] ;" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; object expectedArg = "ID"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelOnRuleRefInLexer() /*throws Exception*/ { string action = "$i.text"; string expecting = "(i!=null?i.getText():null)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : 'z' i=ID {" + action + "};" + "fragment ID : 'a';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "R", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToRuleRefInLexer() /*throws Exception*/ { string action = "$ID.text"; string expecting = "(ID1!=null?ID1.getText():null)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : 'z' ID {" + action + "};" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "R", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToRuleRefInLexerNoAttribute() /*throws Exception*/ { string action = "$ID"; string expecting = "ID1"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : 'z' ID {" + action + "};" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "R", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCharLabelInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : x='z' ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCharListLabelInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : x+='z' ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardCharLabelInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : x=. ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardCharListLabelInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : x+=. ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMissingArgsInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "A : R ;" + "R[int i] : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; object expectedArg = "R"; object expectedArg2 = null; // getting a second error @1:12, probably from nextToken GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerRulePropertyRefs() /*throws Exception*/ { string action = "$text $type $line $pos $channel $index $start $stop"; string expecting = "getText() _type state.tokenStartLine state.tokenStartCharPositionInLine _channel -1 state.tokenStartCharIndex (getCharIndex()-1)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : 'r' {" + action + "};\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "R", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerLabelRefs() /*throws Exception*/ { string action = "$a $b.text $c $d.text"; string expecting = "a (b!=null?b.getText():null) c (d!=null?d.getText():null)"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : a='c' b='hi' c=. d=DUH {" + action + "};\n" + "DUH : 'd' ;\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "R", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSettingLexerRulePropertyRefs() /*throws Exception*/ { string action = "$text $type=1 $line=1 $pos=1 $channel=1 $index"; string expecting = "getText() _type=1 state.tokenStartLine=1 state.tokenStartCharPositionInLine=1 _channel=1 -1"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "lexer grammar t;\n" + "R : 'r' {" + action + "};\n" ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates ActionTranslator translator = new ActionTranslator( generator, "R", new CommonToken( ANTLRParser.ACTION, action ), 1 ); string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestArgsOnTokenInLexerRuleOfCombined() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : R;\n" + "R : 'z' ID[32] ;\n" + "ID : 'a';\n" ); string lexerGrammarStr = g.GetLexerGrammar(); System.IO.StringReader sr = new System.IO.StringReader( lexerGrammarStr ); Grammar lexerGrammar = new Grammar(); lexerGrammar.FileName = "<internally-generated-lexer>"; lexerGrammar.ImportTokenVocabulary( g ); lexerGrammar.ParseAndBuildAST( sr ); lexerGrammar.DefineGrammarSymbols(); lexerGrammar.CheckNameSpaceAndActions(); sr.Close(); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, lexerGrammar, "Java" ); lexerGrammar.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_RULE_HAS_NO_ARGS; object expectedArg = "ID"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, lexerGrammar, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMissingArgsOnTokenInLexerRuleOfCombined() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : R;\n" + "R : 'z' ID ;\n" + "ID[int i] : 'a';\n" ); string lexerGrammarStr = g.GetLexerGrammar(); StringReader sr = new StringReader( lexerGrammarStr ); Grammar lexerGrammar = new Grammar(); lexerGrammar.FileName = "<internally-generated-lexer>"; lexerGrammar.ImportTokenVocabulary( g ); lexerGrammar.ParseAndBuildAST( sr ); lexerGrammar.DefineGrammarSymbols(); lexerGrammar.CheckNameSpaceAndActions(); sr.Close(); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, lexerGrammar, "Java" ); lexerGrammar.CodeGenerator = generator; generator.GenRecognizer(); int expectedMsgID = ErrorManager.MSG_MISSING_RULE_ARGS; object expectedArg = "ID"; object expectedArg2 = null; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, lexerGrammar, null, expectedArg, expectedArg2 ); checkError( equeue, expectedMessage ); } // T R E E S [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenLabelTreeProperty() /*throws Exception*/ { string action = "$id.tree;"; string expecting = "id_tree;"; ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar t;\n" + "a : id=ID {" + action + "} ;\n" + "ID : 'a';\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); ActionTranslator translator = new ActionTranslator( generator, "a", new CommonToken( ANTLRParser.ACTION, action ), 1 ); g.CodeGenerator = generator; generator.GenRecognizer(); // forces load of templates string found = translator.Translate(); Assert.AreEqual(expecting, found); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenRefTreeProperty() /*throws Exception*/ { string action = "$ID.tree;"; string expecting = "ID1_tree;"; diff --git a/Antlr3.Test/TestSymbolDefinitions.cs b/Antlr3.Test/TestSymbolDefinitions.cs index 279aa8a..63602e9 100644 --- a/Antlr3.Test/TestSymbolDefinitions.cs +++ b/Antlr3.Test/TestSymbolDefinitions.cs @@ -1,737 +1,739 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using System; using System.Collections.Generic; using System.Linq; using Antlr.Runtime.JavaExtensions; using Antlr3.Tool; using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using CodeGenerator = Antlr3.Codegen.CodeGenerator; using Label = Antlr3.Analysis.Label; using StringTemplate = Antlr4.StringTemplate.Template; using StringTokenizer = Antlr.Runtime.JavaExtensions.StringTokenizer; [TestClass] public class TestSymbolDefinitions : BaseTest { /** Public default constructor used by TestRig */ public TestSymbolDefinitions() { } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserSimpleTokens() /*throws Exception*/ { Grammar g = new Grammar( "parser grammar t;\n" + "a : A | B;\n" + "b : C ;" ); string rules = "a, b"; string tokenNames = "A, B, C"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserTokensSection() /*throws Exception*/ { Grammar g = new Grammar( "parser grammar t;\n" + "tokens {\n" + " C;\n" + " D;" + "}\n" + "a : A | B;\n" + "b : C ;" ); string rules = "a, b"; string tokenNames = "A, B, C, D"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerTokensSection() /*throws Exception*/ { Grammar g = new Grammar( "lexer grammar t;\n" + "tokens {\n" + " C;\n" + " D;" + "}\n" + "A : 'a';\n" + "C : 'c' ;" ); string rules = "A, C, Tokens"; string tokenNames = "A, C, D"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokensSectionWithAssignmentSection() /*throws Exception*/ { Grammar g = new Grammar( "grammar t;\n" + "tokens {\n" + " C='c';\n" + " D;" + "}\n" + "a : A | B;\n" + "b : C ;" ); string rules = "a, b"; string tokenNames = "A, B, C, D, 'c'"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCombinedGrammarLiterals() /*throws Exception*/ { Grammar g = new Grammar( "grammar t;\n" + "a : 'begin' b 'end';\n" + "b : C ';' ;\n" + "ID : 'a' ;\n" + "FOO : 'foo' ;\n" + // "foo" is not a token name "C : 'c' ;\n" ); // nor is 'c' string rules = "a, b"; string tokenNames = "C, FOO, ID, 'begin', 'end', ';'"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLiteralInParserAndLexer() /*throws Exception*/ { // 'x' is token and char in lexer rule Grammar g = new Grammar( "grammar t;\n" + "a : 'x' E ; \n" + "E: 'x' '0' ;\n" ); // nor is 'c' //String literals = "['x']"; string[] literals = new string[] { "'x'" }; var foundLiterals = g.StringLiterals; Assert.IsTrue( literals.SequenceEqual(foundLiterals) ); string implicitLexer = "lexer grammar t;" + NewLine + "T__5 : 'x' ;" + NewLine + "" + NewLine + "// $ANTLR src \"<string>\" 3" + NewLine + "E: 'x' '0' ;"; Assert.AreEqual( implicitLexer, g.GetLexerGrammar() ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCombinedGrammarWithRefToLiteralButNoTokenIDRef() /*throws Exception*/ { Grammar g = new Grammar( "grammar t;\n" + "a : 'a' ;\n" + "A : 'a' ;\n" ); string rules = "a"; string tokenNames = "A, 'a'"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSetDoesNotMissTokenAliases() /*throws Exception*/ { Grammar g = new Grammar( "grammar t;\n" + "a : 'a'|'b' ;\n" + "A : 'a' ;\n" + "B : 'b' ;\n" ); string rules = "a"; string tokenNames = "A, 'a', B, 'b'"; checkSymbols( g, rules, tokenNames ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimplePlusEqualLabel() /*throws Exception*/ { Grammar g = new Grammar( "parser grammar t;\n" + "a : ids+=ID ( COMMA ids+=ID )* ;\n" ); string rule = "a"; string tokenLabels = "ids"; string ruleLabels = null; checkPlusEqualsLabels( g, rule, tokenLabels, ruleLabels ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMixedPlusEqualLabel() /*throws Exception*/ { Grammar g = new Grammar( "grammar t;\n" + "options {output=AST;}\n" + "a : id+=ID ( ',' e+=expr )* ;\n" + "expr : 'e';\n" + "ID : 'a';\n" ); string rule = "a"; string tokenLabels = "id"; string ruleLabels = "e"; checkPlusEqualsLabels( g, rule, tokenLabels, ruleLabels ); } // T E S T L I T E R A L E S C A P E S [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserCharLiteralWithEscape() /*throws Exception*/ { Grammar g = new Grammar( "grammar t;\n" + "a : '\\n';\n" ); var literals = g.StringLiterals; // must store literals how they appear in the antlr grammar Assert.AreEqual( "'\\n'", literals.ToArray()[0] ); } [TestMethod][TestCategory(TestCategories.Antlr3)] + [TestCategory(TestCategories.SkipOnCI)] public void TestTokenInTokensSectionAndTokenRuleDef() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "tokens { B='}'; }\n" + "a : A B {System.out.println(input);} ;\n" + "A : 'a' ;\n" + "B : '}' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "a}", false ); Assert.AreEqual( "a}" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] + [TestCategory(TestCategories.SkipOnCI)] public void TestTokenInTokensSectionAndTokenRuleDef2() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "tokens { B='}'; }\n" + "a : A '}' {System.out.println(input);} ;\n" + "A : 'a' ;\n" + "B : '}' {/* */} ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "a}", false ); Assert.AreEqual( "a}" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToRuleWithNoReturnValue() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string grammarStr = "grammar P;\n" + "a : x=b ;\n" + "b : B ;\n" + "B : 'b' ;\n"; Grammar g = new Grammar( grammarStr ); AntlrTool antlr = newTool(); CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; StringTemplate recogST = generator.GenRecognizer(); string code = recogST.Render(); Assert.IsTrue(code.IndexOf("x=b();") < 0, "not expecting label"); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } // T E S T E R R O R S [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserStringLiterals() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "parser grammar t;\n" + "a : 'begin' b ;\n" + "b : C ;" ); object expectedArg = "'begin'"; int expectedMsgID = ErrorManager.MSG_LITERAL_NOT_ASSOCIATED_WITH_LEXER_RULE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserCharLiterals() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "parser grammar t;\n" + "a : '(' b ;\n" + "b : C ;" ); object expectedArg = "'('"; int expectedMsgID = ErrorManager.MSG_LITERAL_NOT_ASSOCIATED_WITH_LEXER_RULE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestEmptyNotChar() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar foo;\n" + "a : (~'x')+ ;\n" ); g.BuildNFA(); object expectedArg = "'x'"; int expectedMsgID = ErrorManager.MSG_EMPTY_COMPLEMENT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestEmptyNotToken() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar foo;\n" + "a : (~A)+ ;\n" ); g.BuildNFA(); object expectedArg = "A"; int expectedMsgID = ErrorManager.MSG_EMPTY_COMPLEMENT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestEmptyNotSet() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "grammar foo;\n" + "a : (~(A|B))+ ;\n" ); g.BuildNFA(); object expectedArg = null; int expectedMsgID = ErrorManager.MSG_EMPTY_COMPLEMENT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestStringLiteralInParserTokensSection() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "tokens {\n" + " B='begin';\n" + "}\n" + "a : A B;\n" + "b : C ;" ); object expectedArg = "'begin'"; int expectedMsgID = ErrorManager.MSG_LITERAL_NOT_ASSOCIATED_WITH_LEXER_RULE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCharLiteralInParserTokensSection() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "tokens {\n" + " B='(';\n" + "}\n" + "a : A B;\n" + "b : C ;" ); object expectedArg = "'('"; int expectedMsgID = ErrorManager.MSG_LITERAL_NOT_ASSOCIATED_WITH_LEXER_RULE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCharLiteralInLexerTokensSection() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "lexer grammar t;\n" + "tokens {\n" + " B='(';\n" + "}\n" + "ID : 'a';\n" ); object expectedArg = "'('"; int expectedMsgID = ErrorManager.MSG_CANNOT_ALIAS_TOKENS_IN_LEXER; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleRedefinition() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a : A | B;\n" + "a : C ;" ); object expectedArg = "a"; int expectedMsgID = ErrorManager.MSG_RULE_REDEFINITION; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerRuleRedefinition() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "lexer grammar t;\n" + "ID : 'a' ;\n" + "ID : 'd' ;" ); object expectedArg = "ID"; int expectedMsgID = ErrorManager.MSG_RULE_REDEFINITION; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCombinedRuleRedefinition() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "grammar t;\n" + "x : ID ;\n" + "ID : 'a' ;\n" + "x : ID ID ;" ); object expectedArg = "x"; int expectedMsgID = ErrorManager.MSG_RULE_REDEFINITION; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUndefinedToken() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "grammar t;\n" + "x : ID ;" ); object expectedArg = "ID"; int expectedMsgID = ErrorManager.MSG_NO_TOKEN_DEFINITION; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsWarning( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUndefinedTokenOkInParser() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "x : ID ;" ); Assert.AreEqual(0, equeue.errors.Count, "should not be an error"); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUndefinedRule() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "grammar t;\n" + "x : r ;" ); object expectedArg = "r"; int expectedMsgID = ErrorManager.MSG_UNDEFINED_RULE_REF; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerRuleInParser() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "X : ;" ); object expectedArg = "X"; int expectedMsgID = ErrorManager.MSG_LEXER_RULES_NOT_ALLOWED; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserRuleInLexer() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "lexer grammar t;\n" + "a : ;" ); object expectedArg = "a"; int expectedMsgID = ErrorManager.MSG_PARSER_RULES_NOT_ALLOWED; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleScopeConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "grammar t;\n" + "scope a {\n" + " int n;\n" + "}\n" + "a : \n" + " ;\n" ); object expectedArg = "a"; int expectedMsgID = ErrorManager.MSG_SYMBOL_CONFLICTS_WITH_GLOBAL_SCOPE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenRuleScopeConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "grammar t;\n" + "scope ID {\n" + " int n;\n" + "}\n" + "ID : 'a'\n" + " ;\n" ); object expectedArg = "ID"; int expectedMsgID = ErrorManager.MSG_SYMBOL_CONFLICTS_WITH_GLOBAL_SCOPE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenScopeConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "grammar t;\n" + "tokens { ID; }\n" + "scope ID {\n" + " int n;\n" + "}\n" + "a : \n" + " ;\n" ); object expectedArg = "ID"; int expectedMsgID = ErrorManager.MSG_SYMBOL_CONFLICTS_WITH_GLOBAL_SCOPE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenRuleScopeConflictInLexerGrammar() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "lexer grammar t;\n" + "scope ID {\n" + " int n;\n" + "}\n" + "ID : 'a'\n" + " ;\n" ); object expectedArg = "ID"; int expectedMsgID = ErrorManager.MSG_SYMBOL_CONFLICTS_WITH_GLOBAL_SCOPE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenLabelScopeConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "scope s {\n" + " int n;\n" + "}\n" + "a : s=ID \n" + " ;\n" ); object expectedArg = "s"; int expectedMsgID = ErrorManager.MSG_SYMBOL_CONFLICTS_WITH_GLOBAL_SCOPE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleLabelScopeConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "scope s {\n" + " int n;\n" + "}\n" + "a : s=b \n" + " ;\n" + "b : ;\n" ); object expectedArg = "s"; int expectedMsgID = ErrorManager.MSG_SYMBOL_CONFLICTS_WITH_GLOBAL_SCOPE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelAndRuleNameConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a : c=b \n" + " ;\n" + "b : ;\n" + "c : ;\n" ); object expectedArg = "c"; int expectedMsgID = ErrorManager.MSG_LABEL_CONFLICTS_WITH_RULE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelAndTokenNameConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a : ID=b \n" + " ;\n" + "b : ID ;\n" + "c : ;\n" ); object expectedArg = "ID"; int expectedMsgID = ErrorManager.MSG_LABEL_CONFLICTS_WITH_TOKEN; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelAndArgConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a[int i] returns [int x]: i=ID \n" + " ;\n" ); object expectedArg = "i"; int expectedMsgID = ErrorManager.MSG_LABEL_CONFLICTS_WITH_RULE_ARG_RETVAL; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelAndParameterConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a[int i] returns [int x]: x=ID \n" + " ;\n" ); object expectedArg = "x"; int expectedMsgID = ErrorManager.MSG_LABEL_CONFLICTS_WITH_RULE_ARG_RETVAL; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelRuleScopeConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a\n" + "scope {" + " int n;" + "}\n" + " : n=ID\n" + " ;\n" ); object expectedArg = "n"; object expectedArg2 = "a"; int expectedMsgID = ErrorManager.MSG_LABEL_CONFLICTS_WITH_RULE_SCOPE_ATTRIBUTE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkGrammarSemanticsError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleScopeArgConflict() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); // unique listener per thread Grammar g = new Grammar( "parser grammar t;\n" + "a[int n]\n" + "scope {" + " int n;" + "}\n" + " : \n" + " ;\n" ); object expectedArg = "n"; object expectedArg2 = "a"; int expectedMsgID = ErrorManager.MSG_ATTRIBUTE_CONFLICTS_WITH_RULE_ARG_RETVAL; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkGrammarSemanticsError( equeue, expectedMessage ); }
antlr/antlrcs
80bfa07264066e04033e4bbbcc8251e34e3a5fa2
Use PathSeparator instead of assuming ':' in PathGroupLoader
diff --git a/Antlr3.StringTemplate/PathGroupLoader.cs b/Antlr3.StringTemplate/PathGroupLoader.cs index 2e85e80..cf88af1 100644 --- a/Antlr3.StringTemplate/PathGroupLoader.cs +++ b/Antlr3.StringTemplate/PathGroupLoader.cs @@ -1,226 +1,226 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr3.ST { using System; using System.Collections.ObjectModel; using Antlr3.ST.Extensions; using Antlr3.ST.Language; using Encoding = System.Text.Encoding; using IOException = System.IO.IOException; using Path = System.IO.Path; using Stream = System.IO.Stream; using StreamReader = System.IO.StreamReader; using TextReader = System.IO.TextReader; /** <summary> * A brain dead loader that looks only in the directory(ies) you * specify in the ctor. * </summary> * * <remarks> * You may specify the char encoding. * NOTE: this does not work when you jar things up! Use * CommonGroupLoader instead in that case * </remarks> */ public class PathGroupLoader : IStringTemplateGroupLoader { private IStringTemplateErrorListener _errors = null; /** <summary> * How are the files encoded (ascii, UTF8, ...)? You might want to read * UTF8 for example on an ascii machine. * </summary> */ private Encoding _fileCharEncoding = Encoding.Default; public PathGroupLoader( IStringTemplateErrorListener errors ) { _errors = errors; } /** <summary> * Pass a single dir or multiple dirs separated by colons from which * to load groups/interfaces. * </summary> */ public PathGroupLoader( string dirStr, IStringTemplateErrorListener errors ) { _errors = errors; - Directories = new ReadOnlyCollection<string>(dirStr.Split(':')); + Directories = new ReadOnlyCollection<string>(dirStr.Split(Path.PathSeparator)); } /** <summary>Gets a list of directories to pull groups from</summary> */ public ReadOnlyCollection<string> Directories { get; private set; } /** <summary> * Load a group with a specified superGroup. Groups with * region definitions must know their supergroup to find templates * during parsing. * </summary> */ public virtual StringTemplateGroup LoadGroup( string groupName, Type templateLexer, StringTemplateGroup superGroup ) { StringTemplateGroup group = null; TextReader br = null; // group file format defaults to <...> Type lexer = typeof( AngleBracketTemplateLexer ); if ( templateLexer != null ) { lexer = templateLexer; } try { br = Locate( groupName + ".stg" ); if ( br == null ) { Error( "no such group file " + groupName + ".stg" ); return null; } group = new StringTemplateGroup( br, lexer, _errors, superGroup ); br.Close(); br = null; } catch ( IOException ioe ) { Error( "can't load group " + groupName, ioe ); } finally { if ( br != null ) { try { br.Close(); } catch ( IOException ioe2 ) { Error( "Cannot close template group file: " + groupName + ".stg", ioe2 ); } } } return group; } public virtual StringTemplateGroup LoadGroup( string groupName, StringTemplateGroup superGroup ) { return LoadGroup( groupName, null, superGroup ); } public virtual StringTemplateGroup LoadGroup( string groupName ) { return LoadGroup( groupName, null ); } public virtual StringTemplateGroupInterface LoadInterface( string interfaceName ) { StringTemplateGroupInterface I = null; try { TextReader br = Locate( interfaceName + ".sti" ); if ( br == null ) { Error( "no such interface file " + interfaceName + ".sti" ); return null; } I = new StringTemplateGroupInterface( br, _errors ); } catch ( IOException ioe ) { Error( "can't load interface " + interfaceName, ioe ); } return I; } /** <summary>Look in each directory for the file called 'name'.</summary> */ protected virtual TextReader Locate( string name ) { foreach (string dir in Directories) { string fileName = Path.Combine(dir, name); if ( System.IO.File.Exists( fileName ) ) { System.IO.FileStream fis = System.IO.File.OpenRead( fileName ); StreamReader isr = GetInputStreamReader( new System.IO.BufferedStream( fis ) ); return isr; } } return null; } protected virtual StreamReader GetInputStreamReader( Stream stream ) { return new StreamReader( stream, _fileCharEncoding ); } public virtual Encoding GetFileCharEncoding() { return _fileCharEncoding; } public virtual void SetFileCharEncoding( Encoding fileCharEncoding ) { this._fileCharEncoding = fileCharEncoding ?? Encoding.Default; } public virtual void Error( string msg ) { Error( msg, null ); } public virtual void Error( string msg, Exception e ) { if ( _errors != null ) { _errors.Error( msg, e ); } else { Console.Error.WriteLine( "StringTemplate: " + msg ); if ( e != null ) { e.PrintStackTrace(); } } } } } diff --git a/Antlr3.Test/StringTemplateTests.cs b/Antlr3.Test/StringTemplateTests.cs index 1c0c686..a987f49 100644 --- a/Antlr3.Test/StringTemplateTests.cs +++ b/Antlr3.Test/StringTemplateTests.cs @@ -1,721 +1,721 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using System; using System.Collections.Generic; using System.Text; using Antlr.Runtime.JavaExtensions; using Antlr3.ST; using Microsoft.VisualStudio.TestTools.UnitTesting; using AngleBracketTemplateLexer = Antlr3.ST.Language.AngleBracketTemplateLexer; using DefaultTemplateLexer = Antlr3.ST.Language.TemplateLexer; using IDictionary = System.Collections.IDictionary; using IList = System.Collections.IList; using IOException = System.IO.IOException; using Path = System.IO.Path; using StreamReader = System.IO.StreamReader; using StreamWriter = System.IO.StreamWriter; using StringReader = System.IO.StringReader; using StringWriter = System.IO.StringWriter; /// <summary> /// Summary description for UnitTest1 /// </summary> [TestClass] public class StringTemplateTests { static readonly string newline = Environment.NewLine; class ErrorBuffer : IStringTemplateErrorListener { StringBuilder errorOutput = new StringBuilder( 500 ); int n = 0; public void Error( string msg, Exception e ) { n++; if ( n > 1 ) { errorOutput.Append( '\n' ); } if ( e != null ) { StringWriter duh = new StringWriter(); e.PrintStackTrace( duh ); errorOutput.Append( msg + ": " + duh.ToString() ); } else { errorOutput.Append( msg ); } } public void Warning( string msg ) { n++; errorOutput.Append( msg ); } public override bool Equals( object o ) { string me = this.ToString(); string them = o.ToString(); return me.Equals( them ); } public override int GetHashCode() { return errorOutput.ToString().GetHashCode(); } public override string ToString() { return errorOutput.ToString(); } } public StringTemplateTests() { } /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get; set; } [TestInitialize] public void TestInitialize() { StringTemplateGroup.RegisterDefaultLexer(typeof(DefaultTemplateLexer)); } [TestMethod] [TestCategory(TestCategories.ST3)] public void TestInterfaceFileFormat() { string groupI = "interface test;" + newline + "t();" + newline + "bold(item);" + newline + "optional duh(a,b,c);" + newline; StringTemplateGroupInterface I = new StringTemplateGroupInterface( new StringReader( groupI ) ); string expecting = "interface test;" + newline + "t();" + newline + "bold(item);" + newline + "optional duh(a, b, c);" + newline; Assert.AreEqual( expecting, I.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestNoGroupLoader() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( null ); string templates = "group testG implements blort;" + newline + "t() ::= <<foo>>" + newline + "bold(item) ::= <<foo>>" + newline + "duh(a,b,c) ::= <<foo>>" + newline; WriteFile( tmpdir, "testG.stg", templates ); /*StringTemplateGroup group =*/ new StringTemplateGroup( new StreamReader( System.IO.File.OpenRead( tmpdir + "/testG.stg" ) ), errors ); string expecting = "no group loader registered"; Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestCannotFindInterfaceFile() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string templates = "group testG implements blort;" + newline + "t() ::= <<foo>>" + newline + "bold(item) ::= <<foo>>" + newline + "duh(a,b,c) ::= <<foo>>" + newline; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), errors ); string expecting = "no such interface file blort.sti"; Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestMultiDirGroupLoading() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); if ( !System.IO.Directory.Exists( System.IO.Path.Combine( tmpdir, "sub" ) ) ) { try { System.IO.Directory.CreateDirectory( System.IO.Path.Combine( tmpdir, "sub" ) ); } catch { // create a subdir Console.Error.WriteLine( "can't make subdir in test" ); return; } } StringTemplateGroup.RegisterGroupLoader( - new PathGroupLoader( tmpdir + ":" + tmpdir + "/sub", errors ) + new PathGroupLoader( tmpdir + Path.PathSeparator + tmpdir + "/sub", errors ) ); string templates = "group testG2;" + newline + "t() ::= <<foo>>" + newline + "bold(item) ::= <<foo>>" + newline + "duh(a,b,c) ::= <<foo>>" + newline; WriteFile( tmpdir + "/sub", "testG2.stg", templates ); StringTemplateGroup group = StringTemplateGroup.LoadGroup( "testG2" ); string expecting = "group testG2;" + newline + "bold(item) ::= <<foo>>" + newline + "duh(a,b,c) ::= <<foo>>" + newline + "t() ::= <<foo>>" + newline; Assert.AreEqual( expecting, group.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestGroupSatisfiesSingleInterface() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string groupI = "interface testI;" + newline + "t();" + newline + "bold(item);" + newline + "optional duh(a,b,c);" + newline; WriteFile( tmpdir, "testI.sti", groupI ); string templates = "group testG implements testI;" + newline + "t() ::= <<foo>>" + newline + "bold(item) ::= <<foo>>" + newline + "duh(a,b,c) ::= <<foo>>" + newline; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), errors ); string expecting = ""; // should be no errors Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestGroupExtendsSuperGroup() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string superGroup = "group superG;" + newline + "bold(item) ::= <<*$item$*>>;\n" + newline; WriteFile( tmpdir, "superG.stg", superGroup ); string templates = "group testG : superG;" + newline + "main(x) ::= <<$bold(x)$>>" + newline; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), typeof( DefaultTemplateLexer ), errors ); StringTemplate st = group.GetInstanceOf( "main" ); st.SetAttribute( "x", "foo" ); string expecting = "*foo*"; Assert.AreEqual( expecting, st.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestGroupExtendsSuperGroupWithAngleBrackets() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string superGroup = "group superG;" + newline + "bold(item) ::= <<*<item>*>>;\n" + newline; WriteFile( tmpdir, "superG.stg", superGroup ); string templates = "group testG : superG;" + newline + "main(x) ::= \"<bold(x)>\"" + newline; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), errors ); StringTemplate st = group.GetInstanceOf( "main" ); st.SetAttribute( "x", "foo" ); string expecting = "*foo*"; Assert.AreEqual( expecting, st.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestMissingInterfaceTemplate() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string groupI = "interface testI;" + newline + "t();" + newline + "bold(item);" + newline + "optional duh(a,b,c);" + newline; WriteFile( tmpdir, "testI.sti", groupI ); string templates = "group testG implements testI;" + newline + "t() ::= <<foo>>" + newline + "duh(a,b,c) ::= <<foo>>" + newline; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), errors ); string expecting = "group testG does not satisfy interface testI: missing templates [bold]"; Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestMissingOptionalInterfaceTemplate() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string groupI = "interface testI;" + newline + "t();" + newline + "bold(item);" + newline + "optional duh(a,b,c);" + newline; WriteFile( tmpdir, "testI.sti", groupI ); string templates = "group testG implements testI;" + newline + "t() ::= <<foo>>" + newline + "bold(item) ::= <<foo>>"; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), errors ); string expecting = ""; // should be NO errors Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestMismatchedInterfaceTemplate() { // this also tests the group loader IStringTemplateErrorListener errors = new ErrorBuffer(); string tmpdir = Path.GetTempPath(); StringTemplateGroup.RegisterGroupLoader( new PathGroupLoader( tmpdir, errors ) ); string groupI = "interface testI;" + newline + "t();" + newline + "bold(item);" + newline + "optional duh(a,b,c);" + newline; WriteFile( tmpdir, "testI.sti", groupI ); string templates = "group testG implements testI;" + newline + "t() ::= <<foo>>" + newline + "bold(item) ::= <<foo>>" + newline + "duh(a,c) ::= <<foo>>" + newline; WriteFile( tmpdir, "testG.stg", templates ); StringTemplateGroup group = new StringTemplateGroup( new StreamReader( tmpdir + "/testG.stg" ), errors ); string expecting = "group testG does not satisfy interface testI: mismatched arguments on these templates [optional duh(a, b, c)]"; Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestGroupFileFormat() { string templates = "group test;" + newline + "t() ::= \"literal template\"" + newline + "bold(item) ::= \"<b>$item$</b>\"" + newline + "duh() ::= <<" + newline + "xx" + newline + ">>" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); string expecting = "group test;" + newline + "bold(item) ::= <<<b>$item$</b>>>" + newline + "duh() ::= <<xx>>" + newline + "t() ::= <<literal template>>" + newline; Assert.AreEqual( expecting, group.ToString() ); StringTemplate a = group.GetInstanceOf( "t" ); expecting = "literal template"; Assert.AreEqual( expecting, a.ToString() ); StringTemplate b = group.GetInstanceOf( "bold" ); b.SetAttribute( "item", "dork" ); expecting = "<b>dork</b>"; Assert.AreEqual( expecting, b.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestEscapedTemplateDelimiters() { string templates = "group test;" + newline + "t() ::= <<$\"literal\":{a|$a$\\}}$ template\n>>" + newline + "bold(item) ::= <<<b>$item$</b\\>>>" + newline + "duh() ::= <<" + newline + "xx" + newline + ">>" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); string expecting = "group test;" + newline + "bold(item) ::= <<<b>$item$</b>>>" + newline + "duh() ::= <<xx>>" + newline + "t() ::= <<$\"literal\":{a|$a$\\}}$ template>>" + newline; Assert.AreEqual( expecting, group.ToString() ); StringTemplate b = group.GetInstanceOf( "bold" ); b.SetAttribute( "item", "dork" ); expecting = "<b>dork</b>"; Assert.AreEqual( expecting, b.ToString() ); StringTemplate a = group.GetInstanceOf( "t" ); expecting = "literal} template"; Assert.AreEqual( expecting, a.ToString() ); } /** Check syntax and setAttribute-time errors */ [TestMethod][TestCategory(TestCategories.ST3)] public void TestTemplateParameterDecls() { string templates = "group test;" + newline + "t() ::= \"no args but ref $foo$\"" + newline + "t2(item) ::= \"decl but not used is ok\"" + newline + "t3(a,b,c,d) ::= <<$a$ $d$>>" + newline + "t4(a,b,c,d) ::= <<$a$ $b$ $c$ $d$>>" + newline ; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); // check setting unknown arg in empty formal list StringTemplate a = group.GetInstanceOf( "t" ); string error = null; try { a.SetAttribute( "foo", "x" ); // want NoSuchElementException } catch ( ArgumentException e ) { error = e.Message; } string expecting = "no such attribute: foo in template context [t]"; Assert.AreEqual( expecting, error ); // check setting known arg a = group.GetInstanceOf( "t2" ); a.SetAttribute( "item", "x" ); // shouldn't get exception // check setting unknown arg in nonempty list of formal args a = group.GetInstanceOf( "t3" ); a.SetAttribute( "b", "x" ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestTemplateRedef() { string templates = "group test;" + newline + "a() ::= \"x\"" + newline + "b() ::= \"y\"" + newline + "a() ::= \"z\"" + newline; IStringTemplateErrorListener errors = new ErrorBuffer(); StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), errors ); string expecting = "redefinition of template: a"; Assert.AreEqual( expecting, errors.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestMissingInheritedAttribute() { string templates = "group test;" + newline + "page(title,font) ::= <<" + newline + "<html>" + newline + "<body>" + newline + "$title$<br>" + newline + "$body()$" + newline + "</body>" + newline + "</html>" + newline + ">>" + newline + "body() ::= \"<font face=$font$>my body</font>\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); t.SetAttribute( "title", "my title" ); t.SetAttribute( "font", "Helvetica" ); // body() will see it t.ToString(); // should be no problem } [TestMethod][TestCategory(TestCategories.ST3)] public void TestFormalArgumentAssignment() { string templates = "group test;" + newline + "page() ::= <<$body(font=\"Times\")$>>" + newline + "body(font) ::= \"<font face=$font$>my body</font>\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); string expecting = "<font face=Times>my body</font>"; Assert.AreEqual( expecting, t.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestUndefinedArgumentAssignment() { string templates = "group test;" + newline + "page(x) ::= <<$body(font=x)$>>" + newline + "body() ::= \"<font face=$font$>my body</font>\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); t.SetAttribute( "x", "Times" ); string error = ""; try { t.ToString(); } catch ( ArgumentException iae ) { error = iae.Message; } string expecting = "template body has no such attribute: font in template context [page <invoke body arg context>]"; Assert.AreEqual( expecting, error ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestFormalArgumentAssignmentInApply() { string templates = "group test;" + newline + "page(name) ::= <<$name:bold(font=\"Times\")$>>" + newline + "bold(font) ::= \"<font face=$font$><b>$it$</b></font>\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); t.SetAttribute( "name", "Ter" ); string expecting = "<font face=Times><b>Ter</b></font>"; Assert.AreEqual( expecting, t.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestUndefinedArgumentAssignmentInApply() { string templates = "group test;" + newline + "page(name,x) ::= <<$name:bold(font=x)$>>" + newline + "bold() ::= \"<font face=$font$><b>$it$</b></font>\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); t.SetAttribute( "x", "Times" ); t.SetAttribute( "name", "Ter" ); string error = ""; try { t.ToString(); } catch ( ArgumentException iae ) { error = iae.Message; } string expecting = "template bold has no such attribute: font in template context [page <invoke bold arg context>]"; Assert.AreEqual( expecting, error ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestUndefinedAttributeReference() { string templates = "group test;" + newline + "page() ::= <<$bold()$>>" + newline + "bold() ::= \"$name$\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); string error = ""; try { t.ToString(); } catch ( ArgumentException iae ) { error = iae.Message; } string expecting = "no such attribute: name in template context [page bold]"; Assert.AreEqual( expecting, error ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestUndefinedDefaultAttributeReference() { string templates = "group test;" + newline + "page() ::= <<$bold()$>>" + newline + "bold() ::= \"$it$\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate t = group.GetInstanceOf( "page" ); string error = ""; try { t.ToString(); } catch ( ArgumentException nse ) { error = nse.Message; } string expecting = "no such attribute: it in template context [page bold]"; Assert.AreEqual( expecting, error ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestAngleBracketsWithGroupFile() { string templates = "group test;" + newline + "a(s) ::= \"<s:{case <i> : <it> break;}>\"" + newline + "b(t) ::= \"<t; separator=\\\",\\\">\"" + newline + "c(t) ::= << <t; separator=\",\"> >>" + newline; // mainly testing to ensure we don't get parse errors of above StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ) ); StringTemplate t = group.GetInstanceOf( "a" ); t.SetAttribute( "s", "Test" ); string expecting = "case 1 : Test break;"; Assert.AreEqual( expecting, t.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestAngleBracketsNoGroup() { StringTemplate st = new StringTemplate( "Tokens : <rules; separator=\"|\"> ;", typeof( AngleBracketTemplateLexer ) ); st.SetAttribute( "rules", "A" ); st.SetAttribute( "rules", "B" ); string expecting = "Tokens : A|B ;"; Assert.AreEqual( expecting, st.ToString() ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestRegionRef() { string templates = "group test;" + newline + "a() ::= \"X$@r()$Y\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate st = group.GetInstanceOf( "a" ); string result = st.ToString(); string expecting = "XY"; Assert.AreEqual( expecting, result ); } [TestMethod][TestCategory(TestCategories.ST3)] public void TestEmbeddedRegionRef() { string templates = "group test;" + newline + "a() ::= \"X$@r$blort$@end$Y\"" + newline; StringTemplateGroup group = new StringTemplateGroup( new StringReader( templates ), typeof( DefaultTemplateLexer ) ); StringTemplate st = group.GetInstanceOf( "a" ); string result = st.ToString(); string expecting = "XblortY";
antlr/antlrcs
7fbc152749f2ddaa5316cac35b75589534e343eb
Run Antlr3.Test tests on Travis
diff --git a/.travis.yml b/.travis.yml index 0250460..9d7f00a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: csharp dist: trusty mono: none dotnet: 2.0.0 script: + - dotnet test Antlr3.Test -f netcoreapp2.0 --filter TestCategory!=SkipOnCI - dotnet test Antlr4.Test.StringTemplate -f netcoreapp2.0
antlr/antlrcs
512859f801ba542f9c494c0ecbec1a7e99966065
Add a netstandard2.0 build of Antlr3.StringTemplate
diff --git a/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj b/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj index 07586d1..dec48ef 100644 --- a/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj +++ b/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj @@ -1,78 +1,87 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>net35-client</TargetFrameworks> + <TargetFrameworks>net35-client;netstandard2.0</TargetFrameworks> <RootNamespace>Antlr.ST</RootNamespace> <Description>The C# port of StringTemplate 3.</Description> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <Title>StringTemplate 3</Title> <PackageId>StringTemplate3</PackageId> <PackageTags>stringtemplate st3 stringtemplate3 template</PackageTags> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> </PropertyGroup> <ItemGroup> <PackageReference Include="MSBuild.Sdk.Extras" Version="1.2.1" PrivateAssets="All" /> </ItemGroup> <Target Name="DisableCrazyPackageDeletion" BeforeTargets="Clean"> <PropertyGroup> <GeneratePackageValue>$(GeneratePackageOnBuild)</GeneratePackageValue> <GeneratePackageOnBuild>false</GeneratePackageOnBuild> </PropertyGroup> </Target> <Target Name="EnablePackageGeneration" Condition="'$(GeneratePackageValue)' != ''" BeforeTargets="Build"> <PropertyGroup> <GeneratePackageOnBuild>$(GeneratePackageValue)</GeneratePackageOnBuild> </PropertyGroup> </Target> + <Choose> + <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> + <ItemGroup> + <PackageReference Include="System.Reflection.Emit.ILGeneration" Version="4.3.0" /> + <PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" /> + </ItemGroup> + </When> + </Choose> + <PropertyGroup> <DefineConstants>$(DefineConstants);COMPILE_EXPRESSIONS;CACHE_FUNCTORS</DefineConstants> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> <ItemGroup> <Compile Update="Language\AngleBracketTemplateLexerHelper.cs"> <DependentUpon>AngleBracketTemplateLexer.g3</DependentUpon> </Compile> <Compile Update="Language\TemplateLexerHelper.cs"> <DependentUpon>Template.g3</DependentUpon> </Compile> <Compile Update="Language\TemplateParserHelper.cs"> <DependentUpon>Template.g3</DependentUpon> </Compile> <Compile Update="Language\InterfaceLexerHelper.cs"> <DependentUpon>Interface.g3</DependentUpon> </Compile> <Compile Update="Language\InterfaceParserHelper.cs"> <DependentUpon>Interface.g3</DependentUpon> </Compile> <Compile Update="Language\GroupLexerHelper.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Language\GroupParserHelper.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Language\ActionLexerHelper.cs"> <DependentUpon>Action.g3</DependentUpon> </Compile> <Compile Update="Language\ActionParserHelper.cs"> <DependentUpon>Action.g3</DependentUpon> </Compile> <Compile Update="Language\ActionEvaluatorHelper.cs"> <DependentUpon>ActionEvaluator.g3</DependentUpon> </Compile> </ItemGroup> <Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" /> </Project> \ No newline at end of file diff --git a/Antlr3.StringTemplate/Language/ASTExpr.cs b/Antlr3.StringTemplate/Language/ASTExpr.cs index 4fbaaea..93c5201 100644 --- a/Antlr3.StringTemplate/Language/ASTExpr.cs +++ b/Antlr3.StringTemplate/Language/ASTExpr.cs @@ -1,721 +1,723 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr3.ST.Language { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Antlr.Runtime.JavaExtensions; using FieldInfo = System.Reflection.FieldInfo; using ICollection = System.Collections.ICollection; using IDictionary = System.Collections.IDictionary; using IEnumerable = System.Collections.IEnumerable; using IEnumerator = System.Collections.IEnumerator; using IList = System.Collections.IList; using InvalidOperationException = System.InvalidOperationException; using IOException = System.IO.IOException; using ITree = Antlr.Runtime.Tree.ITree; using MethodInfo = System.Reflection.MethodInfo; using PropertyInfo = System.Reflection.PropertyInfo; using RecognitionException = Antlr.Runtime.RecognitionException; using StringWriter = System.IO.StringWriter; #if COMPILE_EXPRESSIONS using DynamicMethod = System.Reflection.Emit.DynamicMethod; using OpCodes = System.Reflection.Emit.OpCodes; using ParameterAttributes = System.Reflection.ParameterAttributes; #endif /** <summary> * A single string template expression enclosed in $...; separator=...$ * parsed into an AST chunk to be evaluated. * </summary> */ public class ASTExpr : Expr { // writing -1 char means missing, not empty public const int Missing = -1; public const string DefaultAttributeName = "it"; public const string DefaultAttributeNameDeprecated = "attr"; public const string DefaultIndexVariableName = "i"; public const string DefaultIndex0VariableName = "i0"; public const string DefaultMapValueName = "_default_"; public const string DefaultMapKeyName = "key"; /** <summary>Used to indicate "default:key" in maps within groups</summary> */ public static readonly StringTemplate MapKeyValue = new StringTemplate(); /** <summary> * Using an expr option w/o value, makes options table hold EMPTY_OPTION * value for that key. * </summary> */ public const string EmptyOption = "empty expr option"; static readonly IDictionary<string, StringTemplateAST> _defaultOptionValues = new Dictionary<string, StringTemplateAST>() { { "anchor", new StringTemplateAST( ActionEvaluator.STRING, "true" ) }, { "wrap", new StringTemplateAST( ActionEvaluator.STRING, Environment.NewLine ) }, }; /** <summary>John Snyders gave me an example implementation for this checking</summary> */ static readonly HashSet<string> _supportedOptions = new HashSet<string>() { "anchor", "format", "null", "separator", "wrap" }; static readonly Dictionary<Type, Dictionary<string, Func<object, object>>> _memberAccessors = new Dictionary<Type, Dictionary<string, Func<object, object>>>(); private readonly ITree _exprTree; /** <summary>store separator etc...</summary> */ IDictionary<string, object> _options; /** <summary> * A cached value of wrap=expr from the &lt;...> expression. * Computed in write(StringTemplate, StringTemplateWriter) and used * in writeAttribute. * </summary> */ string _wrapString; /** <summary> * For null values in iterated attributes and single attributes that * are null, use this value instead of skipping. For single valued * attributes like &lt;name; null="n/a"> it's a shorthand for * &lt;if(name)>&lt;name>&lt;else>n/a&lt;endif> * For iterated values &lt;values; null="0", separator=",">, you get 0 for * for null list values. Works for template application like: * &lt;values:{v| &lt;v>}; null="0"> also. * </summary> */ string _nullValue; /** <summary> * A cached value of separator=expr from the &lt;...> expression. * Computed in write(StringTemplate, StringTemplateWriter) and used * in writeAttribute. * </summary> */ string _separatorString; /** <summary>A cached value of option format=expr</summary> */ string _formatString; #if COMPILE_EXPRESSIONS public class HoldsActionFuncAndChunk { public System.Func<ASTExpr, StringTemplate, IStringTemplateWriter, int> func; public ASTExpr chunk; internal int Evaluate(StringTemplate template, IStringTemplateWriter writer) { return func(chunk, template, writer); } } public static bool EnableDynamicMethods = false; public static bool EnableFunctionalMethods = true; static int _evaluatorNumber = 0; #if CACHE_FUNCTORS static Dictionary<ITree, DynamicMethod> _methods = new Dictionary<ITree, DynamicMethod>(); #endif System.Func<StringTemplate, IStringTemplateWriter, int> EvaluateAction; #endif public ASTExpr( StringTemplate enclosingTemplate, ITree exprTree, IDictionary<string, object> options ) : base( enclosingTemplate ) { this._exprTree = exprTree; this._options = options; } #region Properties /** <summary>Return the tree interpreted when this template is written out.</summary> */ public ITree AST { get { return _exprTree; } } #endregion public static int EvaluatorCacheHits { get; private set; } public static int EvaluatorCacheMisses { get; private set; } #if COMPILE_EXPRESSIONS private static System.Func<StringTemplate, IStringTemplateWriter, int> GetEvaluator( ASTExpr chunk, ITree condition ) { if ( EnableDynamicMethods ) { try { DynamicMethod method = null; #if CACHE_FUNCTORS if ( !_methods.TryGetValue( condition, out method ) ) #endif { Type[] parameterTypes = { typeof( ASTExpr ), typeof( StringTemplate ), typeof( IStringTemplateWriter ) }; method = new DynamicMethod( "ActionEvaluator" + _evaluatorNumber, typeof( int ), parameterTypes, typeof( ConditionalExpr ), true ); +#if !NETSTANDARD2_0 method.DefineParameter( 1, ParameterAttributes.None, "chunk" ); method.DefineParameter( 2, ParameterAttributes.None, "self" ); method.DefineParameter( 3, ParameterAttributes.None, "writer" ); +#endif _evaluatorNumber++; var gen = method.GetILGenerator(); ActionEvaluator evalCompiled = new ActionEvaluator( null, chunk, null, condition ); evalCompiled.actionCompiled( gen ); gen.Emit( OpCodes.Ret ); #if CACHE_FUNCTORS _methods[condition] = method; #endif } var dynamicEvaluator = (System.Func<StringTemplate, IStringTemplateWriter, int>)method.CreateDelegate( typeof( System.Func<StringTemplate, IStringTemplateWriter, int> ), chunk ); return dynamicEvaluator; } catch { // fall back to functional (or interpreted) version } } if ( EnableFunctionalMethods ) { try { ActionEvaluator evalFunctional = new ActionEvaluator( null, chunk, null, condition ); var functionalEvaluator = evalFunctional.actionFunctional(); HoldsActionFuncAndChunk holder = new HoldsActionFuncAndChunk() { func = functionalEvaluator, chunk = chunk }; return holder.Evaluate; } catch { // fall back to interpreted version } } return ( self, writer ) => { ActionEvaluator eval = new ActionEvaluator( self, chunk, writer, condition ); return eval.action(); }; } #endif /** <summary> * To write out the value of an ASTExpr, invoke the evaluator in eval.g * to walk the tree writing out the values. For efficiency, don't * compute a bunch of strings and then pack them together. Write out directly. * </summary> * * <remarks> * Compute separator and wrap expressions, save as strings so we don't * recompute for each value in a multi-valued attribute or expression. * * If they set anchor option, then inform the writer to push current * char position. * </remarks> */ public override int Write( StringTemplate self, IStringTemplateWriter @out ) { if ( _exprTree == null || self == null || @out == null ) { return 0; } // handle options, anchor, wrap, separator... StringTemplateAST anchorAST = (StringTemplateAST)GetOption( "anchor" ); if ( anchorAST != null ) { // any non-empty expr means true; check presence @out.PushAnchorPoint(); } @out.PushIndentation( Indentation ); HandleExprOptions( self ); //System.out.println("evaluating tree: "+exprTree.toStringList()); ActionEvaluator eval = null; #if COMPILE_EXPRESSIONS bool compile = self.Group != null && self.Group.EnableCompiledExpressions; bool cache = compile && self.Group.EnableCachedExpressions; System.Func<StringTemplate, IStringTemplateWriter, int> evaluator = EvaluateAction; if (compile) { if (!cache || EvaluateAction == null) { // caching won't help here because AST is read only EvaluatorCacheMisses++; evaluator = GetEvaluator(this, AST); if (cache) EvaluateAction = evaluator; } else { EvaluatorCacheHits++; } } else #endif { eval = new ActionEvaluator(self, this, @out, _exprTree); } int n = 0; try { // eval and write out tree #if COMPILE_EXPRESSIONS if (compile) { n = evaluator(self, @out); } else #endif { n = eval.action(); } } catch ( RecognitionException re ) { self.Error( "can't evaluate tree: " + _exprTree.ToStringTree(), re ); } @out.PopIndentation(); if ( anchorAST != null ) { @out.PopAnchorPoint(); } return n; } /** <summary>Grab and cache options; verify options are valid</summary> */ protected virtual void HandleExprOptions( StringTemplate self ) { // make sure options don't use format / renderer. They are usually // strings which might invoke a string renderer etc... _formatString = null; StringTemplateAST wrapAST = (StringTemplateAST)GetOption( "wrap" ); if ( wrapAST != null ) { _wrapString = EvaluateExpression( self, wrapAST ); } StringTemplateAST nullValueAST = (StringTemplateAST)GetOption( "null" ); if ( nullValueAST != null ) { _nullValue = EvaluateExpression( self, nullValueAST ); } StringTemplateAST separatorAST = (StringTemplateAST)GetOption( "separator" ); if ( separatorAST != null ) { _separatorString = EvaluateExpression( self, separatorAST ); } // following addition inspired by John Snyders StringTemplateAST formatAST = (StringTemplateAST)GetOption( "format" ); if ( formatAST != null ) { _formatString = EvaluateExpression( self, formatAST ); } // Check that option is valid if ( _options != null ) { foreach ( string option in _options.Keys ) { if ( !_supportedOptions.Contains( option ) ) self.Warning( "ignoring unsupported option: " + option ); } } } #region Help routines called by the tree walker /** <summary> * For &lt;names,phones:{n,p | ...}> treat the names, phones as lists * to be walked in lock step as n=names[i], p=phones[i]. * </summary> */ public virtual object ApplyTemplateToListOfAttributes( StringTemplate self, IList attributes, StringTemplate templateToApply ) { if ( attributes == null || templateToApply == null || attributes.Count == 0 ) { return null; // do not apply if missing templates or empty values } Dictionary<string, object> argumentContext = null; // indicate it's an ST-created list var results = new StringTemplate.STAttributeList(); // convert all attributes to iterators even if just one value for ( int a = 0; a < attributes.Count; a++ ) { object o = attributes[a]; if ( o != null ) { o = ConvertAnythingToIterator( o ); attributes[a] = o; // alter the list in place } } int numAttributes = attributes.Count; // ensure arguments line up var formalArguments = templateToApply.FormalArguments; if ( formalArguments == null || formalArguments.Count == 0 ) { self.Error( "missing arguments in anonymous" + " template in context " + self.GetEnclosingInstanceStackString() ); return null; } string[] formalArgumentNames = formalArguments.Select( fa => fa.name ).ToArray(); if ( formalArgumentNames.Length != numAttributes ) { string formalArgumentsText = formalArguments.Select( fa => fa.name ).ToList().ToElementString(); self.Error( "number of arguments " + formalArgumentsText + " mismatch between attribute list and anonymous" + " template in context " + self.GetEnclosingInstanceStackString() ); // truncate arg list to match smaller size int shorterSize = Math.Min( formalArgumentNames.Length, numAttributes ); numAttributes = shorterSize; string[] newFormalArgumentNames = new string[shorterSize]; Array.Copy( formalArgumentNames, 0, newFormalArgumentNames, 0, shorterSize ); formalArgumentNames = newFormalArgumentNames; } // keep walking while at least one attribute has values int i = 0; // iteration number from 0 for ( ; ; ) { argumentContext = new Dictionary<string, object>(); // get a value for each attribute in list; put into arg context // to simulate template invocation of anonymous template int numEmpty = 0; for ( int a = 0; a < numAttributes; a++ ) { IEnumerator it = attributes[a] as IEnumerator; if ( it != null && it.MoveNext() ) { string argName = formalArgumentNames[a]; object iteratedValue = it.Current; argumentContext[argName] = iteratedValue; } else { numEmpty++; } } if ( numEmpty == numAttributes ) { break; } argumentContext[DefaultIndexVariableName] = i + 1; argumentContext[DefaultIndex0VariableName] = i; StringTemplate embedded = templateToApply.GetInstanceOf(); embedded.EnclosingInstance = self; embedded.ArgumentContext = argumentContext; results.Add( embedded ); i++; } return results; } public virtual object ApplyListOfAlternatingTemplates( StringTemplate self, object attributeValue, IList<StringTemplate> templatesToApply ) { if ( attributeValue == null || templatesToApply == null || templatesToApply.Count == 0 ) { return null; // do not apply if missing templates or empty value } StringTemplate embedded = null; Dictionary<string, object> argumentContext = null; // normalize collections and such to use iterators // anything iteratable can be used for "APPLY" attributeValue = ConvertArrayToList( attributeValue ); attributeValue = ConvertAnythingIteratableToIterator( attributeValue ); IEnumerator iter = attributeValue as IEnumerator; if ( iter != null ) { // results can be treated list an attribute, indicate ST created list var resultVector = new StringTemplate.STAttributeList(); int i = 0; while ( iter.MoveNext() ) { object ithValue = iter.Current; if ( ithValue == null ) { if ( _nullValue == null ) { continue; } ithValue = _nullValue; } int templateIndex = i % templatesToApply.Count; // rotate through embedded = templatesToApply[templateIndex]; // template to apply is an actual StringTemplate (created in // eval.g), but that is used as the examplar. We must create // a new instance of the embedded template to apply each time // to get new attribute sets etc... StringTemplateAST args = embedded.ArgumentsAST; embedded = embedded.GetInstanceOf(); // make new instance embedded.EnclosingInstance = self; embedded.ArgumentsAST = args; argumentContext = new Dictionary<string, object>(); var formalArgs = embedded.FormalArguments; bool isAnonymous = embedded.Name == StringTemplate.ANONYMOUS_ST_NAME; SetSoleFormalArgumentToIthValue( embedded, argumentContext, ithValue ); // if it's an anonymous template with a formal arg, don't set it/attr if ( !( isAnonymous && formalArgs != null && formalArgs.Count > 0 ) ) { argumentContext[DefaultAttributeName] = ithValue; argumentContext[DefaultAttributeNameDeprecated] = ithValue; } argumentContext[DefaultIndexVariableName] = i + 1; argumentContext[DefaultIndex0VariableName] = i; embedded.ArgumentContext = argumentContext; EvaluateArguments( embedded ); /* System.err.println("i="+i+": applyTemplate("+embedded.getName()+ ", args="+argumentContext+ " to attribute value "+ithValue); */ resultVector.Add( embedded ); i++; } if ( resultVector.Count == 0 ) { resultVector = null; } return resultVector; } else { /* System.out.println("setting attribute "+DEFAULT_ATTRIBUTE_NAME+" in arg context of "+ embedded.getName()+ " to "+attributeValue); */ embedded = templatesToApply[0]; argumentContext = new Dictionary<string, object>(); var formalArgs = embedded.FormalArguments; StringTemplateAST args = embedded.ArgumentsAST; SetSoleFormalArgumentToIthValue( embedded, argumentContext, attributeValue ); bool isAnonymous = embedded.Name == StringTemplate.ANONYMOUS_ST_NAME; // if it's an anonymous template with a formal arg, don't set it/attr if ( !( isAnonymous && formalArgs != null && formalArgs.Count > 0 ) ) { argumentContext[DefaultAttributeName] = attributeValue; argumentContext[DefaultAttributeNameDeprecated] = attributeValue; } argumentContext[DefaultIndexVariableName] = 1; argumentContext[DefaultIndex0VariableName] = 0; embedded.ArgumentContext = argumentContext; EvaluateArguments( embedded ); return embedded; } } protected virtual void SetSoleFormalArgumentToIthValue( StringTemplate embedded, IDictionary argumentContext, object ithValue ) { var formalArgs = embedded.FormalArguments; if ( formalArgs != null ) { string soleArgName = null; bool isAnonymous = embedded.Name == StringTemplate.ANONYMOUS_ST_NAME; if ( formalArgs.Count == 1 || ( isAnonymous && formalArgs.Count > 0 ) ) { if ( isAnonymous && formalArgs.Count > 1 ) { embedded.Error( "too many arguments on {...} template: " + formalArgs ); } // if exactly 1 arg or anonymous, give that the value of // "it" as a convenience like they said // $list:template(arg=it)$ var argNames = formalArgs.Select( fa => fa.name ); soleArgName = argNames.ToArray()[0]; argumentContext[soleArgName] = ithValue; } } } /** <summary>Return o.getPropertyName() given o and propertyName. If o is * a stringtemplate then access it's attributes looking for propertyName * instead (don't check any of the enclosing scopes; look directly into * that object). Also try isXXX() for booleans. Allow Map * as special case (grab value for key). * </summary> * * <remarks> * Cache repeated requests for obj.prop within same group. * </remarks> */ public virtual object GetObjectProperty( StringTemplate self, object o, object propertyName ) { if ( o == null ) return null; ITypeProxyFactory proxyFactory = self.Group.GetTypeProxyFactory(o.GetType()); if (proxyFactory != null) o = proxyFactory.CreateProxy(o); if ( propertyName == null ) { IDictionary dictionary = o as IDictionary; if ( dictionary != null && dictionary.Contains( DefaultMapValueName ) ) propertyName = DefaultMapValueName; else return null; } /* // see if property is cached in group's cache Object cachedValue = self.getGroup().getCachedObjectProperty(o,propertyName); if ( cachedValue!=null ) { return cachedValue; } Object value = rawGetObjectProperty(self, o, propertyName); // take care of array properties...convert to a List so we can // apply templates to the elements etc... value = convertArrayToList(value); self.getGroup().cacheObjectProperty(o,propertyName,value); */ object value = RawGetObjectProperty( self, o, propertyName ); // take care of array properties...convert to a List so we can // apply templates to the elements etc... value = ConvertArrayToList( value ); return value; } private static Func<object, object> FindMember( Type type, string name ) { if (type == null) throw new ArgumentNullException("type"); if (name == null) throw new ArgumentNullException("name"); lock ( _memberAccessors ) { Dictionary<string, Func<object, object>> members; Func<object, object> accessor = null; if ( _memberAccessors.TryGetValue( type, out members ) ) { if ( members.TryGetValue( name, out accessor ) ) return accessor; } else { members = new Dictionary<string, Func<object, object>>(); _memberAccessors[type] = members; } // must look up using reflection string methodSuffix = char.ToUpperInvariant( name[0] ) + name.Substring( 1 ); MethodInfo method = null; if ( method == null ) { System.Reflection.PropertyInfo p = type.GetProperty( methodSuffix ); if ( p != null ) method = p.GetGetMethod(); } if ( method == null ) { method = type.GetMethod("Get" + methodSuffix, Type.EmptyTypes); } if ( method == null ) { method = type.GetMethod("Is" + methodSuffix, Type.EmptyTypes); } if ( method != null ) { accessor = BuildAccessor( method ); } else { // try for an indexer method = type.GetMethod("get_Item", new Type[] { typeof(string) }); if (method == null) { var property = type.GetProperties().FirstOrDefault(IsIndexer); if (property != null) method = property.GetGetMethod(); } if (method != null) { accessor = BuildAccessor(method, name); } else { // try for a visible field FieldInfo field = type.GetField(name); // also check .NET naming convention for fields if (field == null) field = type.GetField("_" + name); if (field != null) accessor = BuildAccessor(field); } } diff --git a/Antlr3.StringTemplate/Language/ConditionalExpr.cs b/Antlr3.StringTemplate/Language/ConditionalExpr.cs index a9bf90d..57317d7 100644 --- a/Antlr3.StringTemplate/Language/ConditionalExpr.cs +++ b/Antlr3.StringTemplate/Language/ConditionalExpr.cs @@ -1,287 +1,289 @@ /* * [The "BSD licence"] * Copyright (c) 2003-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr3.ST.Language { using System.Collections.Generic; using Antlr.Runtime.JavaExtensions; using ITree = Antlr.Runtime.Tree.ITree; using RecognitionException = Antlr.Runtime.RecognitionException; #if COMPILE_EXPRESSIONS using DynamicMethod = System.Reflection.Emit.DynamicMethod; using OpCodes = System.Reflection.Emit.OpCodes; using ParameterAttributes = System.Reflection.ParameterAttributes; using Type = System.Type; #endif /** <summary>A conditional reference to an embedded subtemplate.</summary> */ public class ConditionalExpr : ASTExpr { #if COMPILE_EXPRESSIONS System.Func<StringTemplate, IStringTemplateWriter, bool> EvaluateCondition; #endif StringTemplate _subtemplate; List<ElseIfClauseData> _elseIfSubtemplates; StringTemplate _elseSubtemplate; protected class ElseIfClauseData { #if COMPILE_EXPRESSIONS public System.Func<StringTemplate, IStringTemplateWriter, bool> EvaluateCondition; #endif public ASTExpr expr; public StringTemplate st; } public ConditionalExpr( StringTemplate enclosingTemplate, ITree tree ) : base( enclosingTemplate, tree, null ) { } public StringTemplate Subtemplate { get { return _subtemplate; } set { _subtemplate = value; } } public StringTemplate ElseSubtemplate { get { return _elseSubtemplate; } set { _elseSubtemplate = value; } } #if COMPILE_EXPRESSIONS public class HoldsConditionFuncAndChunk { public System.Func<ASTExpr, StringTemplate, IStringTemplateWriter, bool> func; public ASTExpr chunk; } public static bool CallFunctionalConditionEvaluator( HoldsConditionFuncAndChunk data, StringTemplate self, IStringTemplateWriter writer ) { return data.func( data.chunk, self, writer ); } static int _evaluatorNumber = 0; #if CACHE_FUNCTORS static Dictionary<ITree, DynamicMethod> _methods = new Dictionary<ITree, DynamicMethod>(); #endif static System.Func<StringTemplate, IStringTemplateWriter, bool> GetEvaluator( ASTExpr chunk, ITree condition ) { if ( EnableDynamicMethods ) { try { DynamicMethod method = null; #if CACHE_FUNCTORS if ( !_methods.TryGetValue( condition, out method ) ) #endif { Type[] parameterTypes = { typeof( ASTExpr ), typeof( StringTemplate ), typeof( IStringTemplateWriter ) }; method = new DynamicMethod( "ConditionEvaluator" + _evaluatorNumber, typeof( bool ), parameterTypes, typeof( ConditionalExpr ), true ); +#if !NETSTANDARD2_0 method.DefineParameter( 1, ParameterAttributes.None, "chunk" ); method.DefineParameter( 2, ParameterAttributes.None, "self" ); method.DefineParameter( 3, ParameterAttributes.None, "writer" ); +#endif _evaluatorNumber++; var gen = method.GetILGenerator(); ActionEvaluator evalCompiled = new ActionEvaluator( null, chunk, null, condition ); evalCompiled.ifConditionCompiled( gen ); gen.Emit( OpCodes.Ret ); #if CACHE_FUNCTORS _methods[condition] = method; #endif } var dynamicEvaluator = (System.Func<StringTemplate, IStringTemplateWriter, bool>)method.CreateDelegate( typeof( System.Func<StringTemplate, IStringTemplateWriter, bool> ), chunk ); return dynamicEvaluator; } catch { // fall back to functional (or interpreted) version } } if ( EnableFunctionalMethods ) { try { ActionEvaluator evalFunctional = new ActionEvaluator( null, chunk, null, condition ); var functionalEvaluator = evalFunctional.ifConditionFunctional(); HoldsConditionFuncAndChunk holder = new HoldsConditionFuncAndChunk() { func = functionalEvaluator, chunk = chunk }; return (System.Func<StringTemplate, IStringTemplateWriter, bool>)System.Delegate.CreateDelegate( typeof( System.Func<StringTemplate, IStringTemplateWriter, bool> ), holder, typeof( ConditionalExpr ).GetMethod( "CallFunctionalConditionEvaluator" ) ); } catch { // fall back to interpreted version } } return new System.Func<StringTemplate, IStringTemplateWriter, bool>( ( self, @out ) => { ActionEvaluator eval = new ActionEvaluator( self, chunk, @out, condition ); return eval.ifCondition(); } ); } #endif public virtual void AddElseIfSubtemplate( ASTExpr conditionalTree, StringTemplate subtemplate ) { if ( _elseIfSubtemplates == null ) { _elseIfSubtemplates = new List<ElseIfClauseData>(); } ElseIfClauseData d = new ElseIfClauseData() { expr = conditionalTree, st = subtemplate }; _elseIfSubtemplates.Add( d ); } /** <summary> * To write out the value of a condition expr, invoke the evaluator in eval.g * to walk the condition tree computing the boolean value. If result * is true, then write subtemplate. * </summary> */ public override int Write( StringTemplate self, IStringTemplateWriter @out ) { if ( AST == null || self == null || @out == null ) { return 0; } //System.Console.Out.WriteLine( "evaluating conditional tree: " + AST.ToStringTree() ); #if !COMPILE_EXPRESSIONS ActionEvaluator eval = null; #endif int n = 0; try { bool testedTrue = false; // get conditional from tree and compute result #if COMPILE_EXPRESSIONS if ( EvaluateCondition == null ) EvaluateCondition = GetEvaluator( this, AST.GetChild( 0 ) ); bool includeSubtemplate = EvaluateCondition( self, @out ); // eval and write out tree #else ITree cond = AST.GetChild( 0 ); eval = new ActionEvaluator( self, this, @out, cond ); // eval and write out trees bool includeSubtemplate = eval.ifCondition(); #endif //System.Console.Out.WriteLine( "subtemplate " + _subtemplate ); // IF if ( includeSubtemplate ) { n = WriteSubTemplate( self, @out, _subtemplate ); testedTrue = true; } // ELSEIF else if ( _elseIfSubtemplates != null && _elseIfSubtemplates.Count > 0 ) { for ( int i = 0; i < _elseIfSubtemplates.Count; i++ ) { ElseIfClauseData elseIfClause = _elseIfSubtemplates[i]; #if COMPILE_EXPRESSIONS if ( elseIfClause.EvaluateCondition == null ) elseIfClause.EvaluateCondition = GetEvaluator( this, elseIfClause.expr.AST ); includeSubtemplate = elseIfClause.EvaluateCondition( self, @out ); #else eval = new ActionEvaluator( self, this, @out, elseIfClause.expr.AST ); includeSubtemplate = eval.ifCondition(); #endif if ( includeSubtemplate ) { WriteSubTemplate( self, @out, elseIfClause.st ); testedTrue = true; break; } } } // ELSE if ( !testedTrue && _elseSubtemplate != null ) { // evaluate ELSE clause if present and IF condition failed StringTemplate s = _elseSubtemplate.GetInstanceOf(); s.EnclosingInstance = self; s.Group = self.Group; s.NativeGroup = self.NativeGroup; n = s.Write( @out ); } // cond==false and no else => Missing output not empty if (!testedTrue && _elseSubtemplate == null) n = Missing; } catch ( RecognitionException re ) { self.Error( "can't evaluate tree: " + AST.ToStringTree(), re ); } return n; } protected virtual int WriteSubTemplate( StringTemplate self, IStringTemplateWriter @out, StringTemplate subtemplate ) { /* To evaluate the IF chunk, make a new instance whose enclosingInstance * points at 'self' so get attribute works. Otherwise, enclosingInstance * points at the template used to make the precompiled code. We need a * new template instance every time we exec this chunk to get the new * "enclosing instance" pointer. */ StringTemplate s = subtemplate.GetInstanceOf(); s.EnclosingInstance = self; // make sure we evaluate in context of enclosing template's // group so polymorphism works. :) s.Group = self.Group; s.NativeGroup = self.NativeGroup; return s.Write( @out ); } } } diff --git a/Antlr3.Test/Antlr3.Test.csproj b/Antlr3.Test/Antlr3.Test.csproj index 850b99c..940b097 100644 --- a/Antlr3.Test/Antlr3.Test.csproj +++ b/Antlr3.Test/Antlr3.Test.csproj @@ -1,51 +1,55 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>net45</TargetFrameworks> + <TargetFrameworks>net45;netcoreapp2.0</TargetFrameworks> <RootNamespace>AntlrUnitTests</RootNamespace> <AssemblyName>AntlrUnitTests</AssemblyName> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> </PropertyGroup> + <ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.0'"> + <PackageReference Include="Microsoft.Win32.Registry" Version="4.3.0" /> + </ItemGroup> + <ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" /> <PackageReference Include="MSTest.TestAdapter" Version="1.1.18" /> <PackageReference Include="MSTest.TestFramework" Version="1.1.18" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="body.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="method.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="page.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="row.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="users_list.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> <ProjectReference Include="..\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj" /> <ProjectReference Include="..\Antlr3\Antlr3.csproj" /> <ProjectReference Include="..\Antlr4.StringTemplate\Antlr4.StringTemplate.csproj" /> <ProjectReference Include="..\Antlr3.Targets\Antlr3.Targets.Java\Antlr3.Targets.Java.csproj" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Antlr3.Test/BaseTest.cs b/Antlr3.Test/BaseTest.cs index 9579770..ca9efc1 100644 --- a/Antlr3.Test/BaseTest.cs +++ b/Antlr3.Test/BaseTest.cs @@ -1,626 +1,631 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using System; using System.Collections.Generic; using System.Linq; using Antlr.Runtime; using Antlr.Runtime.JavaExtensions; using Antlr3.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using BindingFlags = System.Reflection.BindingFlags; using CultureInfo = System.Globalization.CultureInfo; using Debugger = System.Diagnostics.Debugger; using Directory = System.IO.Directory; using ErrorManager = Antlr3.Tool.ErrorManager; using FieldInfo = System.Reflection.FieldInfo; using GrammarSemanticsMessage = Antlr3.Tool.GrammarSemanticsMessage; using IANTLRErrorListener = Antlr3.Tool.IANTLRErrorListener; using IList = System.Collections.IList; using IOException = System.IO.IOException; using Label = Antlr3.Analysis.Label; using Message = Antlr3.Tool.Message; using Path = System.IO.Path; using Registry = Microsoft.Win32.Registry; using RegistryKey = Microsoft.Win32.RegistryKey; using RegistryValueOptions = Microsoft.Win32.RegistryValueOptions; using StringBuilder = System.Text.StringBuilder; using StringTemplate = Antlr4.StringTemplate.Template; using StringTemplateGroup = Antlr4.StringTemplate.TemplateGroup; [TestClass] [DeploymentItem(@"Codegen\", "Codegen")] [DeploymentItem(@"Antlr3.Targets.Java.dll", "Targets")] [DeploymentItem(@"Antlr3.Targets.Java.pdb", "Targets")] [DeploymentItem(@"Tool\", "Tool")] public abstract class BaseTest { public readonly string jikes = null; public static readonly string pathSep = System.IO.Path.PathSeparator.ToString(); public readonly string RuntimeJar = Path.Combine( Environment.CurrentDirectory, @"..\..\antlr-runtime-3.3.jar" ); public readonly string Runtime2Jar = Path.Combine( Environment.CurrentDirectory, @"..\..\antlr-2.7.7.jar" ); public readonly string StringTemplateJar = Path.Combine( Environment.CurrentDirectory, @"..\..\stringtemplate-3.2.1.jar" ); private static string javaHome; public string tmpdir; public TestContext TestContext { get; set; } /** If error during parser execution, store stderr here; can't return * stdout and stderr. This doesn't trap errors from running antlr. */ protected string stderrDuringParse; public static readonly string NewLine = Environment.NewLine; [ClassInitialize] public void ClassSetUp( TestContext testContext ) { TestContext = testContext; } public static long currentTimeMillis() { return DateTime.Now.ToFileTime() / 10000; } [TestInitialize] public void setUp() { #if DEBUG string configuration = "Debug"; #else string configuration = "Release"; #endif System.IO.DirectoryInfo currentAssemblyDirectory = new System.IO.FileInfo(typeof(BaseTest).Assembly.Location).Directory; + +#if NET45 AntlrTool.ToolPathRoot = Path.Combine(currentAssemblyDirectory.Parent.Parent.Parent.FullName, "bin", configuration, "net40-client"); +#else + AntlrTool.ToolPathRoot = Path.Combine(currentAssemblyDirectory.Parent.Parent.Parent.FullName, "bin", configuration, "netstandard2.0"); +#endif // new output dir for each test tmpdir = Path.GetFullPath( Path.Combine( Path.GetTempPath(), "antlr-" + currentTimeMillis() ) ); ErrorManager.SetLocale(CultureInfo.GetCultureInfo("en-us")); ErrorManager.SetFormat("antlr"); ErrorManager.ResetErrorState(); StringTemplateGroup.DefaultGroup = new StringTemplateGroup(); // verify token constants in StringTemplate VerifyImportedTokens( typeof( Antlr3.ST.Language.ActionParser ), typeof( Antlr3.ST.Language.ActionLexer ) ); VerifyImportedTokens( typeof( Antlr3.ST.Language.ActionParser ), typeof( Antlr3.ST.Language.ActionEvaluator ) ); VerifyImportedTokens( typeof( Antlr3.ST.Language.TemplateParser ), typeof( Antlr3.ST.Language.TemplateLexer ) ); VerifyImportedTokens( typeof( Antlr3.ST.Language.TemplateParser ), typeof( Antlr3.ST.Language.AngleBracketTemplateLexer ) ); // verify token constants in the ANTLR Tool VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.ANTLRLexer ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.ANTLRTreePrinter ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.AssignTokenTypesWalker ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.CodeGenTreeWalker ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.DefineGrammarItemsWalker ) ); VerifyImportedTokens( typeof( Antlr3.Grammars.ANTLRParser ), typeof( Antlr3.Grammars.TreeToNFAConverter ) ); } [TestCleanup] public void tearDown() { // remove tmpdir if no error. how? if ( TestContext != null && TestContext.CurrentTestOutcome == UnitTestOutcome.Passed ) eraseTempDir(); } private void VerifyImportedTokens( Type source, Type target ) { FieldInfo namesField = source.GetField( "tokenNames", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public ); FieldInfo targetNamesField = target.GetField( "tokenNames", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public ); Assert.IsNotNull( namesField, string.Format( "No tokenNames field was found in grammar {0}.", source.Name ) ); string[] sourceNames = namesField.GetValue( null ) as string[]; string[] targetNames = ( targetNamesField != null ) ? targetNamesField.GetValue( null ) as string[] : null; Assert.IsNotNull( sourceNames, string.Format( "The tokenNames field in grammar {0} was null.", source.Name ) ); for ( int i = 0; i < sourceNames.Length; i++ ) { string tokenName = sourceNames[i]; if ( string.IsNullOrEmpty( tokenName ) || tokenName[0] == '<' ) continue; if ( tokenName[0] == '\'' ) { if ( targetNames != null && targetNames.Length > i ) { // make sure implicit tokens like 'new' that show up in code as T__45 refer to the same token Assert.AreEqual( sourceNames[i], targetNames[i], string.Format( "Implicit token {0} in grammar {1} doesn't match {2} in grammar {3}.", sourceNames[i], source.Name, targetNames[i], target.Name ) ); continue; } else { tokenName = "T__" + i.ToString(); } } FieldInfo sourceToken = source.GetField( tokenName ); FieldInfo targetToken = target.GetField( tokenName ); if ( source != null && target != null ) { int sourceValue = (int)sourceToken.GetValue( null ); int targetValue = (int)targetToken.GetValue( null ); Assert.AreEqual( sourceValue, targetValue, string.Format( "Token {0} with value {1} grammar {2} doesn't match value {3} in grammar {4}.", tokenName, sourceValue, source.Name, targetValue, target.Name ) ); } } } protected AntlrTool newTool(params string[] args) { AntlrTool tool = (args == null || args.Length == 0) ? new AntlrTool() : new AntlrTool(args); tool.SetOutputDirectory( tmpdir ); tool.TestMode = true; return tool; } protected static string JavaHome { get { string home = javaHome; bool debugger = Debugger.IsAttached; if (home == null || debugger) { home = Environment.GetEnvironmentVariable("JAVA_HOME"); if (string.IsNullOrEmpty(home) || !Directory.Exists(home)) { home = CheckForJavaHome(Registry.CurrentUser); if (home == null) home = CheckForJavaHome(Registry.LocalMachine); } if (home != null && !Directory.Exists(home)) home = null; if (!debugger) { javaHome = home; } } return home; } } protected static string CheckForJavaHome(RegistryKey key) { using (RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\JavaSoft\Java Development Kit")) { if (subkey == null) return null; object value = subkey.GetValue("CurrentVersion", null, RegistryValueOptions.None); if (value != null) { using (RegistryKey currentHomeKey = subkey.OpenSubKey(value.ToString())) { if (currentHomeKey == null) return null; value = currentHomeKey.GetValue("JavaHome", null, RegistryValueOptions.None); if (value != null) return value.ToString(); } } } return null; } protected string ClassPath { get { return Path.GetFullPath( RuntimeJar ) + Path.PathSeparator + Path.GetFullPath( Runtime2Jar ) + Path.PathSeparator + Path.GetFullPath( StringTemplateJar ); } } protected string Compiler { get { return Path.Combine( Path.Combine( JavaHome, "bin" ), "javac.exe" ); } } protected string Jvm { get { return Path.Combine( Path.Combine( JavaHome, "bin" ), "java.exe" ); } } protected bool compile( string fileName ) { //String compiler = "javac"; string compiler = Compiler; string classpathOption = "-classpath"; if ( jikes != null ) { compiler = jikes; classpathOption = "-bootclasspath"; } string inputFile = Path.Combine(tmpdir, fileName); string[] args = new string[] { /*compiler,*/ "-d", tmpdir, classpathOption, tmpdir+pathSep+ClassPath, inputFile }; string cmdLine = compiler + " -d " + tmpdir + " " + classpathOption + " " + '"'+tmpdir + pathSep + ClassPath+'"' + " " + fileName; //System.out.println("compile: "+cmdLine); //File outputDir = new File( tmpdir ); try { System.Diagnostics.Process process = System.Diagnostics.Process.Start( new System.Diagnostics.ProcessStartInfo( compiler, '"' + string.Join( "\" \"", args ) + '"' ) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = tmpdir } ); //Process process = // Runtime.getRuntime().exec( args, null, outputDir ); StreamVacuum stdout = new StreamVacuum( process.StandardOutput, inputFile ); StreamVacuum stderr = new StreamVacuum( process.StandardError, inputFile ); stdout.start(); stderr.start(); process.WaitForExit(); if ( stdout.ToString().Length > 0 ) { Console.Error.WriteLine( "compile stdout from: " + cmdLine ); Console.Error.WriteLine( stdout ); } if ( stderr.ToString().Length > 0 ) { Console.Error.WriteLine( "compile stderr from: " + cmdLine ); Console.Error.WriteLine( stderr ); } int ret = process.ExitCode; return ret == 0; } catch ( Exception e ) { Console.Error.WriteLine( "can't exec compilation" ); e.PrintStackTrace( Console.Error ); return false; } } /** Return true if all is ok, no errors */ protected bool antlr( string fileName, string grammarFileName, string grammarStr, bool debug ) { bool allIsWell = true; mkdir( tmpdir ); writeFile( tmpdir, fileName, grammarStr ); try { List<string> options = new List<string>(); options.Add( "-testmode" ); if ( debug ) { options.Add( "-debug" ); } options.Add( "-o" ); options.Add( tmpdir ); options.Add( "-lib" ); options.Add( tmpdir ); options.Add( Path.Combine( tmpdir, grammarFileName ) ); options.Add("-language"); options.Add("Java"); //String[] optionsA = new String[options.size()]; //options.toArray( optionsA ); string[] optionsA = options.ToArray(); /* final ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); */ AntlrTool antlr = new AntlrTool( optionsA ); antlr.Process(); IANTLRErrorListener listener = ErrorManager.GetErrorListener(); if ( listener is ErrorQueue ) { ErrorQueue equeue = (ErrorQueue)listener; if ( equeue.errors.Count > 0 ) { allIsWell = false; Console.Error.WriteLine( "antlr reports errors from [" + string.Join(", ", options) + ']' ); for ( int i = 0; i < equeue.errors.Count; i++ ) { Message msg = (Message)equeue.errors[i]; Console.Error.WriteLine( msg ); } Console.Out.WriteLine( "!!!\ngrammar:" ); Console.Out.WriteLine( grammarStr ); Console.Out.WriteLine( "###" ); } } } catch ( Exception e ) { allIsWell = false; Console.Error.WriteLine( "problems building grammar: " + e ); e.PrintStackTrace( Console.Error ); } return allIsWell; } protected string execLexer( string grammarFileName, string grammarStr, string lexerName, string input, bool debug ) { bool compiled = rawGenerateAndBuildRecognizer( grammarFileName, grammarStr, null, lexerName, debug ); Assert.IsTrue(compiled); writeFile(tmpdir, "input", input); return rawExecRecognizer( null, null, lexerName, null, null, false, false, false, debug ); } protected string execParser( string grammarFileName, string grammarStr, string parserName, string lexerName, string startRuleName, string input, bool debug ) { bool compiled = rawGenerateAndBuildRecognizer( grammarFileName, grammarStr, parserName, lexerName, debug ); Assert.IsTrue(compiled); writeFile(tmpdir, "input", input); bool parserBuildsTrees = grammarStr.IndexOf( "output=AST" ) >= 0 || grammarStr.IndexOf( "output = AST" ) >= 0; bool parserBuildsTemplate = grammarStr.IndexOf( "output=template" ) >= 0 || grammarStr.IndexOf( "output = template" ) >= 0; return rawExecRecognizer( parserName, null, lexerName, startRuleName, null, parserBuildsTrees, parserBuildsTemplate, false, debug ); } protected string execTreeParser( string parserGrammarFileName, string parserGrammarStr, string parserName, string treeParserGrammarFileName, string treeParserGrammarStr, string treeParserName, string lexerName, string parserStartRuleName, string treeParserStartRuleName, string input ) { return execTreeParser( parserGrammarFileName, parserGrammarStr, parserName, treeParserGrammarFileName, treeParserGrammarStr, treeParserName, lexerName, parserStartRuleName, treeParserStartRuleName, input, false ); } protected string execTreeParser( string parserGrammarFileName, string parserGrammarStr, string parserName, string treeParserGrammarFileName, string treeParserGrammarStr, string treeParserName, string lexerName, string parserStartRuleName, string treeParserStartRuleName, string input, bool debug ) { // build the parser bool compiled = rawGenerateAndBuildRecognizer( parserGrammarFileName, parserGrammarStr, parserName, lexerName, debug ); Assert.IsTrue(compiled); // build the tree parser compiled = rawGenerateAndBuildRecognizer( treeParserGrammarFileName, treeParserGrammarStr, treeParserName, lexerName, debug ); Assert.IsTrue(compiled); writeFile( tmpdir, "input", input ); bool parserBuildsTrees = parserGrammarStr.IndexOf( "output=AST" ) >= 0 || parserGrammarStr.IndexOf( "output = AST" ) >= 0; bool treeParserBuildsTrees = treeParserGrammarStr.IndexOf( "output=AST" ) >= 0 || treeParserGrammarStr.IndexOf( "output = AST" ) >= 0; bool parserBuildsTemplate = parserGrammarStr.IndexOf( "output=template" ) >= 0 || parserGrammarStr.IndexOf( "output = template" ) >= 0; return rawExecRecognizer( parserName, treeParserName, lexerName, parserStartRuleName, treeParserStartRuleName, parserBuildsTrees, parserBuildsTemplate, treeParserBuildsTrees, debug ); } /** Return true if all is well */ protected bool rawGenerateAndBuildRecognizer( string grammarFileName, string grammarStr, string parserName, string lexerName, bool debug ) { bool allIsWell = antlr( grammarFileName, grammarFileName, grammarStr, debug ); if (!allIsWell) return false; if ( lexerName != null ) { bool ok; if ( parserName != null ) { ok = compile( parserName + ".java" ); if ( !ok ) { allIsWell = false; } } ok = compile( lexerName + ".java" ); if ( !ok ) { allIsWell = false; } } else { bool ok = compile( parserName + ".java" ); if ( !ok ) { allIsWell = false; } } return allIsWell; } protected string rawExecRecognizer( string parserName, string treeParserName, string lexerName, string parserStartRuleName, string treeParserStartRuleName, bool parserBuildsTrees, bool parserBuildsTemplate, bool treeParserBuildsTrees, bool debug ) { stderrDuringParse = null; WriteRecognizerAndCompile(parserName, treeParserName, lexerName, parserStartRuleName, treeParserStartRuleName, parserBuildsTrees, parserBuildsTemplate, treeParserBuildsTrees, debug); return execRecognizer(); } public string execRecognizer() { try { string inputFile = Path.GetFullPath(Path.Combine(tmpdir, "input")); string[] args = new string[] { /*"java",*/ "-classpath", tmpdir+pathSep+ClassPath, "Test", inputFile }; //String cmdLine = "java -classpath " + CLASSPATH + pathSep + tmpdir + " Test " + Path.GetFullPath( Path.Combine( tmpdir, "input" ) ); //System.out.println("execParser: "+cmdLine); System.Diagnostics.Process process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Jvm, '"' + string.Join("\" \"", args) + '"') { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = tmpdir }); //Process process = // Runtime.getRuntime().exec( args, null, new File( tmpdir ) ); StreamVacuum stdoutVacuum = new StreamVacuum(process.StandardOutput, inputFile); StreamVacuum stderrVacuum = new StreamVacuum(process.StandardError, inputFile); stdoutVacuum.start(); stderrVacuum.start(); process.WaitForExit(); stdoutVacuum.join(); stderrVacuum.join(); string output = null; diff --git a/Runtime/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj b/Runtime/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj index 80c3707..55fa3bd 100644 --- a/Runtime/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj +++ b/Runtime/Antlr3.Runtime.JavaExtensions/Antlr3.Runtime.JavaExtensions.csproj @@ -1,36 +1,36 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>net35-client;net40-client</TargetFrameworks> + <TargetFrameworks>net35-client;net40-client;netstandard2.0</TargetFrameworks> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'net35-client'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40-client'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> </PropertyGroup> </When> </Choose> <ItemGroup> <ProjectReference Include="..\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index b10146a..c8fc1d1 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,23 +1,24 @@ version: 1.0.{build} os: Visual Studio 2017 configuration: Release init: - cmd: >- git config --global core.autocrlf true mkdir ..\..\..\keys\antlr "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sn.exe" -k ..\..\..\keys\antlr\Key.snk install: - git submodule update --init --recursive build_script: - cd build\prep - powershell -Command .\prepare.ps1 -Logger "${env:ProgramFiles}\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" - cd ..\.. test_script: - vstest.console /logger:Appveyor /TestCaseFilter:"TestCategory!=SkipOnCI" "C:\projects\antlrcs\Antlr3.Test\bin\%CONFIGURATION%\net45\AntlrUnitTests.dll" - vstest.console /logger:Appveyor /TestCaseFilter:"TestCategory!=Visualizer" "C:\projects\antlrcs\Antlr4.Test.StringTemplate\bin\%CONFIGURATION%\net45\Antlr4.Test.StringTemplate.dll" +- dotnet vstest /Framework:".NETCoreApp,Version=v2.0" /TestCaseFilter:"TestCategory!=SkipOnCI" "C:\projects\antlrcs\Antlr3.Test\bin\%CONFIGURATION%\netcoreapp2.0\AntlrUnitTests.dll" - dotnet vstest /Framework:".NETCoreApp,Version=v2.0" /TestCaseFilter:"TestCategory!=Visualizer" "C:\projects\antlrcs\Antlr4.Test.StringTemplate\bin\%CONFIGURATION%\netcoreapp2.0\Antlr4.Test.StringTemplate.dll" artifacts: - path: build\prep\nuget\*.nupkg - path: build\prep\dist\*.7z
antlr/antlrcs
3ef6c334dab32326f3ed39eb5d3d6e51dcd5e83f
Pack StringTemplate4 without a separate nuspec
diff --git a/Antlr3.sln b/Antlr3.sln index 70f357e..daa13a6 100644 --- a/Antlr3.sln +++ b/Antlr3.sln @@ -1,233 +1,232 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26724.1 MinimumVisualStudioVersion = 15.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Targets", "Targets", "{3A92893D-7810-4D8B-80D8-E1E8D151FA73}" ProjectSection(SolutionItems) = preProject Antlr3.Targets\Directory.Build.props = Antlr3.Targets\Directory.Build.props Antlr3.Targets\Directory.Build.targets = Antlr3.Targets\Directory.Build.targets EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C0B451C4-EAFC-4942-B18E-49EC73DABABD}" ProjectSection(SolutionItems) = preProject .travis.yml = .travis.yml Antlr3.ruleset = Antlr3.ruleset Antlr3.vsmdi = Antlr3.vsmdi AntlrTestConfig.testrunconfig = AntlrTestConfig.testrunconfig appveyor.yml = appveyor.yml README.md = README.md EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3", "Antlr3\Antlr3.csproj", "{2AB8CAED-C046-4F05-8B18-6948100D2FE7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.StringTemplate", "Antlr3.StringTemplate\Antlr3.StringTemplate.csproj", "{B5910BE2-DE21-4AA9-95C1-486F42B9E794}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Test", "Antlr3.Test\Antlr3.Test.csproj", "{8B58597B-058E-4D7A-B83E-5269BDABBE2C}" ProjectSection(ProjectDependencies) = postProject {696F611F-003B-477D-AFA0-4F15478C9D32} = {696F611F-003B-477D-AFA0-4F15478C9D32} {67012F41-94F9-48E6-9677-E3C56E42917F} = {67012F41-94F9-48E6-9677-E3C56E42917F} {8EFEA650-B9F6-498B-8865-A78103CCB590} = {8EFEA650-B9F6-498B-8865-A78103CCB590} {46171154-755A-4595-99AA-537D684BCA28} = {46171154-755A-4595-99AA-537D684BCA28} {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} = {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} = {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} = {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} {6689F268-CE30-4CEC-AAD5-2DF72C43623C} = {6689F268-CE30-4CEC-AAD5-2DF72C43623C} {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} = {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} = {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} {1551D1E7-D515-4488-A889-5DEBB4950880} = {1551D1E7-D515-4488-A889-5DEBB4950880} {9444ACEF-784D-47B0-B317-F374782FA511} = {9444ACEF-784D-47B0-B317-F374782FA511} EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.ActionScript", "Antlr3.Targets\Antlr3.Targets.ActionScript\Antlr3.Targets.ActionScript.csproj", "{2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.C", "Antlr3.Targets\Antlr3.Targets.C\Antlr3.Targets.C.csproj", "{ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Cpp", "Antlr3.Targets\Antlr3.Targets.Cpp\Antlr3.Targets.Cpp.csproj", "{46171154-755A-4595-99AA-537D684BCA28}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.CSharp2", "Antlr3.Targets\Antlr3.Targets.CSharp2\Antlr3.Targets.CSharp2.csproj", "{5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.CSharp3", "Antlr3.Targets\Antlr3.Targets.CSharp3\Antlr3.Targets.CSharp3.csproj", "{67012F41-94F9-48E6-9677-E3C56E42917F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Delphi", "Antlr3.Targets\Antlr3.Targets.Delphi\Antlr3.Targets.Delphi.csproj", "{6689F268-CE30-4CEC-AAD5-2DF72C43623C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Java", "Antlr3.Targets\Antlr3.Targets.Java\Antlr3.Targets.Java.csproj", "{696F611F-003B-477D-AFA0-4F15478C9D32}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.JavaScript", "Antlr3.Targets\Antlr3.Targets.JavaScript\Antlr3.Targets.JavaScript.csproj", "{1551D1E7-D515-4488-A889-5DEBB4950880}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.ObjC", "Antlr3.Targets\Antlr3.Targets.ObjC\Antlr3.Targets.ObjC.csproj", "{8EFEA650-B9F6-498B-8865-A78103CCB590}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Perl5", "Antlr3.Targets\Antlr3.Targets.Perl5\Antlr3.Targets.Perl5.csproj", "{9444ACEF-784D-47B0-B317-F374782FA511}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Python", "Antlr3.Targets\Antlr3.Targets.Python\Antlr3.Targets.Python.csproj", "{1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Ruby", "Antlr3.Targets\Antlr3.Targets.Ruby\Antlr3.Targets.Ruby.csproj", "{64418260-E75A-4556-BB7E-8BDAAFC2EFB9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime", "Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj", "{8FDC0A87-9005-4D5A-AB75-E55CEB575559}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Debug", "Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj", "{5EE27A90-B023-42C9-AAF1-52B0424C5D0B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.JavaExtensions", "Runtime\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj", "{A7EEC557-EB14-451C-9616-B7A61F4ECE69}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Test", "Runtime\Antlr3.Runtime.Test\Antlr3.Runtime.Test.csproj", "{19B965DE-5100-4064-A580-159644F6980E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AntlrBuildTask", "AntlrBuildTask\AntlrBuildTask.csproj", "{60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.StringTemplate", "Antlr4.StringTemplate\Antlr4.StringTemplate.csproj", "{DE9B7DA2-35DD-46CC-B768-DAEE3C298660}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.Test.StringTemplate", "Antlr4.Test.StringTemplate\Antlr4.Test.StringTemplate.csproj", "{1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.StringTemplate.Visualizer", "Antlr4.StringTemplate.Visualizer\Antlr4.StringTemplate.Visualizer.csproj", "{DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Visualizer", "Antlr3.Runtime.Visualizer\Antlr3.Runtime.Visualizer.csproj", "{2F59DA1C-A502-440C-ABE8-240BDE2D0664}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Python3", "Antlr3.Targets\Antlr3.Targets.Python3\Antlr3.Targets.Python3.csproj", "{5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{D2D979DC-1305-4C44-B21A-9EB3EEE95F7B}" ProjectSection(SolutionItems) = preProject build\prep\Antlr3.CodeGenerator.nuspec = build\prep\Antlr3.CodeGenerator.nuspec build\prep\Antlr3.nuspec = build\prep\Antlr3.nuspec Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets build\prep\prepare.ps1 = build\prep\prepare.ps1 build\prep\push-antlr.ps1 = build\prep\push-antlr.ps1 build\prep\push-st3.ps1 = build\prep\push-st3.ps1 build\prep\push-st4.ps1 = build\prep\push-st4.ps1 - build\prep\StringTemplate4.nuspec = build\prep\StringTemplate4.nuspec build\prep\StringTemplate4.Visualizer.nuspec = build\prep\StringTemplate4.Visualizer.nuspec build\prep\version.ps1 = build\prep\version.ps1 EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Debug|Any CPU.Build.0 = Debug|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Release|Any CPU.ActiveCfg = Release|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Release|Any CPU.Build.0 = Release|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Debug|Any CPU.Build.0 = Debug|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Release|Any CPU.ActiveCfg = Release|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Release|Any CPU.Build.0 = Release|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Debug|Any CPU.Build.0 = Debug|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Release|Any CPU.ActiveCfg = Release|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Release|Any CPU.Build.0 = Release|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Release|Any CPU.Build.0 = Release|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Release|Any CPU.Build.0 = Release|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Debug|Any CPU.Build.0 = Debug|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Release|Any CPU.ActiveCfg = Release|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Release|Any CPU.Build.0 = Release|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Release|Any CPU.Build.0 = Release|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Debug|Any CPU.Build.0 = Debug|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Release|Any CPU.ActiveCfg = Release|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Release|Any CPU.Build.0 = Release|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Debug|Any CPU.Build.0 = Debug|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Release|Any CPU.ActiveCfg = Release|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Release|Any CPU.Build.0 = Release|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Debug|Any CPU.Build.0 = Debug|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Release|Any CPU.ActiveCfg = Release|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Release|Any CPU.Build.0 = Release|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Debug|Any CPU.Build.0 = Debug|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Release|Any CPU.ActiveCfg = Release|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Release|Any CPU.Build.0 = Release|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Debug|Any CPU.Build.0 = Debug|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Release|Any CPU.ActiveCfg = Release|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Release|Any CPU.Build.0 = Release|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Debug|Any CPU.Build.0 = Debug|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Release|Any CPU.ActiveCfg = Release|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Release|Any CPU.Build.0 = Release|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Debug|Any CPU.Build.0 = Debug|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Release|Any CPU.Build.0 = Release|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Debug|Any CPU.Build.0 = Debug|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Release|Any CPU.ActiveCfg = Release|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Release|Any CPU.Build.0 = Release|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Debug|Any CPU.Build.0 = Debug|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Release|Any CPU.ActiveCfg = Release|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Release|Any CPU.Build.0 = Release|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Debug|Any CPU.Build.0 = Debug|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Release|Any CPU.ActiveCfg = Release|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Release|Any CPU.Build.0 = Release|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Debug|Any CPU.Build.0 = Debug|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Release|Any CPU.ActiveCfg = Release|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Release|Any CPU.Build.0 = Release|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Debug|Any CPU.Build.0 = Debug|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Release|Any CPU.ActiveCfg = Release|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Release|Any CPU.Build.0 = Release|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Debug|Any CPU.Build.0 = Debug|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Release|Any CPU.ActiveCfg = Release|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Release|Any CPU.Build.0 = Release|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Debug|Any CPU.Build.0 = Debug|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Release|Any CPU.ActiveCfg = Release|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Release|Any CPU.Build.0 = Release|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Release|Any CPU.Build.0 = Release|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Release|Any CPU.Build.0 = Release|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Release|Any CPU.Build.0 = Release|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Debug|Any CPU.Build.0 = Debug|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Release|Any CPU.ActiveCfg = Release|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {46171154-755A-4595-99AA-537D684BCA28} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {67012F41-94F9-48E6-9677-E3C56E42917F} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {6689F268-CE30-4CEC-AAD5-2DF72C43623C} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {696F611F-003B-477D-AFA0-4F15478C9D32} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {1551D1E7-D515-4488-A889-5DEBB4950880} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {8EFEA650-B9F6-498B-8865-A78103CCB590} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {9444ACEF-784D-47B0-B317-F374782FA511} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {D2D979DC-1305-4C44-B21A-9EB3EEE95F7B} = {C0B451C4-EAFC-4942-B18E-49EC73DABABD} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {46CE14C6-8A1E-4634-A720-69B2E14873EE} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Antlr3.vsmdi EndGlobalSection EndGlobal diff --git a/Antlr4.StringTemplate/Antlr4.StringTemplate.csproj b/Antlr4.StringTemplate/Antlr4.StringTemplate.csproj index c6ef291..8469f1e 100644 --- a/Antlr4.StringTemplate/Antlr4.StringTemplate.csproj +++ b/Antlr4.StringTemplate/Antlr4.StringTemplate.csproj @@ -1,79 +1,68 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net35-client;net40-client;netstandard1.3</TargetFrameworks> - <Description>The C# port of StringTemplate 4</Description> - <Company>Tunnel Vision Laboratories, LLC</Company> - <Copyright>Copyright © Sam Harwell 2011</Copyright> + <Description>The C# port of StringTemplate 4.</Description> <Version>$(STVersion)</Version> <FileVersion>$(STFileVersion)</FileVersion> <InformationalVersion>$(STInformationalVersion)</InformationalVersion> + <Title>StringTemplate 4</Title> + <PackageId>StringTemplate4</PackageId> + <PackageTags>stringtemplate st4 stringtemplate4 template</PackageTags> + <GeneratePackageOnBuild>true</GeneratePackageOnBuild> - <IncludeSymbols>true</IncludeSymbols> - <NuspecFile>..\build\prep\StringTemplate4.nuspec</NuspecFile> - <NuspecProperties>Configuration=$(Configuration);version=$(InformationalVersion);ANTLRVersion=$(ANTLRInformationalVersion)</NuspecProperties> - <PackageOutputPath>..\build\prep\nuget\</PackageOutputPath> </PropertyGroup> + <ItemGroup> + <PackageReference Include="MSBuild.Sdk.Extras" Version="1.2.1" PrivateAssets="All" /> + </ItemGroup> + <Target Name="DisableCrazyPackageDeletion" BeforeTargets="Clean"> <PropertyGroup> <GeneratePackageValue>$(GeneratePackageOnBuild)</GeneratePackageValue> <GeneratePackageOnBuild>false</GeneratePackageOnBuild> </PropertyGroup> </Target> <Target Name="EnablePackageGeneration" Condition="'$(GeneratePackageValue)' != ''" BeforeTargets="Build"> <PropertyGroup> <GeneratePackageOnBuild>$(GeneratePackageValue)</GeneratePackageOnBuild> </PropertyGroup> </Target> <Choose> - <When Condition="'$(TargetFramework)' == 'net35-client'"> - <PropertyGroup> - <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> - <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> - <TargetFrameworkProfile>Client</TargetFrameworkProfile> - </PropertyGroup> - </When> - <When Condition="'$(TargetFramework)' == 'net40-client'"> - <PropertyGroup> - <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <TargetFrameworkProfile>Client</TargetFrameworkProfile> - </PropertyGroup> - </When> <When Condition="'$(TargetFramework)' == 'netstandard1.3'"> <PropertyGroup> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </When> </Choose> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> <ItemGroup> <None Include="Debug\DebugTemplate.cs" /> <Compile Remove="Debug\DebugTemplate.cs" /> </ItemGroup> <ItemGroup> <Compile Update="Compiler\CodeGenerator.g3.cs"> <DependentUpon>CodeGenerator.g3</DependentUpon> </Compile> <Compile Update="Compiler\Group.g3.parser.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Compiler\Group.g3.lexer.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Compiler\TemplateParser.g3.cs"> <DependentUpon>TemplateParser.g3</DependentUpon> </Compile> </ItemGroup> + <Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" /> </Project> \ No newline at end of file diff --git a/build/prep/StringTemplate4.nuspec b/build/prep/StringTemplate4.nuspec deleted file mode 100644 index 69ddcf1..0000000 --- a/build/prep/StringTemplate4.nuspec +++ /dev/null @@ -1,54 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> - <metadata> - <id>StringTemplate4</id> - <version>0.0.0</version> - <authors>Sam Harwell, Terence Parr</authors> - <owners>Sam Harwell</owners> - <description>The C# port of StringTemplate 4.</description> - <language>en-us</language> - <projectUrl>https://github.com/antlr/antlrcs</projectUrl> - <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> - <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> - <copyright>Copyright © Sam Harwell 2013</copyright> - <releaseNotes>https://github.com/antlr/antlrcs/releases/$ANTLRVersion$</releaseNotes> - <requireLicenseAcceptance>true</requireLicenseAcceptance> - <tags>stringtemplate st4 stringtemplate4 template</tags> - <title>StringTemplate 4</title> - <summary>The C# port of StringTemplate 4.</summary> - <dependencies> - <group targetFramework="net35-client"> - <dependency id="Antlr3.Runtime" version="$ANTLRVersion$" /> - </group> - <group targetFramework="netstandard1.3"> - <dependency id="Antlr3.Runtime" version="$ANTLRVersion$" /> - <dependency id="NETStandard.Library" version="1.6.0"/> - </group> - </dependencies> - </metadata> - <files> - <!-- Runtime Libraries --> - - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\net35-client\Antlr4.StringTemplate.dll" target="lib\net35-client"/> - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\net35-client\Antlr4.StringTemplate.pdb" target="lib\net35-client"/> - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\net35-client\Antlr4.StringTemplate.xml" target="lib\net35-client"/> - - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\net40-client\Antlr4.StringTemplate.dll" target="lib\net40-client"/> - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\net40-client\Antlr4.StringTemplate.pdb" target="lib\net40-client"/> - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\net40-client\Antlr4.StringTemplate.xml" target="lib\net40-client"/> - - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\netstandard1.3\Antlr4.StringTemplate.dll" target="lib\netstandard1.3"/> - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\netstandard1.3\Antlr4.StringTemplate.pdb" target="lib\netstandard1.3"/> - <file src="..\..\Antlr4.StringTemplate\bin\$Configuration$\netstandard1.3\Antlr4.StringTemplate.xml" target="lib\netstandard1.3"/> - - <!-- Source Code --> - - <file exclude="..\..\Antlr4.StringTemplate\obj\**\*.cs" src="..\..\Antlr4.StringTemplate\**\*.cs" target="src"/> - <file src="..\..\Antlr4.StringTemplate\obj\$Configuration$\net35-client\**\*.cs" target="src\obj\$Configuration$\net35-client"/> - <file src="..\..\Antlr4.StringTemplate\obj\$Configuration$\net35-client\**\*.tokens" target="src\obj\$Configuration$\net35-client"/> - <file src="..\..\Antlr4.StringTemplate\obj\$Configuration$\net40-client\**\*.cs" target="src\obj\$Configuration$\net40-client"/> - <file src="..\..\Antlr4.StringTemplate\obj\$Configuration$\net40-client\**\*.tokens" target="src\obj\$Configuration$\net40-client"/> - <file src="..\..\Antlr4.StringTemplate\obj\$Configuration$\netstandard1.3\**\*.cs" target="src\obj\$Configuration$\netstandard"/> - <file src="..\..\Antlr4.StringTemplate\obj\$Configuration$\netstandard1.3\**\*.tokens" target="src\obj\$Configuration$\netstandard"/> - </files> -</package>
antlr/antlrcs
15675e2b6511dcf14aa44e72e2e384e7f59ca3f8
Pack Antlr3.Runtime.Debug without a separate nuspec
diff --git a/Antlr3.sln b/Antlr3.sln index c1cdda2..70f357e 100644 --- a/Antlr3.sln +++ b/Antlr3.sln @@ -1,234 +1,233 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26724.1 MinimumVisualStudioVersion = 15.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Targets", "Targets", "{3A92893D-7810-4D8B-80D8-E1E8D151FA73}" ProjectSection(SolutionItems) = preProject Antlr3.Targets\Directory.Build.props = Antlr3.Targets\Directory.Build.props Antlr3.Targets\Directory.Build.targets = Antlr3.Targets\Directory.Build.targets EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C0B451C4-EAFC-4942-B18E-49EC73DABABD}" ProjectSection(SolutionItems) = preProject .travis.yml = .travis.yml Antlr3.ruleset = Antlr3.ruleset Antlr3.vsmdi = Antlr3.vsmdi AntlrTestConfig.testrunconfig = AntlrTestConfig.testrunconfig appveyor.yml = appveyor.yml README.md = README.md EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3", "Antlr3\Antlr3.csproj", "{2AB8CAED-C046-4F05-8B18-6948100D2FE7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.StringTemplate", "Antlr3.StringTemplate\Antlr3.StringTemplate.csproj", "{B5910BE2-DE21-4AA9-95C1-486F42B9E794}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Test", "Antlr3.Test\Antlr3.Test.csproj", "{8B58597B-058E-4D7A-B83E-5269BDABBE2C}" ProjectSection(ProjectDependencies) = postProject {696F611F-003B-477D-AFA0-4F15478C9D32} = {696F611F-003B-477D-AFA0-4F15478C9D32} {67012F41-94F9-48E6-9677-E3C56E42917F} = {67012F41-94F9-48E6-9677-E3C56E42917F} {8EFEA650-B9F6-498B-8865-A78103CCB590} = {8EFEA650-B9F6-498B-8865-A78103CCB590} {46171154-755A-4595-99AA-537D684BCA28} = {46171154-755A-4595-99AA-537D684BCA28} {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} = {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} = {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} = {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} {6689F268-CE30-4CEC-AAD5-2DF72C43623C} = {6689F268-CE30-4CEC-AAD5-2DF72C43623C} {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} = {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} = {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} {1551D1E7-D515-4488-A889-5DEBB4950880} = {1551D1E7-D515-4488-A889-5DEBB4950880} {9444ACEF-784D-47B0-B317-F374782FA511} = {9444ACEF-784D-47B0-B317-F374782FA511} EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.ActionScript", "Antlr3.Targets\Antlr3.Targets.ActionScript\Antlr3.Targets.ActionScript.csproj", "{2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.C", "Antlr3.Targets\Antlr3.Targets.C\Antlr3.Targets.C.csproj", "{ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Cpp", "Antlr3.Targets\Antlr3.Targets.Cpp\Antlr3.Targets.Cpp.csproj", "{46171154-755A-4595-99AA-537D684BCA28}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.CSharp2", "Antlr3.Targets\Antlr3.Targets.CSharp2\Antlr3.Targets.CSharp2.csproj", "{5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.CSharp3", "Antlr3.Targets\Antlr3.Targets.CSharp3\Antlr3.Targets.CSharp3.csproj", "{67012F41-94F9-48E6-9677-E3C56E42917F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Delphi", "Antlr3.Targets\Antlr3.Targets.Delphi\Antlr3.Targets.Delphi.csproj", "{6689F268-CE30-4CEC-AAD5-2DF72C43623C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Java", "Antlr3.Targets\Antlr3.Targets.Java\Antlr3.Targets.Java.csproj", "{696F611F-003B-477D-AFA0-4F15478C9D32}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.JavaScript", "Antlr3.Targets\Antlr3.Targets.JavaScript\Antlr3.Targets.JavaScript.csproj", "{1551D1E7-D515-4488-A889-5DEBB4950880}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.ObjC", "Antlr3.Targets\Antlr3.Targets.ObjC\Antlr3.Targets.ObjC.csproj", "{8EFEA650-B9F6-498B-8865-A78103CCB590}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Perl5", "Antlr3.Targets\Antlr3.Targets.Perl5\Antlr3.Targets.Perl5.csproj", "{9444ACEF-784D-47B0-B317-F374782FA511}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Python", "Antlr3.Targets\Antlr3.Targets.Python\Antlr3.Targets.Python.csproj", "{1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Ruby", "Antlr3.Targets\Antlr3.Targets.Ruby\Antlr3.Targets.Ruby.csproj", "{64418260-E75A-4556-BB7E-8BDAAFC2EFB9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime", "Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj", "{8FDC0A87-9005-4D5A-AB75-E55CEB575559}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Debug", "Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj", "{5EE27A90-B023-42C9-AAF1-52B0424C5D0B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.JavaExtensions", "Runtime\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj", "{A7EEC557-EB14-451C-9616-B7A61F4ECE69}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Test", "Runtime\Antlr3.Runtime.Test\Antlr3.Runtime.Test.csproj", "{19B965DE-5100-4064-A580-159644F6980E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AntlrBuildTask", "AntlrBuildTask\AntlrBuildTask.csproj", "{60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.StringTemplate", "Antlr4.StringTemplate\Antlr4.StringTemplate.csproj", "{DE9B7DA2-35DD-46CC-B768-DAEE3C298660}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.Test.StringTemplate", "Antlr4.Test.StringTemplate\Antlr4.Test.StringTemplate.csproj", "{1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.StringTemplate.Visualizer", "Antlr4.StringTemplate.Visualizer\Antlr4.StringTemplate.Visualizer.csproj", "{DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Visualizer", "Antlr3.Runtime.Visualizer\Antlr3.Runtime.Visualizer.csproj", "{2F59DA1C-A502-440C-ABE8-240BDE2D0664}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Python3", "Antlr3.Targets\Antlr3.Targets.Python3\Antlr3.Targets.Python3.csproj", "{5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{D2D979DC-1305-4C44-B21A-9EB3EEE95F7B}" ProjectSection(SolutionItems) = preProject build\prep\Antlr3.CodeGenerator.nuspec = build\prep\Antlr3.CodeGenerator.nuspec build\prep\Antlr3.nuspec = build\prep\Antlr3.nuspec - build\prep\Antlr3.Runtime.Debug.nuspec = build\prep\Antlr3.Runtime.Debug.nuspec Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets build\prep\prepare.ps1 = build\prep\prepare.ps1 build\prep\push-antlr.ps1 = build\prep\push-antlr.ps1 build\prep\push-st3.ps1 = build\prep\push-st3.ps1 build\prep\push-st4.ps1 = build\prep\push-st4.ps1 build\prep\StringTemplate4.nuspec = build\prep\StringTemplate4.nuspec build\prep\StringTemplate4.Visualizer.nuspec = build\prep\StringTemplate4.Visualizer.nuspec build\prep\version.ps1 = build\prep\version.ps1 EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Debug|Any CPU.Build.0 = Debug|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Release|Any CPU.ActiveCfg = Release|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Release|Any CPU.Build.0 = Release|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Debug|Any CPU.Build.0 = Debug|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Release|Any CPU.ActiveCfg = Release|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Release|Any CPU.Build.0 = Release|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Debug|Any CPU.Build.0 = Debug|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Release|Any CPU.ActiveCfg = Release|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Release|Any CPU.Build.0 = Release|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Release|Any CPU.Build.0 = Release|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Release|Any CPU.Build.0 = Release|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Debug|Any CPU.Build.0 = Debug|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Release|Any CPU.ActiveCfg = Release|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Release|Any CPU.Build.0 = Release|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Release|Any CPU.Build.0 = Release|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Debug|Any CPU.Build.0 = Debug|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Release|Any CPU.ActiveCfg = Release|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Release|Any CPU.Build.0 = Release|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Debug|Any CPU.Build.0 = Debug|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Release|Any CPU.ActiveCfg = Release|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Release|Any CPU.Build.0 = Release|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Debug|Any CPU.Build.0 = Debug|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Release|Any CPU.ActiveCfg = Release|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Release|Any CPU.Build.0 = Release|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Debug|Any CPU.Build.0 = Debug|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Release|Any CPU.ActiveCfg = Release|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Release|Any CPU.Build.0 = Release|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Debug|Any CPU.Build.0 = Debug|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Release|Any CPU.ActiveCfg = Release|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Release|Any CPU.Build.0 = Release|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Debug|Any CPU.Build.0 = Debug|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Release|Any CPU.ActiveCfg = Release|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Release|Any CPU.Build.0 = Release|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Debug|Any CPU.Build.0 = Debug|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Release|Any CPU.Build.0 = Release|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Debug|Any CPU.Build.0 = Debug|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Release|Any CPU.ActiveCfg = Release|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Release|Any CPU.Build.0 = Release|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Debug|Any CPU.Build.0 = Debug|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Release|Any CPU.ActiveCfg = Release|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Release|Any CPU.Build.0 = Release|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Debug|Any CPU.Build.0 = Debug|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Release|Any CPU.ActiveCfg = Release|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Release|Any CPU.Build.0 = Release|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Debug|Any CPU.Build.0 = Debug|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Release|Any CPU.ActiveCfg = Release|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Release|Any CPU.Build.0 = Release|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Debug|Any CPU.Build.0 = Debug|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Release|Any CPU.ActiveCfg = Release|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Release|Any CPU.Build.0 = Release|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Debug|Any CPU.Build.0 = Debug|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Release|Any CPU.ActiveCfg = Release|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Release|Any CPU.Build.0 = Release|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Debug|Any CPU.Build.0 = Debug|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Release|Any CPU.ActiveCfg = Release|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Release|Any CPU.Build.0 = Release|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Release|Any CPU.Build.0 = Release|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Release|Any CPU.Build.0 = Release|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Release|Any CPU.Build.0 = Release|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Debug|Any CPU.Build.0 = Debug|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Release|Any CPU.ActiveCfg = Release|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {46171154-755A-4595-99AA-537D684BCA28} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {67012F41-94F9-48E6-9677-E3C56E42917F} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {6689F268-CE30-4CEC-AAD5-2DF72C43623C} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {696F611F-003B-477D-AFA0-4F15478C9D32} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {1551D1E7-D515-4488-A889-5DEBB4950880} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {8EFEA650-B9F6-498B-8865-A78103CCB590} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {9444ACEF-784D-47B0-B317-F374782FA511} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {D2D979DC-1305-4C44-B21A-9EB3EEE95F7B} = {C0B451C4-EAFC-4942-B18E-49EC73DABABD} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {46CE14C6-8A1E-4634-A720-69B2E14873EE} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Antlr3.vsmdi EndGlobalSection EndGlobal diff --git a/Runtime/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj b/Runtime/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj index c774128..dec21e2 100644 --- a/Runtime/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj +++ b/Runtime/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj @@ -1,53 +1,45 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net20;net40-client;netstandard2.0</TargetFrameworks> <RootNamespace>Antlr.Runtime.Debug</RootNamespace> - <Description>The C# port of ANTLR 3</Description> - <Company>Tunnel Vision Laboratories, LLC</Company> - <Copyright>Copyright © Sam Harwell 2011</Copyright> + <Description>The library includes the debug support for parsers generated by the C# target of ANTLR 3. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2008 or newer.</Description> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> + <Title>ANTLR 3 Runtime (Debug Library)</Title> + <PackageTags>antlr antlr3 parsing</PackageTags> + <GeneratePackageOnBuild>true</GeneratePackageOnBuild> - <IncludeSymbols>true</IncludeSymbols> - <NuspecFile>..\..\build\prep\Antlr3.Runtime.Debug.nuspec</NuspecFile> - <NuspecProperties>Configuration=$(Configuration);version=$(InformationalVersion);ANTLRVersion=$(InformationalVersion)</NuspecProperties> - <PackageOutputPath>..\..\build\prep\nuget\</PackageOutputPath> </PropertyGroup> + <ItemGroup> + <PackageReference Include="MSBuild.Sdk.Extras" Version="1.2.1" PrivateAssets="All" /> + </ItemGroup> + <Target Name="DisableCrazyPackageDeletion" BeforeTargets="Clean"> <PropertyGroup> <GeneratePackageValue>$(GeneratePackageOnBuild)</GeneratePackageValue> <GeneratePackageOnBuild>false</GeneratePackageOnBuild> </PropertyGroup> </Target> <Target Name="EnablePackageGeneration" Condition="'$(GeneratePackageValue)' != ''" BeforeTargets="Build"> <PropertyGroup> <GeneratePackageOnBuild>$(GeneratePackageValue)</GeneratePackageOnBuild> </PropertyGroup> </Target> - <Choose> - <When Condition="'$(TargetFramework)' == 'net40-client'"> - <PropertyGroup> - <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <TargetFrameworkProfile>Client</TargetFrameworkProfile> - </PropertyGroup> - </When> - </Choose> - <ItemGroup> <None Include="ParserDebugger.cs" /> <Compile Remove="ParserDebugger.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> + <Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" /> </Project> \ No newline at end of file diff --git a/build/prep/Antlr3.Runtime.Debug.nuspec b/build/prep/Antlr3.Runtime.Debug.nuspec deleted file mode 100644 index 8ee75c3..0000000 --- a/build/prep/Antlr3.Runtime.Debug.nuspec +++ /dev/null @@ -1,38 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> - <metadata> - <id>Antlr3.Runtime.Debug</id> - <version>0.0.0</version> - <authors>Sam Harwell, Terence Parr</authors> - <owners>Sam Harwell</owners> - <description>The library includes the debug support for parsers generated by the C# target of ANTLR 3. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2008 or newer.</description> - <language>en-us</language> - <projectUrl>https://github.com/antlr/antlrcs</projectUrl> - <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> - <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> - <copyright>Copyright © Sam Harwell 2013</copyright> - <releaseNotes>https://github.com/antlr/antlrcs/releases/$version$</releaseNotes> - <requireLicenseAcceptance>true</requireLicenseAcceptance> - <tags>antlr antlr3 parsing</tags> - <title>ANTLR 3 Runtime (Debug Library)</title> - <summary>The optional debug component library for parsers generated by the C# target of ANTLR 3.</summary> - <dependencies> - <dependency id="Antlr3.Runtime" version="$version$" /> - </dependencies> - </metadata> - <files> - <!-- Runtime Libraries --> - - <file src="..\..\Runtime\Antlr3.Runtime.Debug\bin\$Configuration$\net20\Antlr3.Runtime.Debug.dll" target="lib\net20"/> - <file src="..\..\Runtime\Antlr3.Runtime.Debug\bin\$Configuration$\net20\Antlr3.Runtime.Debug.pdb" target="lib\net20"/> - <file src="..\..\Runtime\Antlr3.Runtime.Debug\bin\$Configuration$\net20\Antlr3.Runtime.Debug.xml" target="lib\net20"/> - - <file src="..\..\Runtime\Antlr3.Runtime.Debug\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.dll" target="lib\net40-client"/> - <file src="..\..\Runtime\Antlr3.Runtime.Debug\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.pdb" target="lib\net40-client"/> - <file src="..\..\Runtime\Antlr3.Runtime.Debug\bin\$Configuration$\net40-client\Antlr3.Runtime.Debug.xml" target="lib\net40-client"/> - - <!-- Source Code --> - - <file exclude="..\..\Runtime\Antlr3.Runtime.Debug\obj\**\*.cs" src="..\..\Runtime\Antlr3.Runtime.Debug\**\*.cs" target="src"/> - </files> -</package>
antlr/antlrcs
2ff7d6d80d24da59cedf1cfc6bdc998cc1085487
Pack Antlr4.Runtime and Antlr3.StringTemplate without a separate nuspec
diff --git a/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj b/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj index 842425a..07586d1 100644 --- a/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj +++ b/Antlr3.StringTemplate/Antlr3.StringTemplate.csproj @@ -1,85 +1,78 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net35-client</TargetFrameworks> <RootNamespace>Antlr.ST</RootNamespace> - <Description>The C# port of StringTemplate 3</Description> - <Company>Tunnel Vision Laboratories, LLC</Company> - <Copyright>Copyright © Sam Harwell 2011</Copyright> + <Description>The C# port of StringTemplate 3.</Description> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> + <Title>StringTemplate 3</Title> + <PackageId>StringTemplate3</PackageId> + <PackageTags>stringtemplate st3 stringtemplate3 template</PackageTags> + <GeneratePackageOnBuild>true</GeneratePackageOnBuild> - <IncludeSymbols>true</IncludeSymbols> - <NuspecFile>..\build\prep\StringTemplate3.nuspec</NuspecFile> - <NuspecProperties>Configuration=$(Configuration);version=$(InformationalVersion);ANTLRVersion=$(InformationalVersion)</NuspecProperties> - <PackageOutputPath>..\build\prep\nuget\</PackageOutputPath> </PropertyGroup> + <ItemGroup> + <PackageReference Include="MSBuild.Sdk.Extras" Version="1.2.1" PrivateAssets="All" /> + </ItemGroup> + <Target Name="DisableCrazyPackageDeletion" BeforeTargets="Clean"> <PropertyGroup> <GeneratePackageValue>$(GeneratePackageOnBuild)</GeneratePackageValue> <GeneratePackageOnBuild>false</GeneratePackageOnBuild> </PropertyGroup> </Target> <Target Name="EnablePackageGeneration" Condition="'$(GeneratePackageValue)' != ''" BeforeTargets="Build"> <PropertyGroup> <GeneratePackageOnBuild>$(GeneratePackageValue)</GeneratePackageOnBuild> </PropertyGroup> </Target> - <Choose> - <When Condition="'$(TargetFramework)' == 'net35-client'"> - <PropertyGroup> - <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> - <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> - <TargetFrameworkProfile>Client</TargetFrameworkProfile> - </PropertyGroup> - </When> - </Choose> - <PropertyGroup> <DefineConstants>$(DefineConstants);COMPILE_EXPRESSIONS;CACHE_FUNCTORS</DefineConstants> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> <ItemGroup> <Compile Update="Language\AngleBracketTemplateLexerHelper.cs"> <DependentUpon>AngleBracketTemplateLexer.g3</DependentUpon> </Compile> <Compile Update="Language\TemplateLexerHelper.cs"> <DependentUpon>Template.g3</DependentUpon> </Compile> <Compile Update="Language\TemplateParserHelper.cs"> <DependentUpon>Template.g3</DependentUpon> </Compile> <Compile Update="Language\InterfaceLexerHelper.cs"> <DependentUpon>Interface.g3</DependentUpon> </Compile> <Compile Update="Language\InterfaceParserHelper.cs"> <DependentUpon>Interface.g3</DependentUpon> </Compile> <Compile Update="Language\GroupLexerHelper.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Language\GroupParserHelper.cs"> <DependentUpon>Group.g3</DependentUpon> </Compile> <Compile Update="Language\ActionLexerHelper.cs"> <DependentUpon>Action.g3</DependentUpon> </Compile> <Compile Update="Language\ActionParserHelper.cs"> <DependentUpon>Action.g3</DependentUpon> </Compile> <Compile Update="Language\ActionEvaluatorHelper.cs"> <DependentUpon>ActionEvaluator.g3</DependentUpon> </Compile> </ItemGroup> + <Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" /> </Project> \ No newline at end of file diff --git a/Antlr3.sln b/Antlr3.sln index a94a084..c1cdda2 100644 --- a/Antlr3.sln +++ b/Antlr3.sln @@ -1,236 +1,234 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26724.1 MinimumVisualStudioVersion = 15.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Targets", "Targets", "{3A92893D-7810-4D8B-80D8-E1E8D151FA73}" ProjectSection(SolutionItems) = preProject Antlr3.Targets\Directory.Build.props = Antlr3.Targets\Directory.Build.props Antlr3.Targets\Directory.Build.targets = Antlr3.Targets\Directory.Build.targets EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C0B451C4-EAFC-4942-B18E-49EC73DABABD}" ProjectSection(SolutionItems) = preProject .travis.yml = .travis.yml Antlr3.ruleset = Antlr3.ruleset Antlr3.vsmdi = Antlr3.vsmdi AntlrTestConfig.testrunconfig = AntlrTestConfig.testrunconfig appveyor.yml = appveyor.yml README.md = README.md EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3", "Antlr3\Antlr3.csproj", "{2AB8CAED-C046-4F05-8B18-6948100D2FE7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.StringTemplate", "Antlr3.StringTemplate\Antlr3.StringTemplate.csproj", "{B5910BE2-DE21-4AA9-95C1-486F42B9E794}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Test", "Antlr3.Test\Antlr3.Test.csproj", "{8B58597B-058E-4D7A-B83E-5269BDABBE2C}" ProjectSection(ProjectDependencies) = postProject {696F611F-003B-477D-AFA0-4F15478C9D32} = {696F611F-003B-477D-AFA0-4F15478C9D32} {67012F41-94F9-48E6-9677-E3C56E42917F} = {67012F41-94F9-48E6-9677-E3C56E42917F} {8EFEA650-B9F6-498B-8865-A78103CCB590} = {8EFEA650-B9F6-498B-8865-A78103CCB590} {46171154-755A-4595-99AA-537D684BCA28} = {46171154-755A-4595-99AA-537D684BCA28} {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} = {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} = {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} = {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} {6689F268-CE30-4CEC-AAD5-2DF72C43623C} = {6689F268-CE30-4CEC-AAD5-2DF72C43623C} {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} = {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} = {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} {1551D1E7-D515-4488-A889-5DEBB4950880} = {1551D1E7-D515-4488-A889-5DEBB4950880} {9444ACEF-784D-47B0-B317-F374782FA511} = {9444ACEF-784D-47B0-B317-F374782FA511} EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.ActionScript", "Antlr3.Targets\Antlr3.Targets.ActionScript\Antlr3.Targets.ActionScript.csproj", "{2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.C", "Antlr3.Targets\Antlr3.Targets.C\Antlr3.Targets.C.csproj", "{ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Cpp", "Antlr3.Targets\Antlr3.Targets.Cpp\Antlr3.Targets.Cpp.csproj", "{46171154-755A-4595-99AA-537D684BCA28}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.CSharp2", "Antlr3.Targets\Antlr3.Targets.CSharp2\Antlr3.Targets.CSharp2.csproj", "{5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.CSharp3", "Antlr3.Targets\Antlr3.Targets.CSharp3\Antlr3.Targets.CSharp3.csproj", "{67012F41-94F9-48E6-9677-E3C56E42917F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Delphi", "Antlr3.Targets\Antlr3.Targets.Delphi\Antlr3.Targets.Delphi.csproj", "{6689F268-CE30-4CEC-AAD5-2DF72C43623C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Java", "Antlr3.Targets\Antlr3.Targets.Java\Antlr3.Targets.Java.csproj", "{696F611F-003B-477D-AFA0-4F15478C9D32}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.JavaScript", "Antlr3.Targets\Antlr3.Targets.JavaScript\Antlr3.Targets.JavaScript.csproj", "{1551D1E7-D515-4488-A889-5DEBB4950880}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.ObjC", "Antlr3.Targets\Antlr3.Targets.ObjC\Antlr3.Targets.ObjC.csproj", "{8EFEA650-B9F6-498B-8865-A78103CCB590}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Perl5", "Antlr3.Targets\Antlr3.Targets.Perl5\Antlr3.Targets.Perl5.csproj", "{9444ACEF-784D-47B0-B317-F374782FA511}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Python", "Antlr3.Targets\Antlr3.Targets.Python\Antlr3.Targets.Python.csproj", "{1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Ruby", "Antlr3.Targets\Antlr3.Targets.Ruby\Antlr3.Targets.Ruby.csproj", "{64418260-E75A-4556-BB7E-8BDAAFC2EFB9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime", "Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj", "{8FDC0A87-9005-4D5A-AB75-E55CEB575559}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Debug", "Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj", "{5EE27A90-B023-42C9-AAF1-52B0424C5D0B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.JavaExtensions", "Runtime\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj", "{A7EEC557-EB14-451C-9616-B7A61F4ECE69}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Test", "Runtime\Antlr3.Runtime.Test\Antlr3.Runtime.Test.csproj", "{19B965DE-5100-4064-A580-159644F6980E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AntlrBuildTask", "AntlrBuildTask\AntlrBuildTask.csproj", "{60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.StringTemplate", "Antlr4.StringTemplate\Antlr4.StringTemplate.csproj", "{DE9B7DA2-35DD-46CC-B768-DAEE3C298660}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.Test.StringTemplate", "Antlr4.Test.StringTemplate\Antlr4.Test.StringTemplate.csproj", "{1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr4.StringTemplate.Visualizer", "Antlr4.StringTemplate.Visualizer\Antlr4.StringTemplate.Visualizer.csproj", "{DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Runtime.Visualizer", "Antlr3.Runtime.Visualizer\Antlr3.Runtime.Visualizer.csproj", "{2F59DA1C-A502-440C-ABE8-240BDE2D0664}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Antlr3.Targets.Python3", "Antlr3.Targets\Antlr3.Targets.Python3\Antlr3.Targets.Python3.csproj", "{5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{D2D979DC-1305-4C44-B21A-9EB3EEE95F7B}" ProjectSection(SolutionItems) = preProject build\prep\Antlr3.CodeGenerator.nuspec = build\prep\Antlr3.CodeGenerator.nuspec build\prep\Antlr3.nuspec = build\prep\Antlr3.nuspec build\prep\Antlr3.Runtime.Debug.nuspec = build\prep\Antlr3.Runtime.Debug.nuspec - build\prep\Antlr3.Runtime.nuspec = build\prep\Antlr3.Runtime.nuspec Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets build\prep\prepare.ps1 = build\prep\prepare.ps1 build\prep\push-antlr.ps1 = build\prep\push-antlr.ps1 build\prep\push-st3.ps1 = build\prep\push-st3.ps1 build\prep\push-st4.ps1 = build\prep\push-st4.ps1 - build\prep\StringTemplate3.nuspec = build\prep\StringTemplate3.nuspec build\prep\StringTemplate4.nuspec = build\prep\StringTemplate4.nuspec build\prep\StringTemplate4.Visualizer.nuspec = build\prep\StringTemplate4.Visualizer.nuspec build\prep\version.ps1 = build\prep\version.ps1 EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Debug|Any CPU.Build.0 = Debug|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Release|Any CPU.ActiveCfg = Release|Any CPU {2AB8CAED-C046-4F05-8B18-6948100D2FE7}.Release|Any CPU.Build.0 = Release|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Debug|Any CPU.Build.0 = Debug|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Release|Any CPU.ActiveCfg = Release|Any CPU {B5910BE2-DE21-4AA9-95C1-486F42B9E794}.Release|Any CPU.Build.0 = Release|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Debug|Any CPU.Build.0 = Debug|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Release|Any CPU.ActiveCfg = Release|Any CPU {8B58597B-058E-4D7A-B83E-5269BDABBE2C}.Release|Any CPU.Build.0 = Release|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4}.Release|Any CPU.Build.0 = Release|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6}.Release|Any CPU.Build.0 = Release|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Debug|Any CPU.Build.0 = Debug|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Release|Any CPU.ActiveCfg = Release|Any CPU {46171154-755A-4595-99AA-537D684BCA28}.Release|Any CPU.Build.0 = Release|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Debug|Any CPU.Build.0 = Debug|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9}.Release|Any CPU.Build.0 = Release|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Debug|Any CPU.Build.0 = Debug|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Release|Any CPU.ActiveCfg = Release|Any CPU {67012F41-94F9-48E6-9677-E3C56E42917F}.Release|Any CPU.Build.0 = Release|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Debug|Any CPU.Build.0 = Debug|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Release|Any CPU.ActiveCfg = Release|Any CPU {6689F268-CE30-4CEC-AAD5-2DF72C43623C}.Release|Any CPU.Build.0 = Release|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Debug|Any CPU.Build.0 = Debug|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Release|Any CPU.ActiveCfg = Release|Any CPU {696F611F-003B-477D-AFA0-4F15478C9D32}.Release|Any CPU.Build.0 = Release|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Debug|Any CPU.Build.0 = Debug|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Release|Any CPU.ActiveCfg = Release|Any CPU {1551D1E7-D515-4488-A889-5DEBB4950880}.Release|Any CPU.Build.0 = Release|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Debug|Any CPU.Build.0 = Debug|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Release|Any CPU.ActiveCfg = Release|Any CPU {8EFEA650-B9F6-498B-8865-A78103CCB590}.Release|Any CPU.Build.0 = Release|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Debug|Any CPU.Build.0 = Debug|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Release|Any CPU.ActiveCfg = Release|Any CPU {9444ACEF-784D-47B0-B317-F374782FA511}.Release|Any CPU.Build.0 = Release|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Debug|Any CPU.Build.0 = Debug|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB}.Release|Any CPU.Build.0 = Release|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Debug|Any CPU.Build.0 = Debug|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Release|Any CPU.ActiveCfg = Release|Any CPU {64418260-E75A-4556-BB7E-8BDAAFC2EFB9}.Release|Any CPU.Build.0 = Release|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Debug|Any CPU.Build.0 = Debug|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Release|Any CPU.ActiveCfg = Release|Any CPU {8FDC0A87-9005-4D5A-AB75-E55CEB575559}.Release|Any CPU.Build.0 = Release|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Debug|Any CPU.Build.0 = Debug|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Release|Any CPU.ActiveCfg = Release|Any CPU {5EE27A90-B023-42C9-AAF1-52B0424C5D0B}.Release|Any CPU.Build.0 = Release|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Debug|Any CPU.Build.0 = Debug|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Release|Any CPU.ActiveCfg = Release|Any CPU {A7EEC557-EB14-451C-9616-B7A61F4ECE69}.Release|Any CPU.Build.0 = Release|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Debug|Any CPU.Build.0 = Debug|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Release|Any CPU.ActiveCfg = Release|Any CPU {19B965DE-5100-4064-A580-159644F6980E}.Release|Any CPU.Build.0 = Release|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Debug|Any CPU.Build.0 = Debug|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Release|Any CPU.ActiveCfg = Release|Any CPU {60F8B554-5C53-4DE2-B868-A0BFEF4EF80E}.Release|Any CPU.Build.0 = Release|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Debug|Any CPU.Build.0 = Debug|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Release|Any CPU.ActiveCfg = Release|Any CPU {DE9B7DA2-35DD-46CC-B768-DAEE3C298660}.Release|Any CPU.Build.0 = Release|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {1B70CBF4-B592-4A9C-B7B3-AD1A087F4B9C}.Release|Any CPU.Build.0 = Release|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC0A9616-0B69-4A3B-ADC7-62FCA9207B98}.Release|Any CPU.Build.0 = Release|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F59DA1C-A502-440C-ABE8-240BDE2D0664}.Release|Any CPU.Build.0 = Release|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Debug|Any CPU.Build.0 = Debug|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Release|Any CPU.ActiveCfg = Release|Any CPU {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {2A03CB56-C3E2-4B65-92C0-004C9D78E2A4} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {ABFF04E1-91CE-4F31-AAA0-0C70E3DBB4A6} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {46171154-755A-4595-99AA-537D684BCA28} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {5CBAC55A-A209-45CA-9F57-D0BFFFE2B7F9} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {67012F41-94F9-48E6-9677-E3C56E42917F} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {6689F268-CE30-4CEC-AAD5-2DF72C43623C} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {696F611F-003B-477D-AFA0-4F15478C9D32} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {1551D1E7-D515-4488-A889-5DEBB4950880} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {8EFEA650-B9F6-498B-8865-A78103CCB590} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {9444ACEF-784D-47B0-B317-F374782FA511} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {1DEA6EB4-2288-4B6C-B5F4-1D102B8745BB} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {64418260-E75A-4556-BB7E-8BDAAFC2EFB9} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {5B7F1199-FB67-4AC1-A482-6BF1DA6CCDC5} = {3A92893D-7810-4D8B-80D8-E1E8D151FA73} {D2D979DC-1305-4C44-B21A-9EB3EEE95F7B} = {C0B451C4-EAFC-4942-B18E-49EC73DABABD} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {46CE14C6-8A1E-4634-A720-69B2E14873EE} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Antlr3.vsmdi EndGlobalSection EndGlobal diff --git a/Directory.Build.props b/Directory.Build.props index 540bdf9..9f241f4 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,46 +1,68 @@ <?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> + <PropertyGroup> + <!-- Default NuGet package properties. Additional items set in Directory.Build.targets. --> + <Company>Tunnel Vision Laboratories, LLC</Company> + <Copyright>Copyright © Sam Harwell 2011</Copyright> + <Authors>Sam Harwell, Terence Parr</Authors> + <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> + <PackageLicenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</PackageLicenseUrl> + <PackageProjectUrl>https://github.com/antlr/antlrcs</PackageProjectUrl> + <PackageIconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</PackageIconUrl> + <PackageReleaseNotes>https://github.com/antlr/antlrcs/releases/$(ANTLRInformationalVersion)</PackageReleaseNotes> + + <IncludeSymbols>true</IncludeSymbols> + <IncludeSource>true</IncludeSource> + <PackageOutputPath>$(MSBuildThisFileDirectory)build\prep\nuget\</PackageOutputPath> + </PropertyGroup> + <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta1" PrivateAssets="all" /> </ItemGroup> + <!-- Workaround to ensure generated ANTLR parsers are included in NuGet source package. --> + <Target Name="AntlrBeforeSourceFiles" + Condition="'$(BootstrapBuild)' != 'true'" + BeforeTargets="SourceFilesProjectOutputGroup" + DependsOnTargets="AntlrCompile;AntlrCompileAddFilesGenerated" /> + <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project> diff --git a/Directory.Build.targets b/Directory.Build.targets index 9447c47..4071059 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,13 +1,18 @@ <?xml version="1.0" encoding="utf-8"?> <Project> + <PropertyGroup> + <!-- Default NuGet package properties. Additional items set in Directory.Build.props. --> + <PackageVersion Condition="'$(PackageVersion)' == ''">$(InformationalVersion)</PackageVersion> + </PropertyGroup> + <ItemGroup> <None Condition="'$(SignAssembly)' == 'true'" Include="$(AssemblyOriginatorKeyFile)" Link="%(Filename)%(Extension)" /> </ItemGroup> <ItemGroup Condition="'$(GeneratePackageOnBuild)' == 'true'"> <!-- Workaround for https://github.com/NuGet/Home/issues/6582 --> <UpToDateCheckInput Condition="'$(NuspecFile)' != ''" Include="$(NuspecFile)" /> </ItemGroup> </Project> diff --git a/Runtime/Antlr3.Runtime/Antlr3.Runtime.csproj b/Runtime/Antlr3.Runtime/Antlr3.Runtime.csproj index b631e5c..87a85b0 100644 --- a/Runtime/Antlr3.Runtime/Antlr3.Runtime.csproj +++ b/Runtime/Antlr3.Runtime/Antlr3.Runtime.csproj @@ -1,62 +1,49 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>net20;net40-client;portable40-net40+sl5+win8+wp8+wpa81;netstandard1.1</TargetFrameworks> + <TargetFrameworks>net20;net40-client;portable-net40+sl5+win8+wp8+wpa81;netstandard1.1</TargetFrameworks> <RootNamespace>Antlr.Runtime</RootNamespace> - <Description>The C# port of ANTLR 3</Description> - <Company>Tunnel Vision Laboratories, LLC</Company> - <Copyright>Copyright © Sam Harwell 2011</Copyright> + <Description>The runtime library for parsers generated by the C# target of ANTLR 3. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2008 or newer.</Description> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> + <Title>ANTLR 3 Runtime</Title> + <PackageTags>antlr antlr3 parsing</PackageTags> + <GeneratePackageOnBuild>true</GeneratePackageOnBuild> - <IncludeSymbols>true</IncludeSymbols> - <NuspecFile>..\..\build\prep\Antlr3.Runtime.nuspec</NuspecFile> - <NuspecProperties>Configuration=$(Configuration);version=$(InformationalVersion);ANTLRVersion=$(InformationalVersion)</NuspecProperties> - <PackageOutputPath>..\..\build\prep\nuget\</PackageOutputPath> </PropertyGroup> + <ItemGroup> + <PackageReference Include="MSBuild.Sdk.Extras" Version="1.2.1" PrivateAssets="All" /> + </ItemGroup> + <Target Name="DisableCrazyPackageDeletion" BeforeTargets="Clean"> <PropertyGroup> <GeneratePackageValue>$(GeneratePackageOnBuild)</GeneratePackageValue> <GeneratePackageOnBuild>false</GeneratePackageOnBuild> </PropertyGroup> </Target> <Target Name="EnablePackageGeneration" Condition="'$(GeneratePackageValue)' != ''" BeforeTargets="Build"> <PropertyGroup> <GeneratePackageOnBuild>$(GeneratePackageValue)</GeneratePackageOnBuild> </PropertyGroup> </Target> <Choose> - <When Condition="'$(TargetFramework)' == 'net40-client'"> - <PropertyGroup> - <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <TargetFrameworkProfile>Client</TargetFrameworkProfile> - </PropertyGroup> - </When> <When Condition="'$(TargetFramework)' == 'netstandard1.1'"> <PropertyGroup> <DefineConstants>$(DefineConstants);PORTABLE;NETSTANDARD;NET45PLUS;NET40PLUS;NET35PLUS;NET20PLUS</DefineConstants> </PropertyGroup> </When> - <When Condition="'$(TargetFramework)' == 'portable40-net40+sl5+win8+wp8+wpa81'"> + <When Condition="'$(TargetFramework)' == 'portable-net40+sl5+win8+wp8+wpa81'"> <PropertyGroup> - <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier> - <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> - <TargetFrameworkProfile>Profile328</TargetFrameworkProfile> <DefineConstants>$(DefineConstants);PORTABLE;NET40;NET40PLUS;NET35PLUS;NET20PLUS</DefineConstants> </PropertyGroup> - - <ItemGroup> - <Reference Include="System" /> - <Reference Include="System.Core" /> - </ItemGroup> </When> </Choose> + <Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" /> </Project> \ No newline at end of file diff --git a/build/prep/Antlr3.Runtime.nuspec b/build/prep/Antlr3.Runtime.nuspec deleted file mode 100644 index 607514f..0000000 --- a/build/prep/Antlr3.Runtime.nuspec +++ /dev/null @@ -1,51 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> - <metadata> - <id>Antlr3.Runtime</id> - <version>0.0.0</version> - <authors>Sam Harwell, Terence Parr</authors> - <owners>Sam Harwell</owners> - <description>The runtime library for parsers generated by the C# target of ANTLR 3. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2008 or newer.</description> - <language>en-us</language> - <projectUrl>https://github.com/antlr/antlrcs</projectUrl> - <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> - <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> - <copyright>Copyright © Sam Harwell 2013</copyright> - <releaseNotes>https://github.com/antlr/antlrcs/releases/$version$</releaseNotes> - <requireLicenseAcceptance>true</requireLicenseAcceptance> - <tags>antlr antlr3 parsing</tags> - <title>ANTLR 3 Runtime</title> - <summary>The runtime library for parsers generated by the C# target of ANTLR 3.</summary> - <dependencies> - <group targetFramework="net20" /> - <group targetFramework="net40-client" /> - <group targetFramework="portable-net4+sl5+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1" /> - <group targetFramework="netstandard1.1"> - <dependency id="NETStandard.Library" version="1.6.0"/> - </group> - </dependencies> - </metadata> - <files> - <!-- Runtime Libraries --> - - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\net20\Antlr3.Runtime.dll" target="lib\net20"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\net20\Antlr3.Runtime.pdb" target="lib\net20"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\net20\Antlr3.Runtime.xml" target="lib\net20"/> - - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\net40-client\Antlr3.Runtime.dll" target="lib\net40-client"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\net40-client\Antlr3.Runtime.pdb" target="lib\net40-client"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\net40-client\Antlr3.Runtime.xml" target="lib\net40-client"/> - - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\portable40-net40+sl5+win8+wp8+wpa81\Antlr3.Runtime.dll" target="lib\portable-net4+sl5+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\portable40-net40+sl5+win8+wp8+wpa81\Antlr3.Runtime.pdb" target="lib\portable-net4+sl5+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\portable40-net40+sl5+win8+wp8+wpa81\Antlr3.Runtime.xml" target="lib\portable-net4+sl5+netcore45+wpa81+wp8+MonoAndroid1+MonoTouch1"/> - - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\netstandard1.1\Antlr3.Runtime.dll" target="lib\netstandard1.1"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\netstandard1.1\Antlr3.Runtime.pdb" target="lib\netstandard1.1"/> - <file src="..\..\Runtime\Antlr3.Runtime\bin\$Configuration$\netstandard1.1\Antlr3.Runtime.xml" target="lib\netstandard1.1"/> - - <!-- Source Code --> - - <file exclude="..\..\Runtime\Antlr3.Runtime\obj\**\*.cs" src="..\..\Runtime\Antlr3.Runtime\**\*.cs" target="src"/> - </files> -</package> diff --git a/build/prep/StringTemplate3.nuspec b/build/prep/StringTemplate3.nuspec deleted file mode 100644 index 54e43ce..0000000 --- a/build/prep/StringTemplate3.nuspec +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> - <metadata> - <id>StringTemplate3</id> - <version>0.0.0</version> - <authors>Sam Harwell, Terence Parr</authors> - <owners>Sam Harwell</owners> - <description>The C# port of StringTemplate 3.</description> - <language>en-us</language> - <projectUrl>https://github.com/antlr/antlrcs</projectUrl> - <licenseUrl>https://raw.githubusercontent.com/antlr/antlrcs/master/LICENSE.txt</licenseUrl> - <iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl> - <copyright>Copyright © Sam Harwell 2013</copyright> - <releaseNotes>https://github.com/antlr/antlrcs/releases/$ANTLRVersion$</releaseNotes> - <requireLicenseAcceptance>true</requireLicenseAcceptance> - <tags>stringtemplate st3 stringtemplate3 template</tags> - <title>StringTemplate 3</title> - <summary>The C# port of StringTemplate 3.</summary> - <dependencies> - <dependency id="Antlr3.Runtime" version="$ANTLRVersion$" /> - </dependencies> - </metadata> - <files> - <!-- Runtime Libraries --> - - <file src="..\..\Antlr3.StringTemplate\obj\$Configuration$\net35-client\Antlr3.StringTemplate.dll" target="lib\net35-client"/> - <file src="..\..\Antlr3.StringTemplate\obj\$Configuration$\net35-client\Antlr3.StringTemplate.pdb" target="lib\net35-client"/> - <file src="..\..\Antlr3.StringTemplate\obj\$Configuration$\net35-client\Antlr3.StringTemplate.xml" target="lib\net35-client"/> - - <!-- Source Code --> - - <file exclude="..\..\Antlr3.StringTemplate\obj\**\*.cs" src="..\..\Antlr3.StringTemplate\**\*.cs" target="src"/> - <file src="..\..\Antlr3.StringTemplate\obj\$Configuration$\net35-client\**\*.cs" target="src\obj\$Configuration$\net35-client"/> - <file src="..\..\Antlr3.StringTemplate\obj\$Configuration$\net35-client\**\*.tokens" target="src\obj\$Configuration$\net35-client"/> - </files> -</package>
antlr/antlrcs
d76e41c298a895b56f5304841fef87e7aeeef7a0
Mark Antlr3.CodeGenerator as a development dependency in its PackageReference
diff --git a/Directory.Build.props b/Directory.Build.props index 4a1f727..540bdf9 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,46 +1,46 @@ <?xml version="1.0" encoding="utf-8"?> <Project> <PropertyGroup> <ANTLRVersion>3.5.0.2</ANTLRVersion> <ANTLRFileVersion>3.5.2.0</ANTLRFileVersion> <ANTLRInformationalVersion>3.5.2-dev</ANTLRInformationalVersion> <STVersion>4.0.7.0</STVersion> <STFileVersion>4.0.9.0</STFileVersion> <STInformationalVersion>4.0.9-dev</STInformationalVersion> </PropertyGroup> <PropertyGroup> <SignAssembly Condition="'$(OS)' != 'Unix'">true</SignAssembly> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DebugSymbols>true</DebugSymbols> </PropertyGroup> <PropertyGroup> <GenerateDocumentationFile>True</GenerateDocumentationFile> <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Antlr3.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <PropertyGroup> <BootstrapBuild Condition="'$(BootstrapBuild)' == '' AND Exists('$(MSBuildThisFileDirectory)NuGet.config')">True</BootstrapBuild> </PropertyGroup> <ItemGroup Condition="'$(BootstrapBuild)' != 'true'"> - <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta1" /> + <PackageReference Include="Antlr3.CodeGenerator" Version="3.5.2-beta1" PrivateAssets="all" /> </ItemGroup> <ItemGroup Condition="'$(BootstrapBuild)' == 'true'"> - <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" /> + <PackageReference Include="Antlr3.CodeGenerator" Version="$(ANTLRInformationalVersion)" PrivateAssets="all" /> </ItemGroup> </Project>
antlr/antlrcs
76b6412ed133975eb6fd639c1e2b5fa19548129f
Add a reference to Microsoft.NET.Test.Sdk in test projects
diff --git a/Antlr3.Test/Antlr3.Test.csproj b/Antlr3.Test/Antlr3.Test.csproj index 1890e7d..850b99c 100644 --- a/Antlr3.Test/Antlr3.Test.csproj +++ b/Antlr3.Test/Antlr3.Test.csproj @@ -1,50 +1,51 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net45</TargetFrameworks> <RootNamespace>AntlrUnitTests</RootNamespace> <AssemblyName>AntlrUnitTests</AssemblyName> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> </PropertyGroup> <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" /> <PackageReference Include="MSTest.TestAdapter" Version="1.1.18" /> <PackageReference Include="MSTest.TestFramework" Version="1.1.18" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="body.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="method.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="page.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="row.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <EmbeddedResource Include="users_list.st"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> <ProjectReference Include="..\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj" /> <ProjectReference Include="..\Antlr3\Antlr3.csproj" /> <ProjectReference Include="..\Antlr4.StringTemplate\Antlr4.StringTemplate.csproj" /> <ProjectReference Include="..\Antlr3.Targets\Antlr3.Targets.Java\Antlr3.Targets.Java.csproj" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Runtime/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj b/Runtime/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj index 460dabe..0046be6 100644 --- a/Runtime/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj +++ b/Runtime/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj @@ -1,144 +1,145 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net45</TargetFrameworks> <EnableDefaultAntlrItems>false</EnableDefaultAntlrItems> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> </PropertyGroup> <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" /> <PackageReference Include="MSTest.TestAdapter" Version="1.1.18" /> <PackageReference Include="MSTest.TestFramework" Version="1.1.18" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj" /> <ProjectReference Include="..\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj" /> <ProjectReference Include="..\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj" /> <ProjectReference Include="..\Antlr3.Runtime\Antlr3.Runtime.csproj" /> </ItemGroup> <ItemGroup> <Antlr3 Include="SimpleExpression.g3" /> <Antlr3 Include="FastSimpleExpression.g3" /> <None Include="JavaCompat\Expr.g3" /> <Antlr3 Include="BuildOptions\DebugGrammar.g3"> <!--<GrammarOptions>-debug</GrammarOptions>--> </Antlr3> <Antlr3 Include="BuildOptions\DebugTreeGrammar.g3"> <!--<GrammarOptions>-debug</GrammarOptions>--> </Antlr3> <Antlr3 Include="StringTemplateOutput.g3" /> <Antlr3 Include="TestActionFeatures.g3" /> <Antlr3 Include="SemanticPredicateReduction.g3" /> <Antlr3 Include="Composition\Reduce.g3" /> <Antlr3 Include="Composition\Simplify.g3" /> <Antlr3 Include="Composition\VecMath.g3" /> <AntlrAbstractGrammar Include="Composition\VecMath_Lexer.g3"> <Generator>MSBuild:Compile</Generator> </AntlrAbstractGrammar> <AntlrAbstractGrammar Include="Composition\VecMath_Parser.g3"> <Generator>MSBuild:Compile</Generator> </AntlrAbstractGrammar> <Antlr3 Include="PreprocessorLexer.g3" /> <Antlr3 Include="SynpredTreeParser.g3" /> </ItemGroup> <ItemGroup> <Compile Remove="BuildOptions\DebugGrammarLexer.cs" /> <Compile Remove="BuildOptions\DebugGrammarParser.cs" /> <Compile Remove="BuildOptions\DebugTreeGrammar.cs" /> <Compile Remove="BuildOptions\ProfileGrammarLexer.cs" /> <Compile Remove="BuildOptions\ProfileGrammarParser.cs" /> <Compile Remove="BuildOptions\ProfileTreeGrammar.cs" /> </ItemGroup> <ItemGroup> <Compile Update="PreprocessorLexer.g3.cs"> <DependentUpon>PreprocessorLexer.g3</DependentUpon> </Compile> <Compile Update="SemanticPredicateReduction.g3.lexer.cs"> <DependentUpon>SemanticPredicateReduction.g3</DependentUpon> </Compile> <Compile Update="SemanticPredicateReduction.g3.parser.cs"> <DependentUpon>SemanticPredicateReduction.g3</DependentUpon> </Compile> <Compile Update="SimpleExpressionLexerHelper.cs"> <DependentUpon>SimpleExpression.g3</DependentUpon> </Compile> <Compile Update="SimpleExpressionParserHelper.cs"> <DependentUpon>SimpleExpression.g3</DependentUpon> </Compile> <Compile Update="FastSimpleExpressionLexerHelper.cs"> <DependentUpon>FastSimpleExpression.g3</DependentUpon> </Compile> <Compile Update="FastSimpleExpressionParserHelper.cs"> <DependentUpon>FastSimpleExpression.g3</DependentUpon> </Compile> <Compile Update="BuildOptions\DebugGrammarLexerHelper.cs"> <DependentUpon>DebugGrammar.g3</DependentUpon> </Compile> <Compile Update="BuildOptions\DebugGrammarParserHelper.cs"> <DependentUpon>DebugGrammar.g3</DependentUpon> </Compile> <Compile Update="BuildOptions\DebugTreeGrammarHelper.cs"> <DependentUpon>DebugTreeGrammar.g3</DependentUpon> </Compile> <Compile Update="StringTemplateOutput.g3.lexer.cs"> <DependentUpon>StringTemplateOutput.g3</DependentUpon> </Compile> <Compile Update="StringTemplateOutput.g3.parser.cs"> <DependentUpon>StringTemplateOutput.g3</DependentUpon> </Compile> <Compile Update="SynpredTreeParser.g3.cs"> <DependentUpon>SynpredTreeParser.g3</DependentUpon> </Compile> <Compile Update="TestActionFeatures.g3.lexer.cs"> <DependentUpon>TestActionFeatures.g3</DependentUpon> </Compile> <Compile Update="TestActionFeatures.g3.parser.cs"> <DependentUpon>TestActionFeatures.g3</DependentUpon> </Compile> <Compile Update="TestExpressionFeatures.g3.lexer.cs"> <DependentUpon>TestExpressionFeatures.g3</DependentUpon> </Compile> <Compile Update="TestExpressionFeatures.g3.parser.cs"> <DependentUpon>TestExpressionFeatures.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <None Include="BuildOptions\ProfileGrammar.g3"> <!--<GrammarOptions>-profile</GrammarOptions>--> </None> <None Include="BuildOptions\ProfileGrammarLexerHelper.cs"> <DependentUpon>ProfileGrammar.g3</DependentUpon> </None> <None Include="BuildOptions\ProfileGrammarParserHelper.cs"> <DependentUpon>ProfileGrammar.g3</DependentUpon> </None> <None Include="TestExpressionFeatures.g3" /> <Compile Remove="BuildOptions\ProfileGrammarLexerHelper.cs" /> <Compile Remove="BuildOptions\ProfileGrammarParserHelper.cs" /> </ItemGroup> <ItemGroup> <None Include="BuildOptions\ProfileTreeGrammar.g3"> <!--<GrammarOptions>-profile</GrammarOptions>--> </None> <None Include="BuildOptions\ProfileTreeGrammarHelper.cs"> <DependentUpon>ProfileTreeGrammar.g3</DependentUpon> </None> <Compile Remove="BuildOptions\ProfileTreeGrammarHelper.cs" /> </ItemGroup> </Project> \ No newline at end of file
antlr/antlrcs
6219b5d4a77d6f106932226de1a22f0917042252
Fix casing for the C++ target
diff --git a/Antlr3.Targets/Antlr3.Targets.Cpp/CPPTarget.cs b/Antlr3.Targets/Antlr3.Targets.Cpp/CppTarget.cs similarity index 99% rename from Antlr3.Targets/Antlr3.Targets.Cpp/CPPTarget.cs rename to Antlr3.Targets/Antlr3.Targets.Cpp/CppTarget.cs index a177bab..b6c3032 100644 --- a/Antlr3.Targets/Antlr3.Targets.Cpp/CPPTarget.cs +++ b/Antlr3.Targets/Antlr3.Targets.Cpp/CppTarget.cs @@ -1,413 +1,413 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr3.Targets { using System.Collections.Generic; using Aggregate = Antlr4.StringTemplate.Misc.Aggregate; using CodeGenerator = Antlr3.Codegen.CodeGenerator; using Grammar = Antlr3.Tool.Grammar; using GrammarType = Antlr3.Tool.GrammarType; using StringBuilder = System.Text.StringBuilder; using StringTemplate = Antlr4.StringTemplate.Template; using Target = Antlr3.Codegen.Target; - public class CPPTarget : Target + public class CppTarget : Target { List<string> strings = new List<string>(); protected override void GenRecognizerFile(AntlrTool tool, CodeGenerator generator, Grammar grammar, StringTemplate outputFileST) { // Before we write this, and cause it to generate its string, // we need to add all the string literals that we are going to match // outputFileST.Add("literals", strings); string fileName = generator.GetRecognizerFileName(grammar.name, grammar.type); generator.Write(outputFileST, fileName); } protected override void GenRecognizerHeaderFile(AntlrTool tool, CodeGenerator generator, Grammar grammar, StringTemplate headerFileST, string extName) { //Its better we remove the EOF Token, as it would have been defined everywhere in C. //we define it later as "EOF_TOKEN" instead of "EOF" IList<object> tokens = (IList<object>)headerFileST.GetAttribute("tokens"); for (int i = 0; i < tokens.Count; ++i) { bool can_break = false; object tok = tokens[i]; if (tok is Aggregate) { Aggregate atok = (Aggregate)tok; foreach (var pair in atok.Properties) { if (pair.Value.Equals("EOF")) { tokens.RemoveAt(i); can_break = true; break; } } } if (can_break) break; } // Pick up the file name we are generating. This method will return a // a file suffixed with .c, so we must substring and add the extName // to it as we cannot assign into strings in Java. // string fileName = generator.GetRecognizerFileName(grammar.name, grammar.type); fileName = fileName.Substring(0, fileName.Length - 4) + extName; generator.Write(headerFileST, fileName); } protected StringTemplate chooseWhereCyclicDFAsGo(AntlrTool tool, CodeGenerator generator, Grammar grammar, StringTemplate recognizerST, StringTemplate cyclicDFAST) { return recognizerST; } /** Is scope in @scope::name {action} valid for this kind of grammar? * Targets like C++ may want to allow new scopes like headerfile or * some such. The action names themselves are not policed at the * moment so targets can add template actions w/o having to recompile * ANTLR. */ public override bool IsValidActionScope(GrammarType grammarType, string scope) { switch (grammarType) { case GrammarType.Lexer: if (scope == "lexer") { return true; } if (scope == "header") { return true; } if (scope == "includes") { return true; } if (scope == "preincludes") { return true; } if (scope == "overrides") { return true; } if (scope == "namespace") { return true; } break; case GrammarType.Parser: if (scope == "parser") { return true; } if (scope == "header") { return true; } if (scope == "includes") { return true; } if (scope == "preincludes") { return true; } if (scope == "overrides") { return true; } if (scope == "namespace") { return true; } break; case GrammarType.Combined: if (scope == "parser") { return true; } if (scope == "lexer") { return true; } if (scope == "header") { return true; } if (scope == "includes") { return true; } if (scope == "preincludes") { return true; } if (scope == "overrides") { return true; } if (scope == "namespace") { return true; } break; case GrammarType.TreeParser: if (scope == "treeparser") { return true; } if (scope == "header") { return true; } if (scope == "includes") { return true; } if (scope == "preincludes") { return true; } if (scope == "overrides") { return true; } if (scope == "namespace") { return true; } break; } return false; } public override string GetTargetCharLiteralFromANTLRCharLiteral( CodeGenerator generator, string literal) { if (literal.StartsWith("'\\u")) { literal = "0x" + literal.Substring(3, 4); } else { int c = literal[1]; if (c < 32 || c > 127) { literal = "0x" + c.ToString("X"); } } return literal; } /** Convert from an ANTLR string literal found in a grammar file to * an equivalent string literal in the C target. * Because we must support Unicode character sets and have chosen * to have the lexer match UTF32 characters, then we must encode * string matches to use 32 bit character arrays. Here then we * must produce the C array and cater for the case where the * lexer has been encoded with a string such as 'xyz\n', */ public override string GetTargetStringLiteralFromANTLRStringLiteral( CodeGenerator generator, string literal) { int index; string bytes; StringBuilder buf = new StringBuilder(); buf.Append("{ "); // We need ot lose any escaped characters of the form \x and just // replace them with their actual values as well as lose the surrounding // quote marks. // for (int i = 1; i < literal.Length - 1; i++) { buf.Append("0x"); if (literal[i] == '\\') { i++; // Assume that there is a next character, this will just yield // invalid strings if not, which is what the input would be of course - invalid switch (literal[i]) { case 'u': case 'U': buf.Append(literal.Substring(i + 1, 4)); // Already a hex string i = i + 5; // Move to next string/char/escape break; case 'n': case 'N': buf.Append("0A"); break; case 'r': case 'R': buf.Append("0D"); break; case 't': case 'T': buf.Append("09"); break; case 'b': case 'B': buf.Append("08"); break; case 'f': case 'F': buf.Append("0C"); break; default: // Anything else is what it is! // buf.Append(((int)literal[i]).ToString("X")); break; } } else { buf.Append(((int)literal[i]).ToString("X")); } buf.Append(", "); } buf.Append(" antlr3::ANTLR_STRING_TERMINATOR}"); bytes = buf.ToString(); index = strings.IndexOf(bytes); if (index == -1) { strings.Add(bytes); index = strings.IndexOf(bytes); } string strref = "lit_" + (index + 1); return strref; } /** * Overrides the standard grammar analysis so we can prepare the analyser * a little differently from the other targets. * * In particular we want to influence the way the code generator makes assumptions about * switchs vs ifs, vs table driven DFAs. In general, C code should be generated that * has the minimum use of tables, and tha meximum use of large switch statements. This * allows the optimizers to generate very efficient code, it can reduce object code size * by about 30% and give about a 20% performance improvement over not doing this. Hence, * for the C target only, we change the defaults here, but only if they are still set to the * defaults. * * @param generator An instance of the generic code generator class. * @param grammar The grammar that we are currently analyzing */ protected override void PerformGrammarAnalysis(CodeGenerator generator, Grammar grammar) { // Check to see if the maximum inline DFA states is still set to // the default size. If it is then whack it all the way up to the maximum that // we can sensibly get away with. // if (CodeGenerator.MaxAcyclicDfaStatesInline == CodeGenerator.DefaultMaxAcyclicDfaStatesInline) { CodeGenerator.MaxAcyclicDfaStatesInline = 65535; } // Check to see if the maximum switch size is still set to the default // and bring it up much higher if it is. Modern C compilers can handle // much bigger switch statements than say Java can and if anyone finds a compiler // that cannot deal with such big switches, all the need do is generate the // code with a reduced -Xmaxswitchcaselabels nnn // if (CodeGenerator.MaxSwitchCaseLabels == CodeGenerator.DefaultMaxSwitchCaseLabels) { CodeGenerator.MaxSwitchCaseLabels = 3000; } // Check to see if the number of transitions considered a miminum for using // a switch is still at the default. Because a switch is still generally faster than // an if even with small sets, and given that the optimizer will do the best thing with it // anyway, then we simply want to generate a switch for any number of states. // if (CodeGenerator.MinSwitchAlts == CodeGenerator.DefaultMinSwitchAlts) { CodeGenerator.MinSwitchAlts = 1; } // Now we allow the superclass implementation to do whatever it feels it // must do. // base.PerformGrammarAnalysis(generator, grammar); } } } diff --git a/Antlr3/Antlr3.csproj b/Antlr3/Antlr3.csproj index 43f575b..e1b6026 100644 --- a/Antlr3/Antlr3.csproj +++ b/Antlr3/Antlr3.csproj @@ -1,384 +1,384 @@ <?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>net35-client;net40-client;netstandard2.0</TargetFrameworks> <OutputType>Exe</OutputType> <Description>The C# port of ANTLR 3</Description> <Company>Tunnel Vision Laboratories, LLC</Company> <Copyright>Copyright © Sam Harwell 2011</Copyright> <Version>$(ANTLRVersion)</Version> <FileVersion>$(ANTLRFileVersion)</FileVersion> <InformationalVersion>$(ANTLRInformationalVersion)</InformationalVersion> <OutputPath>..\bin\$(Configuration)\</OutputPath> </PropertyGroup> <Choose> <When Condition="'$(TargetFramework)' == 'net35-client'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'net40-client'"> <PropertyGroup> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> </PropertyGroup> </When> <When Condition="'$(TargetFramework)' == 'netstandard2.0'"> <PropertyGroup> <DefineConstants>$(DefineConstants);NETSTANDARD</DefineConstants> </PropertyGroup> </When> </Choose> <ItemGroup> <Compile Update="Grammars\LeftRecursiveRuleWalker.g3.cs"> <DependentUpon>LeftRecursiveRuleWalker.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\ActionTranslatorHelper.cs"> <DependentUpon>ActionTranslator.g3</DependentUpon> </Compile> <Compile Update="Grammars\CodeGenTreeWalkerHelper.cs"> <DependentUpon>CodeGenTreeWalker.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\ActionAnalysisLexerHelper.cs"> <DependentUpon>ActionAnalysisLexer.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\ANTLRParserHelper.cs"> <DependentUpon>ANTLR.g3</DependentUpon> </Compile> <Compile Update="Grammars\ANTLRLexerHelper.cs"> <DependentUpon>ANTLR.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\ANTLRTreePrinterHelper.cs"> <DependentUpon>ANTLRTreePrinter.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\AssignTokenTypesWalkerHelper.cs"> <DependentUpon>AssignTokenTypesWalker.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\DefineGrammarItemsWalkerHelper.cs"> <DependentUpon>DefineGrammarItemsWalker.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Compile Update="Grammars\TreeToNFAConverterHelper.cs"> <DependentUpon>TreeToNFAConverter.g3</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ActionScript\ActionScript.stg"> <Link>Codegen\Templates\ActionScript\ActionScript.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ActionScript\AST.stg"> <Link>Codegen\Templates\ActionScript\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ActionScript\ASTParser.stg"> <Link>Codegen\Templates\ActionScript\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ActionScript\ASTTreeParser.stg"> <Link>Codegen\Templates\ActionScript\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\AST.stg"> <Link>Codegen\Templates\CSharp3\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\ASTDbg.stg"> <Link>Codegen\Templates\CSharp3\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\ASTParser.stg"> <Link>Codegen\Templates\CSharp3\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\ASTTreeParser.stg"> <Link>Codegen\Templates\CSharp3\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\CSharp3.stg"> <Link>Codegen\Templates\CSharp3\CSharp3.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\Dbg.stg"> <Link>Codegen\Templates\CSharp3\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp3\ST.stg"> <Link>Codegen\Templates\CSharp3\ST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\AST.stg"> <Link>Codegen\Templates\CSharp2\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\ASTDbg.stg"> <Link>Codegen\Templates\CSharp2\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\ASTParser.stg"> <Link>Codegen\Templates\CSharp2\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\ASTTreeParser.stg"> <Link>Codegen\Templates\CSharp2\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\CSharp2.stg"> <Link>Codegen\Templates\CSharp2\CSharp2.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\Dbg.stg"> <Link>Codegen\Templates\CSharp2\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CSharp2\ST.stg"> <Link>Codegen\Templates\CSharp2\ST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\C\AST.stg"> <Link>Codegen\Templates\C\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\C\ASTDbg.stg"> <Link>Codegen\Templates\C\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\C\ASTParser.stg"> <Link>Codegen\Templates\C\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\C\ASTTreeParser.stg"> <Link>Codegen\Templates\C\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\C\C.stg"> <Link>Codegen\Templates\C\C.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\C\Dbg.stg"> <Link>Codegen\Templates\C\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> - <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\CPP\CPP.stg"> - <Link>Codegen\Templates\CPP\CPP.stg</Link> + <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Cpp\Cpp.stg"> + <Link>Codegen\Templates\Cpp\Cpp.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Delphi\AST.stg"> <Link>Codegen\Templates\Delphi\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Delphi\ASTParser.stg"> <Link>Codegen\Templates\Delphi\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Delphi\ASTTreeParser.stg"> <Link>Codegen\Templates\Delphi\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Delphi\Delphi.stg"> <Link>Codegen\Templates\Delphi\Delphi.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\JavaScript\AST.stg"> <Link>Codegen\Templates\JavaScript\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\JavaScript\ASTParser.stg"> <Link>Codegen\Templates\JavaScript\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\JavaScript\ASTTreeParser.stg"> <Link>Codegen\Templates\JavaScript\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\JavaScript\JavaScript.stg"> <Link>Codegen\Templates\JavaScript\JavaScript.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\AST.stg"> <Link>Codegen\Templates\Java\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\ASTDbg.stg"> <Link>Codegen\Templates\Java\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\ASTParser.stg"> <Link>Codegen\Templates\Java\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\ASTTreeParser.stg"> <Link>Codegen\Templates\Java\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\Dbg.stg"> <Link>Codegen\Templates\Java\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\Java.stg"> <Link>Codegen\Templates\Java\Java.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Java\ST.stg"> <Link>Codegen\Templates\Java\ST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ObjC\AST.stg"> <Link>Codegen\Templates\ObjC\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ObjC\ASTDbg.stg"> <Link>Codegen\Templates\ObjC\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ObjC\ASTParser.stg"> <Link>Codegen\Templates\ObjC\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ObjC\ASTTreeParser.stg"> <Link>Codegen\Templates\ObjC\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ObjC\Dbg.stg"> <Link>Codegen\Templates\ObjC\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\ObjC\ObjC.stg"> <Link>Codegen\Templates\ObjC\ObjC.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Perl5\ASTTreeParser.stg"> <Link>Codegen\Templates\Perl5\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Perl5\Perl5.stg"> <Link>Codegen\Templates\Perl5\Perl5.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\AST.stg"> <Link>Codegen\Templates\Python\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\ASTDbg.stg"> <Link>Codegen\Templates\Python\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\ASTParser.stg"> <Link>Codegen\Templates\Python\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\ASTTreeParser.stg"> <Link>Codegen\Templates\Python\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\Dbg.stg"> <Link>Codegen\Templates\Python\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\Python.stg"> <Link>Codegen\Templates\Python\Python.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Python\ST.stg"> <Link>Codegen\Templates\Python\ST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\Ruby.stg"> <Link>Codegen\Templates\Ruby\Ruby.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\tool\templates\depend.stg"> <Link>Tool\Templates\depend.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <EmbeddedResource Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\tool\templates\messages\formats\antlr.stg"> <Link>Tool\Templates\messages\formats\antlr.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\tool\templates\messages\formats\gnu.stg"> <Link>Tool\Templates\messages\formats\gnu.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\tool\templates\messages\formats\vs2005.stg"> <Link>Tool\Templates\messages\formats\vs2005.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <EmbeddedResource Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\tool\templates\messages\languages\en.stg"> <Link>Tool\Templates\messages\languages\en.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\tool\templates\dot\dot.stg"> <Link>Tool\Templates\dot\dot.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\AST.stg"> <Link>Codegen\Templates\Ruby\AST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\ASTDbg.stg"> <Link>Codegen\Templates\Ruby\ASTDbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\ASTParser.stg"> <Link>Codegen\Templates\Ruby\ASTParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\ASTTreeParser.stg"> <Link>Codegen\Templates\Ruby\ASTTreeParser.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\Dbg.stg"> <Link>Codegen\Templates\Ruby\Dbg.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\Ruby\ST.stg"> <Link>Codegen\Templates\Ruby\ST.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <EmbeddedResource Include="..\Reference\antlr3\tool\src\main\resources\org\antlr\codegen\templates\LeftRecursiveRules.stg"> <Link>Codegen\Templates\LeftRecursiveRules.stg</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> <None Include="app.config" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Runtime\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj" /> <ProjectReference Include="..\Runtime\Antlr3.Runtime\Antlr3.Runtime.csproj" /> <ProjectReference Condition="'$(TargetFramework)' != 'netstandard2.0'" Include="..\Antlr4.StringTemplate.Visualizer\Antlr4.StringTemplate.Visualizer.csproj" /> <ProjectReference Include="..\Antlr4.StringTemplate\Antlr4.StringTemplate.csproj" /> </ItemGroup> </Project> \ No newline at end of file
antlr/antlrcs
50bcff1785c61d91fd05f5784cc15bddb6142e4c
Skip very slow tests on CI
diff --git a/Antlr3.Test/TestAutoAST.cs b/Antlr3.Test/TestAutoAST.cs index cd6ac0a..24f4a84 100644 --- a/Antlr3.Test/TestAutoAST.cs +++ b/Antlr3.Test/TestAutoAST.cs @@ -1,549 +1,550 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestAutoAST : BaseTest { protected bool debug = false; [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenList() /*throws Exception*/ { string grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenListInSingleAltBlock() /*throws Exception*/ { string grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : (ID INT) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleRootAtOuterLevel() /*throws Exception*/ { string grammar = "grammar foo;\n" + "options {output=AST;}\n" + "a : ID^ INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "abc 34", debug ); Assert.AreEqual( "(abc 34)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleRootAtOuterLevelReverse() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT ID^ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34 abc", debug ); Assert.AreEqual( "(abc 34)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestBang() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT! ID! INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34 dag 4532", debug ); Assert.AreEqual( "abc 4532" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalThenRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ( ID INT )? ID^ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 1 b", debug ); Assert.AreEqual( "(b a 1)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabeledStringRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : v='void'^ ID ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void foo;", debug ); Assert.AreEqual( "(void foo ;)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcard() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : v='void'^ . ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void foo;", debug ); Assert.AreEqual( "(void foo ;)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : v='void' .^ ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void foo;", debug ); Assert.AreEqual( "(foo void ;)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardRootWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : v='void' x=.^ ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void foo;", debug ); Assert.AreEqual( "(foo void ;)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardRootWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : v='void' x=.^ ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void foo;", debug ); Assert.AreEqual( "(foo void ;)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardBangWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : v='void' x=.! ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void foo;", debug ); Assert.AreEqual( "void ;" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRootRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID^ INT^ ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 34 c", debug ); Assert.AreEqual( "(34 a c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRootRoot2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT^ ID^ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 34 c", debug ); Assert.AreEqual( "(c (34 a))" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRootThenRootInLoop() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID^ (INT '*'^ ID)+ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 34 * b 9 * c", debug ); Assert.AreEqual( "(* (* (a 34) b 9) c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNestedSubrule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'void' (({;}ID|INT) ID | 'null' ) ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void a b;", debug ); Assert.AreEqual( "void a b ;" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestInvokeRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : type ID ;\n" + "type : {;}'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "int a", debug ); Assert.AreEqual( "int a" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestInvokeRuleAsRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : type^ ID ;\n" + "type : {;}'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "int a", debug ); Assert.AreEqual( "(int a)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestInvokeRuleAsRootWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=type^ ID ;\n" + "type : {;}'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "int a", debug ); Assert.AreEqual( "(int a)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestInvokeRuleAsRootWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x+=type^ ID ;\n" + "type : {;}'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "int a", debug ); Assert.AreEqual( "(int a)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleRootInLoop() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ('+'^ ID)* ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a+b+c+d", debug ); Assert.AreEqual( "(+ (+ (+ a b) c) d)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleInvocationRuleRootInLoop() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID (op^ ID)* ;\n" + "op : {;}'+' | '-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a+b+c-d", debug ); Assert.AreEqual( "(- (+ (+ a b) c) d)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTailRecursion() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "s : a ;\n" + "a : atom ('exp'^ a)? ;\n" + "atom : INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "3 exp 4 exp 5", debug ); Assert.AreEqual( "(exp 3 (exp 4 5))" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID|INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSetRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ('+' | '-')^ ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "+abc", debug ); Assert.AreEqual( "(+ abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSetRootWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=('+' | '-')^ ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "+abc", debug ); Assert.AreEqual( "(+ abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSetAsRuleRootInLoop() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID (('+'|'-')^ ID)* ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a+b-c", debug ); Assert.AreEqual( "(- (+ a b) c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ~ID '+' INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34+2", debug ); Assert.AreEqual( "34 + 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSetWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=~ID '+' INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34+2", debug ); Assert.AreEqual( "34 + 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSetWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=~ID '+' INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34+2", debug ); Assert.AreEqual( "34 + 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSetRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ~'+'^ INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34 55", debug ); Assert.AreEqual( "(34 55)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSetRootWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ~'+'^ INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34 55", debug ); Assert.AreEqual( "(34 55)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSetRootWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ~'+'^ INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "34 55", debug ); Assert.AreEqual( "(34 55)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotSetRuleRootInLoop() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT (~INT^ INT)* ;\n" + "blort : '+' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "3+4+5", debug ); Assert.AreEqual( "(+ (+ 3 4) 5)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenLabelReuse() /*throws Exception*/ { // check for compilation problem due to multiple defines string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : id=ID id=ID {System.out.print(\"2nd id=\"+$id.text+';');} ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a b", debug ); Assert.AreEqual( "2nd id=b;a b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenLabelReuse2() /*throws Exception*/ { // check for compilation problem due to multiple defines string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : id=ID id=ID^ {System.out.print(\"2nd id=\"+$id.text+';');} ;\n" + "ID : 'a'..'z'+ ;\n" + diff --git a/Antlr3.Test/TestCategories.cs b/Antlr3.Test/TestCategories.cs index af31da6..aec557d 100644 --- a/Antlr3.Test/TestCategories.cs +++ b/Antlr3.Test/TestCategories.cs @@ -1,10 +1,12 @@ namespace AntlrUnitTests { internal static class TestCategories { public const string Antlr3 = "ANTLR 3"; public const string ST3 = "ST3"; public const string Antlr3LeftRecursion = Antlr3 + " (Left Recursion)"; + + public const string SkipOnCI = nameof(SkipOnCI); } } diff --git a/Antlr3.Test/TestCompositeGrammars.cs b/Antlr3.Test/TestCompositeGrammars.cs index 0651113..6db3a4a 100644 --- a/Antlr3.Test/TestCompositeGrammars.cs +++ b/Antlr3.Test/TestCompositeGrammars.cs @@ -1,554 +1,555 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Antlr.Runtime.JavaExtensions; using Antlr3.Tool; using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using Regex = System.Text.RegularExpressions.Regex; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestCompositeGrammars : BaseTest { protected bool debug = false; [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardStillWorks() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string grammar = "parser grammar S;\n" + "a : B . C ;\n"; // not qualified ID Grammar g = new Grammar( grammar ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorInvokesDelegateRule() /*throws Exception*/ { string slave = "parser grammar S;\n" + "a : B {System.out.println(\"S.a\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : a ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "s", "b", debug ); Assert.AreEqual( "S.a" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorInvokesDelegateRuleWithArgs() /*throws Exception*/ { // must generate something like: // public int a(int x) throws RecognitionException { return gS.a(x); } // in M. string slave = "parser grammar S;\n" + "a[int x] returns [int y] : B {System.out.print(\"S.a\"); $y=1000;} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : label=a[3] {System.out.println($label.y);} ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "s", "b", debug ); Assert.AreEqual( "S.a1000" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorInvokesDelegateRuleWithReturnStruct() /*throws Exception*/ { // must generate something like: // public int a(int x) throws RecognitionException { return gS.a(x); } // in M. string slave = "parser grammar S;\n" + "a : B {System.out.print(\"S.a\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : a {System.out.println($a.text);} ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "s", "b", debug ); Assert.AreEqual( "S.ab" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorAccessesDelegateMembers() /*throws Exception*/ { string slave = "parser grammar S;\n" + "@members {\n" + " public void foo() {System.out.println(\"foo\");}\n" + "}\n" + "a : B ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + // uses no rules from the import "import S;\n" + "s : 'b' {gS.foo();} ;\n" + // gS is import pointer "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "s", "b", debug ); Assert.AreEqual( "foo" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorInvokesFirstVersionOfDelegateRule() /*throws Exception*/ { string slave = "parser grammar S;\n" + "a : b {System.out.println(\"S.a\");} ;\n" + "b : B ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string slave2 = "parser grammar T;\n" + "a : B {System.out.println(\"T.a\");} ;\n"; // hidden by S.a writeFile( tmpdir, "T.g", slave2 ); string master = "grammar M;\n" + "import S,T;\n" + "s : a ;\n" + "B : 'b' ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "s", "b", debug ); Assert.AreEqual( "S.a" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatesSeeSameTokenType() /*throws Exception*/ { string slave = "parser grammar S;\n" + // A, B, C token type order "tokens { A; B; C; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string slave2 = "parser grammar T;\n" + "tokens { C; B; A; }\n" + // reverse order "y : A {System.out.println(\"T.y\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "T.g", slave2 ); // The lexer will create rules to match letters a, b, c. // The associated token types A, B, C must have the same value // and all import'd parsers. Since ANTLR regenerates all imports // for use with the delegator M, it can generate the same token type // mapping in each parser: // public static final int C=6; // public static final int EOF=-1; // public static final int B=5; // public static final int WS=7; // public static final int A=4; string master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + // matches AA, which should be "aa" "B : 'b' ;\n" + // another order: B, A, C "A : 'a' ;\n" + "C : 'c' ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "s", "aa", debug ); Assert.AreEqual( "S.x" + NewLine + "T.y" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatesSeeSameTokenType2() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + // A, B, C token type order "tokens { A; B; C; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string slave2 = "parser grammar T;\n" + "tokens { C; B; A; }\n" + // reverse order "y : A {System.out.println(\"T.y\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "T.g", slave2 ); string master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + // matches AA, which should be "aa" "B : 'b' ;\n" + // another order: B, A, C "A : 'a' ;\n" + "C : 'c' ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); string expectedTokenIDToTypeMap = "[A=4, B=5, C=6, WS=7]"; string expectedStringLiteralToTypeMap = "{}"; string expectedTypeToTokenList = "[A, B, C, WS]"; Assert.AreEqual( expectedTokenIDToTypeMap, realElements( g.composite.TokenIDToTypeMap ).ToElementString() ); Assert.AreEqual( expectedStringLiteralToTypeMap, g.composite.StringLiteralToTypeMap.ToElementString() ); Assert.AreEqual( expectedTypeToTokenList, realElements( g.composite.TypeToTokenList ).ToElementString() ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCombinedImportsCombined() /*throws Exception*/ { //Assert.Inconclusive( "May be failing on just my port..." ); // for now, we don't allow combined to import combined ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "grammar S;\n" + // A, B, C token type order "tokens { A; B; C; }\n" + "x : 'x' INT {System.out.println(\"S.x\");} ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : x INT ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); Assert.AreEqual(1, equeue.errors.Count, "unexpected errors: " + equeue); string expectedError = "error(161): " + Regex.Replace(tmpdir.ToString(), "\\-[0-9]+", "") + "/M.g:2:8: combined grammar M cannot import combined grammar S"; Assert.AreEqual(expectedError, Regex.Replace(equeue.errors[0].ToString(), "\\-[0-9]+", ""), "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSameStringTwoNames() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string slave2 = "parser grammar T;\n" + "tokens { X='a'; }\n" + "y : X {System.out.println(\"T.y\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "T.g", slave2 ); string master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); string expectedTokenIDToTypeMap = "[A=4, WS=5, X=6]"; string expectedStringLiteralToTypeMap = "{'a'=4}"; string expectedTypeToTokenList = "[A, WS, X]"; Assert.AreEqual( expectedTokenIDToTypeMap, realElements( g.composite.TokenIDToTypeMap ).ToElementString() ); Assert.AreEqual( expectedStringLiteralToTypeMap, g.composite.StringLiteralToTypeMap.ToElementString() ); Assert.AreEqual( expectedTypeToTokenList, realElements( g.composite.TypeToTokenList ).ToElementString() ); object expectedArg = "X='a'"; object expectedArg2 = "A"; int expectedMsgID = ErrorManager.MSG_TOKEN_ALIAS_CONFLICT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkGrammarSemanticsError( equeue, expectedMessage ); Assert.AreEqual(1, equeue.errors.Count, "unexpected errors: " + equeue); string expectedError = "error(158): T.g:2:10: cannot alias X='a'; string already assigned to A"; Assert.AreEqual( expectedError, equeue.errors[0].ToString() ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSameNameTwoStrings() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string slave2 = "parser grammar T;\n" + "tokens { A='x'; }\n" + "y : A {System.out.println(\"T.y\");} ;\n"; writeFile( tmpdir, "T.g", slave2 ); string master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); string expectedTokenIDToTypeMap = "[A=4, T__6=6, WS=5]"; string expectedStringLiteralToTypeMap = "{'a'=4, 'x'=6}"; string expectedTypeToTokenList = "[A, WS, T__6]"; Assert.AreEqual( expectedTokenIDToTypeMap, realElements( g.composite.TokenIDToTypeMap ).ToElementString() ); Assert.AreEqual( expectedStringLiteralToTypeMap, sortMapToString( g.composite.StringLiteralToTypeMap ) ); Assert.AreEqual( expectedTypeToTokenList, realElements( g.composite.TypeToTokenList ).ToElementString() ); object expectedArg = "A='x'"; object expectedArg2 = "'a'"; int expectedMsgID = ErrorManager.MSG_TOKEN_ALIAS_REASSIGNMENT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg, expectedArg2 ); checkGrammarSemanticsError( equeue, expectedMessage ); Assert.AreEqual(1, equeue.errors.Count, "unexpected errors: " + equeue); string expectedError = "error(159): T.g:2:10: cannot alias A='x'; token name already assigned to 'a'"; Assert.AreEqual( expectedError, equeue.errors[0].ToString() ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImportedTokenVocabIgnoredWithWarning() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + "options {tokenVocab=whatever;}\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); object expectedArg = "S"; int expectedMsgID = ErrorManager.MSG_TOKEN_VOCAB_IN_DELEGATE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage( expectedMsgID, g, null, expectedArg ); checkGrammarSemanticsWarning( equeue, expectedMessage ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); Assert.AreEqual(1, equeue.warnings.Count, "unexpected errors: " + equeue); string expectedError = "warning(160): S.g:2:10: tokenVocab option ignored in imported grammar S"; Assert.AreEqual( expectedError, equeue.warnings[0].ToString() ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImportedTokenVocabWorksInRoot() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string tokens = "A=99\n"; writeFile( tmpdir, "Test.tokens", tokens ); string master = "grammar M;\n" + "options {tokenVocab=Test;}\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); string expectedTokenIDToTypeMap = "[A=99, WS=101]"; string expectedStringLiteralToTypeMap = "{'a'=100}"; string expectedTypeToTokenList = "[A, 'a', WS]"; Assert.AreEqual( expectedTokenIDToTypeMap, realElements( g.composite.TokenIDToTypeMap ).ToElementString() ); Assert.AreEqual( expectedStringLiteralToTypeMap, g.composite.StringLiteralToTypeMap.ToElementString() ); Assert.AreEqual( expectedTypeToTokenList, realElements( g.composite.TypeToTokenList ).ToElementString() ); Assert.AreEqual(0, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSyntaxErrorsInImportsNotThrownOut() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + "options {toke\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); // whole bunch of errors from bad S.g file Assert.AreEqual(5, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSyntaxErrorsInImportsNotThrownOut2() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string slave = "parser grammar S;\n" + ": A {System.out.println(\"S.x\");} ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; writeFile( tmpdir, "M.g", master ); AntlrTool antlr = newTool( new string[] { "-lib", tmpdir } ); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar( antlr, tmpdir + "/M.g", composite ); composite.SetDelegationRoot( g ); g.ParseAndBuildAST(); g.composite.AssignTokenTypes(); // whole bunch of errors from bad S.g file Assert.AreEqual(3, equeue.errors.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorRuleOverridesDelegate() /*throws Exception*/ { string slave = "parser grammar S;\n" + "a : b {System.out.println(\"S.a\");} ;\n" + "b : B ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "S.g", slave ); string master = "grammar M;\n" + "import S;\n" + "b : 'b'|'c' ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; string found = execParser( "M.g", master, "MParser", "MLexer", "a", "c", debug ); Assert.AreEqual( "S.a" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelegatorRuleOverridesLookaheadInDelegate() /*throws Exception*/ { string slave = "parser grammar JavaDecl;\n" + "type : 'int' ;\n" + "decl : type ID ';'\n" + " | type ID init ';' {System.out.println(\"JavaDecl: \"+$decl.text);}\n" + " ;\n" + "init : '=' INT ;\n"; mkdir( tmpdir ); writeFile( tmpdir, "JavaDecl.g", slave ); string master = "grammar Java;\n" + "import JavaDecl;\n" + "prog : decl ;\n" + "type : 'int' | 'float' ;\n" + "\n" + diff --git a/Antlr3.Test/TestHeteroAST.cs b/Antlr3.Test/TestHeteroAST.cs index 18260a6..92b3128 100644 --- a/Antlr3.Test/TestHeteroAST.cs +++ b/Antlr3.Test/TestHeteroAST.cs @@ -1,550 +1,551 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; /** Test hetero trees in parsers and tree parsers */ [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestHeteroAST : BaseTest { protected bool debug = false; // PARSERS -- AUTO AST [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenCommonTree() { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID<node=CommonTree> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "a", debug); Assert.AreEqual("a" + NewLine, found); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenWithQualifiedType() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID<node=TParser.V> ;\n" + // TParser.V is qualified name "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : x=ID<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : x+=ID<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID<node=V>^ ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenRootWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : x+=ID<node=V>^ ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestString() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : 'begin'<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "begin", debug ); Assert.AreEqual( "begin<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestStringRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : 'begin'<node=V>^ ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "begin", debug ); Assert.AreEqual( "begin<V>" + NewLine, found ); } // PARSERS -- REWRITE AST [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID -> ID<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteTokenWithArgs() /*throws Exception*/ { // arg to ID<V>[42,19,30] means you're constructing node not associated with ID // so must pass in token manually string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {\n" + "static class V extends CommonTree {\n" + " public int x,y,z;\n" + " public V(int ttype, int x, int y, int z) { this.x=x; this.y=y; this.z=z; token=new CommonToken(ttype,\"\"); }\n" + " public V(int ttype, Token t, int x) { token=t; this.x=x;}\n" + " public String toString() { return (token!=null?token.getText():\"\")+\"<V>;\"+x+y+z;}\n" + "}\n" + "}\n" + "a : ID -> ID<node=V>[42,19,30] ID<node=V>[$ID,99] ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "<V>;421930 a<V>;9900" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteTokenRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID INT -> ^(ID<node=V> INT) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 2", debug ); Assert.AreEqual( "(a<V> 2)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteString() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : 'begin' -> 'begin'<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "begin", debug ); Assert.AreEqual( "begin<V>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteStringRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : 'begin' INT -> ^('begin'<node=V> INT) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "begin 2", debug ); Assert.AreEqual( "(begin<V> 2)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteRuleResults() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {LIST;}\n" + "@members {\n" + "static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "static class W extends CommonTree {\n" + " public W(int tokenType, String txt) { super(new CommonToken(tokenType,txt)); }\n" + " public W(Token t) { token=t;}\n" + " public String toString() { return token.getText()+\"<W>\";}\n" + "}\n" + "}\n" + "a : id (',' id)* -> ^(LIST<node=W>[\"LIST\"] id+);\n" + "id : ID -> ID<node=V>;\n" + "ID : 'a'..'z'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a,b,c", debug ); Assert.AreEqual( "(LIST<W> a<V> b<V> c<V>)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCopySemanticsWithHetero() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "@members {\n" + "static class V extends CommonTree {\n" + " public V(Token t) { token=t;}\n" + // for 'int'<V> " public V(V node) { super(node); }\n\n" + // for dupNode " public Tree dupNode() { return new V(this); }\n" + // for dup'ing type " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "}\n" + "a : type ID (',' ID)* ';' -> ^(type ID)+;\n" + "type : 'int'<node=V> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "int a, b, c;", debug ); Assert.AreEqual( "(int<V> a) (int<V> b) (int<V> c)" + NewLine, found ); } // TREE PARSERS -- REWRITE AST [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserRewriteFlatList() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "@members {\n" + "static class V extends CommonTree {\n" + " public V(Object t) { super((CommonTree)t); }\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "static class W extends CommonTree {\n" + " public W(Object t) { super((CommonTree)t); }\n" + " public String toString() { return token.getText()+\"<W>\";}\n" + "}\n" + "}\n" + "a : ID INT -> INT<node=V> ID<node=W>\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "34<V> abc<W>" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserRewriteTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "@members {\n" + "static class V extends CommonTree {\n" + " public V(Object t) { super((CommonTree)t); }\n" + " public String toString() { return token.getText()+\"<V>\";}\n" + "}\n" + "static class W extends CommonTree {\n" + " public W(Object t) { super((CommonTree)t); }\n" + " public String toString() { return token.getText()+\"<W>\";}\n" + "}\n" + "}\n" + "a : ID INT -> ^(INT<node=V> ID<node=W>)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "(34<V> abc<W>)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserRewriteImaginary() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "tokens { ROOT; }\n" + "@members {\n" + "class V extends CommonTree {\n" + " public V(int tokenType) { super(new CommonToken(tokenType)); }\n" + " public String toString() { return tokenNames[token.getType()]+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID -> ROOT<node=V> ID\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "ROOT<V> abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserRewriteImaginaryWithArgs() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "tokens { ROOT; }\n" + "@members {\n" + "class V extends CommonTree {\n" + " public int x;\n" + " public V(int tokenType, int x) { super(new CommonToken(tokenType)); this.x=x;}\n" + " public String toString() { return tokenNames[token.getType()]+\"<V>;\"+x;}\n" + "}\n" + "}\n" + "a : ID -> ROOT<node=V>[42] ID\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "ROOT<V>;42 abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserRewriteImaginaryRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "tokens { ROOT; }\n" + "@members {\n" + "class V extends CommonTree {\n" + " public V(int tokenType) { super(new CommonToken(tokenType)); }\n" + " public String toString() { return tokenNames[token.getType()]+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID -> ^(ROOT<node=V> ID)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "(ROOT<V> abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserRewriteImaginaryFromReal() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "tokens { ROOT; }\n" + "@members {\n" + "class V extends CommonTree {\n" + " public V(int tokenType) { super(new CommonToken(tokenType)); }\n" + " public V(int tokenType, Object tree) { super((CommonTree)tree); token.setType(tokenType); }\n" + " public String toString() { return tokenNames[token.getType()]+\"<V>@\"+token.getLine();}\n" + "}\n" + "}\n" + "a : ID -> ROOT<node=V>[$ID]\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "ROOT<V>@1" + NewLine, found ); // at line 1; shows copy of ID's stuff } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserAutoHeteroAST() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ';' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "tokens { ROOT; }\n" + "@members {\n" + "class V extends CommonTree {\n" + " public V(CommonTree t) { super(t); }\n" + // NEEDS SPECIAL CTOR " public String toString() { return super.toString()+\"<V>\";}\n" + "}\n" + "}\n" + "a : ID<node=V> ';'<node=V>\n" + " ;\n"; diff --git a/Antlr3.Test/TestJavaCodeGeneration.cs b/Antlr3.Test/TestJavaCodeGeneration.cs index dcd6645..445587e 100644 --- a/Antlr3.Test/TestJavaCodeGeneration.cs +++ b/Antlr3.Test/TestJavaCodeGeneration.cs @@ -1,197 +1,198 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; /** General code generation testing; compilation and/or execution. * These tests are more about avoiding duplicate var definitions * etc... than testing a particular ANTLR feature. */ [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestJavaCodeGeneration : BaseTest { [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDupVarDefForPinchedState() { // so->s2 and s0->s3->s1 pinches back to s1 // LA3_1, s1 state for DFA 3, was defined twice in similar scope // just wrapped in curlies and it's cool. string grammar = "grammar T;\n" + "a : (| A | B) X Y\n" + " | (| A | B) X Z\n" + " ;\n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, "TParser", null, false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabeledNotSetsInLexer() { // d must be an int string grammar = "lexer grammar T;\n" + "A : d=~('x'|'y') e='0'..'9'\n" + " ; \n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, null, "T", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabeledSetsInLexer() { // d must be an int string grammar = "grammar T;\n" + "a : A ;\n" + "A : d=('x'|'y') {System.out.println((char)$d);}\n" + " ; \n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", false ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabeledRangeInLexer() { // d must be an int string grammar = "grammar T;\n" + "a : A;\n" + "A : d='a'..'z' {System.out.println((char)$d);} \n" + " ; \n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", false ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabeledWildcardInLexer() { // d must be an int string grammar = "grammar T;\n" + "a : A;\n" + "A : d=. {System.out.println((char)$d);}\n" + " ; \n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", false ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynpredWithPlusLoop() { string grammar = "grammar T; \n" + "a : (('x'+)=> 'x'+)?;\n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, "TParser", "TLexer", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDoubleQuoteEscape() { string grammar = "lexer grammar T; \n" + "A : '\\\\\"';\n" + // this is A : '\\"', which should give "\\\"" at Java level; "B : '\\\"';\n" + // this is B: '\"', which shodl give "\"" at Java level; "C : '\\'\\'';\n" + // this is C: '\'\'', which shoudl give "''" at Java level "D : '\\k';\n"; // this is D: '\k', which shoudl give just "k" at Java level; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, null, "T", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestUserExceptionInParser() { string grammar = "grammar T;\n" + "@parser::header {import java.io.IOException;}" + "a throws IOException : 'x' {throw new java.io.IOException();};\n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, "TParser", "TLexer", false ); bool expecting = true; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestBlankRuleGetsNoException() { string grammar = "grammar T;\n" + "a : sync (ID sync)* ;\n" + "sync : ;\n" + "ID : 'a'..'z'+;\n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, "TParser", "TLexer", false); bool expecting = true; // should be ok Assert.AreEqual(expecting, found); } /** * This is a regression test for antlr/antlr3#20: StackOverflow error when * compiling grammar with backtracking. * https://github.com/antlr/antlr3/issues/20 */ [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSemanticPredicateAnalysisStackOverflow() { string grammar = "grammar T;\n" + "\n" + "options {\n" + " backtrack=true;\n" + "}\n" + "\n" + "main : ('x'*)*;\n"; bool success = rawGenerateAndBuildRecognizer("T.g", grammar, "TParser", "TLexer", false); Assert.IsTrue(success); } } } diff --git a/Antlr3.Test/TestLexer.cs b/Antlr3.Test/TestLexer.cs index ddedc68..7f831db 100644 --- a/Antlr3.Test/TestLexer.cs +++ b/Antlr3.Test/TestLexer.cs @@ -1,287 +1,288 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Antlr.Runtime.JavaExtensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using CodeGenerator = Antlr3.Codegen.CodeGenerator; using Grammar = Antlr3.Tool.Grammar; using StringTemplate = Antlr4.StringTemplate.Template; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestLexer : BaseTest { protected bool debug = false; /** Public default constructor used by TestRig */ public TestLexer() { } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSetText() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "a : A {System.out.println(input);} ;\n" + "A : '\\\\' 't' {setText(\"\t\");} ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "\\t", debug ); Assert.AreEqual( "\t" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToRuleDoesNotSetTokenNorEmitAnother() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "a : A EOF {System.out.println(input);} ;\n" + "A : '-' I ;\n" + "I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "-34", debug ); Assert.AreEqual( "-34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToRuleDoesNotSetChannel() /*throws Exception*/ { // this must set channel of A to HIDDEN. $channel is local to rule // like $type. string grammar = "grammar P;\n" + "a : A EOF {System.out.println($A.text+\", channel=\"+$A.channel);} ;\n" + "A : '-' WS I ;\n" + "I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "- 34", debug ); Assert.AreEqual( "- 34, channel=0" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWeCanSetType() /*throws Exception*/ { string grammar = "grammar P;\n" + "tokens {X;}\n" + "a : X EOF {System.out.println(input);} ;\n" + "A : '-' I {$type = X;} ;\n" + "I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "-34", debug ); Assert.AreEqual( "-34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToFragment() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "a : A {System.out.println(input);} ;\n" + "A : '-' I ;\n" + "fragment I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "-34", debug ); Assert.AreEqual( "-34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMultipleRefToFragment() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "a : A EOF {System.out.println(input);} ;\n" + "A : I '.' I ;\n" + "fragment I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "3.14159", debug ); Assert.AreEqual( "3.14159" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLabelInSubrule() /*throws Exception*/ { // can we see v outside? string grammar = "grammar P;\n" + "a : A EOF ;\n" + "A : 'hi' WS (v=I)? {$channel=0; System.out.println($v.text);} ;\n" + "fragment I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "hi 342", debug ); Assert.AreEqual( "342" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRefToTokenInLexer() /*throws Exception*/ { string grammar = "grammar P;\n" + "a : A EOF ;\n" + "A : I {System.out.println($I.text);} ;\n" + "fragment I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "342", debug ); Assert.AreEqual( "342" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestListLabelInLexer() /*throws Exception*/ { string grammar = "grammar P;\n" + "a : A ;\n" + "A : i+=I+ {for (Object t : $i) System.out.print(\" \"+((Token)t).getText());} ;\n" + "fragment I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "33 297", debug ); Assert.AreEqual( " 33 297" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDupListRefInLexer() /*throws Exception*/ { string grammar = "grammar P;\n" + "a : A ;\n" + "A : i+=I WS i+=I {$channel=0; for (Object t : $i) System.out.print(\" \"+((Token)t).getText());} ;\n" + "fragment I : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "33 297", debug ); Assert.AreEqual( " 33 297" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCharLabelInLexer() { string grammar = "grammar T;\n" + "a : B ;\n" + "B : x='a' {System.out.println((char)$x);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRepeatedLabelInLexer() { string grammar = "lexer grammar T;\n" + "B : x='a' x='b' ;\n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, null, "T", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRepeatedRuleLabelInLexer() { string grammar = "lexer grammar T;\n" + "B : x=A x=A ;\n" + "fragment A : 'a' ;\n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, null, "T", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestIsolatedEOTEdge() { string grammar = "lexer grammar T;\n" + "QUOTED_CONTENT \n" + " : 'q' (~'q')* (('x' 'q') )* 'q' ; \n"; bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, null, "T", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestEscapedLiterals() { /* Grammar: A : '\"' ; should match a single double-quote: " B : '\\\"' ; should match input \" */ string grammar = "lexer grammar T;\n" + "A : '\\\"' ;\n" + "B : '\\\\\\\"' ;\n"; // '\\\"' bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, null, "T", false ); bool expecting = true; // should be ok Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNewlineLiterals() /*throws Exception*/ { Grammar g = new Grammar( "lexer grammar T;\n" + "A : '\\n\\n' ;\n" // ANTLR sees '\n\n' ); string expecting = "match(\"\\n\\n\")"; AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); // codegen phase sets some vars we need StringTemplate codeST = generator.RecognizerST; string code = codeST.Render(); int m = code.IndexOf( "match(\"" ); string found = code.Substring( m, expecting.Length ); Assert.AreEqual( expecting, found ); } } } diff --git a/Antlr3.Test/TestRewriteAST.cs b/Antlr3.Test/TestRewriteAST.cs index ef794a6..b3c5011 100644 --- a/Antlr3.Test/TestRewriteAST.cs +++ b/Antlr3.Test/TestRewriteAST.cs @@ -1,555 +1,556 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using CodeGenerator = Antlr3.Codegen.CodeGenerator; using ErrorManager = Antlr3.Tool.ErrorManager; using Grammar = Antlr3.Tool.Grammar; using GrammarSemanticsMessage = Antlr3.Tool.GrammarSemanticsMessage; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestRewriteAST : BaseTest { protected bool debug = false; [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelete() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "", found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ID;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleTokenToNewNode() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ID[\"x\"];\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleTokenToNewNodeRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ^(ID[\"x\"] INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "(x INT)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleTokenToNewNode2() /*throws Exception*/ { // Allow creation of new nodes w/o args. string grammar = "grammar TT;\n" + "options {output=AST;}\n" + "a : ID -> ID[ ];\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "TT.g", grammar, "TTParser", "TTLexer", "a", "abc", debug ); Assert.AreEqual( "ID" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleCharLiteral() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'c' -> 'c';\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "c", debug ); Assert.AreEqual( "c" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleStringLiteral() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'ick' -> 'ick';\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "ick", debug ); Assert.AreEqual( "ick" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b -> b;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReorderTokens() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> INT ID;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "34 abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReorderTokenAndRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b INT -> INT b;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "34 abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(INT ID);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "(34 abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenTreeAfterOtherStuff() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'void' ID INT -> 'void' ^(INT ID);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "void abc 34", debug ); Assert.AreEqual( "void (34 abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNestedTokenTreeWithOuterLoop() /*throws Exception*/ { // verify that ID and INT both iterate over outer index variable string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {DUH;}\n" + "a : ID INT ID INT -> ^( DUH ID ^( DUH INT) )+ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 1 b 2", debug ); Assert.AreEqual( "(DUH a (DUH 1)) (DUH b (DUH 2))" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalSingleToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> ID? ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestClosureSingleToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ID -> ID* ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a b", debug ); Assert.AreEqual( "a b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPositiveClosureSingleToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ID -> ID+ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a b", debug ); Assert.AreEqual( "a b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalSingleRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b -> b?;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestClosureSingleRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b b -> b*;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a b", debug ); Assert.AreEqual( "a b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestClosureOfLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x+=b x+=b -> $x*;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a b", debug ); Assert.AreEqual( "a b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalLabelNoListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : (x=ID)? -> $x?;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "a" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPositiveClosureSingleRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b b -> b+;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a b", debug ); Assert.AreEqual( "a b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSinglePredicateT() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> {true}? ID -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSinglePredicateF() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID -> {false}? ID -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc", debug ); Assert.AreEqual( "", found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMultiplePredicate() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> {false}? ID\n" + " -> {true}? INT\n" + " -> \n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 2", debug ); Assert.AreEqual( "2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMultiplePredicateTrees() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> {false}? ^(ID INT)\n" + " -> {true}? ^(INT ID)\n" + " -> ID\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 2", debug ); Assert.AreEqual( "(2 a)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : op INT -> ^(op INT);\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "-34", debug ); Assert.AreEqual( "(- 34)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleTree2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : op INT -> ^(INT op);\n" + "op : '+'|'-' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "+ 34", debug ); Assert.AreEqual( "(34 +)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNestedTrees() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'var' (ID ':' type ';')+ -> ^('var' ^(':' ID type)+) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "var a:int; b:float;", debug ); Assert.AreEqual( "(var (: a int) (: b float))" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImaginaryTokenCopy() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n" + "a : ID (',' ID)*-> ^(VAR ID)+ ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a,b,c", debug ); Assert.AreEqual( "(VAR a) (VAR b) (VAR c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTokenUnreferencedOnLeftButDefined() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n" + "a : b -> ID ;\n" + "b : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a", debug ); Assert.AreEqual( "ID" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImaginaryTokenCopySetText() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {VAR;}\n" + "a : ID (',' ID)*-> ^(VAR[\"var\"] ID)+ ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a,b,c", debug ); Assert.AreEqual( "(var a) (var b) (var c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImaginaryTokenNoCopyFromToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "{a b c}", debug ); Assert.AreEqual( "({ a b c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestImaginaryTokenNoCopyFromTokenSetText() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : lc='{' ID+ '}' -> ^(BLOCK[$lc,\"block\"] ID+) ;\n" + "type : 'int' | 'float' ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "{a b c}", debug ); Assert.AreEqual( "(block a b c)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMixedRewriteAndAutoAST() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {BLOCK;}\n" + "a : b b^ ;\n" + // 2nd b matches only an INT; can make it root "b : ID INT -> INT ID\n" + " | INT\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "a 1 2", debug ); Assert.AreEqual( "(2 1 a)" + NewLine, found ); } diff --git a/Antlr3.Test/TestRewriteTemplates.cs b/Antlr3.Test/TestRewriteTemplates.cs index dae0813..48206c5 100644 --- a/Antlr3.Test/TestRewriteTemplates.cs +++ b/Antlr3.Test/TestRewriteTemplates.cs @@ -1,345 +1,346 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using CodeGenerator = Antlr3.Codegen.CodeGenerator; using ErrorManager = Antlr3.Tool.ErrorManager; using Grammar = Antlr3.Tool.Grammar; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestRewriteTemplates : BaseTest { protected bool debug = false; [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelete() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "", found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAction() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> {new StringTemplate($ID.text)} ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestEmbeddedLiteralConstructor() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> {%{$ID.text}} ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestInlineTemplate() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> template(x={$ID},y={$INT}) <<x:<x.text>, y:<y.text>;>> ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "x:abc, y:34;" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNamedTemplate() /*throws Exception*/ { // the support code adds template group in it's output Test.java // that defines template foo. string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> foo(x={$ID.text},y={$INT.text}) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestIndirectTemplate() /*throws Exception*/ { // the support code adds template group in it's output Test.java // that defines template foo. string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> ({\"foo\"})(x={$ID.text},y={$INT.text}) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestInlineTemplateInvokingLib() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> template(x={$ID.text},y={$INT.text}) \"<foo(...)>\" ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPredicatedAlts() /*throws Exception*/ { // the support code adds template group in it's output Test.java // that defines template foo. string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : ID INT -> {false}? foo(x={$ID.text},y={$INT.text})\n" + " -> foo(x={\"hi\"}, y={$ID.text})\n" + " ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "hi abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTemplateReturn() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : b {System.out.println($b.st);} ;\n" + "b : ID INT -> foo(x={$ID.text},y={$INT.text}) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestReturnValueWithTemplate() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a : b {System.out.println($b.i);} ;\n" + "b returns [int i] : ID INT {$i=8;} ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "8" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTemplateRefToDynamicAttributes() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=template;}\n" + "a scope {String id;} : ID {$a::id=$ID.text;} b\n" + " {System.out.println($b.st.toString());}\n" + " ;\n" + "b : INT -> foo(x={$a::id}) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abc 34", debug ); Assert.AreEqual( "abc " + NewLine, found ); } // tests for rewriting templates in tree parsers [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleNode() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {ASTLabelType=CommonTree; output=template;}\n" + "s : a {System.out.println($a.st);} ;\n" + "a : ID -> template(x={$ID.text}) <<|<x>|>> ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "s", "abc" ); Assert.AreEqual( "|abc|" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSingleNodeRewriteMode() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {ASTLabelType=CommonTree; output=template; rewrite=true;}\n" + "s : a {System.out.println(input.getTokenStream().toString(0,0));} ;\n" + "a : ID -> template(x={$ID.text}) <<|<x>|>> ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "s", "abc" ); Assert.AreEqual( "|abc|" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteRuleAndRewriteModeOnSimpleElements() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "tree grammar TP;\n" + "options {ASTLabelType=CommonTree; output=template; rewrite=true;}\n" + "a: ^(A B) -> {ick}\n" + " | y+=INT -> {ick}\n" + " | x=ID -> {ick}\n" + " | BLORT -> {ick}\n" + " ;\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); Assert.AreEqual(0, equeue.warnings.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteRuleAndRewriteModeIgnoreActionsPredicates() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "tree grammar TP;\n" + "options {ASTLabelType=CommonTree; output=template; rewrite=true;}\n" + "a: {action} {action2} x=A -> {ick}\n" + " | {pred1}? y+=B -> {ick}\n" + " | C {action} -> {ick}\n" + " | {pred2}?=> z+=D -> {ick}\n" + " | (E)=> ^(F G) -> {ick}\n" + " ;\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); Assert.AreEqual(0, equeue.warnings.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteRuleAndRewriteModeNotSimple() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "tree grammar TP;\n" + "options {ASTLabelType=CommonTree; output=template; rewrite=true;}\n" + "a : ID+ -> {ick}\n" + " | INT INT -> {ick}\n" + " ;\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); Assert.AreEqual(0, equeue.warnings.Count, "unexpected errors: " + equeue); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRewriteRuleAndRewriteModeRefRule() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); Grammar g = new Grammar( "tree grammar TP;\n" + "options {ASTLabelType=CommonTree; output=template; rewrite=true;}\n" + "a : b+ -> {ick}\n" + " | b b A -> {ick}\n" + " ;\n" + "b : B ;\n" ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); Assert.AreEqual(0, equeue.warnings.Count, "unexpected errors: " + equeue); } } } diff --git a/Antlr3.Test/TestSemanticPredicateEvaluation.cs b/Antlr3.Test/TestSemanticPredicateEvaluation.cs index 42ca2a7..8150154 100644 --- a/Antlr3.Test/TestSemanticPredicateEvaluation.cs +++ b/Antlr3.Test/TestSemanticPredicateEvaluation.cs @@ -1,339 +1,340 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestSemanticPredicateEvaluation : BaseTest { [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleCyclicDFAWithPredicate() /*throws Exception*/ { string grammar = "grammar foo;\n" + "a : {false}? 'x'* 'y' {System.out.println(\"alt1\");}\n" + " | {true}? 'x'* 'y' {System.out.println(\"alt2\");}\n" + " ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "xxxy", false ); Assert.AreEqual( "alt2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleCyclicDFAWithInstanceVarPredicate() /*throws Exception*/ { string grammar = "grammar foo;\n" + "@members {boolean v=true;}\n" + "a : {false}? 'x'* 'y' {System.out.println(\"alt1\");}\n" + " | {v}? 'x'* 'y' {System.out.println(\"alt2\");}\n" + " ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "xxxy", false ); Assert.AreEqual( "alt2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPredicateValidation() /*throws Exception*/ { string grammar = "grammar foo;\n" + "@members {\n" + "public void reportError(RecognitionException e) {\n" + " System.out.println(\"error: \"+e.toString());\n" + "}\n" + "}\n" + "\n" + "a : {false}? 'x'\n" + " ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "x", false ); Assert.AreEqual( "error: FailedPredicateException(a,{false}?)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPreds() /*throws Exception*/ { string grammar = "grammar foo;" + "@lexer::members {boolean p=false;}\n" + "a : (A|B)+ ;\n" + "A : {p}? 'a' {System.out.println(\"token 1\");} ;\n" + "B : {!p}? 'a' {System.out.println(\"token 2\");} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "a", false ); // "a" is ambig; can match both A, B. Pred says match 2 Assert.AreEqual( "token 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPreds2() /*throws Exception*/ { string grammar = "grammar foo;" + "@lexer::members {boolean p=true;}\n" + "a : (A|B)+ ;\n" + "A : {p}? 'a' {System.out.println(\"token 1\");} ;\n" + "B : ('a'|'b')+ {System.out.println(\"token 2\");} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "a", false ); // "a" is ambig; can match both A, B. Pred says match 1 Assert.AreEqual( "token 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPredInExitBranch() /*throws Exception*/ { // p says it's ok to exit; it has precendence over the !p loopback branch string grammar = "grammar foo;" + "@lexer::members {boolean p=true;}\n" + "a : (A|B)+ ;\n" + "A : ('a' {System.out.print(\"1\");})*\n" + " {p}?\n" + " ('a' {System.out.print(\"2\");})* ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aaa", false ); Assert.AreEqual( "222" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPredInExitBranch2() /*throws Exception*/ { string grammar = "grammar foo;" + "@lexer::members {boolean p=true;}\n" + "a : (A|B)+ ;\n" + "A : ({p}? 'a' {System.out.print(\"1\");})*\n" + " ('a' {System.out.print(\"2\");})* ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aaa", false ); Assert.AreEqual( "111" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPredInExitBranch3() /*throws Exception*/ { string grammar = "grammar foo;" + "@lexer::members {boolean p=true;}\n" + "a : (A|B)+ ;\n" + "A : ({p}? 'a' {System.out.print(\"1\");} | )\n" + " ('a' {System.out.print(\"2\");})* ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aaa", false ); Assert.AreEqual( "122" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPredInExitBranch4() /*throws Exception*/ { string grammar = "grammar foo;" + "a : (A|B)+ ;\n" + "A @init {int n=0;} : ({n<2}? 'a' {System.out.print(n++);})+\n" + " ('a' {System.out.print(\"x\");})* ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aaaaa", false ); Assert.AreEqual( "01xxx" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPredsInCyclicDFA() /*throws Exception*/ { string grammar = "grammar foo;" + "@lexer::members {boolean p=false;}\n" + "a : (A|B)+ ;\n" + "A : {p}? ('a')+ 'x' {System.out.println(\"token 1\");} ;\n" + "B : ('a')+ 'x' {System.out.println(\"token 2\");} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aax", false ); Assert.AreEqual( "token 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPredsInCyclicDFA2() /*throws Exception*/ { string grammar = "grammar foo;" + "@lexer::members {boolean p=false;}\n" + "a : (A|B)+ ;\n" + "A : {p}? ('a')+ 'x' ('y')? {System.out.println(\"token 1\");} ;\n" + "B : ('a')+ 'x' {System.out.println(\"token 2\");} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aax", false ); Assert.AreEqual( "token 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestGatedPred() /*throws Exception*/ { string grammar = "grammar foo;" + "a : (A|B)+ ;\n" + "A : {true}?=> 'a' {System.out.println(\"token 1\");} ;\n" + "B : {false}?=>('a'|'b')+ {System.out.println(\"token 2\");} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aa", false ); // "a" is ambig; can match both A, B. Pred says match A twice Assert.AreEqual( "token 1" + NewLine + "token 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestGatedPred2() /*throws Exception*/ { string grammar = "grammar foo;\n" + "@lexer::members {boolean sig=false;}\n" + "a : (A|B)+ ;\n" + "A : 'a' {System.out.print(\"A\"); sig=true;} ;\n" + "B : 'b' ;\n" + "C : {sig}?=> ('a'|'b') {System.out.print(\"C\");} ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aa", false ); Assert.AreEqual( "AC" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPredWithActionTranslation() /*throws Exception*/ { string grammar = "grammar foo;\n" + "a : b[2] ;\n" + "b[int i]\n" + " : {$i==1}? 'a' {System.out.println(\"alt 1\");}\n" + " | {$b.i==2}? 'a' {System.out.println(\"alt 2\");}\n" + " ;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "aa", false ); Assert.AreEqual( "alt 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPredicatesOnEOTTarget() /*throws Exception*/ { string grammar = "grammar foo; \n" + "@lexer::members {boolean p=true, q=false;}" + "a : B ;\n" + "A: '</'; \n" + "B: {p}? '<!' {System.out.println(\"B\");};\n" + "C: {q}? '<' {System.out.println(\"C\");}; \n" + "D: '<';\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "<!", false ); Assert.AreEqual( "B" + NewLine, found ); } #if true // my lookahead tests [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynpredLookahead() { string grammar = "grammar foo;\n" + "a : B EOF {System.out.println(\"B\");};\n" + "B : '/*'\n" + " ( ('/' ~'*') => '/'\n" + " | ('*' ~'/') => '*'\n" + " | B\n" + " | (~('*'|'/')) => .\n" + " )*\n" + " '*/'\n" + " ;" ; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "/* */", false ); Assert.AreEqual( "B" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPredicatesWithGlobalScope() { string grammar = "grammar foo;\n" + "scope S { boolean value; }\n" + "a scope S; @init{$S::value = true;} : {$S::value}? => B EOF {System.out.println(\"B\");};\n" + "B : 'a'..'z'+;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "a", false ); Assert.AreEqual( "B" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPredicatesWithGlobalScope2() { string grammar = "grammar foo;\n" + "scope S { boolean value; }\n" + "a\n" + " scope S;\n" + " @init{$S::value = true;}\n" + " : (b {$S::value}?) => b EOF\n" + " | B EOF {System.out.println(\"A\");}\n" + " ;\n" + "b\n" + " scope S;\n" + " @init{$S::value = false;}\n" + " : B {!$S::value}? {System.out.println(\"B\");}\n" + " ;\n" + "B : 'a'..'z'+;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "a", false ); Assert.AreEqual( "B" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] [Ignore] public void TestPredicatesWithGlobalScope3() { string grammar = "grammar foo;\n" + "scope S { boolean value; }\n" + "a\n" + " scope S;\n" + " @init{$S::value = true;}\n" + " : (b {$S::value}?) => b EOF\n" + " | B EOF {System.out.println(\"A\");}\n" + " ;\n" + "b\n" + " scope S;\n" + " @init{$S::value = false;}\n" + " : {!$S::value}? B {System.out.println(\"B\");}\n" + " ;\n" + "B : 'a'..'z'+;\n"; string found = execParser( "foo.g", grammar, "fooParser", "fooLexer", "a", "a", false ); Assert.AreEqual( "B" + NewLine, found ); } #endif // S U P P O R T public void _test() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {channel=99;} ;\n"; string found = execParser( "t.g", grammar, "T", "TLexer", "a", "abc 34", false ); Assert.AreEqual( "" + NewLine, found ); } } } diff --git a/Antlr3.Test/TestSets.cs b/Antlr3.Test/TestSets.cs index 9c550e8..71fa776 100644 --- a/Antlr3.Test/TestSets.cs +++ b/Antlr3.Test/TestSets.cs @@ -1,322 +1,323 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; /** Test the set stuff in lexer and parser */ [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestSets : BaseTest { protected bool debug = false; /** Public default constructor used by TestRig */ public TestSets() { } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSeqDoesNotBecomeSet() /*throws Exception*/ { // this must return A not I to the parser; calling a nonfragment rule // from a nonfragment rule does not set the overall token. string grammar = "grammar P;\n" + "a : C {System.out.println(input);} ;\n" + "fragment A : '1' | '2';\n" + "fragment B : '3' '4';\n" + "C : A | B;\n"; string found = execParser( "P.g", grammar, "PParser", "PLexer", "a", "34", debug ); Assert.AreEqual( "34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : t=('x'|'y') {System.out.println($t.text);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserNotSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : t=~('x'|'y') 'z' {System.out.println($t.text);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "zz", debug ); Assert.AreEqual( "z" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserNotToken() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : ~'x' 'z' {System.out.println(input);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "zz", debug ); Assert.AreEqual( "zz" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestParserNotTokenWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : t=~'x' 'z' {System.out.println($t.text);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "zz", debug ); Assert.AreEqual( "z" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleAsSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a @after {System.out.println(input);} : 'a' | 'b' |'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "b", debug ); Assert.AreEqual( "b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestRuleAsSetAST() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : 'a' | 'b' |'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "b", debug ); Assert.AreEqual( "b" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotChar() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : ~'b' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalSingleElement() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A? 'c' {System.out.println(input);} ;\n" + "A : 'b' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "bc", debug ); Assert.AreEqual( "bc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalLexerSingleElement() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println(input);} ;\n" + "A : 'b'? 'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "bc", debug ); Assert.AreEqual( "bc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestStarLexerSingleElement() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println(input);} ;\n" + "A : 'b'* 'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "bbbbc", debug ); Assert.AreEqual( "bbbbc" + NewLine, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "c", debug ); Assert.AreEqual( "c" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPlusLexerSingleElement() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println(input);} ;\n" + "A : 'b'+ 'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "bbbbc", debug ); Assert.AreEqual( "bbbbc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : ('a'|'b')? 'c' {System.out.println(input);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "ac", debug ); Assert.AreEqual( "ac" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestStarSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : ('a'|'b')* 'c' {System.out.println(input);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abaac", debug ); Assert.AreEqual( "abaac" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestPlusSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : ('a'|'b')+ 'c' {System.out.println(input);} ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abaac", debug ); Assert.AreEqual( "abaac" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerOptionalSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println(input);} ;\n" + "A : ('a'|'b')? 'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "ac", debug ); Assert.AreEqual( "ac" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerStarSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println(input);} ;\n" + "A : ('a'|'b')* 'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abaac", debug ); Assert.AreEqual( "abaac" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLexerPlusSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println(input);} ;\n" + "A : ('a'|'b')+ 'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "abaac", debug ); Assert.AreEqual( "abaac" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotCharSet() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : ~('b'|'c') ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotCharSetWithLabel() /*throws Exception*/ { // This doesn't work in lexer yet. // Generates: h=input.LA(1); but h is defined as a Token string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : h=~('b'|'c') ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotCharSetWithRuleRef() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : ~('a'|B) ;\n" + "B : 'b' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotCharSetWithRuleRef2() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : ~('a'|B) ;\n" + "B : 'b'|'c' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotCharSetWithRuleRef3() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : ('a'|B) ;\n" + "fragment\n" + "B : ~('a'|'c') ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNotCharSetWithRuleRef4() /*throws Exception*/ { string grammar = "grammar T;\n" + "a : A {System.out.println($A.text);} ;\n" + "A : ('a'|B) ;\n" + "fragment\n" + "B : ~('a'|C) ;\n" + "fragment\n" + "C : 'c'|'d' ;\n "; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", debug ); Assert.AreEqual( "x" + NewLine, found ); } } } diff --git a/Antlr3.Test/TestSyntacticPredicateEvaluation.cs b/Antlr3.Test/TestSyntacticPredicateEvaluation.cs index 902d880..613fb36 100644 --- a/Antlr3.Test/TestSyntacticPredicateEvaluation.cs +++ b/Antlr3.Test/TestSyntacticPredicateEvaluation.cs @@ -1,443 +1,444 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestSyntacticPredicateEvaluation : BaseTest { [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTwoPredsWithNakedAlt() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : (a ';')+ ;\n" + "a\n" + "options {\n" + " k=1;\n" + "}\n" + " : (b '.')=> b '.' {System.out.println(\"alt 1\");}\n" + " | (b)=> b {System.out.println(\"alt 2\");}\n" + " | c {System.out.println(\"alt 3\");}\n" + " ;\n" + "b\n" + "@init {System.out.println(\"enter b\");}\n" + " : '(' 'x' ')' ;\n" + "c\n" + "@init {System.out.println(\"enter c\");}\n" + " : '(' c ')' | 'x' ;\n" + "WS : (' '|'\\n')+ {$channel=HIDDEN;}\n" + " ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "(x) ;", false ); string expecting = "enter b" + NewLine + "enter b" + NewLine + "enter b" + NewLine + "alt 2" + NewLine; Assert.AreEqual( expecting, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "(x). ;", false ); expecting = "enter b" + NewLine + "enter b" + NewLine + "alt 1" + NewLine; Assert.AreEqual( expecting, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "((x)) ;", false ); expecting = "enter b" + NewLine + "enter b" + NewLine + "enter c" + NewLine + "enter c" + NewLine + "enter c" + NewLine + "alt 3" + NewLine; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTwoPredsWithNakedAltNotLast() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : (a ';')+ ;\n" + "a\n" + "options {\n" + " k=1;\n" + "}\n" + " : (b '.')=> b '.' {System.out.println(\"alt 1\");}\n" + " | c {System.out.println(\"alt 2\");}\n" + " | (b)=> b {System.out.println(\"alt 3\");}\n" + " ;\n" + "b\n" + "@init {System.out.println(\"enter b\");}\n" + " : '(' 'x' ')' ;\n" + "c\n" + "@init {System.out.println(\"enter c\");}\n" + " : '(' c ')' | 'x' ;\n" + "WS : (' '|'\\n')+ {$channel=HIDDEN;}\n" + " ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "(x) ;", false ); string expecting = "enter b" + NewLine + "enter c" + NewLine + "enter c" + NewLine + "alt 2" + NewLine; Assert.AreEqual( expecting, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "(x). ;", false ); expecting = "enter b" + NewLine + "enter b" + NewLine + "alt 1" + NewLine; Assert.AreEqual( expecting, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "((x)) ;", false ); expecting = "enter b" + NewLine + "enter c" + NewLine + "enter c" + NewLine + "enter c" + NewLine + "alt 2" + NewLine; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TesTLexerPred() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : A ;\n" + "A options {k=1;}\n" + // force backtracking " : (B '.')=>B '.' {System.out.println(\"alt1\");}\n" + " | B {System.out.println(\"alt2\");}" + " ;\n" + "fragment\n" + "B : 'x'+ ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "xxx", false ); Assert.AreEqual( "alt2" + NewLine, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "xxx.", false ); Assert.AreEqual( "alt1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TesTLexerWithPredLongerThanAlt() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : A ;\n" + "A options {k=1;}\n" + // force backtracking " : (B '.')=>B {System.out.println(\"alt1\");}\n" + " | B {System.out.println(\"alt2\");}" + " ;\n" + "D : '.' {System.out.println(\"D\");} ;\n" + "fragment\n" + "B : 'x'+ ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "xxx", false ); Assert.AreEqual( "alt2" + NewLine, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "xxx.", false ); Assert.AreEqual( "alt1"+NewLine+"D" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TesTLexerPredCyclicPrediction() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : A ;\n" + "A : (B)=>(B|'y'+) {System.out.println(\"alt1\");}\n" + " | B {System.out.println(\"alt2\");}\n" + " | 'y'+ ';'" + " ;\n" + "fragment\n" + "B : 'x'+ ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "xxx", false ); Assert.AreEqual( "alt1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TesTLexerPredCyclicPrediction2() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : A ;\n" + "A : (B '.')=>(B|'y'+) {System.out.println(\"alt1\");}\n" + " | B {System.out.println(\"alt2\");}\n" + " | 'y'+ ';'" + " ;\n" + "fragment\n" + "B : 'x'+ ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "xxx", false ); Assert.AreEqual( "alt2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleNestedPred() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : (expr ';')+ ;\n" + "expr\n" + "options {\n" + " k=1;\n" + "}\n" + "@init {System.out.println(\"enter expr \"+input.LT(1).getText());}\n" + " : (atom 'x') => atom 'x'\n" + " | atom\n" + ";\n" + "atom\n" + "@init {System.out.println(\"enter atom \"+input.LT(1).getText());}\n" + " : '(' expr ')'\n" + " | INT\n" + " ;\n" + "INT: '0'..'9'+ ;\n" + "WS : (' '|'\\n')+ {$channel=HIDDEN;}\n" + " ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "(34)x;", false ); string expecting = "enter expr (" + NewLine + "enter atom (" + NewLine + "enter expr 34" + NewLine + "enter atom 34" + NewLine + "enter atom 34" + NewLine + "enter atom (" + NewLine + "enter expr 34" + NewLine + "enter atom 34" + NewLine + "enter atom 34" + NewLine; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTripleNestedPredInLexer() /*throws Exception*/ { string grammar = "grammar T;\n" + "s : (.)+ {System.out.println(\"done\");} ;\n" + "EXPR\n" + "options {\n" + " k=1;\n" + "}\n" + "@init {System.out.println(\"enter expr \"+(char)input.LT(1));}\n" + " : (ATOM 'x') => ATOM 'x' {System.out.println(\"ATOM x\");}\n" + " | ATOM {System.out.println(\"ATOM \"+$ATOM.text);}\n" + ";\n" + "fragment ATOM\n" + "@init {System.out.println(\"enter atom \"+(char)input.LT(1));}\n" + " : '(' EXPR ')'\n" + " | INT\n" + " ;\n" + "fragment INT: '0'..'9'+ ;\n" + "fragment WS : (' '|'\\n')+ \n" + " ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "s", "((34)x)x", false ); string expecting = // has no memoization "enter expr (" + NewLine + "enter atom (" + NewLine + "enter expr (" + NewLine + "enter atom (" + NewLine + "enter expr 3" + NewLine + "enter atom 3" + NewLine + "enter atom 3" + NewLine + "enter atom (" + NewLine + "enter expr 3" + NewLine + "enter atom 3" + NewLine + "enter atom 3" + NewLine + "enter atom (" + NewLine + "enter expr (" + NewLine + "enter atom (" + NewLine + "enter expr 3" + NewLine + "enter atom 3" + NewLine + "enter atom 3" + NewLine + "enter atom (" + NewLine + "enter expr 3" + NewLine + "enter atom 3" + NewLine + "enter atom 3" + NewLine + "ATOM 34" + NewLine + "ATOM x" + NewLine + "ATOM x" + NewLine + "done" + NewLine; Assert.AreEqual( expecting, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserWithSynPred() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT+ (PERIOD|SEMI);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {k=1; backtrack=true; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID INT+ PERIOD {System.out.print(\"alt 1\");}" + " | ID INT+ SEMI {System.out.print(\"alt 2\");}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 1 2 3;" ); Assert.AreEqual( "alt 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTreeParserWithNestedSynPred() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT+ (PERIOD|SEMI);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; // backtracks in a and b due to k=1 string treeGrammar = "tree grammar TP;\n" + "options {k=1; backtrack=true; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID b {System.out.print(\" a:alt 1\");}" + " | ID INT+ SEMI {System.out.print(\" a:alt 2\");}\n" + " ;\n" + "b : INT PERIOD {System.out.print(\"b:alt 1\");}" + // choose this alt for just one INT " | INT+ PERIOD {System.out.print(\"b:alt 2\");}" + " ;"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 1 2 3." ); Assert.AreEqual( "b:alt 2 a:alt 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynPredWithOutputTemplate() /*throws Exception*/ { // really just seeing if it will compile string grammar = "grammar T;\n" + "options {output=template;}\n" + "a\n" + "options {\n" + " k=1;\n" + "}\n" + " : ('x'+ 'y')=> 'x'+ 'y' -> template(a={$text}) <<1:<a>;>>\n" + " | 'x'+ 'z' -> template(a={$text}) <<2:<a>;>>\n" + " ;\n" + "WS : (' '|'\\n')+ {$channel=HIDDEN;}\n" + " ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "xxxy", false ); Assert.AreEqual( "1:xxxy;" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynPredWithOutputAST() /*throws Exception*/ { // really just seeing if it will compile string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a\n" + "options {\n" + " k=1;\n" + "}\n" + " : ('x'+ 'y')=> 'x'+ 'y'\n" + " | 'x'+ 'z'\n" + " ;\n" + "WS : (' '|'\\n')+ {$channel=HIDDEN;}\n" + " ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "xxxy", false ); Assert.AreEqual( "x x x y" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestOptionalBlockWithSynPred() /*throws Exception*/ { string grammar = "grammar T;\n" + "\n" + "a : ( (b)=> b {System.out.println(\"b\");})? b ;\n" + "b : 'x' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "xx", false ); Assert.AreEqual( "b" + NewLine, found ); found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "x", false ); Assert.AreEqual( "", found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynPredK2() /*throws Exception*/ { // all manually specified syn predicates are gated (i.e., forced // to execute). string grammar = "grammar T;\n" + "\n" + "a : (b)=> b {System.out.println(\"alt1\");} | 'a' 'c' ;\n" + "b : 'a' 'b' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "ab", false ); Assert.AreEqual( "alt1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynPredKStar() /*throws Exception*/ { string grammar = "grammar T;\n" + "\n" + "a : (b)=> b {System.out.println(\"alt1\");} | 'a'+ 'c' ;\n" + "b : 'a'+ 'b' ;\n"; string found = execParser( "T.g", grammar, "TParser", "TLexer", "a", "aaab", false ); Assert.AreEqual( "alt1" + NewLine, found ); } } } diff --git a/Antlr3.Test/TestSyntaxErrors.cs b/Antlr3.Test/TestSyntaxErrors.cs index 637eb8f..f0a50a4 100644 --- a/Antlr3.Test/TestSyntaxErrors.cs +++ b/Antlr3.Test/TestSyntaxErrors.cs @@ -1,184 +1,185 @@ /* * [The "BSD licence"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; using Console = System.Console; using ErrorManager = Antlr3.Tool.ErrorManager; using Path = System.IO.Path; using Regex = System.Text.RegularExpressions.Regex; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestSyntaxErrors : BaseTest { [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLL2() { string grammar = "grammar T;\n" + "a : 'a' 'b'" + " | 'a' 'c'" + ";\n" + "q : 'e' ;\n"; string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "ae", false); string expecting = "line 1:1 no viable alternative at input 'e'" + NewLine; string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input "); Assert.AreEqual(expecting, result); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLL3() { string grammar = "grammar T;\n" + "a : 'a' 'b'* 'c'" + " | 'a' 'b' 'd'" + " ;\n" + "q : 'e' ;\n"; Console.WriteLine(grammar); string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abe", false); string expecting = "line 1:2 no viable alternative at input 'e'" + NewLine; string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input "); Assert.AreEqual(expecting, result); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLLStar() { string grammar = "grammar T;\n" + "a : 'a'+ 'b'" + " | 'a'+ 'c'" + ";\n" + "q : 'e' ;\n"; string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "aaae", false); string expecting = "line 1:3 no viable alternative at input 'e'" + NewLine; string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input "); Assert.AreEqual(expecting, result); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSynPred() { string grammar = "grammar T;\n" + "a : (e '.')=> e '.'" + " | (e ';')=> e ';'" + " | 'z'" + " ;\n" + "e : '(' e ')'" + " | 'i'" + " ;\n"; Console.WriteLine(grammar); string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "((i))z", false); string expecting = "line 1:1 no viable alternative at input '('" + NewLine; string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input "); Assert.AreEqual(expecting, result); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLL1ErrorInfo() { string grammar = "grammar T;\n" + "start : animal (AND acClass)? service EOF;\n" + "animal : (DOG | CAT );\n" + "service : (HARDWARE | SOFTWARE) ;\n" + "AND : 'and';\n" + "DOG : 'dog';\n" + "CAT : 'cat';\n" + "HARDWARE: 'hardware';\n" + "SOFTWARE: 'software';\n" + "WS : ' ' {skip();} ;" + "acClass\n" + "@init\n" + "{ System.out.println(computeContextSensitiveRuleFOLLOW().toString(tokenNames)); }\n" + " : ;\n"; string result = execParser("T.g", grammar, "TParser", "TLexer", "start", "dog and software", false); string expecting = "{HARDWARE,SOFTWARE}" + NewLine; Assert.AreEqual(expecting, result); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestStrayBracketRecovery() { string grammar = "grammar T;\n" + "options {output = AST;}\n" + "tokens{NODE;}\n" + "s : a=ID INT -> ^(NODE[$a]] INT);\n" + "ID: 'a'..'z'+;\n" + "INT: '0'..'9'+;\n"; ErrorQueue errorQueue = new ErrorQueue(); ErrorManager.SetErrorListener(errorQueue); bool found = rawGenerateAndBuildRecognizer( "T.g", grammar, "TParser", "TLexer", false); Assert.IsFalse(found); Assert.AreEqual( "[error(100): :4:27: syntax error: antlr: dangling ']'? make sure to escape with \\]]", '[' + string.Join(", ", errorQueue.errors) + ']'); } /** * This is a regression test for antlr/antlr3#61. * https://github.com/antlr/antlr3/issues/61 */ [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestMissingAttributeAccessPreventsCodeGeneration() { string grammar = "grammar T;\n" + "options {\n" + " backtrack = true; \n" + "}\n" + "// if b is rule ref, gens bad void x=null code\n" + "a : x=b {Object o = $x; System.out.println(\"alt1\");}\n" + " | y=b\n" + " ;\n" + "\n" + "b : 'a' ;\n"; ErrorQueue errorQueue = new ErrorQueue(); ErrorManager.SetErrorListener(errorQueue); bool success = rawGenerateAndBuildRecognizer("T.g", grammar, "TParser", "TLexer", false); Assert.IsFalse(success); Assert.AreEqual( "[error(117): " + tmpdir.ToString() + Path.DirectorySeparatorChar + "T.g:6:9: missing attribute access on rule scope: x]", '[' + string.Join(", ", errorQueue.errors) + ']'); } } } diff --git a/Antlr3.Test/TestTreeGrammarRewriteAST.cs b/Antlr3.Test/TestTreeGrammarRewriteAST.cs index fb7d232..5376eeb 100644 --- a/Antlr3.Test/TestTreeGrammarRewriteAST.cs +++ b/Antlr3.Test/TestTreeGrammarRewriteAST.cs @@ -1,561 +1,562 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; using AntlrTool = Antlr3.AntlrTool; using CodeGenerator = Antlr3.Codegen.CodeGenerator; using ErrorManager = Antlr3.Tool.ErrorManager; using Grammar = Antlr3.Tool.Grammar; using GrammarSyntaxMessage = Antlr3.Tool.GrammarSyntaxMessage; using RecognitionException = Antlr.Runtime.RecognitionException; /** Tree rewrites in tree parsers are basically identical to rewrites * in a normal grammar except that the atomic element is a node not * a Token. Tests here ensure duplication of nodes occurs properly * and basic functionality. */ [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestTreeGrammarRewriteAST : BaseTest { protected bool debug = false; [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestFlatList() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID INT -> INT ID\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "34 abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(ID INT) -> ^(INT ID)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "(34 abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNonImaginaryWithCtor() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : INT ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : INT -> INT[\"99\"]\n" + // make new INT node " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "34" ); Assert.AreEqual( "99" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCombinedRewriteAndAuto() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT) | INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(ID INT) -> ^(INT ID) | INT\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "(34 abc)" + NewLine, found ); found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "34" ); Assert.AreEqual( "34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAvoidDup() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID -> ^(ID ID)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "(abc abc)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestLoop() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID+ INT+ -> (^(ID INT))+ ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : (^(ID INT))+ -> INT+ ID+\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a b c 3 4 5" ); Assert.AreEqual( "3 4 5 a b c" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDup() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID \n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupRule() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : b c ;\n" + "b : ID ;\n" + "c : INT ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 1" ); Assert.AreEqual( "a 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoWildcard() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID . \n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNoWildcardAsRootError() /*throws Exception*/ { ErrorQueue equeue = new ErrorQueue(); ErrorManager.SetErrorListener( equeue ); string treeGrammar = "tree grammar TP;\n" + "options {output=AST;}\n" + "a : ^(. INT) \n" + " ;\n"; Grammar g = new Grammar( treeGrammar ); AntlrTool antlr = newTool(); antlr.SetOutputDirectory( null ); // write to /dev/null CodeGenerator generator = new CodeGenerator( antlr, g, "Java" ); g.CodeGenerator = generator; generator.GenRecognizer(); Assert.AreEqual(1, equeue.errors.Count, "unexpected errors: " + equeue); int expectedMsgID = ErrorManager.MSG_WILDCARD_AS_ROOT; object expectedArg = null; RecognitionException expectedExc = null; GrammarSyntaxMessage expectedMessage = new GrammarSyntaxMessage( expectedMsgID, g, null, expectedArg, expectedExc ); checkError( equeue, expectedMessage ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoWildcard2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(ID .) \n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "(abc 34)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoWildcardWithLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID c=. \n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoWildcardWithListLabel() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID c+=. \n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "abc 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupMultiple() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ID ID INT\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a b 3" ); Assert.AreEqual( "a b 3" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(ID INT)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3" ); Assert.AreEqual( "(a 3)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTree2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT INT -> ^(ID INT INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(ID b b)\n" + " ;\n" + "b : INT ;"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3 4" ); Assert.AreEqual( "(a 3 4)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTreeWithLabels() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(x=ID y=INT)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3" ); Assert.AreEqual( "(a 3)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTreeWithListLabels() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(x+=ID y+=INT)\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3" ); Assert.AreEqual( "(a 3)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTreeWithRuleRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(b INT) ;\n" + "b : ID ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3" ); Assert.AreEqual( "(a 3)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTreeWithRuleRootAndLabels() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(x=b INT) ;\n" + "b : ID ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3" ); Assert.AreEqual( "(a 3)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTreeWithRuleRootAndListLabels() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(x+=b y+=c) ;\n" + "b : ID ;\n" + "c : INT ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 3" ); Assert.AreEqual( "(a 3)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupNestedTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=ID y=ID INT -> ^($x ^($y INT));\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(ID ^(ID INT))\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a b 3" ); Assert.AreEqual( "(a (b 3))" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestAutoDupTreeWithSubruleInside() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "tokens {OP;}\n" + "a : (x=ID|x=INT) -> ^(OP $x) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=AST; ASTLabelType=CommonTree; tokenVocab=T;}\n" + "a : ^(OP (b|c)) ;\n" + "b : ID ;\n" + "c : INT ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a" ); Assert.AreEqual( "(OP a)" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestDelete() /*throws Exception*/ { string grammar = "grammar T;\n" + diff --git a/Antlr3.Test/TestTreeParsing.cs b/Antlr3.Test/TestTreeParsing.cs index e51aa30..14b2eb9 100644 --- a/Antlr3.Test/TestTreeParsing.cs +++ b/Antlr3.Test/TestTreeParsing.cs @@ -1,366 +1,367 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace AntlrUnitTests { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] + [TestCategory(TestCategories.SkipOnCI)] public class TestTreeParsing : BaseTest { [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestFlatList() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : ID INT\n" + " {System.out.println($ID+\", \"+$INT);}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "abc, 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestSimpleTree() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT -> ^(ID INT);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : ^(ID INT)\n" + " {System.out.println($ID+\", \"+$INT);}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc 34" ); Assert.AreEqual( "abc, 34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestFlatVsTreeDecision() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b c ;\n" + "b : ID INT -> ^(ID INT);\n" + "c : ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : b b ;\n" + "b : ID INT {System.out.print($ID+\" \"+$INT);}\n" + " | ^(ID INT) {System.out.print(\"^(\"+$ID+\" \"+$INT+')');}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 1 b 2" ); Assert.AreEqual( "^(a 1)b 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestFlatVsTreeDecision2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : b c ;\n" + "b : ID INT+ -> ^(ID INT+);\n" + "c : ID INT+;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : b b ;\n" + "b : ID INT+ {System.out.print($ID+\" \"+$INT);}\n" + " | ^(x=ID (y=INT)+) {System.out.print(\"^(\"+$x+' '+$y+')');}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 1 2 3 b 4 5" ); Assert.AreEqual( "^(a 3)b 5" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestCyclicDFALookahead() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT+ PERIOD;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : ID INT+ PERIOD {System.out.print(\"alt 1\");}" + " | ID INT+ SEMI {System.out.print(\"alt 2\");}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a 1 2 3." ); Assert.AreEqual( "alt 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestTemplateOutput() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP;\n" + "options {output=template; ASTLabelType=CommonTree;}\n" + "s : a {System.out.println($a.st);};\n" + "a : ID INT -> {new StringTemplate($INT.text)}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "s", "abc 34" ); Assert.AreEqual( "34" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNullableChildList() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT? -> ^(ID INT?);\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : ^(ID INT?)\n" + " {System.out.println($ID);}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc" ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNullableChildList2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID INT? SEMI -> ^(ID INT?) SEMI ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : ^(ID INT?) SEMI\n" + " {System.out.println($ID);}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc;" ); Assert.AreEqual( "abc" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestNullableChildList3() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=ID INT? (y=ID)? SEMI -> ^($x INT? $y?) SEMI ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a : ^(ID INT? b) SEMI\n" + " {System.out.println($ID+\", \"+$b.text);}\n" + " ;\n" + "b : ID? ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc def;" ); Assert.AreEqual( "abc, def" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestActionsAfterRoot() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : x=ID INT? SEMI -> ^($x INT?) ;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {ASTLabelType=CommonTree;}\n" + "a @init {int x=0;} : ^(ID {x=1;} {x=2;} INT?)\n" + " {System.out.println($ID+\", \"+x);}\n" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "abc;" ); Assert.AreEqual( "abc, 2" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardLookahead() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID '+'^ INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {tokenVocab=T; ASTLabelType=CommonTree;}\n" + "a : ^('+' . INT) {System.out.print(\"alt 1\");}" + " ;\n"; string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a + 2" ); Assert.AreEqual( "alt 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardLookahead2() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID '+'^ INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {tokenVocab=T; ASTLabelType=CommonTree;}\n" + "a : ^('+' . INT) {System.out.print(\"alt 1\");}" + " | ^('+' . .) {System.out.print(\"alt 2\");}\n" + " ;\n"; // AMBIG upon '+' DOWN INT UP etc.. but so what. string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a + 2" ); Assert.AreEqual( "alt 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardLookahead3() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID '+'^ INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {tokenVocab=T; ASTLabelType=CommonTree;}\n" + "a : ^('+' ID INT) {System.out.print(\"alt 1\");}" + " | ^('+' . .) {System.out.print(\"alt 2\");}\n" + " ;\n"; // AMBIG upon '+' DOWN INT UP etc.. but so what. string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a + 2" ); Assert.AreEqual( "alt 1" + NewLine, found ); } [TestMethod][TestCategory(TestCategories.Antlr3)] public void TestWildcardPlusLookahead() /*throws Exception*/ { string grammar = "grammar T;\n" + "options {output=AST;}\n" + "a : ID '+'^ INT;\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+;\n" + "SEMI : ';' ;\n" + "PERIOD : '.' ;\n" + "WS : (' '|'\\n') {$channel=HIDDEN;} ;\n"; string treeGrammar = "tree grammar TP; options {tokenVocab=T; ASTLabelType=CommonTree;}\n" + "a : ^('+' INT INT ) {System.out.print(\"alt 1\");}" + " | ^('+' .+) {System.out.print(\"alt 2\");}\n" + " ;\n"; // AMBIG upon '+' DOWN INT UP etc.. but so what. string found = execTreeParser( "T.g", grammar, "TParser", "TP.g", treeGrammar, "TP", "TLexer", "a", "a", "a + 2" ); Assert.AreEqual( "alt 2" + NewLine, found ); } } } diff --git a/appveyor.yml b/appveyor.yml index 388ed03..b10146a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,23 +1,23 @@ version: 1.0.{build} os: Visual Studio 2017 configuration: Release init: - cmd: >- git config --global core.autocrlf true mkdir ..\..\..\keys\antlr "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sn.exe" -k ..\..\..\keys\antlr\Key.snk install: - git submodule update --init --recursive build_script: - cd build\prep - powershell -Command .\prepare.ps1 -Logger "${env:ProgramFiles}\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" - cd ..\.. test_script: -- vstest.console /logger:Appveyor "C:\projects\antlrcs\Antlr3.Test\bin\%CONFIGURATION%\net45\AntlrUnitTests.dll" +- vstest.console /logger:Appveyor /TestCaseFilter:"TestCategory!=SkipOnCI" "C:\projects\antlrcs\Antlr3.Test\bin\%CONFIGURATION%\net45\AntlrUnitTests.dll" - vstest.console /logger:Appveyor /TestCaseFilter:"TestCategory!=Visualizer" "C:\projects\antlrcs\Antlr4.Test.StringTemplate\bin\%CONFIGURATION%\net45\Antlr4.Test.StringTemplate.dll" - dotnet vstest /Framework:".NETCoreApp,Version=v2.0" /TestCaseFilter:"TestCategory!=Visualizer" "C:\projects\antlrcs\Antlr4.Test.StringTemplate\bin\%CONFIGURATION%\netcoreapp2.0\Antlr4.Test.StringTemplate.dll" artifacts: - path: build\prep\nuget\*.nupkg - path: build\prep\dist\*.7z
antlr/antlrcs
8ae5beb0d1b51ae1ededda7fb945f3aaac5e4006
Fix ErrorManager.ResetErrorState()
diff --git a/Antlr3/Tool/ErrorManager.cs b/Antlr3/Tool/ErrorManager.cs index e618969..72b03a2 100644 --- a/Antlr3/Tool/ErrorManager.cs +++ b/Antlr3/Tool/ErrorManager.cs @@ -134,910 +134,911 @@ namespace Antlr3.Tool public const int MSG_DOUBLE_QUOTES_ILLEGAL = 145; public const int MSG_INVALID_TEMPLATE_ACTION = 146; public const int MSG_MISSING_ATTRIBUTE_NAME = 147; public const int MSG_ARG_INIT_VALUES_ILLEGAL = 148; public const int MSG_REWRITE_OR_OP_WITH_NO_OUTPUT_OPTION = 149; public const int MSG_NO_RULES = 150; public const int MSG_WRITE_TO_READONLY_ATTR = 151; public const int MSG_MISSING_AST_TYPE_IN_TREE_GRAMMAR = 152; public const int MSG_REWRITE_FOR_MULTI_ELEMENT_ALT = 153; public const int MSG_RULE_INVALID_SET = 154; public const int MSG_HETERO_ILLEGAL_IN_REWRITE_ALT = 155; public const int MSG_NO_SUCH_GRAMMAR_SCOPE = 156; public const int MSG_NO_SUCH_RULE_IN_SCOPE = 157; public const int MSG_TOKEN_ALIAS_CONFLICT = 158; public const int MSG_TOKEN_ALIAS_REASSIGNMENT = 159; public const int MSG_TOKEN_VOCAB_IN_DELEGATE = 160; public const int MSG_INVALID_IMPORT = 161; public const int MSG_IMPORTED_TOKENS_RULE_EMPTY = 162; public const int MSG_IMPORT_NAME_CLASH = 163; public const int MSG_AST_OP_WITH_NON_AST_OUTPUT_OPTION = 164; public const int MSG_AST_OP_IN_ALT_WITH_REWRITE = 165; public const int MSG_WILDCARD_AS_ROOT = 166; public const int MSG_CONFLICTING_OPTION_IN_TREE_FILTER = 167; public const int MSG_ILLEGAL_OPTION_VALUE = 168; public const int MSG_ALL_OPS_NEED_SAME_ASSOC = 169; public const int MSG_RANGE_OP_ILLEGAL = 170; // GRAMMAR WARNINGS public const int MSG_GRAMMAR_NONDETERMINISM = 200; // A predicts alts 1,2 public const int MSG_UNREACHABLE_ALTS = 201; // nothing predicts alt i public const int MSG_DANGLING_STATE = 202; // no edges out of state public const int MSG_INSUFFICIENT_PREDICATES = 203; public const int MSG_DUPLICATE_SET_ENTRY = 204; // (A|A) public const int MSG_ANALYSIS_ABORTED = 205; public const int MSG_RECURSION_OVERLOW = 206; public const int MSG_LEFT_RECURSION = 207; public const int MSG_UNREACHABLE_TOKENS = 208; // nothing predicts token public const int MSG_TOKEN_NONDETERMINISM = 209; // alts of Tokens rule public const int MSG_LEFT_RECURSION_CYCLES = 210; public const int MSG_NONREGULAR_DECISION = 211; public const int MAX_MESSAGE_NUMBER = 211; /** Do not do perform analysis if one of these happens */ public static readonly BitSet ErrorsForcingNoAnalysis = new BitSet() { MSG_CANNOT_CREATE_TARGET_GENERATOR, MSG_RULE_REDEFINITION, MSG_UNDEFINED_RULE_REF, MSG_LEFT_RECURSION_CYCLES, MSG_REWRITE_OR_OP_WITH_NO_OUTPUT_OPTION, MSG_NO_RULES, MSG_NO_SUCH_GRAMMAR_SCOPE, MSG_NO_SUCH_RULE_IN_SCOPE, MSG_LEXER_RULES_NOT_ALLOWED, MSG_WILDCARD_AS_ROOT }; /** Do not do code gen if one of these happens */ public static readonly BitSet ErrorsForcingNoCodegen = new BitSet() { MSG_NONREGULAR_DECISION, MSG_RECURSION_OVERLOW, MSG_UNREACHABLE_ALTS, MSG_FILE_AND_GRAMMAR_NAME_DIFFER, MSG_INVALID_IMPORT, MSG_AST_OP_WITH_NON_AST_OUTPUT_OPTION }; /** Only one error can be emitted for any entry in this table. * Map from string to a set where the key is a method name like danglingState. * The set is whatever that method accepts or derives like a DFA. */ public static readonly IDictionary<string, ICollection<object>> emitSingleError = new Dictionary<string, ICollection<object>>() { { "danglingState", new HashSet<object>() } }; /** Messages should be sensitive to the locale. */ private static CultureInfo locale; private static string formatName; /** Each thread might need it's own error listener; e.g., a GUI with * multiple window frames holding multiple grammars. */ [ThreadStatic] private static IANTLRErrorListener _listener; public class ErrorState { public int errors; public int warnings; public int infos; public BitSet errorMsgIDs = new BitSet(); public BitSet warningMsgIDs = new BitSet(); } /** Track the number of errors regardless of the listener but track * per thread. */ [ThreadStatic] private static ErrorState _errorState; /** Each thread has its own ptr to a Tool object, which knows how * to panic, for example. In a GUI, the thread might just throw an Error * to exit rather than the suicide System.exit. */ [ThreadStatic] private static Tool _tool; /** The group of templates that represent all possible ANTLR errors. */ private static TemplateGroup messages; /** The group of templates that represent the current message format. */ private static TemplateGroup format; /** From a msgID how can I get the name of the template that describes * the error or warning? */ private static readonly String[] idToMessageTemplateName = new String[MAX_MESSAGE_NUMBER + 1]; static ErrorManager() { InitIdToMessageNameMapping(); } public static TraceListener ExternalListener { get; set; } private class DefaultErrorListener : IANTLRErrorListener { public virtual void Info( String msg ) { if ( FormatWantsSingleLineMessage() ) { msg = msg.Replace( '\n', ' ' ); } Console.Error.WriteLine( msg ); if (ExternalListener != null) ExternalListener.WriteLine(msg); } public virtual void Error( Message msg ) { String outputMsg = msg.ToString(); if ( FormatWantsSingleLineMessage() ) { outputMsg = outputMsg.Replace( '\n', ' ' ); } Console.Error.WriteLine( outputMsg ); if (ExternalListener != null) ExternalListener.WriteLine(outputMsg); } public virtual void Warning( Message msg ) { String outputMsg = msg.ToString(); if ( FormatWantsSingleLineMessage() ) { outputMsg = outputMsg.Replace( '\n', ' ' ); } Console.Error.WriteLine( outputMsg ); if (ExternalListener != null) ExternalListener.WriteLine(outputMsg); } public virtual void Error( ToolMessage msg ) { String outputMsg = msg.ToString(); if ( FormatWantsSingleLineMessage() ) { outputMsg = outputMsg.Replace( '\n', ' ' ); } Console.Error.WriteLine( outputMsg ); if (ExternalListener != null) ExternalListener.WriteLine(outputMsg); } } private static IANTLRErrorListener theDefaultErrorListener = new DefaultErrorListener(); private class InitSTListener : ITemplateErrorListener { public void CompiletimeError(TemplateMessage msg) { Console.Error.WriteLine("ErrorManager init error: " + msg); } public void RuntimeError(TemplateMessage msg) { Console.Error.WriteLine("ErrorManager init error: " + msg); } public void IOError(TemplateMessage msg) { Console.Error.WriteLine("ErrorManager init error: " + msg); } public void InternalError(TemplateMessage msg) { Console.Error.WriteLine("ErrorManager init error: " + msg); } } /** Handle all ST error listeners here (code gen, Grammar, and this class * use templates. */ private static ITemplateErrorListener initSTListener = new InitSTListener(); private sealed class BlankSTListener : ITemplateErrorListener { public void CompiletimeError(TemplateMessage msg) { } public void RuntimeError(TemplateMessage msg) { } public void IOError(TemplateMessage msg) { } public void InternalError(TemplateMessage msg) { } } /** During verification of the messages group file, don't gen errors. * I'll handle them here. This is used only after file has loaded ok * and only for the messages STG. */ private static ITemplateErrorListener blankSTListener = new BlankSTListener(); private class DefaultSTListener : ITemplateErrorListener { public void CompiletimeError(TemplateMessage msg) { ErrorManager.Error(ErrorManager.MSG_INTERNAL_ERROR, msg.ToString(), msg.Cause); } public void RuntimeError(TemplateMessage msg) { ErrorManager.Error(ErrorManager.MSG_INTERNAL_ERROR, msg.ToString(), msg.Cause); } public void IOError(TemplateMessage msg) { ErrorManager.Error(ErrorManager.MSG_INTERNAL_ERROR, msg.ToString(), msg.Cause); } public void InternalError(TemplateMessage msg) { ErrorManager.Error(ErrorManager.MSG_INTERNAL_ERROR, msg.ToString(), msg.Cause); } } /** Errors during initialization related to ST must all go to System.err. */ private static ITemplateErrorListener theDefaultSTListener = new DefaultSTListener(); internal static void Initialize() { // it is inefficient to set the default locale here if another // piece of code is going to set the locale, but that would // require that a user call an init() function or something. I prefer // that this class be ready to go when loaded as I'm absentminded ;) SetLocale( CultureInfo.CurrentCulture ); // try to load the message format group // the user might have specified one on the command line // if not, or if the user has given an illegal value, we will fall back to "antlr" SetFormat( "antlr" ); } public static ITemplateErrorListener GetStringTemplateErrorListener() { return theDefaultSTListener; } /** We really only need a single locale for entire running ANTLR code * in a single VM. Only pay attention to the language, not the country * so that French Canadians and French Frenchies all get the same * template file, fr.stg. Just easier this way. */ public static void SetLocale( CultureInfo locale ) { if (ErrorManager.locale == locale) return; ErrorManager.locale = locale; string language = locale.TwoLetterISOLanguageName; string fileName = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(AntlrTool.ToolPathRoot, "Tool"), "Templates"), "messages"), "languages"), language + ".stg"); if (!File.Exists(fileName) && locale.TwoLetterISOLanguageName != CultureInfo.GetCultureInfo("en-us").TwoLetterISOLanguageName) { SetLocale(CultureInfo.GetCultureInfo("en-us")); return; } messages = new TemplateGroupFile(fileName); messages.EnableCache = AntlrTool.EnableTemplateCache; messages.Listener = initSTListener; if (!messages.IsDefined("INTERNAL_ERROR")) { // pick random msg to load if (language.Equals(CultureInfo.GetCultureInfo("en-us").TwoLetterISOLanguageName)) { RawError("ANTLR installation corrupted; cannot find English messages file " + fileName); Panic(); } else { // recurse on this rule, trying the US locale SetLocale(CultureInfo.GetCultureInfo("en-us")); } } messages.Listener = blankSTListener; bool messagesOK = VerifyMessages(); if ( !messagesOK && language.Equals(CultureInfo.GetCultureInfo("en-us").TwoLetterISOLanguageName) ) { RawError("ANTLR installation corrupted; English messages file "+language+".stg incomplete"); Panic(); } else if ( !messagesOK ) { SetLocale(CultureInfo.GetCultureInfo("en-us")); // try US to see if that will work } } /** The format gets reset either from the Tool if the user supplied a command line option to that effect * Otherwise we just use the default "antlr". */ public static void SetFormat( String formatName ) { if (ErrorManager.formatName == formatName) return; ErrorManager.formatName = formatName; string fileName = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(AntlrTool.ToolPathRoot, "Tool"), "Templates"), "messages"), "formats"), formatName + ".stg"); format = new TemplateGroupFile(fileName); if (!File.Exists(fileName) && formatName != "antlr") { SetFormat("antlr"); return; } format.EnableCache = AntlrTool.EnableTemplateCache; format.Listener = initSTListener; if (!format.IsDefined("message")) { // pick random msg to load if (formatName.Equals("antlr")) { RawError("no such message format file " + fileName + " retrying with default ANTLR format"); // recurse on this rule, trying the default message format SetFormat("antlr"); return; } else { // recurse on this rule, trying the default message format SetFormat("antlr"); } } format.Listener = blankSTListener; bool formatOK = VerifyFormat(); if ( !formatOK && formatName.Equals( "antlr" ) ) { RawError( "ANTLR installation corrupted; ANTLR messages format file " + formatName + ".stg incomplete" ); Panic(); } else if ( !formatOK ) { SetFormat( "antlr" ); // recurse on this rule, trying the default message format } } /** Encodes the error handling found in setLocale, but does not trigger * panics, which would make GUI tools die if ANTLR's installation was * a bit screwy. Duplicated code...ick. public static Locale getLocaleForValidMessages(Locale locale) { ErrorManager.locale = locale; String language = locale.getLanguage(); String fileName = "org/antlr/tool/templates/messages/"+language+".stg"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream(fileName); if ( is==null &amp;&amp; language.equals(Locale.US.getLanguage()) ) { return null; } else if ( is==null ) { return getLocaleForValidMessages(Locale.US); // recurse on this rule, trying the US locale } boolean messagesOK = verifyMessages(); if ( !messagesOK &amp;&amp; language.equals(Locale.US.getLanguage()) ) { return null; } else if ( !messagesOK ) { return getLocaleForValidMessages(Locale.US); // try US to see if that will work } return true; } */ /** In general, you'll want all errors to go to a single spot. * However, in a GUI, you might have two frames up with two * different grammars. Two threads might launch to process the * grammars--you would want errors to go to different objects * depending on the thread. I store a single listener per * thread. */ public static void SetErrorListener( IANTLRErrorListener listener ) { ErrorManager._listener = listener; } public static void RemoveErrorListener() { ErrorManager._listener = null; } public static Tool GetTool() { return _tool; } public static void SetTool( Tool tool ) { _tool = tool; } /** Given a message ID, return a StringTemplate that somebody can fill * with data. We need to convert the int ID to the name of a template * in the messages ST group. */ public static StringTemplate GetMessage( int msgID ) { String msgName = idToMessageTemplateName[msgID]; return messages.GetInstanceOf( msgName ); } public static String GetMessageType( int msgID ) { if ( GetErrorState().warningMsgIDs.Contains( msgID ) ) { return messages.GetInstanceOf( "warning" ).Render(); } else if ( GetErrorState().errorMsgIDs.Contains( msgID ) ) { return messages.GetInstanceOf( "error" ).Render(); } AssertTrue( false, "Assertion failed! Message ID " + msgID + " created but is not present in errorMsgIDs or warningMsgIDs." ); return ""; } /** Return a StringTemplate that refers to the current format used for * emitting messages. */ public static StringTemplate GetLocationFormat() { return format.GetInstanceOf( "location" ); } public static StringTemplate GetReportFormat() { return format.GetInstanceOf( "report" ); } public static StringTemplate GetMessageFormat() { return format.GetInstanceOf( "message" ); } public static bool FormatWantsSingleLineMessage() { return format.GetInstanceOf( "wantsSingleLineMessage" ).Render().Equals( "true" ); } public static IANTLRErrorListener GetErrorListener() { IANTLRErrorListener el = _listener; if ( el == null ) return theDefaultErrorListener; return el; } public static ErrorState GetErrorState() { ErrorState ec = _errorState; if ( ec == null ) { ec = new ErrorState(); _errorState = ec; } return ec; } public static int GetNumErrors() { return GetErrorState().errors; } public static void ResetErrorState() { - _errorState = new ErrorState(); + _listener = null; + _errorState = null; } public static void Info( String msg ) { GetErrorState().infos++; GetErrorListener().Info( msg ); } public static void Error( int msgID ) { GetErrorState().errors++; GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( new ToolMessage( msgID ) ); } public static void Error( int msgID, Exception e ) { GetErrorState().errors++; GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( new ToolMessage( msgID, e ) ); } public static void Error( int msgID, Object arg ) { GetErrorState().errors++; GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( new ToolMessage( msgID, arg ) ); } public static void Error( int msgID, Object arg, Object arg2 ) { GetErrorState().errors++; GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( new ToolMessage( msgID, arg, arg2 ) ); } public static void Error( int msgID, Object arg, Exception e ) { GetErrorState().errors++; GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( new ToolMessage( msgID, arg, e ) ); } public static void Warning( int msgID, Object arg ) { GetErrorState().warnings++; GetErrorState().warningMsgIDs.Add( msgID ); GetErrorListener().Warning( new ToolMessage( msgID, arg ) ); } public static void Nondeterminism( DecisionProbe probe, DFAState d ) { GetErrorState().warnings++; Message msg = new GrammarNonDeterminismMessage( probe, d ); GetErrorState().warningMsgIDs.Add( msg.msgID ); GetErrorListener().Warning( msg ); } public static void DanglingState( DecisionProbe probe, DFAState d ) { GetErrorState().errors++; Message msg = new GrammarDanglingStateMessage( probe, d ); GetErrorState().errorMsgIDs.Add( msg.msgID ); ICollection<object> seen; emitSingleError.TryGetValue("danglingState", out seen); if ( !seen.Contains( d.Dfa.DecisionNumber + "|" + d.AltSet ) ) { GetErrorListener().Error( msg ); // we've seen this decision and this alt set; never again seen.Add( d.Dfa.DecisionNumber + "|" + d.AltSet ); } } public static void AnalysisAborted( DecisionProbe probe ) { GetErrorState().warnings++; Message msg = new GrammarAnalysisAbortedMessage( probe ); GetErrorState().warningMsgIDs.Add( msg.msgID ); GetErrorListener().Warning( msg ); } public static void UnreachableAlts( DecisionProbe probe, IEnumerable<int> alts ) { GetErrorState().errors++; Message msg = new GrammarUnreachableAltsMessage( probe, alts ); GetErrorState().errorMsgIDs.Add( msg.msgID ); GetErrorListener().Error( msg ); } public static void InsufficientPredicates( DecisionProbe probe, DFAState d, IDictionary<int, ICollection<IToken>> altToUncoveredLocations ) { GetErrorState().warnings++; Message msg = new GrammarInsufficientPredicatesMessage( probe, d, altToUncoveredLocations ); GetErrorState().warningMsgIDs.Add( msg.msgID ); GetErrorListener().Warning( msg ); } public static void NonLLStarDecision( DecisionProbe probe ) { GetErrorState().errors++; Message msg = new NonRegularDecisionMessage( probe, probe.NonDeterministicAlts ); GetErrorState().errorMsgIDs.Add( msg.msgID ); GetErrorListener().Error( msg ); } public static void RecursionOverflow( DecisionProbe probe, DFAState sampleBadState, int alt, ICollection<string> targetRules, ICollection<ICollection<NFAState>> callSiteStates ) { GetErrorState().errors++; Message msg = new RecursionOverflowMessage( probe, sampleBadState, alt, targetRules, callSiteStates ); GetErrorState().errorMsgIDs.Add( msg.msgID ); GetErrorListener().Error( msg ); } #if false // TODO: we can remove I think. All detected now with cycles check. public static void LeftRecursion(DecisionProbe probe, int alt, ICollection targetRules, ICollection callSiteStates) { getErrorState().warnings++; Message msg = new LeftRecursionMessage(probe, alt, targetRules, callSiteStates); getErrorState().warningMsgIDs.add(msg.msgID); getErrorListener().Warning(msg); } #endif public static void LeftRecursionCycles( ICollection cycles ) { GetErrorState().errors++; Message msg = new LeftRecursionCyclesMessage( cycles ); GetErrorState().errorMsgIDs.Add( msg.msgID ); GetErrorListener().Error( msg ); } public static void GrammarError( int msgID, Grammar g, IToken token, Object arg, Object arg2 ) { GetErrorState().errors++; Message msg = new GrammarSemanticsMessage( msgID, g, token, arg, arg2 ); GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( msg ); } public static void GrammarError( int msgID, Grammar g, IToken token, Object arg ) { GrammarError( msgID, g, token, arg, null ); } public static void GrammarError( int msgID, Grammar g, IToken token ) { GrammarError( msgID, g, token, null, null ); } public static void GrammarWarning( int msgID, Grammar g, IToken token, Object arg, Object arg2 ) { GetErrorState().warnings++; Message msg = new GrammarSemanticsMessage( msgID, g, token, arg, arg2 ); GetErrorState().warningMsgIDs.Add( msgID ); GetErrorListener().Warning( msg ); } public static void GrammarWarning( int msgID, Grammar g, IToken token, Object arg ) { GrammarWarning( msgID, g, token, arg, null ); } public static void GrammarWarning( int msgID, Grammar g, IToken token ) { GrammarWarning( msgID, g, token, null, null ); } public static void SyntaxError( int msgID, Grammar grammar, IToken token, Object arg, RecognitionException re ) { GetErrorState().errors++; GetErrorState().errorMsgIDs.Add( msgID ); GetErrorListener().Error( new GrammarSyntaxMessage( msgID, grammar, token, arg, re ) ); } public static void InternalError( Object error, Exception e ) { StackFrame location = GetLastNonErrorManagerCodeLocation( e ); String msg = "Exception " + e + "@" + location + ": " + error; ErrorManager.Error( MSG_INTERNAL_ERROR, msg ); } public static void InternalError( Object error ) { StackFrame location = GetLastNonErrorManagerCodeLocation( new Exception() ); String msg = location + ": " + error; ErrorManager.Error( MSG_INTERNAL_ERROR, msg ); } public static bool DoNotAttemptAnalysis() { return !GetErrorState().errorMsgIDs.And( ErrorsForcingNoAnalysis ).IsNil; } public static bool DoNotAttemptCodeGen() { return DoNotAttemptAnalysis() || !GetErrorState().errorMsgIDs.And( ErrorsForcingNoCodegen ).IsNil; } /** Return first non ErrorManager code location for generating messages */ private static StackFrame GetLastNonErrorManagerCodeLocation( Exception e ) { StackFrame[] stack = e.GetStackTrace(); int i = 0; for ( ; i < stack.Length; i++ ) { StackFrame t = stack[i]; if ( t.ToString().IndexOf( "ErrorManager" ) < 0 ) { break; } } StackFrame location = stack[i]; return location; } // A S S E R T I O N C O D E public static void AssertTrue( bool condition, String message ) { if ( !condition ) { InternalError( message ); } } // S U P P O R T C O D E static bool InitIdToMessageNameMapping() { // make sure a message exists, even if it's just to indicate a problem for ( int i = 0; i < idToMessageTemplateName.Length; i++ ) { idToMessageTemplateName[i] = "INVALID MESSAGE ID: " + i; } // get list of fields and use it to fill in idToMessageTemplateName mapping FieldInfo[] fields = typeof( ErrorManager ).GetFields(); for ( int i = 0; i < fields.Length; i++ ) { FieldInfo f = fields[i]; String fieldName = f.Name; if ( !fieldName.StartsWith( "MSG_" ) ) { continue; } String templateName = fieldName.Substring( "MSG_".Length ); int msgID = 0; try { // get the constant value from this class object msgID = (int)f.GetValue( null ); //msgID = f.getInt( typeof( ErrorManager ) ); } catch ( FieldAccessException /*iae*/ ) { Console.Out.WriteLine( "cannot get const value for " + f.Name ); continue; } if ( fieldName.StartsWith( "MSG_" ) ) { idToMessageTemplateName[msgID] = templateName; } } return true; } /** Use reflection to find list of MSG_ fields and then verify a * template exists for each one from the locale's group. */ static bool VerifyMessages() { bool ok = true; FieldInfo[] fields = typeof( ErrorManager ).GetFields(); for ( int i = 0; i < fields.Length; i++ ) { FieldInfo f = fields[i]; String fieldName = f.Name; String templateName = fieldName.Substring( "MSG_".Length ); if ( fieldName.StartsWith( "MSG_" ) ) { if ( !messages.IsDefined( templateName ) ) { Console.Out.WriteLine( "Message " + templateName + " in locale " + locale + " not found" ); ok = false; } } } // check for special templates if ( !messages.IsDefined( "warning" ) ) { Console.Error.WriteLine( "Message template 'warning' not found in locale " + locale ); ok = false; } if ( !messages.IsDefined( "error" ) ) { Console.Error.WriteLine( "Message template 'error' not found in locale " + locale ); ok = false; } return ok; } /** Verify the message format template group */ static bool VerifyFormat() { bool ok = true; if ( !format.IsDefined( "location" ) ) { Console.Error.WriteLine( "Format template 'location' not found in " + formatName ); ok = false; } if ( !format.IsDefined( "message" ) ) { Console.Error.WriteLine( "Format template 'message' not found in " + formatName ); ok = false; } if ( !format.IsDefined( "report" ) ) { Console.Error.WriteLine( "Format template 'report' not found in " + formatName ); ok = false; } return ok; } /** If there are errors during ErrorManager init, we have no choice * but to go to System.err. */ static void RawError( String msg ) { Console.Error.WriteLine( msg ); } static void RawError( String msg, Exception e ) { RawError( msg ); e.PrintStackTrace( Console.Error ); } /** I *think* this will allow Tool subclasses to exit gracefully * for GUIs etc... */ public static void Panic() { Tool tool = _tool; if ( tool == null ) { // no tool registered, exit throw new Exception( "ANTLR ErrorManager panic" ); } else { tool.Panic(); } } } }