1 /* 2 * ==================================================================== 3 * About Sarissa: http://dev.abiss.gr/sarissa 4 * ==================================================================== 5 * Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs. 6 * The library supports Gecko based browsers like Mozilla and Firefox, 7 * Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and Opera 8 * @version 0.9.9.5 9 * @author: Copyright 2004-2008 Emmanouil Batsis, mailto: mbatsis at users full stop sourceforge full stop net 10 * ==================================================================== 11 * Licence 12 * ==================================================================== 13 * Sarissa is free software distributed under the GNU GPL version 2 (see <a href="gpl.txt">gpl.txt</a>) or higher, 14 * GNU LGPL version 2.1 (see <a href="lgpl.txt">lgpl.txt</a>) or higher and Apache Software License 2.0 or higher 15 * (see <a href="asl.txt">asl.txt</a>). This means you can choose one of the three and use that if you like. If 16 * you make modifications under the ASL, i would appreciate it if you submitted those. 17 * In case your copy of Sarissa does not include the license texts, you may find 18 * them online in various formats at <a href="http://www.gnu.org">http://www.gnu.org</a> and 19 * <a href="http://www.apache.org">http://www.apache.org</a>. 20 * 21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 22 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 23 * WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE 24 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 25 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 27 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 28 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 29 */ 30 /** 31 * <p>Sarissa is a utility class. Provides "static" methods for DOMDocument, 32 * DOM Node serialization to XML strings and other utility goodies.</p> 33 * @constructor 34 * @static 35 */ 36 function Sarissa(){} 37 Sarissa.VERSION = "0.9.9.5"; 38 Sarissa.PARSED_OK = "Document contains no parsing errors"; 39 Sarissa.PARSED_EMPTY = "Document is empty"; 40 Sarissa.PARSED_UNKNOWN_ERROR = "Not well-formed or other error"; 41 Sarissa.IS_ENABLED_TRANSFORM_NODE = false; 42 Sarissa.REMOTE_CALL_FLAG = "gr.abiss.sarissa.REMOTE_CALL_FLAG"; 43 /** @private */ 44 Sarissa._lastUniqueSuffix = 0; 45 /** @private */ 46 Sarissa._getUniqueSuffix = function(){ 47 return Sarissa._lastUniqueSuffix++; 48 }; 49 /** @private */ 50 Sarissa._SARISSA_IEPREFIX4XSLPARAM = ""; 51 /** @private */ 52 Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION = document.implementation && true; 53 /** @private */ 54 Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT = Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.createDocument; 55 /** @private */ 56 Sarissa._SARISSA_HAS_DOM_FEATURE = Sarissa._SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.hasFeature; 57 /** @private */ 58 Sarissa._SARISSA_IS_MOZ = Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT && Sarissa._SARISSA_HAS_DOM_FEATURE; 59 /** @private */ 60 Sarissa._SARISSA_IS_SAFARI = navigator.userAgent.toLowerCase().indexOf("safari") != -1 || navigator.userAgent.toLowerCase().indexOf("konqueror") != -1; 61 /** @private */ 62 Sarissa._SARISSA_IS_SAFARI_OLD = Sarissa._SARISSA_IS_SAFARI && (parseInt((navigator.userAgent.match(/AppleWebKit\/(\d+)/)||{})[1], 10) < 420); 63 /** @private */ 64 Sarissa._SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1; 65 /** @private */ 66 Sarissa._SARISSA_IS_OPERA = navigator.userAgent.toLowerCase().indexOf("opera") != -1; 67 if(!window.Node || !Node.ELEMENT_NODE){ 68 Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12}; 69 } 70 71 //This breaks for(x in o) loops in the old Safari 72 if(Sarissa._SARISSA_IS_SAFARI_OLD){ 73 HTMLHtmlElement = document.createElement("html").constructor; 74 Node = HTMLElement = {}; 75 HTMLElement.prototype = HTMLHtmlElement.__proto__.__proto__; 76 HTMLDocument = Document = document.constructor; 77 var x = new DOMParser(); 78 XMLDocument = x.constructor; 79 Element = x.parseFromString("<Single />", "text/xml").documentElement.constructor; 80 x = null; 81 } 82 if(typeof XMLDocument == "undefined" && typeof Document !="undefined"){ XMLDocument = Document; } 83 84 // IE initialization 85 if(Sarissa._SARISSA_IS_IE){ 86 // for XSLT parameter names, prefix needed by IE 87 Sarissa._SARISSA_IEPREFIX4XSLPARAM = "xsl:"; 88 // used to store the most recent ProgID available out of the above 89 var _SARISSA_DOM_PROGID = ""; 90 var _SARISSA_XMLHTTP_PROGID = ""; 91 var _SARISSA_DOM_XMLWRITER = ""; 92 /** 93 * Called when the sarissa.js file is parsed, to pick most recent 94 * ProgIDs for IE, then gets destroyed. 95 * @memberOf Sarissa 96 * @private 97 * @param idList an array of MSXML PROGIDs from which the most recent will be picked for a given object 98 * @param enabledList an array of arrays where each array has two items; the index of the PROGID for which a certain feature is enabled 99 */ 100 Sarissa.pickRecentProgID = function (idList){ 101 // found progID flag 102 var bFound = false, e; 103 var o2Store; 104 for(var i=0; i < idList.length && !bFound; i++){ 105 try{ 106 var oDoc = new ActiveXObject(idList[i]); 107 o2Store = idList[i]; 108 bFound = true; 109 }catch (objException){ 110 // trap; try next progID 111 e = objException; 112 } 113 } 114 if (!bFound) { 115 throw "Could not retrieve a valid progID of Class: " + idList[idList.length-1]+". (original exception: "+e+")"; 116 } 117 idList = null; 118 return o2Store; 119 }; 120 // pick best available MSXML progIDs 121 _SARISSA_DOM_PROGID = null; 122 _SARISSA_THREADEDDOM_PROGID = null; 123 _SARISSA_XSLTEMPLATE_PROGID = null; 124 _SARISSA_XMLHTTP_PROGID = null; 125 // commenting the condition out; we need to redefine XMLHttpRequest 126 // anyway as IE7 hardcodes it to MSXML3.0 causing version problems 127 // between different activex controls 128 //if(!window.XMLHttpRequest){ 129 /** 130 * Emulate XMLHttpRequest 131 * @constructor 132 */ 133 XMLHttpRequest = function() { 134 if(!_SARISSA_XMLHTTP_PROGID){ 135 _SARISSA_XMLHTTP_PROGID = Sarissa.pickRecentProgID(["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]); 136 } 137 return new ActiveXObject(_SARISSA_XMLHTTP_PROGID); 138 }; 139 //} 140 // we dont need this anymore 141 //============================================ 142 // Factory methods (IE) 143 //============================================ 144 // see non-IE version 145 Sarissa.getDomDocument = function(sUri, sName){ 146 if(!_SARISSA_DOM_PROGID){ 147 try{ 148 _SARISSA_DOM_PROGID = Sarissa.pickRecentProgID(["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"]); 149 }catch(e){ 150 _SARISSA_DOM_PROGID = "noActiveX"; 151 } 152 } 153 154 // Not sure how far IE can carry this but try to do something useful when ActiveX is disabled 155 var oDoc = _SARISSA_DOM_PROGID == "noActiveX" ? document.createElement("xml") : new ActiveXObject(_SARISSA_DOM_PROGID); 156 // set validation off, make sure older IEs dont choke (no time or IEs to test ;-) 157 try{ 158 oDoc.validateOnParse = false; 159 oDoc.resolveExternals = "false"; 160 oDoc.setProperty("ProhibitDTD", false); 161 }catch(e){} 162 163 // if a root tag name was provided, we need to load it in the DOM object 164 if (sName){ 165 // create an artifical namespace prefix 166 // or reuse existing prefix if applicable 167 var prefix = ""; 168 if(sUri){ 169 if(sName.indexOf(":") > 1){ 170 prefix = sName.substring(0, sName.indexOf(":")); 171 sName = sName.substring(sName.indexOf(":")+1); 172 }else{ 173 prefix = "a" + Sarissa._getUniqueSuffix(); 174 } 175 } 176 // use namespaces if a namespace URI exists 177 if(sUri){ 178 oDoc.loadXML('<' + prefix+':'+sName + " xmlns:" + prefix + "=\"" + sUri + "\"" + " />"); 179 } else { 180 oDoc.loadXML('<' + sName + " />"); 181 } 182 } 183 return oDoc; 184 }; 185 // see non-IE version 186 Sarissa.getParseErrorText = function (oDoc) { 187 var parseErrorText = Sarissa.PARSED_OK; 188 if(oDoc && oDoc.parseError && oDoc.parseError.errorCode && oDoc.parseError.errorCode != 0){ 189 parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason + 190 "\nLocation: " + oDoc.parseError.url + 191 "\nLine Number " + oDoc.parseError.line + ", Column " + 192 oDoc.parseError.linepos + 193 ":\n" + oDoc.parseError.srcText + 194 "\n"; 195 for(var i = 0; i < oDoc.parseError.linepos;i++){ 196 parseErrorText += "-"; 197 } 198 parseErrorText += "^\n"; 199 } 200 else if(oDoc.documentElement === null){ 201 parseErrorText = Sarissa.PARSED_EMPTY; 202 } 203 return parseErrorText; 204 }; 205 // see non-IE version 206 Sarissa.setXpathNamespaces = function(oDoc, sNsSet) { 207 oDoc.setProperty("SelectionLanguage", "XPath"); 208 oDoc.setProperty("SelectionNamespaces", sNsSet); 209 }; 210 /** 211 * A class that reuses the same XSLT stylesheet for multiple transforms. 212 * @constructor 213 */ 214 XSLTProcessor = function(){ 215 if(!_SARISSA_XSLTEMPLATE_PROGID){ 216 _SARISSA_XSLTEMPLATE_PROGID = Sarissa.pickRecentProgID(["Msxml2.XSLTemplate.6.0", "MSXML2.XSLTemplate.3.0"]); 217 } 218 this.template = new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID); 219 this.processor = null; 220 }; 221 /** 222 * Imports the given XSLT DOM and compiles it to a reusable transform 223 * <b>Note:</b> If the stylesheet was loaded from a URL and contains xsl:import or xsl:include elements,it will be reloaded to resolve those 224 * @param {DOMDocument} xslDoc The XSLT DOMDocument to import 225 */ 226 XSLTProcessor.prototype.importStylesheet = function(xslDoc){ 227 if(!_SARISSA_THREADEDDOM_PROGID){ 228 _SARISSA_THREADEDDOM_PROGID = Sarissa.pickRecentProgID(["MSXML2.FreeThreadedDOMDocument.6.0", "MSXML2.FreeThreadedDOMDocument.3.0"]); 229 } 230 xslDoc.setProperty("SelectionLanguage", "XPath"); 231 xslDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"); 232 // convert stylesheet to free threaded 233 var converted = new ActiveXObject(_SARISSA_THREADEDDOM_PROGID); 234 // make included/imported stylesheets work if exist and xsl was originally loaded from url 235 try{ 236 converted.resolveExternals = true; 237 converted.setProperty("AllowDocumentFunction", true); 238 converted.setProperty("AllowXsltScript", true); 239 } 240 catch(e){ 241 // Ignore. "AllowDocumentFunction" and "AllowXsltScript" is only supported in MSXML 3.0 SP4+ and 3.0 SP8+ respectively. 242 } 243 if(xslDoc.url && xslDoc.selectSingleNode("//xsl:*[local-name() = 'import' or local-name() = 'include']") != null){ 244 converted.async = false; 245 converted.load(xslDoc.url); 246 } 247 else { 248 converted.loadXML(xslDoc.xml); 249 } 250 converted.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"); 251 var output = converted.selectSingleNode("//xsl:output"); 252 //this.outputMethod = output ? output.getAttribute("method") : "html"; 253 if(output) { 254 this.outputMethod = output.getAttribute("method"); 255 } 256 else { 257 delete this.outputMethod; 258 } 259 this.template.stylesheet = converted; 260 this.processor = this.template.createProcessor(); 261 // for getParameter and clearParameters 262 this.paramsSet = []; 263 }; 264 265 /** 266 * Transform the given XML DOM and return the transformation result as a new DOM document 267 * @param {DOMDocument} sourceDoc The XML DOMDocument to transform 268 * @return {DOMDocument} The transformation result as a DOM Document 269 */ 270 XSLTProcessor.prototype.transformToDocument = function(sourceDoc){ 271 // fix for bug 1549749 272 var outDoc; 273 if(_SARISSA_THREADEDDOM_PROGID){ 274 this.processor.input=sourceDoc; 275 outDoc=new ActiveXObject(_SARISSA_DOM_PROGID); 276 this.processor.output=outDoc; 277 this.processor.transform(); 278 return outDoc; 279 } 280 else{ 281 if(!_SARISSA_DOM_XMLWRITER){ 282 _SARISSA_DOM_XMLWRITER = Sarissa.pickRecentProgID(["Msxml2.MXXMLWriter.6.0", "Msxml2.MXXMLWriter.3.0", "MSXML2.MXXMLWriter", "MSXML.MXXMLWriter", "Microsoft.XMLDOM"]); 283 } 284 this.processor.input = sourceDoc; 285 outDoc = new ActiveXObject(_SARISSA_DOM_XMLWRITER); 286 this.processor.output = outDoc; 287 this.processor.transform(); 288 var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID); 289 oDoc.loadXML(outDoc.output+""); 290 return oDoc; 291 } 292 }; 293 294 /** 295 * Transform the given XML DOM and return the transformation result as a new DOM fragment. 296 * <b>Note</b>: The xsl:output method must match the nature of the owner document (XML/HTML). 297 * @param {DOMDocument} sourceDoc The XML DOMDocument to transform 298 * @param {DOMDocument} ownerDoc The owner of the result fragment 299 * @return {DOMDocument} The transformation result as a DOM Document 300 */ 301 XSLTProcessor.prototype.transformToFragment = function (sourceDoc, ownerDoc) { 302 this.processor.input = sourceDoc; 303 this.processor.transform(); 304 var s = this.processor.output; 305 var f = ownerDoc.createDocumentFragment(); 306 var container; 307 if (this.outputMethod == 'text') { 308 f.appendChild(ownerDoc.createTextNode(s)); 309 } else if (ownerDoc.body && ownerDoc.body.innerHTML) { 310 container = ownerDoc.createElement('div'); 311 container.innerHTML = s; 312 while (container.hasChildNodes()) { 313 f.appendChild(container.firstChild); 314 } 315 } 316 else { 317 var oDoc = new ActiveXObject(_SARISSA_DOM_PROGID); 318 if (s.substring(0, 5) == '<?xml') { 319 s = s.substring(s.indexOf('?>') + 2); 320 } 321 var xml = ''.concat('<my>', s, '</my>'); 322 oDoc.loadXML(xml); 323 container = oDoc.documentElement; 324 while (container.hasChildNodes()) { 325 f.appendChild(container.firstChild); 326 } 327 } 328 return f; 329 }; 330 331 /** 332 * Set global XSLT parameter of the imported stylesheet. This method should 333 * only be used <strong>after</strong> the importStylesheet method for the 334 * context XSLTProcessor instance. 335 * @param {String} nsURI The parameter namespace URI 336 * @param {String} name The parameter base name 337 * @param {String} value The new parameter value 338 */ 339 XSLTProcessor.prototype.setParameter = function(nsURI, name, value){ 340 // make value a zero length string if null to allow clearing 341 value = value ? value : ""; 342 // nsURI is optional but cannot be null 343 if(nsURI){ 344 this.processor.addParameter(name, value, nsURI); 345 }else{ 346 this.processor.addParameter(name, value); 347 } 348 // update updated params for getParameter 349 nsURI = "" + (nsURI || ""); 350 if(!this.paramsSet[nsURI]){ 351 this.paramsSet[nsURI] = []; 352 } 353 this.paramsSet[nsURI][name] = value; 354 }; 355 /** 356 * Gets a parameter if previously set by setParameter. Returns null 357 * otherwise 358 * @param {String} name The parameter base name 359 * @param {String} value The new parameter value 360 * @return {String} The parameter value if reviously set by setParameter, null otherwise 361 */ 362 XSLTProcessor.prototype.getParameter = function(nsURI, name){ 363 nsURI = "" + (nsURI || ""); 364 if(this.paramsSet[nsURI] && this.paramsSet[nsURI][name]){ 365 return this.paramsSet[nsURI][name]; 366 }else{ 367 return null; 368 } 369 }; 370 371 /** 372 * Clear parameters (set them to default values as defined in the stylesheet itself) 373 */ 374 XSLTProcessor.prototype.clearParameters = function(){ 375 for(var nsURI in this.paramsSet){ 376 for(var name in this.paramsSet[nsURI]){ 377 if(nsURI!=""){ 378 this.processor.addParameter(name, "", nsURI); 379 }else{ 380 this.processor.addParameter(name, ""); 381 } 382 } 383 } 384 this.paramsSet = []; 385 }; 386 }else{ /* end IE initialization, try to deal with real browsers now ;-) */ 387 if(Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT){ 388 /** 389 * <p>Ensures the document was loaded correctly, otherwise sets the 390 * parseError to -1 to indicate something went wrong. Internal use</p> 391 * @private 392 */ 393 Sarissa.__handleLoad__ = function(oDoc){ 394 Sarissa.__setReadyState__(oDoc, 4); 395 }; 396 /** 397 * <p>Attached by an event handler to the load event. Internal use.</p> 398 * @private 399 */ 400 _sarissa_XMLDocument_onload = function(){ 401 Sarissa.__handleLoad__(this); 402 }; 403 /** 404 * <p>Sets the readyState property of the given DOM Document object. 405 * Internal use.</p> 406 * @memberOf Sarissa 407 * @private 408 * @param oDoc the DOM Document object to fire the 409 * readystatechange event 410 * @param iReadyState the number to change the readystate property to 411 */ 412 Sarissa.__setReadyState__ = function(oDoc, iReadyState){ 413 oDoc.readyState = iReadyState; 414 oDoc.readystate = iReadyState; 415 if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function") { 416 oDoc.onreadystatechange(); 417 } 418 }; 419 420 Sarissa.getDomDocument = function(sUri, sName){ 421 var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null); 422 if(!oDoc.onreadystatechange){ 423 424 /** 425 * <p>Emulate IE's onreadystatechange attribute</p> 426 */ 427 oDoc.onreadystatechange = null; 428 } 429 if(!oDoc.readyState){ 430 /** 431 * <p>Emulates IE's readyState property, which always gives an integer from 0 to 4:</p> 432 * <ul><li>1 == LOADING,</li> 433 * <li>2 == LOADED,</li> 434 * <li>3 == INTERACTIVE,</li> 435 * <li>4 == COMPLETED</li></ul> 436 */ 437 oDoc.readyState = 0; 438 } 439 oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false); 440 return oDoc; 441 }; 442 if(window.XMLDocument){ 443 // do nothing 444 }// TODO: check if the new document has content before trying to copynodes, check for error handling in DOM 3 LS 445 else if(Sarissa._SARISSA_HAS_DOM_FEATURE && window.Document && !Document.prototype.load && document.implementation.hasFeature('LS', '3.0')){ 446 //Opera 9 may get the XPath branch which gives creates XMLDocument, therefore it doesn't reach here which is good 447 /** 448 * <p>Factory method to obtain a new DOM Document object</p> 449 * @memberOf Sarissa 450 * @param {String} sUri the namespace of the root node (if any) 451 * @param {String} sUri the local name of the root node (if any) 452 * @returns {DOMDOcument} a new DOM Document 453 */ 454 Sarissa.getDomDocument = function(sUri, sName){ 455 var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null); 456 return oDoc; 457 }; 458 } 459 else { 460 Sarissa.getDomDocument = function(sUri, sName){ 461 var oDoc = document.implementation.createDocument(sUri?sUri:null, sName?sName:null, null); 462 // looks like safari does not create the root element for some unknown reason 463 if(oDoc && (sUri || sName) && !oDoc.documentElement){ 464 oDoc.appendChild(oDoc.createElementNS(sUri, sName)); 465 } 466 return oDoc; 467 }; 468 } 469 }//if(Sarissa._SARISSA_HAS_DOM_CREATE_DOCUMENT) 470 } 471 //========================================== 472 // Common stuff 473 //========================================== 474 if(!window.DOMParser){ 475 if(Sarissa._SARISSA_IS_SAFARI){ 476 /** 477 * DOMParser is a utility class, used to construct DOMDocuments from XML strings 478 * @constructor 479 */ 480 DOMParser = function() { }; 481 /** 482 * Construct a new DOM Document from the given XMLstring 483 * @param {String} sXml the given XML string 484 * @param {String} contentType the content type of the document the given string represents (one of text/xml, application/xml, application/xhtml+xml). 485 * @return {DOMDocument} a new DOM Document from the given XML string 486 */ 487 DOMParser.prototype.parseFromString = function(sXml, contentType){ 488 var xmlhttp = new XMLHttpRequest(); 489 xmlhttp.open("GET", "data:text/xml;charset=utf-8," + encodeURIComponent(sXml), false); 490 xmlhttp.send(null); 491 return xmlhttp.responseXML; 492 }; 493 }else if(Sarissa.getDomDocument && Sarissa.getDomDocument() && Sarissa.getDomDocument(null, "bar").xml){ 494 DOMParser = function() { }; 495 DOMParser.prototype.parseFromString = function(sXml, contentType){ 496 var doc = Sarissa.getDomDocument(); 497 try{ 498 doc.validateOnParse = false; 499 doc.setProperty("ProhibitDTD", false); 500 }catch(e){} 501 doc.loadXML(sXml); 502 return doc; 503 }; 504 } 505 } 506 507 if((typeof(document.importNode) == "undefined") && Sarissa._SARISSA_IS_IE){ 508 try{ 509 /** 510 * Implementation of importNode for the context window document in IE. 511 * If <code>oNode</code> is a TextNode, <code>bChildren</code> is ignored. 512 * @param {DOMNode} oNode the Node to import 513 * @param {boolean} bChildren whether to include the children of oNode 514 * @returns the imported node for further use 515 */ 516 document.importNode = function(oNode, bChildren){ 517 var tmp; 518 if (oNode.nodeName=='#text') { 519 return document.createTextNode(oNode.data); 520 } 521 else { 522 if(oNode.nodeName == "tbody" || oNode.nodeName == "tr"){ 523 tmp = document.createElement("table"); 524 } 525 else if(oNode.nodeName == "td"){ 526 tmp = document.createElement("tr"); 527 } 528 else if(oNode.nodeName == "option"){ 529 tmp = document.createElement("select"); 530 } 531 else{ 532 tmp = document.createElement("div"); 533 } 534 if(bChildren){ 535 tmp.innerHTML = oNode.xml ? oNode.xml : oNode.outerHTML; 536 }else{ 537 tmp.innerHTML = oNode.xml ? oNode.cloneNode(false).xml : oNode.cloneNode(false).outerHTML; 538 } 539 return tmp.getElementsByTagName("*")[0]; 540 } 541 }; 542 }catch(e){ } 543 } 544 if(!Sarissa.getParseErrorText){ 545 /** 546 * <p>Returns a human readable description of the parsing error. Usefull 547 * for debugging. Tip: append the returned error string in a <pre> 548 * element if you want to render it.</p> 549 * <p>Many thanks to Christian Stocker for the initial patch.</p> 550 * @memberOf Sarissa 551 * @param {DOMDocument} oDoc The target DOM document 552 * @returns {String} The parsing error description of the target Document in 553 * human readable form (preformated text) 554 */ 555 Sarissa.getParseErrorText = function (oDoc){ 556 var parseErrorText = Sarissa.PARSED_OK; 557 if((!oDoc) || (!oDoc.documentElement)){ 558 parseErrorText = Sarissa.PARSED_EMPTY; 559 } else if(oDoc.documentElement.tagName == "parsererror"){ 560 parseErrorText = oDoc.documentElement.firstChild.data; 561 parseErrorText += "\n" + oDoc.documentElement.firstChild.nextSibling.firstChild.data; 562 } else if(oDoc.getElementsByTagName("parsererror").length > 0){ 563 var parsererror = oDoc.getElementsByTagName("parsererror")[0]; 564 parseErrorText = Sarissa.getText(parsererror, true)+"\n"; 565 } else if(oDoc.parseError && oDoc.parseError.errorCode != 0){ 566 parseErrorText = Sarissa.PARSED_UNKNOWN_ERROR; 567 } 568 return parseErrorText; 569 }; 570 } 571 /** 572 * Get a string with the concatenated values of all string nodes under the given node 573 * @param {DOMNode} oNode the given DOM node 574 * @param {boolean} deep whether to recursively scan the children nodes of the given node for text as well. Default is <code>false</code> 575 * @memberOf Sarissa 576 */ 577 Sarissa.getText = function(oNode, deep){ 578 var s = ""; 579 var nodes = oNode.childNodes; 580 // opera fix, finds no child text node for attributes so we use .value 581 if (oNode.nodeType == Node.ATTRIBUTE_NODE && nodes.length == 0) { 582 return oNode.value; 583 } 584 // END opera fix 585 for(var i=0; i < nodes.length; i++){ 586 var node = nodes[i]; 587 var nodeType = node.nodeType; 588 if(nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE){ 589 s += node.data; 590 } else if(deep === true && (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE || nodeType == Node.DOCUMENT_FRAGMENT_NODE)){ 591 s += Sarissa.getText(node, true); 592 } 593 } 594 return s; 595 }; 596 if(!window.XMLSerializer && Sarissa.getDomDocument && Sarissa.getDomDocument("","foo", null).xml){ 597 /** 598 * Utility class to serialize DOM Node objects to XML strings 599 * @constructor 600 */ 601 XMLSerializer = function(){}; 602 /** 603 * Serialize the given DOM Node to an XML string 604 * @param {DOMNode} oNode the DOM Node to serialize 605 */ 606 XMLSerializer.prototype.serializeToString = function(oNode) { 607 return oNode.xml; 608 }; 609 } 610 611 /** 612 * Strips tags from the given markup string. If the given string is 613 * <code>undefined</code>, <code>null</code> or empty, it is returned as is. 614 * @memberOf Sarissa 615 * @param {String} s the string to strip the tags from 616 */ 617 Sarissa.stripTags = function (s) { 618 return s?s.replace(/<[^>]+>/g,""):s; 619 }; 620 /** 621 * <p>Deletes all child nodes of the given node</p> 622 * @memberOf Sarissa 623 * @param {DOMNode} oNode the Node to empty 624 */ 625 Sarissa.clearChildNodes = function(oNode) { 626 // need to check for firstChild due to opera 8 bug with hasChildNodes 627 while(oNode.firstChild) { 628 oNode.removeChild(oNode.firstChild); 629 } 630 }; 631 /** 632 * <p> Copies the childNodes of nodeFrom to nodeTo</p> 633 * <p> <b>Note:</b> The second object's original content is deleted before 634 * the copy operation, unless you supply a true third parameter</p> 635 * @memberOf Sarissa 636 * @param {DOMNode} nodeFrom the Node to copy the childNodes from 637 * @param {DOMNode} nodeTo the Node to copy the childNodes to 638 * @param {boolean} bPreserveExisting whether to preserve the original content of nodeTo, default is false 639 */ 640 Sarissa.copyChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) { 641 if(Sarissa._SARISSA_IS_SAFARI && nodeTo.nodeType == Node.DOCUMENT_NODE){ // SAFARI_OLD ?? 642 nodeTo = nodeTo.documentElement; //Apparently there's a bug in safari where you can't appendChild to a document node 643 } 644 645 if((!nodeFrom) || (!nodeTo)){ 646 throw "Both source and destination nodes must be provided"; 647 } 648 if(!bPreserveExisting){ 649 Sarissa.clearChildNodes(nodeTo); 650 } 651 var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument; 652 var nodes = nodeFrom.childNodes; 653 var i; 654 if(typeof(ownerDoc.importNode) != "undefined") { 655 for(i=0;i < nodes.length;i++) { 656 nodeTo.appendChild(ownerDoc.importNode(nodes[i], true)); 657 } 658 } else { 659 for(i=0;i < nodes.length;i++) { 660 nodeTo.appendChild(nodes[i].cloneNode(true)); 661 } 662 } 663 }; 664 665 /** 666 * <p> Moves the childNodes of nodeFrom to nodeTo</p> 667 * <p> <b>Note:</b> The second object's original content is deleted before 668 * the move operation, unless you supply a true third parameter</p> 669 * @memberOf Sarissa 670 * @param {DOMNode} nodeFrom the Node to copy the childNodes from 671 * @param {DOMNode} nodeTo the Node to copy the childNodes to 672 * @param {boolean} bPreserveExisting whether to preserve the original content of nodeTo, default is 673 */ 674 Sarissa.moveChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) { 675 if((!nodeFrom) || (!nodeTo)){ 676 throw "Both source and destination nodes must be provided"; 677 } 678 if(!bPreserveExisting){ 679 Sarissa.clearChildNodes(nodeTo); 680 } 681 var nodes = nodeFrom.childNodes; 682 // if within the same doc, just move, else copy and delete 683 if(nodeFrom.ownerDocument == nodeTo.ownerDocument){ 684 while(nodeFrom.firstChild){ 685 nodeTo.appendChild(nodeFrom.firstChild); 686 } 687 } else { 688 var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument; 689 var i; 690 if(typeof(ownerDoc.importNode) != "undefined") { 691 for(i=0;i < nodes.length;i++) { 692 nodeTo.appendChild(ownerDoc.importNode(nodes[i], true)); 693 } 694 }else{ 695 for(i=0;i < nodes.length;i++) { 696 nodeTo.appendChild(nodes[i].cloneNode(true)); 697 } 698 } 699 Sarissa.clearChildNodes(nodeFrom); 700 } 701 }; 702 703 /** 704 * <p>Serialize any <strong>non</strong> DOM object to an XML string. All properties are serialized using the property name 705 * as the XML element name. Array elements are rendered as <code>array-item</code> elements, 706 * using their index/key as the value of the <code>key</code> attribute.</p> 707 * @memberOf Sarissa 708 * @param {Object} anyObject the object to serialize 709 * @param {String} objectName a name for that object, to be used as the root element name 710 * @param {String} indentSpace Optional, the indentation space to use, default is an empty 711 * string. A single space character is added in any recursive call. 712 * @param {noolean} skipEscape Optional, whether to skip escaping characters that map to the 713 * five predefined XML entities. Default is <code>false</code>. 714 * @return {String} the XML serialization of the given object as a string 715 */ 716 Sarissa.xmlize = function(anyObject, objectName, indentSpace, skipEscape){ 717 indentSpace = indentSpace?indentSpace:''; 718 var s = indentSpace + '<' + objectName + '>'; 719 var isLeaf = false; 720 if(!(anyObject instanceof Object) || anyObject instanceof Number || anyObject instanceof String || anyObject instanceof Boolean || anyObject instanceof Date){ 721 s += (skipEscape ? Sarissa.escape(anyObject) : anyObject); 722 isLeaf = true; 723 }else{ 724 s += "\n"; 725 var isArrayItem = anyObject instanceof Array; 726 for(var name in anyObject){ 727 // do not xmlize functions 728 if (anyObject[name] instanceof Function){ 729 continue; 730 } 731 s += Sarissa.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + " "); 732 } 733 s += indentSpace; 734 } 735 return (s += (objectName.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName + ">\n")); 736 }; 737 738 /** 739 * Escape the given string chacters that correspond to the five predefined XML entities 740 * @memberOf Sarissa 741 * @param {String} sXml the string to escape 742 */ 743 Sarissa.escape = function(sXml){ 744 return sXml.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); 745 }; 746 747 /** 748 * Unescape the given string. This turns the occurences of the predefined XML 749 * entities to become the characters they represent correspond to the five predefined XML entities 750 * @memberOf Sarissa 751 * @param {String}sXml the string to unescape 752 */ 753 Sarissa.unescape = function(sXml){ 754 return sXml.replace(/'/g,"'").replace(/"/g,"\"").replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"); 755 }; 756 757 /** @private */ 758 Sarissa.updateCursor = function(oTargetElement, sValue) { 759 if(oTargetElement && oTargetElement.style && oTargetElement.style.cursor != undefined ){ 760 oTargetElement.style.cursor = sValue; 761 } 762 }; 763 764 /** 765 * Asynchronously update an element with response of a GET request on the given URL. Passing a configured XSLT 766 * processor will result in transforming and updating oNode before using it to update oTargetElement. 767 * You can also pass a callback function to be executed when the update is finished. The function will be called as 768 * <code>functionName(oNode, oTargetElement);</code> 769 * @memberOf Sarissa 770 * @param {String} sFromUrl the URL to make the request to 771 * @param {DOMElement} oTargetElement the element to update 772 * @param {XSLTProcessor} xsltproc (optional) the transformer to use on the returned 773 * content before updating the target element with it 774 * @param {Function} callback (optional) a Function object to execute once the update is finished successfuly, called as <code>callback(sFromUrl, oTargetElement)</code>. 775 * In case an exception is thrown during execution, the callback is called as called as <code>callback(sFromUrl, oTargetElement, oException)</code> 776 * @param {boolean} skipCache (optional) whether to skip any cache 777 */ 778 Sarissa.updateContentFromURI = function(sFromUrl, oTargetElement, xsltproc, callback, skipCache) { 779 try{ 780 Sarissa.updateCursor(oTargetElement, "wait"); 781 var xmlhttp = new XMLHttpRequest(); 782 xmlhttp.open("GET", sFromUrl, true); 783 xmlhttp.onreadystatechange = function() { 784 if (xmlhttp.readyState == 4) { 785 try{ 786 var oDomDoc = xmlhttp.responseXML; 787 if(oDomDoc && Sarissa.getParseErrorText(oDomDoc) == Sarissa.PARSED_OK){ 788 Sarissa.updateContentFromNode(xmlhttp.responseXML, oTargetElement, xsltproc); 789 if(callback){ 790 callback(sFromUrl, oTargetElement); 791 } 792 } 793 else{ 794 throw Sarissa.getParseErrorText(oDomDoc); 795 } 796 } 797 catch(e){ 798 if(callback){ 799 callback(sFromUrl, oTargetElement, e); 800 } 801 else{ 802 throw e; 803 } 804 } 805 } 806 }; 807 if (skipCache) { 808 var oldage = "Sat, 1 Jan 2000 00:00:00 GMT"; 809 xmlhttp.setRequestHeader("If-Modified-Since", oldage); 810 } 811 xmlhttp.send(""); 812 } 813 catch(e){ 814 Sarissa.updateCursor(oTargetElement, "auto"); 815 if(callback){ 816 callback(sFromUrl, oTargetElement, e); 817 } 818 else{ 819 throw e; 820 } 821 } 822 }; 823 824 /** 825 * Update an element's content with the given DOM node. Passing a configured XSLT 826 * processor will result in transforming and updating oNode before using it to update oTargetElement. 827 * You can also pass a callback function to be executed when the update is finished. The function will be called as 828 * <code>functionName(oNode, oTargetElement);</code> 829 * @memberOf Sarissa 830 * @param {DOMNode} oNode the URL to make the request to 831 * @param {DOMElement} oTargetElement the element to update 832 * @param {XSLTProcessor} xsltproc (optional) the transformer to use on the given 833 * DOM node before updating the target element with it 834 */ 835 Sarissa.updateContentFromNode = function(oNode, oTargetElement, xsltproc) { 836 try { 837 Sarissa.updateCursor(oTargetElement, "wait"); 838 Sarissa.clearChildNodes(oTargetElement); 839 // check for parsing errors 840 var ownerDoc = oNode.nodeType == Node.DOCUMENT_NODE?oNode:oNode.ownerDocument; 841 if(ownerDoc.parseError && ownerDoc.parseError.errorCode != 0) { 842 var pre = document.createElement("pre"); 843 pre.appendChild(document.createTextNode(Sarissa.getParseErrorText(ownerDoc))); 844 oTargetElement.appendChild(pre); 845 } 846 else { 847 // transform if appropriate 848 if(xsltproc) { 849 oNode = xsltproc.transformToDocument(oNode); 850 } 851 // be smart, maybe the user wants to display the source instead 852 if(oTargetElement.tagName.toLowerCase() == "textarea" || oTargetElement.tagName.toLowerCase() == "input") { 853 oTargetElement.value = new XMLSerializer().serializeToString(oNode); 854 } 855 else { 856 // ok that was not smart; it was paranoid. Keep up the good work by trying to use DOM instead of innerHTML 857 try{ 858 oTargetElement.appendChild(oTargetElement.ownerDocument.importNode(oNode, true)); 859 } 860 catch(e){ 861 oTargetElement.innerHTML = new XMLSerializer().serializeToString(oNode); 862 } 863 } 864 } 865 } 866 catch(e) { 867 throw e; 868 } 869 finally{ 870 Sarissa.updateCursor(oTargetElement, "auto"); 871 } 872 }; 873 874 875 /** 876 * Creates an HTTP URL query string from the given HTML form data 877 * @memberOf Sarissa 878 * @param {HTMLFormElement} oForm the form to construct the query string from 879 */ 880 Sarissa.formToQueryString = function(oForm){ 881 var qs = ""; 882 for(var i = 0;i < oForm.elements.length;i++) { 883 var oField = oForm.elements[i]; 884 var sFieldName = oField.getAttribute("name") ? oField.getAttribute("name") : oField.getAttribute("id"); 885 // ensure we got a proper name/id and that the field is not disabled 886 if(sFieldName && 887 ((!oField.disabled) || oField.type == "hidden")) { 888 switch(oField.type) { 889 case "hidden": 890 case "text": 891 case "textarea": 892 case "password": 893 qs += sFieldName + "=" + encodeURIComponent(oField.value) + "&"; 894 break; 895 case "select-one": 896 qs += sFieldName + "=" + encodeURIComponent(oField.options[oField.selectedIndex].value) + "&"; 897 break; 898 case "select-multiple": 899 for (var j = 0; j < oField.length; j++) { 900 var optElem = oField.options[j]; 901 if (optElem.selected === true) { 902 qs += sFieldName + "[]" + "=" + encodeURIComponent(optElem.value) + "&"; 903 } 904 } 905 break; 906 case "checkbox": 907 case "radio": 908 if(oField.checked) { 909 qs += sFieldName + "=" + encodeURIComponent(oField.value) + "&"; 910 } 911 break; 912 } 913 } 914 } 915 // return after removing last '&' 916 return qs.substr(0, qs.length - 1); 917 }; 918 919 920 /** 921 * Asynchronously update an element with response of an XMLHttpRequest-based emulation of a form submission. <p>The form <code>action</code> and 922 * <code>method</code> attributess will be followed. Passing a configured XSLT processor will result in 923 * transforming and updating the server response before using it to update the target element. 924 * You can also pass a callback function to be executed when the update is finished. The function will be called as 925 * <code>functionName(oNode, oTargetElement);</code></p> 926 * <p>Here is an example of using this in a form element:</p> 927 * <pre name="code" class="xml"> 928 * <div id="targetId"> this content will be updated</div> 929 * <form action="/my/form/handler" method="post" 930 * onbeforesubmit="return Sarissa.updateContentFromForm(this, document.getElementById('targetId'));"><pre> 931 * <p>If JavaScript is supported, the form will not be submitted. Instead, Sarissa will 932 * scan the form and make an appropriate AJAX request, also adding a parameter 933 * to signal to the server that this is an AJAX call. The parameter is 934 * constructed as <code>Sarissa.REMOTE_CALL_FLAG = "=true"</code> so you can change the name in your webpage 935 * simply by assigning another value to Sarissa.REMOTE_CALL_FLAG. If JavaScript is not supported 936 * the form will be submitted normally. 937 * @memberOf Sarissa 938 * @param {HTMLFormElement} oForm the form submition to emulate 939 * @param {DOMElement} oTargetElement the element to update 940 * @param {XSLTProcessor} xsltproc (optional) the transformer to use on the returned 941 * content before updating the target element with it 942 * @param {Function} callback (optional) a Function object to execute once the update is finished successfuly, called as <code>callback(oNode, oTargetElement)</code>. 943 * In case an exception occurs during excecution and a callback function was provided, the exception is cought and the callback is called as 944 * <code>callback(oForm, oTargetElement, exception)</code> 945 */ 946 Sarissa.updateContentFromForm = function(oForm, oTargetElement, xsltproc, callback) { 947 try{ 948 Sarissa.updateCursor(oTargetElement, "wait"); 949 // build parameters from form fields 950 var params = Sarissa.formToQueryString(oForm) + "&" + Sarissa.REMOTE_CALL_FLAG + "=true"; 951 var xmlhttp = new XMLHttpRequest(); 952 var bUseGet = oForm.getAttribute("method") && oForm.getAttribute("method").toLowerCase() == "get"; 953 if(bUseGet) { 954 xmlhttp.open("GET", oForm.getAttribute("action")+"?"+params, true); 955 } 956 else{ 957 xmlhttp.open('POST', oForm.getAttribute("action"), true); 958 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 959 xmlhttp.setRequestHeader("Content-length", params.length); 960 xmlhttp.setRequestHeader("Connection", "close"); 961 } 962 xmlhttp.onreadystatechange = function() { 963 try{ 964 if (xmlhttp.readyState == 4) { 965 var oDomDoc = xmlhttp.responseXML; 966 if(oDomDoc && Sarissa.getParseErrorText(oDomDoc) == Sarissa.PARSED_OK){ 967 Sarissa.updateContentFromNode(xmlhttp.responseXML, oTargetElement, xsltproc); 968 if(callback){ 969 callback(oForm, oTargetElement); 970 } 971 } 972 else{ 973 throw Sarissa.getParseErrorText(oDomDoc); 974 } 975 } 976 } 977 catch(e){ 978 if(callback){ 979 callback(oForm, oTargetElement, e); 980 } 981 else{ 982 throw e; 983 } 984 } 985 }; 986 xmlhttp.send(bUseGet?"":params); 987 } 988 catch(e){ 989 Sarissa.updateCursor(oTargetElement, "auto"); 990 if(callback){ 991 callback(oForm, oTargetElement, e); 992 } 993 else{ 994 throw e; 995 } 996 } 997 return false; 998 }; 999 1000 /** 1001 * Get the name of a function created like: 1002 * <pre>function functionName(){}</pre> 1003 * If a name is not found, attach the function to 1004 * the window object with a new name and return that 1005 * @param {Function} oFunc the function object 1006 */ 1007 Sarissa.getFunctionName = function(oFunc){ 1008 if(!oFunc || (typeof oFunc != 'function' )){ 1009 throw "The value of parameter 'oFunc' must be a function"; 1010 } 1011 if(oFunc.name) { 1012 return oFunc.name; 1013 } 1014 // try to parse the function name from the defintion 1015 var sFunc = oFunc.toString(); 1016 alert("sFunc: "+sFunc); 1017 var name = sFunc.substring(sFunc.indexOf('function') + 8 , sFunc.indexOf('(')); 1018 if(!name || name.length == 0 || name == " "){ 1019 // attach to window object under a new name 1020 name = "SarissaAnonymous" + Sarissa._getUniqueSuffix(); 1021 window[name] = oFunc; 1022 } 1023 return name; 1024 }; 1025 1026 /** 1027 * 1028 */ 1029 Sarissa.setRemoteJsonCallback = function(url, callback, callbackParam) { 1030 if(!callbackParam){ 1031 callbackParam = "callback"; 1032 } 1033 var callbackFunctionName = Sarissa.getFunctionName(callback); 1034 //alert("callbackFunctionName: '" + callbackFunctionName+"', length: "+callbackFunctionName.length); 1035 var id = "sarissa_json_script_id_" + Sarissa._getUniqueSuffix(); 1036 var oHead = document.getElementsByTagName("head")[0]; 1037 var scriptTag = document.createElement('script'); 1038 scriptTag.type = 'text/javascript'; 1039 scriptTag.id = id; 1040 scriptTag.onload = function(){ 1041 // cleanUp 1042 // document.removeChild(scriptTag); 1043 }; 1044 if(url.indexOf("?") != -1){ 1045 url += ("&" + callbackParam + "=" + callbackFunctionName); 1046 } 1047 else{ 1048 url += ("?" + callbackParam + "=" + callbackFunctionName); 1049 } 1050 scriptTag.src = url; 1051 oHead.appendChild(scriptTag); 1052 return id; 1053 }; 1054 1055 // EOF 1056