=self.st and self.cy<=self.sb:
for i in range(l[0]):
self.scroll_up(self.cy,self.sb)
def csi_P(self,l):
w,cx,cy=self.width,self.cx,self.cy
end=self.peek(cy,cx,cy,w)
self.csi_K([0])
self.poke(cy,cx,end[l[0]:])
def csi_X(self,l):
self.zero(self.cy,self.cx,self.cy,self.cx+l[0])
def csi_a(self,l):
self.csi_C(l)
def csi_c(self,l):
#'\x1b[?0c' 0-8 cursor size
pass
def csi_d(self,l):
self.cy=min(self.height,l[0])-1
def csi_e(self,l):
self.csi_B(l)
def csi_f(self,l):
self.csi_H(l)
def csi_h(self,l):
if l[0]==4:
pass
# print "insert on"
def csi_l(self,l):
if l[0]==4:
pass
# print "insert off"
def csi_m(self,l):
for i in l:
if i==0 or i==39 or i==49 or i==27:
self.sgr=0x000700
elif i==1:
self.sgr=(self.sgr|0x000800)
elif i==7:
self.sgr=0x070000
elif i>=30 and i<=37:
c=i-30
self.sgr=(self.sgr&0xff08ff)|(c<<8)
elif i>=40 and i<=47:
c=i-40
self.sgr=(self.sgr&0x00ffff)|(c<<16)
# else:
# print "CSI sgr ignore",l,i
# print 'sgr: %r %x'%(l,self.sgr)
def csi_r(self,l):
if len(l)<2: l=[0,self.height]
self.st=min(self.height-1,l[0]-1)
self.sb=min(self.height-1,l[1]-1)
self.sb=max(self.st,self.sb)
def csi_s(self,l):
self.esc_save(0)
def csi_u(self,l):
self.esc_restore(0)
def escape(self):
e=self.buf
if len(e)>32:
# print "error %r"%e
self.buf=""
elif e in self.esc_seq:
self.esc_seq[e](e)
self.buf=""
else:
for r,f in self.esc_re:
mo=r.match(e)
if mo:
f(e,mo)
self.buf=""
break
# if self.buf=='': print "ESC %r\n"%e
def write(self,s):
for i in s:
if len(self.buf) or (i in self.esc_seq):
self.buf+=i
self.escape()
elif i == '\x1b':
self.buf+=i
else:
self.echo(i)
def read(self):
b=self.outbuf
self.outbuf=""
return b
def dump(self):
r=''
for i in self.scr:
r+=chr(i&255)
return r
def dumplatin1(self):
return self.dump().translate(self.trl1)
def dumphtml(self,color=1):
h=self.height
w=self.width
r=""
span=""
span_bg,span_fg=-1,-1
for i in range(h*w):
q,c=divmod(self.scr[i],256)
if color:
bg,fg=divmod(q,256)
else:
bg,fg=0,7
if i==self.cy*w+self.cx:
bg,fg=1,7
if (bg!=span_bg or fg!=span_fg or i==h*w-1):
if len(span):
r+='%s'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml)))
span=""
span_bg,span_fg=bg,fg
span+=chr(c)
if i%w==w-1:
span+='\n'
r='%s
'%r
if self.last_html==r:
return ''
else:
self.last_html=r
# print self
return r
def __repr__(self):
d=self.dumplatin1()
r=""
for i in range(self.height):
r+="|%s|\n"%d[self.width*i:self.width*(i+1)]
return r
class SynchronizedMethod:
def __init__(self,lock,orig):
self.lock=lock
self.orig=orig
def __call__(self,*l):
self.lock.acquire()
r=self.orig(*l)
self.lock.release()
return r
class Multiplex:
def __init__(self,cmd=None):
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
self.cmd=cmd
self.proc={}
self.lock=threading.RLock()
self.thread=threading.Thread(target=self.loop)
self.alive=1
# synchronize methods
for name in ['create','fds','proc_read','proc_write','dump','die','run']:
orig=getattr(self,name)
setattr(self,name,SynchronizedMethod(self.lock,orig))
self.thread.start()
def create(self,w=80,h=25):
pid,fd=pty.fork()
if pid==0:
try:
fdl=[int(i) for i in os.listdir('/proc/self/fd')]
except OSError:
fdl=range(256)
for i in [i for i in fdl if i>2]:
try:
os.close(i)
except OSError:
pass
if self.cmd:
cmd=['/bin/sh','-c',self.cmd]
elif os.getuid()==0:
cmd=['/bin/login']
else:
sys.stdout.write("Login: ")
login=sys.stdin.readline().strip()
if re.match('^[0-9A-Za-z-_. ]+$',login):
cmd=['ssh']
cmd+=['-oPreferredAuthentications=keyboard-interactive,password']
cmd+=['-oNoHostAuthenticationForLocalhost=yes']
cmd+=['-oLogLevel=FATAL']
cmd+=['-F/dev/null','-l',login,'localhost']
else:
os._exit(0)
env={}
env["COLUMNS"]=str(w)
env["LINES"]=str(h)
env["TERM"]="linux"
env["PATH"]=os.environ['PATH']
os.execvpe(cmd[0],cmd,env)
else:
fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
# python bug http://python.org/sf/1112949 on amd64
fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",h,w,0,0))
self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()}
return fd
def die(self):
self.alive=0
def run(self):
return self.alive
def fds(self):
return self.proc.keys()
def proc_kill(self,fd):
if fd in self.proc:
self.proc[fd]['time']=0
t=time.time()
for i in self.proc.keys():
t0=self.proc[i]['time']
if (t-t0)>120:
try:
os.close(i)
os.kill(self.proc[i]['pid'],signal.SIGTERM)
except (IOError,OSError):
pass
del self.proc[i]
def proc_read(self,fd):
try:
t=self.proc[fd]['term']
t.write(os.read(fd,65536))
reply=t.read()
if reply:
os.write(fd,reply)
self.proc[fd]['time']=time.time()
except (KeyError,IOError,OSError):
self.proc_kill(fd)
def proc_write(self,fd,s):
try:
os.write(fd,s)
except (IOError,OSError):
self.proc_kill(fd)
def dump(self,fd,color=1):
try:
return self.proc[fd]['term'].dumphtml(color)
except KeyError:
return False
def loop(self):
while self.run():
fds=self.fds()
i,o,e=select.select(fds, [], [], 1.0)
for fd in i:
self.proc_read(fd)
if len(i):
time.sleep(0.002)
for i in self.proc.keys():
try:
os.close(i)
os.kill(self.proc[i]['pid'],signal.SIGTERM)
except (IOError,OSError):
pass
class AjaxTerm:
def __init__(self,cmd=None,index_file='ajaxterm.html'):
self.files={}
for i in ['css','html','js']:
for j in glob.glob('*.%s'%i):
self.files[j]=file(j).read()
self.files['index']=file(index_file).read()
self.mime = mimetypes.types_map.copy()
self.mime['.html']= 'text/html; charset=UTF-8'
self.multi = Multiplex(cmd)
self.session = {}
def __call__(self, environ, start_response):
req = qweb.QWebRequest(environ, start_response,session=None)
if req.PATH_INFO.endswith('/u'):
s=req.REQUEST["s"]
k=req.REQUEST["k"]
c=req.REQUEST["c"]
w=req.REQUEST.int("w")
h=req.REQUEST.int("h")
if s in self.session:
term=self.session[s]
else:
if not (w>2 and w<256 and h>2 and h<100):
w,h=80,25
term=self.session[s]=self.multi.create(w,h)
if k:
self.multi.proc_write(term,k)
time.sleep(0.002)
dump=self.multi.dump(term,c)
req.response_headers['Content-Type']='text/xml'
if isinstance(dump,str):
req.write(dump)
req.response_gzencode=1
else:
del self.session[s]
req.write('')
# print "sessions %r"%self.session
else:
n=os.path.basename(req.PATH_INFO)
if n in self.files:
req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
req.write(self.files[n])
else:
req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
req.write(self.files['index'])
return req
def main():
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)")
parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)")
parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)")
parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background")
parser.add_option("-P", "--pidfile",dest="pidfile",default="/var/run/ajaxterm.pid",help="set the pidfile (default: /var/run/ajaxterm.pid)")
parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)")
parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id")
(o, a) = parser.parse_args()
if o.daemon:
pid=os.fork()
if pid == 0:
#os.setsid() ?
os.setpgrp()
nullin = file('/dev/null', 'r')
nullout = file('/dev/null', 'w')
os.dup2(nullin.fileno(), sys.stdin.fileno())
os.dup2(nullout.fileno(), sys.stdout.fileno())
os.dup2(nullout.fileno(), sys.stderr.fileno())
if os.getuid()==0 and o.uid:
try:
os.setuid(int(o.uid))
except:
os.setuid(pwd.getpwnam(o.uid).pw_uid)
else:
try:
file(o.pidfile,'w+').write(str(pid)+'\n')
except:
pass
print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid)
sys.exit(0)
else:
print 'AjaxTerm at http://localhost:%s/' % o.port
at=AjaxTerm(o.cmd,o.index_file)
# f=lambda:os.system('firefox http://localhost:%s/&'%o.port)
# qweb.qweb_wsgi_autorun(at,ip='localhost',port=int(o.port),threaded=0,log=o.log,callback_ready=None)
try:
qweb.QWebWSGIServer(at,ip='localhost',port=int(o.port),threaded=0,log=o.log).serve_forever()
except KeyboardInterrupt,e:
sys.excepthook(*sys.exc_info())
at.multi.die()
if __name__ == '__main__':
main()
Ajaxterm-0.10/configure 0000755 0001750 0001750 00000002574 10521013567 013312 0 ustar wis wis #!/usr/bin/env python
import optparse,os
parser = optparse.OptionParser()
parser.add_option("", "--prefix", dest="prefix",default="/usr/local",help="installation prefix (default: /usr/local)")
parser.add_option("", "--confdir", dest="confdir", default="/etc",help="configuration files directory prefix (default: /etc)")
parser.add_option("", "--port", dest="port", default="8022", help="set the listening TCP port (default: 8022)")
parser.add_option("", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)")
(o, a) = parser.parse_args()
print "Configuring prefix=",o.prefix," port=",o.port
etc=o.confdir
port=o.port
cmd=o.cmd
bin=os.path.join(o.prefix,"bin")
lib=os.path.join(o.prefix,"share/ajaxterm")
man=os.path.join(o.prefix,"share/man/man1")
file("ajaxterm.bin","w").write(file("configure.ajaxterm.bin").read()%locals())
file("Makefile","w").write(file("configure.makefile").read()%locals())
if os.path.isfile("/etc/gentoo-release"):
file("ajaxterm.initd","w").write(file("configure.initd.gentoo").read()%locals())
elif os.path.isfile("/etc/fedora-release") or os.path.isfile("/etc/redhat-release"):
file("ajaxterm.initd","w").write(file("configure.initd.redhat").read()%locals())
else:
file("ajaxterm.initd","w").write(file("configure.initd.debian").read()%locals())
os.system("chmod a+x ajaxterm.bin")
os.system("chmod a+x ajaxterm.initd")
Ajaxterm-0.10/configure.ajaxterm.bin 0000644 0001750 0001750 00000000071 10521013567 015656 0 ustar wis wis #!/bin/sh
PYTHONPATH=%(lib)s exec %(lib)s/ajaxterm.py $@
Ajaxterm-0.10/configure.initd.debian 0000644 0001750 0001750 00000001167 10521013567 015633 0 ustar wis wis #!/bin/sh
PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
DAEMON=%(bin)s/ajaxterm
PORT=%(port)s
PIDFILE=/var/run/ajaxterm.pid
[ -x "$DAEMON" ] || exit 0
#. /lib/lsb/init-functions
case "$1" in
start)
echo "Starting ajaxterm on port $PORT"
start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON -- --daemon --port=$PORT --uid=nobody || return 2
;;
stop)
echo "Stopping ajaxterm"
start-stop-daemon --stop --pidfile $PIDFILE
rm -f $PIDFILE
;;
restart|force-reload)
$0 stop
sleep 1
$0 start
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
exit 3
;;
esac
:
Ajaxterm-0.10/configure.initd.gentoo 0000644 0001750 0001750 00000000723 10521013567 015701 0 ustar wis wis #!/sbin/runscript
# AjaxTerm Gentoo script, 08 May 2006 Mark Gillespie
DAEMON=%(bin)s/ajaxterm
PORT=%(port)s
PIDFILE=/var/run/ajaxterm.pid
depend()
{
need net
}
start()
{
ebegin "Starting AjaxTerm on port $PORT"
start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON -- --daemon --port=$PORT --uid=nobody
eend $?
}
stop()
{
ebegin "Stopping AjaxTerm"
start-stop-daemon --stop --pidfile $PIDFILE
rm -f $PIDFILE
eend $?
}
Ajaxterm-0.10/configure.initd.redhat 0000644 0001750 0001750 00000002616 10521013567 015660 0 ustar wis wis #
# ajaxterm Startup script for ajaxterm
#
# chkconfig: - 99 99
# description: Ajaxterm is a yadda yadda yadda
# processname: ajaxterm
# pidfile: /var/run/ajaxterm.pid
# version: 1.0 Kevin Reichhart - ajaxterminit at lastname dot org
# Source function library.
. /etc/rc.d/init.d/functions
if [ -f /etc/sysconfig/ajaxterm ]; then
. /etc/sysconfig/ajaxterm
fi
ajaxterm=/usr/local/bin/ajaxterm
prog=ajaxterm
pidfile=${PIDFILE-/var/run/ajaxterm.pid}
lockfile=${LOCKFILE-/var/lock/subsys/ajaxterm}
port=${PORT-8022}
user=${xUSER-nobody}
RETVAL=0
start() {
echo -n $"Starting $prog: "
daemon $ajaxterm --daemon --port=$port --uid=$user $OPTIONS
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch ${lockfile}
return $RETVAL
}
stop() {
echo -n $"Stopping $prog: "
killproc $ajaxterm
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}
reload() {
echo -n $"Reloading $prog: "
killproc $ajaxterm -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status python ajaxterm
RETVAL=$?
;;
restart)
stop
start
;;
condrestart)
if [ -f ${pidfile} ] ; then
stop
start
fi
;;
*)
echo $"Usage: $prog {start|stop|restart|condrestart}"
exit 1
esac
exit $RETVAL
Ajaxterm-0.10/configure.makefile 0000644 0001750 0001750 00000000727 10521013567 015061 0 ustar wis wis build:
true
install:
install -d "%(bin)s"
install -d "%(lib)s"
install ajaxterm.bin "%(bin)s/ajaxterm"
install ajaxterm.initd "%(etc)s/init.d/ajaxterm"
install -m 644 ajaxterm.css ajaxterm.html ajaxterm.js qweb.py sarissa.js sarissa_dhtml.js "%(lib)s"
install -m 755 ajaxterm.py "%(lib)s"
gzip --best -c ajaxterm.1 > ajaxterm.1.gz
install -d "%(man)s"
install ajaxterm.1.gz "%(man)s"
clean:
rm ajaxterm.bin
rm ajaxterm.initd
rm ajaxterm.1.gz
rm Makefile
Ajaxterm-0.10/sarissa.js 0000644 0001750 0001750 00000065156 10521013567 013413 0 ustar wis wis /**
* ====================================================================
* About
* ====================================================================
* Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
* The library supports Gecko based browsers like Mozilla and Firefox,
* Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and a little of Opera
* @version 0.9.6.1
* @author: Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
* ====================================================================
* Licence
* ====================================================================
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 or
* the GNU Lesser General Public License version 2.1 as published by
* the Free Software Foundation (your choice between the two).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License or GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* or GNU Lesser General Public License along with this program; if not,
* write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* or visit http://www.gnu.org
*
*/
/**
* Sarissa is a utility class. Provides "static" methods for DOMDocument and
* XMLHTTP objects, DOM Node serializatrion to XML strings and other goodies.
* @constructor
*/
function Sarissa(){};
/** @private */
Sarissa.PARSED_OK = "Document contains no parsing errors";
/**
* Tells you whether transformNode and transformNodeToObject are available. This functionality
* is contained in sarissa_ieemu_xslt.js and is deprecated. If you want to control XSLT transformations
* use the XSLTProcessor
* @deprecated
* @type boolean
*/
Sarissa.IS_ENABLED_TRANSFORM_NODE = false;
/**
* tells you whether XMLHttpRequest (or equivalent) is available
* @type boolean
*/
Sarissa.IS_ENABLED_XMLHTTP = false;
/**
* tells you whether selectNodes/selectSingleNode is available
* @type boolean
*/
Sarissa.IS_ENABLED_SELECT_NODES = false;
var _sarissa_iNsCounter = 0;
var _SARISSA_IEPREFIX4XSLPARAM = "";
var _SARISSA_HAS_DOM_IMPLEMENTATION = document.implementation && true;
var _SARISSA_HAS_DOM_CREATE_DOCUMENT = _SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.createDocument;
var _SARISSA_HAS_DOM_FEATURE = _SARISSA_HAS_DOM_IMPLEMENTATION && document.implementation.hasFeature;
var _SARISSA_IS_MOZ = _SARISSA_HAS_DOM_CREATE_DOCUMENT && _SARISSA_HAS_DOM_FEATURE;
var _SARISSA_IS_SAFARI = (navigator.userAgent && navigator.vendor && (navigator.userAgent.toLowerCase().indexOf("applewebkit") != -1 || navigator.vendor.indexOf("Apple") != -1));
var _SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1;
if(!window.Node || !window.Node.ELEMENT_NODE){
var 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};
};
// IE initialization
if(_SARISSA_IS_IE){
// for XSLT parameter names, prefix needed by IE
_SARISSA_IEPREFIX4XSLPARAM = "xsl:";
// used to store the most recent ProgID available out of the above
var _SARISSA_DOM_PROGID = "";
var _SARISSA_XMLHTTP_PROGID = "";
/**
* Called when the Sarissa_xx.js file is parsed, to pick most recent
* ProgIDs for IE, then gets destroyed.
* @param idList an array of MSXML PROGIDs from which the most recent will be picked for a given object
* @param enabledList an array of arrays where each array has two items; the index of the PROGID for which a certain feature is enabled
*/
pickRecentProgID = function (idList, enabledList){
// found progID flag
var bFound = false;
for(var i=0; i < idList.length && !bFound; i++){
try{
var oDoc = new ActiveXObject(idList[i]);
o2Store = idList[i];
bFound = true;
for(var j=0;j");
// don't use the same prefix again
++_sarissa_iNsCounter;
}
else
oDoc.loadXML("<" + sName + "/>");
};
return oDoc;
};
// see non-IE version
Sarissa.getParseErrorText = function (oDoc) {
var parseErrorText = Sarissa.PARSED_OK;
if(oDoc.parseError != 0){
parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason +
"\nLocation: " + oDoc.parseError.url +
"\nLine Number " + oDoc.parseError.line + ", Column " +
oDoc.parseError.linepos +
":\n" + oDoc.parseError.srcText +
"\n";
for(var i = 0; i < oDoc.parseError.linepos;i++){
parseErrorText += "-";
};
parseErrorText += "^\n";
};
return parseErrorText;
};
// see non-IE version
Sarissa.setXpathNamespaces = function(oDoc, sNsSet) {
oDoc.setProperty("SelectionLanguage", "XPath");
oDoc.setProperty("SelectionNamespaces", sNsSet);
};
/**
* Basic implementation of Mozilla's XSLTProcessor for IE.
* Reuses the same XSLT stylesheet for multiple transforms
* @constructor
*/
XSLTProcessor = function(){
this.template = new ActiveXObject(_SARISSA_XSLTEMPLATE_PROGID);
this.processor = null;
};
/**
* Impoprts the given XSLT DOM and compiles it to a reusable transform
* @argument xslDoc The XSLT DOMDocument to import
*/
XSLTProcessor.prototype.importStylesheet = function(xslDoc){
// convert stylesheet to free threaded
var converted = new ActiveXObject(_SARISSA_THREADEDDOM_PROGID);
converted.loadXML(xslDoc.xml);
this.template.stylesheet = converted;
this.processor = this.template.createProcessor();
// (re)set default param values
this.paramsSet = new Array();
};
/**
* Transform the given XML DOM
* @argument sourceDoc The XML DOMDocument to transform
* @return The transformation result as a DOM Document
*/
XSLTProcessor.prototype.transformToDocument = function(sourceDoc){
this.processor.input = sourceDoc;
var outDoc = new ActiveXObject(_SARISSA_DOM_PROGID);
this.processor.output = outDoc;
this.processor.transform();
return outDoc;
};
/**
* Set global XSLT parameter of the imported stylesheet
* @argument nsURI The parameter namespace URI
* @argument name The parameter base name
* @argument value The new parameter value
*/
XSLTProcessor.prototype.setParameter = function(nsURI, name, value){
/* nsURI is optional but cannot be null */
if(nsURI){
this.processor.addParameter(name, value, nsURI);
}else{
this.processor.addParameter(name, value);
};
/* update updated params for getParameter */
if(!this.paramsSet[""+nsURI]){
this.paramsSet[""+nsURI] = new Array();
};
this.paramsSet[""+nsURI][name] = value;
};
/**
* Gets a parameter if previously set by setParameter. Returns null
* otherwise
* @argument name The parameter base name
* @argument value The new parameter value
* @return The parameter value if reviously set by setParameter, null otherwise
*/
XSLTProcessor.prototype.getParameter = function(nsURI, name){
nsURI = nsURI || "";
if(nsURI in this.paramsSet && name in this.paramsSet[nsURI]){
return this.paramsSet[nsURI][name];
}else{
return null;
};
};
}
else{ /* end IE initialization, try to deal with real browsers now ;-) */
if(_SARISSA_HAS_DOM_CREATE_DOCUMENT){
/**
* Ensures the document was loaded correctly, otherwise sets the
* parseError to -1 to indicate something went wrong. Internal use
* @private
*/
Sarissa.__handleLoad__ = function(oDoc){
if (!oDoc.documentElement || oDoc.documentElement.tagName == "parsererror")
oDoc.parseError = -1;
Sarissa.__setReadyState__(oDoc, 4);
};
/**
* Attached by an event handler to the load event. Internal use.
* @private
*/
_sarissa_XMLDocument_onload = function(){
Sarissa.__handleLoad__(this);
};
/**
* Sets the readyState property of the given DOM Document object.
* Internal use.
* @private
* @argument oDoc the DOM Document object to fire the
* readystatechange event
* @argument iReadyState the number to change the readystate property to
*/
Sarissa.__setReadyState__ = function(oDoc, iReadyState){
oDoc.readyState = iReadyState;
if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function")
oDoc.onreadystatechange();
};
Sarissa.getDomDocument = function(sUri, sName){
var oDoc = document.implementation.createDocument(sUri?sUri:"", sName?sName:"", null);
oDoc.addEventListener("load", _sarissa_XMLDocument_onload, false);
return oDoc;
};
if(window.XMLDocument){
/**
* Emulate IE's onreadystatechange attribute
*/
XMLDocument.prototype.onreadystatechange = null;
/**
* Emulates IE's readyState property, which always gives an integer from 0 to 4:
* - 1 == LOADING,
* - 2 == LOADED,
* - 3 == INTERACTIVE,
* - 4 == COMPLETED
*/
XMLDocument.prototype.readyState = 0;
/**
* Emulate IE's parseError attribute
*/
XMLDocument.prototype.parseError = 0;
// NOTE: setting async to false will only work with documents
// called over HTTP (meaning a server), not the local file system,
// unless you are using Moz 1.4+.
// BTW the try>catch block is for 1.4; I haven't found a way to check if
// the property is implemented without
// causing an error and I dont want to use user agent stuff for that...
var _SARISSA_SYNC_NON_IMPLEMENTED = false;// ("async" in XMLDocument.prototype) ? false: true;
/**
* Keeps a handle to the original load() method. Internal use and only
* if Mozilla version is lower than 1.4
* @private
*/
XMLDocument.prototype._sarissa_load = XMLDocument.prototype.load;
/**
* Overrides the original load method to provide synchronous loading for
* Mozilla versions prior to 1.4, using an XMLHttpRequest object (if
* async is set to false)
* @returns the DOM Object as it was before the load() call (may be empty)
*/
XMLDocument.prototype.load = function(sURI) {
var oDoc = document.implementation.createDocument("", "", null);
Sarissa.copyChildNodes(this, oDoc);
this.parseError = 0;
Sarissa.__setReadyState__(this, 1);
try {
if(this.async == false && _SARISSA_SYNC_NON_IMPLEMENTED) {
var tmp = new XMLHttpRequest();
tmp.open("GET", sURI, false);
tmp.send(null);
Sarissa.__setReadyState__(this, 2);
Sarissa.copyChildNodes(tmp.responseXML, this);
Sarissa.__setReadyState__(this, 3);
}
else {
this._sarissa_load(sURI);
};
}
catch (objException) {
this.parseError = -1;
}
finally {
if(this.async == false){
Sarissa.__handleLoad__(this);
};
};
return oDoc;
};
}//if(window.XMLDocument)
else if(document.implementation && document.implementation.hasFeature && document.implementation.hasFeature('LS', '3.0')){
Document.prototype.async = true;
Document.prototype.onreadystatechange = null;
Document.prototype.parseError = 0;
Document.prototype.load = function(sURI) {
var parser = document.implementation.createLSParser(this.async ? document.implementation.MODE_ASYNCHRONOUS : document.implementation.MODE_SYNCHRONOUS, null);
if(this.async){
var self = this;
parser.addEventListener("load",
function(e) {
self.readyState = 4;
Sarissa.copyChildNodes(e.newDocument, self.documentElement, false);
self.onreadystatechange.call();
},
false);
};
try {
var oDoc = parser.parseURI(sURI);
}
catch(e){
this.parseError = -1;
};
if(!this.async)
Sarissa.copyChildNodes(oDoc, this.documentElement, false);
return oDoc;
};
/**
* Factory method to obtain a new DOM Document object
* @argument sUri the namespace of the root node (if any)
* @argument sUri the local name of the root node (if any)
* @returns a new DOM Document
*/
Sarissa.getDomDocument = function(sUri, sName){
return document.implementation.createDocument(sUri?sUri:"", sName?sName:"", null);
};
};
};//if(_SARISSA_HAS_DOM_CREATE_DOCUMENT)
};
//==========================================
// Common stuff
//==========================================
if(!window.DOMParser){
/*
* DOMParser is a utility class, used to construct DOMDocuments from XML strings
* @constructor
*/
DOMParser = function() {
};
if(_SARISSA_IS_SAFARI){
/**
* Construct a new DOM Document from the given XMLstring
* @param sXml the given XML string
* @param contentType the content type of the document the given string represents (one of text/xml, application/xml, application/xhtml+xml).
* @return a new DOM Document from the given XML string
*/
DOMParser.prototype.parseFromString = function(sXml, contentType){
if(contentType.toLowerCase() != "application/xml"){
throw "Cannot handle content type: \"" + contentType + "\"";
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data:text/xml;charset=utf-8," + encodeURIComponent(str), false);
xmlhttp.send(null);
return xmlhttp.responseXML;
};
}else if(Sarissa.getDomDocument && Sarissa.getDomDocument() && "loadXML" in Sarissa.getDomDocument()){
DOMParser.prototype.parseFromString = function(sXml, contentType){
var doc = Sarissa.getDomDocument();
doc.loadXML(sXml);
return doc;
};
};
};
if(window.XMLHttpRequest){
Sarissa.IS_ENABLED_XMLHTTP = true;
}
else if(_SARISSA_IS_IE){
/**
* Emulate XMLHttpRequest
* @constructor
*/
XMLHttpRequest = function() {
return new ActiveXObject(_SARISSA_XMLHTTP_PROGID);
};
Sarissa.IS_ENABLED_XMLHTTP = true;
};
if(!window.document.importNode && _SARISSA_IS_IE){
try{
/**
* Implements importNode for the current window document in IE using innerHTML.
* Testing showed that DOM was multiple times slower than innerHTML for this,
* sorry folks. If you encounter trouble (who knows what IE does behind innerHTML)
* please gimme a call.
* @param oNode the Node to import
* @param bChildren whether to include the children of oNode
* @returns the imported node for further use
*/
window.document.importNode = function(oNode, bChildren){
var importNode = document.createElement("div");
if(bChildren)
importNode.innerHTML = Sarissa.serialize(oNode);
else
importNode.innerHTML = Sarissa.serialize(oNode.cloneNode(false));
return importNode.firstChild;
};
}catch(e){};
};
if(!Sarissa.getParseErrorText){
/**
* Returns a human readable description of the parsing error. Usefull
* for debugging. Tip: append the returned error string in a <pre>
* element if you want to render it.
* Many thanks to Christian Stocker for the initial patch.
* @argument oDoc The target DOM document
* @returns The parsing error description of the target Document in
* human readable form (preformated text)
*/
Sarissa.getParseErrorText = function (oDoc){
var parseErrorText = Sarissa.PARSED_OK;
if(oDoc && oDoc.parseError && oDoc.parseError != 0){
/*moz*/
if(oDoc.documentElement.tagName == "parsererror"){
parseErrorText = oDoc.documentElement.firstChild.data;
parseErrorText += "\n" + oDoc.documentElement.firstChild.nextSibling.firstChild.data;
}/*konq*/
else{
parseErrorText = Sarissa.getText(oDoc.documentElement);/*.getElementsByTagName("h1")[0], false) + "\n";
parseErrorText += Sarissa.getText(oDoc.documentElement.getElementsByTagName("body")[0], false) + "\n";
parseErrorText += Sarissa.getText(oDoc.documentElement.getElementsByTagName("pre")[0], false);*/
};
};
return parseErrorText;
};
};
Sarissa.getText = function(oNode, deep){
var s = "";
var nodes = oNode.childNodes;
for(var i=0; i < nodes.length; i++){
var node = nodes[i];
var nodeType = node.nodeType;
if(nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE){
s += node.data;
}else if(deep == true
&& (nodeType == Node.ELEMENT_NODE
|| nodeType == Node.DOCUMENT_NODE
|| nodeType == Node.DOCUMENT_FRAGMENT_NODE)){
s += Sarissa.getText(node, true);
};
};
return s;
};
if(window.XMLSerializer){
/**
* Factory method to obtain the serialization of a DOM Node
* @returns the serialized Node as an XML string
*/
Sarissa.serialize = function(oDoc){
var s = null;
if(oDoc){
s = oDoc.innerHTML?oDoc.innerHTML:(new XMLSerializer()).serializeToString(oDoc);
};
return s;
};
}else{
if(Sarissa.getDomDocument && (Sarissa.getDomDocument("","foo", null)).xml){
// see non-IE version
Sarissa.serialize = function(oDoc) {
var s = null;
if(oDoc){
s = oDoc.innerHTML?oDoc.innerHTML:oDoc.xml;
};
return s;
};
/**
* Utility class to serialize DOM Node objects to XML strings
* @constructor
*/
XMLSerializer = function(){};
/**
* Serialize the given DOM Node to an XML string
* @param oNode the DOM Node to serialize
*/
XMLSerializer.prototype.serializeToString = function(oNode) {
return oNode.xml;
};
};
};
/**
* strips tags from a markup string
*/
Sarissa.stripTags = function (s) {
return s.replace(/<[^>]+>/g,"");
};
/**
* Deletes all child nodes of the given node
* @argument oNode the Node to empty
*/
Sarissa.clearChildNodes = function(oNode) {
// need to check for firstChild due to opera 8 bug with hasChildNodes
while(oNode.firstChild){
oNode.removeChild(oNode.firstChild);
};
};
/**
* Copies the childNodes of nodeFrom to nodeTo
* Note: The second object's original content is deleted before
* the copy operation, unless you supply a true third parameter
* @argument nodeFrom the Node to copy the childNodes from
* @argument nodeTo the Node to copy the childNodes to
* @argument bPreserveExisting whether to preserve the original content of nodeTo, default is false
*/
Sarissa.copyChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
if((!nodeFrom) || (!nodeTo)){
throw "Both source and destination nodes must be provided";
};
if(!bPreserveExisting){
Sarissa.clearChildNodes(nodeTo);
};
var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
var nodes = nodeFrom.childNodes;
if(ownerDoc.importNode && (!_SARISSA_IS_IE)) {
for(var i=0;i < nodes.length;i++) {
nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
};
}
else{
for(var i=0;i < nodes.length;i++) {
nodeTo.appendChild(nodes[i].cloneNode(true));
};
};
};
/**
* Moves the childNodes of nodeFrom to nodeTo
* Note: The second object's original content is deleted before
* the move operation, unless you supply a true third parameter
* @argument nodeFrom the Node to copy the childNodes from
* @argument nodeTo the Node to copy the childNodes to
* @argument bPreserveExisting whether to preserve the original content of nodeTo, default is
*/
Sarissa.moveChildNodes = function(nodeFrom, nodeTo, bPreserveExisting) {
if((!nodeFrom) || (!nodeTo)){
throw "Both source and destination nodes must be provided";
};
if(!bPreserveExisting){
Sarissa.clearChildNodes(nodeTo);
};
var nodes = nodeFrom.childNodes;
// if within the same doc, just move, else copy and delete
if(nodeFrom.ownerDocument == nodeTo.ownerDocument){
while(nodeFrom.firstChild){
nodeTo.appendChild(nodeFrom.firstChild);
};
}else{
var ownerDoc = nodeTo.nodeType == Node.DOCUMENT_NODE ? nodeTo : nodeTo.ownerDocument;
if(ownerDoc.importNode && (!_SARISSA_IS_IE)) {
for(var i=0;i < nodes.length;i++) {
nodeTo.appendChild(ownerDoc.importNode(nodes[i], true));
};
}else{
for(var i=0;i < nodes.length;i++) {
nodeTo.appendChild(nodes[i].cloneNode(true));
};
};
Sarissa.clearChildNodes(nodeFrom);
};
};
/**
* Serialize any object to an XML string. All properties are serialized using the property name
* as the XML element name. Array elements are rendered as array-item
elements,
* using their index/key as the value of the key
attribute.
* @argument anyObject the object to serialize
* @argument objectName a name for that object
* @return the XML serializationj of the given object as a string
*/
Sarissa.xmlize = function(anyObject, objectName, indentSpace){
indentSpace = indentSpace?indentSpace:'';
var s = indentSpace + '<' + objectName + '>';
var isLeaf = false;
if(!(anyObject instanceof Object) || anyObject instanceof Number || anyObject instanceof String
|| anyObject instanceof Boolean || anyObject instanceof Date){
s += Sarissa.escape(""+anyObject);
isLeaf = true;
}else{
s += "\n";
var itemKey = '';
var isArrayItem = anyObject instanceof Array;
for(var name in anyObject){
s += Sarissa.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + " ");
};
s += indentSpace;
};
return s += (objectName.indexOf(' ')!=-1?"\n":"" + objectName + ">\n");
};
/**
* Escape the given string chacters that correspond to the five predefined XML entities
* @param sXml the string to escape
*/
Sarissa.escape = function(sXml){
return sXml.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
/**
* Unescape the given string. This turns the occurences of the predefined XML
* entities to become the characters they represent correspond to the five predefined XML entities
* @param sXml the string to unescape
*/
Sarissa.unescape = function(sXml){
return sXml.replace(/'/g,"'")
.replace(/"/g,"\"")
.replace(/>/g,">")
.replace(/</g,"<")
.replace(/&/g,"&");
};
// EOF
Ajaxterm-0.10/sarissa_dhtml.js 0000644 0001750 0001750 00000010401 10521013567 014562 0 ustar wis wis /**
* ====================================================================
* About
* ====================================================================
* Sarissa cross browser XML library - AJAX module
* @version 0.9.6.1
* @author: Copyright Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
*
* This module contains some convinient AJAX tricks based on Sarissa
*
* ====================================================================
* Licence
* ====================================================================
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 or
* the GNU Lesser General Public License version 2.1 as published by
* the Free Software Foundation (your choice between the two).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License or GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* or GNU Lesser General Public License along with this program; if not,
* write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* or visit http://www.gnu.org
*
*/
/**
* Update an element with response of a GET request on the given URL.
* @addon
* @param sFromUrl the URL to make the request to
* @param oTargetElement the element to update
* @param xsltproc (optional) the transformer to use on the returned
* content before updating the target element with it
*/
Sarissa.updateContentFromURI = function(sFromUrl, oTargetElement, xsltproc) {
try{
oTargetElement.style.cursor = "wait";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", sFromUrl);
function sarissa_dhtml_loadHandler() {
if (xmlhttp.readyState == 4) {
oTargetElement.style.cursor = "auto";
Sarissa.updateContentFromNode(xmlhttp.responseXML, oTargetElement, xsltproc);
};
};
xmlhttp.onreadystatechange = sarissa_dhtml_loadHandler;
xmlhttp.send(null);
oTargetElement.style.cursor = "auto";
}
catch(e){
oTargetElement.style.cursor = "auto";
throw e;
};
};
/**
* Update an element's content with the given DOM node.
* @addon
* @param sFromUrl the URL to make the request to
* @param oTargetElement the element to update
* @param xsltproc (optional) the transformer to use on the given
* DOM node before updating the target element with it
*/
Sarissa.updateContentFromNode = function(oNode, oTargetElement, xsltproc) {
try {
oTargetElement.style.cursor = "wait";
Sarissa.clearChildNodes(oTargetElement);
// check for parsing errors
var ownerDoc = oNode.nodeType == Node.DOCUMENT_NODE?oNode:oNode.ownerDocument;
if(ownerDoc.parseError && ownerDoc.parseError != 0) {
var pre = document.createElement("pre");
pre.appendChild(document.createTextNode(Sarissa.getParseErrorText(ownerDoc)));
oTargetElement.appendChild(pre);
}
else {
// transform if appropriate
if(xsltproc) {
oNode = xsltproc.transformToDocument(oNode);
};
// be smart, maybe the user wants to display the source instead
if(oTargetElement.tagName.toLowerCase == "textarea" || oTargetElement.tagName.toLowerCase == "input") {
oTargetElement.value = Sarissa.serialize(oNode);
}
else {
// ok that was not smart; it was paranoid. Keep up the good work by trying to use DOM instead of innerHTML
if(oNode.nodeType == Node.DOCUMENT_NODE || oNode.ownerDocument.documentElement == oNode) {
oTargetElement.innerHTML = Sarissa.serialize(oNode);
}
else{
oTargetElement.appendChild(oTargetElement.ownerDocument.importNode(oNode, true));
};
};
};
}
catch(e) {
throw e;
}
finally{
oTargetElement.style.cursor = "auto";
};
};