1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
|
#! /usr/bin/python -Qwarnall
#
# -*- coding: latin-1 -*-
#
# This script is run by ./validateODF.py
# Author: unknown
# Maintainer: Hanna Skott
#
# This file contains a script that converts documents to ODF format using calligraconverter
# it also validates the content of the resulting ODF file against RelaxNG XML using jing.
#
# EXAMPLE of use: $ ./convertAndValidateODF.py validate_or_not file_directory filename
# validate_or_not values are: yes, no
# NOTE! Jing jar has to be in the same directory as this script for this to work, and it must be named jing.jar
#
import sys, os, os.path, tempfile, subprocess, lxml.etree, zipfile, urllib, hashlib, shlex, shutil, re, getopt
# this function gets jing, then for each file in fileList it converts the file, and validates its XML against RelaxNG
def convertAndValidateFilesInDir(dir):
print "dir is "+dir
# insert the path to the directory of interest here
for root, dirs, files in os.walk(dir):
for name in files:
singleFileConvertAndValidate(name, root)
#This function converts a file using calligraconverter and then tries to validate the resulting ODF file against RelaxNG using jing
def singleFileConvertAndValidate(filename, validate):
filepath = filename
# Create a filename for the output odt file
filename, extension = os.path.splitext(filepath)
src_extension = getExtByMime(filepath)
if src_extension is not None:
# Create filename for where conversion is stored
dst_extension = getConvertExtension(src_extension)
convertedfile = filepath + "." + dst_extension
if "." + dst_extension == src_extension:
applicationname = getApplicationName(dst_extension)
# Do the conversion
args = [applicationname, "--roundtrip-filename", convertedfile, filepath]
else:
args = ["calligraconverter", "--batch", filepath, convertedfile]
print args
fnull = open(os.devnull, 'w')
p = subprocess.call(args, stdout = fnull, stderr = fnull)
# validate out.odt
if not os.path.exists(convertedfile):
print "converted file "+convertedfile+" does not EXIST - Conversion failed!"
return 1
else:
if validate:
# Get jing and validate the odf file according to RelaxNG
jingjar = newGetJing()
validator = jingodfvalidator(jingjar)
e = validator.validate(convertedfile)
if not e:
print "file "+convertedfile+" did not validate against RelaxNG - validation failed!"
removeFileCommand = ["rm", "-f", convertedfile]
p = subprocess.call(removeFileCommand)
return 1
else:
removeFileCommand = ["rm", "-f", convertedfile]
p = subprocess.call(removeFileCommand)
return 0
else:
removeFileCommand = ["rm", "-f", convertedfile]
p = subprocess.call(removeFileCommand)
return 0
else:
print "file "+filename+" is not of a file format that can be converted to ODF"
return 1
#def getConversionResultingMime(file):
# file_extension = file.split(".")[-1]
# if file_extension:
# if file_extension == ".doc" or file_extension == ".docx" or file_extension == ".txt":
# textMime = "odt"
# return textMime
# if file_extension == ".ppt" or file_extension == ".pptx":
# pptMime = "odp"
# return pptMime
# if file_extension == ".csv" or file_extension == ".xls" or file_extension == ".xlsx":
# spreadsheetMime = "ods"
# return spreadsheetMime
# else:
# return None
#This function gets the input file formats closest match in ODF format for version
def getExtByMime(filename):
(path, pathext) = os.path.splitext(filename)
return pathext
def getConvertExtension(extension):
if extension == ".odt" or extension == ".docx" or extension == ".doc" or extension == ".txt":
return "odt"
if extension == ".odp" or extension == ".ppt" or extension == ".pptx":
return "odp"
if extension == ".ods" or extension == ".xls" or extension == ".xlsx":
return "ods"
def getApplicationName(extension):
if extension == "odt":
return "calligrawords"
if extension == "odp":
return "calligrastage"
if extension == "ods":
return "calligrasheets"
def getODFVersion(zip):
content = lxml.etree.parse(zip.open("content.xml", "r"))
return content.getroot().get(
"{urn:oasis:names:tc:opendocument:xmlns:office:1.0}version")
def newGetJing():
currentdir = os.curdir
jingjar = os.path.join(currentdir, "jing.jar")
path = os.path.join(sys.path[0], jingjar)
if os.path.isfile(path):
return path
def getJing():
jingjar = "jing-20091111/bin/jing.jar"
# jingjar = "jing-20081028/bin/jing.jar"
path = os.path.join(sys.path[0], jingjar)
if os.path.isfile(path):
return path
print "Downloading jing.jar"
z = "jing-20091111.zip"
# VALID 2011-03-29
urllib.urlretrieve("http://code.google.com/p/jing-trang/downloads/detail?name=jing-20091111.zip", z);
# urllib.urlretrieve("http://jing-trang.googlecode.com/files/" + z, z);
zip = zipfile.ZipFile(z, "r");
zip.extract(jingjar, sys.path[0])
os.unlink(z)
f = open(path, "rb")
h = hashlib.sha1()
h.update(f.read())
f.close()
hash = h.hexdigest()
# hash for jing 2011-03-29
if hash != "2e8eacf399249d226ad4f6ca1d6907ff69430118":
# if hash != "60197956be7f8f2e29e1941ca42273abe7315293":
print "Wrong hash code: wrong file."
os.unlink(path)
return
return path
schemas = {
"1.0": ["OpenDocument-schema-v1.0-os.rng",
"OpenDocument-manifest-schema-v1.0-os.rng"],
"1.1": ["OpenDocument-schema-v1.1.rng",
"OpenDocument-manifest-schema-v1.1.rng"],
"1.2": ["OpenDocument-v1.2-cs01-schema-calligra.rng",
"OpenDocument-v1.2-cs01-manifest-schema.rng"]
}
class jingodfvalidator:
def __init__(self, jingjar):
self.jingjar = jingjar;
def validate(self, odfpath):
zip = zipfile.ZipFile(odfpath, 'r')
odfversion = getODFVersion(zip)
if not odfversion in schemas:
return "Document has no version number"
err = self.validateFile(zip, 'content.xml',
schemas[odfversion][0])
if (err):
return err
err = self.validateFile(zip, 'styles.xml',
schemas[odfversion][0])
if (err):
return err
err = self.validateFile(zip, 'META-INF/manifest.xml',
schemas[odfversion][1])
if (err):
return err
return None
def validateFile(self, zip, filepath, schema):
schema = os.path.join(sys.path[0], schema)
suffix = "_" + filepath.replace("/", "_")
tmp = tempfile.NamedTemporaryFile(suffix = suffix)
tmp.write(zip.open(filepath, "r").read())
tmp.flush()
args = ["java", "-jar", self.jingjar, "-i", schema, tmp.name]
r = subprocess.call(args)
tmp.close()
if r:
return filepath + " is not valid."
def createValidator(name):
xml = lxml.etree.parse(open(os.path.join(sys.path[0], name), "rb"))
return lxml.etree.RelaxNG(xml)
class odfvalidator:
def __init__(self):
path = sys.path[0]
self.validators = {}
for key in schemas.keys():
self.validators[key] = [
createValidator(schemas[key][0]),
createValidator(schemas[key][1])
]
# returns error string on error, None otherwise
def validate(self, odfpath):
zip = zipfile.ZipFile(odfpath, 'r')
odfversion = getODFVersion(zip)
if not odfversion in schemas:
return "Document has no version number"
err = self.validateFile(zip, 'content.xml',
self.validators[odfversion][0])
if (err):
return err
err = self.validateFile(zip, 'styles.xml',
self.validators[odfversion][0])
if (err):
return err
err = self.validateFile(zip, 'META-INF/manifest.xml',
self.validators[odfversion][1])
if (err):
return err
return None
def validateFile(self, zip, file, validator):
try:
xml = lxml.etree.XML(zip.read(file));
except lxml.etree.XMLSyntaxError as e:
return file + ':' + str(e)
except KeyError as e:
return e
if not validator.validate(xml):
return file + ':' + str(validator.error_log.last_error)
#
if __name__ == '__main__':
if sys.argv[1] and sys.argv[2] and sys.argv[3]:
if not os.path.exists(sys.argv[2]):
print "Wrong use of script: missing path to directory in which file resides"
sys.exit(1)
else:
#NOTE! sys.argv[1] is hardcoded to "no" in CMakeList.txt under /calligra/tools/scripts/
if sys.argv[1] == "yes":
jingjar = newGetJing()
if jingjar:
validator = jingodfvalidator(jingjar)
else:
validator = odfvalidator()
filepath = os.path.abspath(os.path.join(sys.argv[2], sys.argv[3]))
if os.path.exists(filepath):
ret = singleFileConvertAndValidate(filepath, True)
sys.exit(ret)
elif sys.argv[1] == "no":
filepath = os.path.abspath(os.path.join(sys.argv[2], sys.argv[3]))
print filepath
if os.path.exists(filepath):
ret = singleFileConvertAndValidate(filepath, False)
sys.exit(ret)
else:
print "Wrong use of script: validation neither yes or no"
sys.exit(1)
else:
print "Wrong use of script: parameters missing:"
sys.exit(1)
|