cve
large_string | desc
large_string | repo
large_string | commit_id
large_string | commit_message
large_string | diff
large_string | label
int64 | rank
uint32 |
|---|---|---|---|---|---|---|---|
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
4927240d1f8fca0806df1e48e5b09ef067bd3930
|
automatic post-release commit for mutt-2.2.7
|
commit 4927240d1f8fca0806df1e48e5b09ef067bd3930
Author: Kevin McCarthy <[email protected]>
Date: Sun Aug 7 10:20:17 2022 -0700
automatic post-release commit for mutt-2.2.7
diff --git a/ChangeLog b/ChangeLog
index 9a356c55..1665b5c1 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,151 @@
+2022-08-07 10:15:32 -0700 Kevin McCarthy <[email protected]> (7b41537e)
+
+ * Update UPDATING file for 2.2.7 release.
+
+M UPDATING
+
+2022-08-02 20:51:17 -0700 Kevin McCarthy <[email protected]> (40228035)
+
+ * Fix mutt_read_rfc822_line() to use is_email_wsp().
+
+ ISSPACE() uses isspace() which is locale-dependent. On some
+ platforms, unexpected 8-bit chars, such as 0xa0 or 0x85 return true.
+
+ When using $edit_headers, this can result in Subject: lines being
+ truncated if a multi-byte character ending in one of these values is
+ at the end of a line.
+
+ There are probably other bugs that could be triggered by this, such as
+ in IMAP parsing. However, I need more time to investigate before
+ making large-scale changes that could introduce new bugs.
+
+M parse.c
+
+2022-08-04 10:25:26 +0200 Matthias Andree <[email protected]> (4d2b33ba)
+
+ * Drop X509 *cert from sslsockdata, unused.
+
+ Signed-off-by: Matthias Andree <[email protected]>
+ (cherry picked from commit 0d03501ac9ddd1a4a62a7274651d64da0c4c3865)
+
+M mutt_ssl.c
+
+2022-07-29 19:52:45 -0700 Kevin McCarthy <[email protected]> (a1a08067)
+
+ * Change mutt_display_message() $pager to use %s if present.
+
+ Other places in the code all use mutt_do_pager(), which uses
+ mutt_expand_file_fmt().
+
+ The use of %s was not documented (and likely not used since it's
+ broken when displaying messages), so add documentation to the $pager
+ option.
+
+M commands.c
+M init.h
+
+2022-07-29 10:40:33 -0700 Kevin McCarthy <[email protected]> (4f672027)
+
+ * Overide SSL_CTX min/max protocol versions.
+
+ Newer versions of OpenSSL disable old (insecure) protocols by default.
+ Reset the allowed versions, so that Mutt's configuration variables
+ enabling old protocols actually work if needed.
+
+ Thanks to Matthias Andree for the patch, which this commit is based
+ upon.
+
+M mutt_ssl.c
+
+2022-03-04 15:26:56 -0800 Kevin McCarthy <[email protected]> (b022931d)
+
+ * Tighten $query_command parsing to allow empty name field.
+
+ The documentation writes the output should be "each line containing a
+ tab separated address then name then some other optional information".
+ The wiki page at
+ <https://gitlab.com/muttmua/mutt/-/wikis/MuttGuide/Aliases> also
+ implies a single tab between each field.
+
+ Since the function used strtok, consecutive tab delimeters were
+ treated as a single delimiter. This caused a missing name field to
+ use the comment field as the name.
+
+ Change the function to use strchr instead. This is not without risk,
+ as the functionality is old. Who knows what all programs have been
+ written that might assume initial, or multiple delimiters are
+ acceptable...
+
+ Thanks to Magnus Groß for reporting the problem along with a patch,
+ which this commit is derived from.
+
+M query.c
+
+2022-07-10 14:58:40 +0200 Matthias Andree <[email protected]> (135fb67e)
+
+ * version.sh: fix robustness on git failure
+
+ for instance, with untrusted directory under sudo.
+
+ Signed-off-by: Matthias Andree <[email protected]>
+
+M version.sh
+
+2022-07-17 22:20:12 +0200 Matthias Andree <[email protected]> (607efef7)
+
+ * de.po: Fix German certificate dialog translation.
+
+ Remove the full-stop to ensure reader will continue reading rather
+ than mistake this as a conclusion.
+
+ Also, from: to: here translate to von: bis: (not an: which would be
+ spatial not temporal).
+
+ Finally, fix a mistranslation where SHA256 was translated as SHA1
+
+ Reviewed by: Helge Kreutzmann <[email protected]>
+ Signed-off-by: Matthias Andree <[email protected]>
+
+M po/de.po
+
+2022-07-06 14:39:42 -0700 Kevin McCarthy <[email protected]> (0614c38c)
+
+ * Comment out undesirable default settings in smime.rc.
+
+ Some distributions, such as Debian, use the contrib/smime.rc as a
+ default system configuration file (under /etc/Muttrc.d). However
+ settings such as $smime_is_default and $crypt_autosign should not be
+ enabled by default for everyone.
+
+ Debian previously maintained a patch against the file, commenting out
+ those settings, but the patch somehow got dropped and is causing
+ confusion for Debian users.
+
+ Since the settings aren't necessarily desirable for anyone who wants
+ to use S/MIME, comment them out in the contrib file.
+
+M contrib/smime.rc
+
+2022-06-09 09:22:03 -0700 Kevin McCarthy <[email protected]> (97f8eee2)
+
+ * Decrypt S/MIME when mime-forwarding with $forward_decrypt set.
+
+ The code was performing a decode for S/MIME, but this had the effect
+ of running attachments through the autoview routines.
+
+ Change so it only performs a decrypt. This is also how copying is
+ handled in set_copy_flags(), so I believe the decode was just a
+ mistake.
+
+M sendlib.c
+
+2022-06-05 11:20:00 -0700 Kevin McCarthy <[email protected]> (d1ee1314)
+
+ * automatic post-release commit for mutt-2.2.6
+
+M ChangeLog
+M VERSION
+
2022-06-05 11:13:47 -0700 Kevin McCarthy <[email protected]> (42c9d1ea)
* Update UPDATING file for 2.2.6 release.
diff --git a/VERSION b/VERSION
index bda8fbec..5bc1cc43 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-2.2.6
+2.2.7
| 0 | 7 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
848834424235c850947c164ff782d4b8292e084d
|
Fix next_token() oob read. (closes #3787)
With specially crafted input to 'mutt -H', the line "Return-Path:<() "
is read and passed to mutt_parse_rfc822_line(). "<() " is then passed
through to rfc822_parse_adrlist().
Eventually, inside next_token(), is_special(*s) is called when s
points to the end of the string ('\0'). This macro calls strchr,
which will actually match and return a pointer to the trailing '\0' in
RFC822Specials! This causes "s + 1" to be returned, skipping past the
end of string inside parse_mailboxdomain().
This patch adds a check to make sure *s is non-null before calling
is_special(*s).
|
commit 848834424235c850947c164ff782d4b8292e084d
Author: Kevin McCarthy <[email protected]>
Date: Sun Oct 18 19:45:51 2015 +0800
Fix next_token() oob read. (closes #3787)
With specially crafted input to 'mutt -H', the line "Return-Path:<() "
is read and passed to mutt_parse_rfc822_line(). "<() " is then passed
through to rfc822_parse_adrlist().
Eventually, inside next_token(), is_special(*s) is called when s
points to the end of the string ('\0'). This macro calls strchr,
which will actually match and return a pointer to the trailing '\0' in
RFC822Specials! This causes "s + 1" to be returned, skipping past the
end of string inside parse_mailboxdomain().
This patch adds a check to make sure *s is non-null before calling
is_special(*s).
diff --git a/rfc822.c b/rfc822.c
index 884c00b1..80347824 100644
--- a/rfc822.c
+++ b/rfc822.c
@@ -202,7 +202,7 @@ next_token (const char *s, char *token, size_t *tokenlen, size_t tokenmax)
return (parse_comment (s + 1, token, tokenlen, tokenmax));
if (*s == '"')
return (parse_quote (s + 1, token, tokenlen, tokenmax));
- if (is_special (*s))
+ if (*s && is_special (*s))
{
if (*tokenlen < tokenmax)
token[(*tokenlen)++] = *s;
| 0 | 6 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
85a0ec8505d8cf9ab29765a07fc721f6018f59ea
|
Fix pgp_application_pgp_handler to remove all tempfiles.
If multiple PGP blocks are present in an email, Mutt only cleans up the
tempfiles for the last block. Thanks to Dennis Preiser for the patch
and sample mbox file demonstrating the problem.
This patch also fixes the argument to mutt_perror for the pgpout
tempfile.
|
commit 85a0ec8505d8cf9ab29765a07fc721f6018f59ea
Author: Kevin McCarthy <[email protected]>
Date: Wed Mar 4 19:24:31 2015 -0800
Fix pgp_application_pgp_handler to remove all tempfiles.
If multiple PGP blocks are present in an email, Mutt only cleans up the
tempfiles for the last block. Thanks to Dennis Preiser for the patch
and sample mbox file demonstrating the problem.
This patch also fixes the argument to mutt_perror for the pgpout
tempfile.
diff --git a/pgp.c b/pgp.c
index ee9751f0..65507771 100644
--- a/pgp.c
+++ b/pgp.c
@@ -373,7 +373,7 @@ int pgp_application_pgp_handler (BODY *m, STATE *s)
mutt_mktemp (outfile, sizeof (outfile));
if ((pgpout = safe_fopen (outfile, "w+")) == NULL)
{
- mutt_perror (tmpfname);
+ mutt_perror (outfile);
return -1;
}
@@ -485,6 +485,18 @@ int pgp_application_pgp_handler (BODY *m, STATE *s)
fgetconv_close (&fc);
}
+ /*
+ * Multiple PGP blocks can exist, so these need to be closed and
+ * unlinked inside the loop.
+ */
+ safe_fclose (&tmpfp);
+ mutt_unlink (tmpfname);
+ if (pgpout)
+ {
+ safe_fclose (&pgpout);
+ mutt_unlink (outfile);
+ }
+
if (s->flags & M_DISPLAY)
{
state_putc ('\n', s);
| 0 | 2 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
4fc97a2026f671a35e3d296bbfdeb3794d6313c7
|
Display error if no imap authenticators are available.
Without SASL enabled, and with an explicit value in
$imap_authenticators not natively implemented by Mutt, no calls to
authenticator->authenticate() were occuring.
This resulted in the default r value of -1 passing through, which did
not trigger the mutt_error() message after the loop.
Without that message, an empty index would display with the
"connecting" message still on the bottom, giving the appearance that
Mutt is hung.
|
commit 4fc97a2026f671a35e3d296bbfdeb3794d6313c7
Author: Kevin McCarthy <[email protected]>
Date: Wed Apr 8 09:20:54 2020 -0700
Display error if no imap authenticators are available.
Without SASL enabled, and with an explicit value in
$imap_authenticators not natively implemented by Mutt, no calls to
authenticator->authenticate() were occuring.
This resulted in the default r value of -1 passing through, which did
not trigger the mutt_error() message after the loop.
Without that message, an empty index would display with the
"connecting" message still on the bottom, giving the appearance that
Mutt is hung.
diff --git a/imap/auth.c b/imap/auth.c
index e32b5ab4..48909cd8 100644
--- a/imap/auth.c
+++ b/imap/auth.c
@@ -55,7 +55,7 @@ int imap_authenticate (IMAP_DATA* idata)
char* methods;
char* method;
char* delim;
- int r = -1;
+ int r = IMAP_AUTH_UNAVAIL;
if (ImapAuthenticators)
{
| 0 | 5 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
c160ca1d74915f7b6a2fa18a5f4bdfc1663b7c88
|
Reset invalid parsed received dates to 0. (closes #3878)
The actual problem in the ticket would be solved by d3f31cf9239e (see
#3798). However there is still the bug that Mutt considers a
(hdr->received != 0) to be set and usable, despite not checking the
return value of mutt_parse_date().
Change mutt_read_rfc822_header() to unset an invalid received value
back to 0. We don't do this inside mutt_read_rfc822_line() because
that would cause the next received line to be parsed.
|
commit c160ca1d74915f7b6a2fa18a5f4bdfc1663b7c88
Author: Kevin McCarthy <[email protected]>
Date: Sun Sep 25 13:11:03 2016 -0700
Reset invalid parsed received dates to 0. (closes #3878)
The actual problem in the ticket would be solved by d3f31cf9239e (see
#3798). However there is still the bug that Mutt considers a
(hdr->received != 0) to be set and usable, despite not checking the
return value of mutt_parse_date().
Change mutt_read_rfc822_header() to unset an invalid received value
back to 0. We don't do this inside mutt_read_rfc822_line() because
that would cause the next received line to be parsed.
diff --git a/parse.c b/parse.c
index 92cfeb0f..0ae55940 100644
--- a/parse.c
+++ b/parse.c
@@ -1455,6 +1455,12 @@ ENVELOPE *mutt_read_rfc822_header (FILE *f, HEADER *hdr, short user_hdrs,
e->real_subj = e->subject;
}
+ if (hdr->received < 0)
+ {
+ dprint(1,(debugfile,"read_rfc822_header(): resetting invalid received time to 0\n"));
+ hdr->received = 0;
+ }
+
/* check for missing or invalid date */
if (hdr->date_sent <= 0)
{
| 0 | 1 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
3d8baab528e370cabb12baf9102d668cead809a7
|
I've attached a patch for bug number 1036, as reported at
http://bugs.guug.de/db/pa/lmutt.html ("segfault when more than one
msg is postponed"). This is a patch against mutt 1.4.1.
As it was previously left, no one could reproduce it. The problem
occurs because sorting is disabled when opening the postponed
folder, but the Sort global variable still tells mutt to use
whatever sorting algorithm the $sort config option indicates.
Eventually, the code would get to mutt_messages_in_thread and try to
dereference a NULL thread object, causing the segfault.
|
commit 3d8baab528e370cabb12baf9102d668cead809a7
Author: Dan Fandrich <[email protected]>
Date: Wed Sep 3 17:22:09 2003 +0000
I've attached a patch for bug number 1036, as reported at
http://bugs.guug.de/db/pa/lmutt.html ("segfault when more than one
msg is postponed"). This is a patch against mutt 1.4.1.
As it was previously left, no one could reproduce it. The problem
occurs because sorting is disabled when opening the postponed
folder, but the Sort global variable still tells mutt to use
whatever sorting algorithm the $sort config option indicates.
Eventually, the code would get to mutt_messages_in_thread and try to
dereference a NULL thread object, causing the segfault.
diff --git a/postpone.c b/postpone.c
index 53a42300..ac611079 100644
--- a/postpone.c
+++ b/postpone.c
@@ -23,6 +23,7 @@
#include "mime.h"
#include "mailbox.h"
#include "mapping.h"
+#include "sort.h"
#ifdef USE_IMAP
#include "mx.h"
#include "imap.h"
@@ -153,6 +154,7 @@ static HEADER *select_msg (void)
MUTTMENU *menu;
int i, done=0, r=-1;
char helpstr[SHORT_STRING];
+ short orig_sort;
menu = mutt_new_menu ();
menu->make_entry = post_entry;
@@ -162,6 +164,12 @@ static HEADER *select_msg (void)
menu->data = PostContext;
menu->help = mutt_compile_help (helpstr, sizeof (helpstr), MENU_POST, PostponeHelp);
+ /* The postponed mailbox is setup to have sorting disabled, but the global
+ * Sort variable may indicate something different. Sorting has to be
+ * disabled while the postpone menu is being displayed. */
+ orig_sort = Sort;
+ Sort = SORT_ORDER;
+
while (!done)
{
switch (i = mutt_menuLoop (menu))
@@ -197,6 +205,7 @@ static HEADER *select_msg (void)
}
}
+ Sort = orig_sort;
mutt_menuDestroy (&menu);
return (r > -1 ? PostContext->hdrs[r] : NULL);
}
| 0 | 8 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
356ef5a5f9a508c8f935eb0839b1cc574672057d
|
Pause for a moment when a hostname fails to resolve. Closes #1942.
There are a number of cases where mutt cascades error messages. It might
be nice if there were an error stack so that low level functions could
push_error instead of displaying it right away, and the higher level ones
could eg mutt_message(_("Failed to write FCC: %s"), pop_error ())...
|
commit 356ef5a5f9a508c8f935eb0839b1cc574672057d
Author: Brendan Cully <[email protected]>
Date: Mon Aug 8 18:59:43 2005 +0000
Pause for a moment when a hostname fails to resolve. Closes #1942.
There are a number of cases where mutt cascades error messages. It might
be nice if there were an error stack so that low level functions could
push_error instead of displaying it right away, and the higher level ones
could eg mutt_message(_("Failed to write FCC: %s"), pop_error ())...
diff --git a/mutt_socket.c b/mutt_socket.c
index 8d9f8391..bc859f5d 100644
--- a/mutt_socket.c
+++ b/mutt_socket.c
@@ -440,6 +440,7 @@ int raw_socket_open (CONNECTION* conn)
if (rc)
{
mutt_error (_("Could not find the host \"%s\""), conn->account.host);
+ mutt_sleep (2);
return -1;
}
| 0 | 3 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
50e6f343e055dd32be1e3080de4bc9a7e560e685
|
Manual: Add a short chapter summarizing security considerations
|
commit 50e6f343e055dd32be1e3080de4bc9a7e560e685
Author: Rocco Rutte <[email protected]>
Date: Sat Apr 4 14:28:58 2009 +0200
Manual: Add a short chapter summarizing security considerations
diff --git a/doc/Makefile.am b/doc/Makefile.am
index 65d01765..eb568769 100644
--- a/doc/Makefile.am
+++ b/doc/Makefile.am
@@ -31,7 +31,7 @@ EXTRA_DIST = dotlock.man \
HTML_DOCFILES = manual.html index.html intro.html gettingstarted.html \
configuration.html mimesupport.html advancedusage.html \
- optionalfeatures.html tuning.html reference.html miscellany.html
+ optionalfeatures.html security.html tuning.html reference.html miscellany.html
BUILT_DISTFILES = stamp-doc-xml stamp-doc-chunked manual.txt $(HTML_DOCFILES)
diff --git a/doc/manual.xml.head b/doc/manual.xml.head
index 61f2e8c2..6b4f12d5 100644
--- a/doc/manual.xml.head
+++ b/doc/manual.xml.head
@@ -7191,6 +7191,178 @@ for the latter syntax. <literal>EXACT_ADDRESS</literal> in the output of
</chapter>
+<chapter id="security">
+<title>Security Considerations</title>
+
+<para>
+First of all, Mutt contains no security holes included by intention but
+may contain unknown security holes. As a consequence, please run Mutt
+only with as few permissions as possible. Especially, do not run Mutt as
+the super user.
+</para>
+
+<para>
+When configuring Mutt, there're some points to note about secure setups
+so please read this chapter carefully.
+</para>
+
+<sect1 id="security-passwords">
+<title>Passwords</title>
+
+<para>
+Although Mutt can be told the various passwords for accounts, please
+never store passwords in configuration files. Besides the fact that the
+system's operator can always read them, you could forget to mask it out
+when reporting a bug or asking for help via a mailing list. Even worse,
+your mail including your password could be archived by internet search
+engines, mail-to-news gateways etc. It may already too late before you
+notice your mistake.
+</para>
+
+</sect1>
+
+<sect1 id="security-tempfiles">
+<title>Temporary Files</title>
+
+<para>
+Mutt uses many temporary files for viewing messages, verifying digital
+signatures, etc. As long as being used, these files are visible by other
+users and maybe even readable in case of misconfiguration. Also, a
+different location for these files may be desired which can be changed
+via the <link linkend="tmpdir">$tmpdir</link> variable.
+</para>
+
+</sect1>
+
+<sect1 id="security-leaks">
+<title>Information Leaks</title>
+
+<sect2 id="security-leaks-mid">
+<title>Message-ID: headers</title>
+
+<para>
+Message-Id: headers contain a local part that is to be created in a
+unique fashion. In order to do so, Mutt will <quote>leak</quote> some
+information to the outside world when sending messages: the generation
+of this header includes a step counter which is increased (and rotated)
+with every message sent. In a longer running mutt session, others can
+make assumptions about your mailing habbits depending on the number of
+messages sent. If this is not desired, the header can be manually
+provided using <link
+linkend="edit-headers">$edit_headers</link> (though not
+recommended).
+</para>
+
+</sect2>
+
+<sect2 id="security-leaks-mailto">
+<title><literal>mailto:</literal>-style links</title>
+
+<para>
+As Mutt be can be set up to be the mail client to handle
+<literal>mailto:</literal> style links in websites, there're security
+considerations, too. Arbitrary header fields can be embedded in these
+links which could override existing header fields or attach arbitrary
+files using <link linkend="attach-header">the Attach:
+psuedoheader</link>. This may be problematic if the <link
+linkend="edit-headers">$edit-headers</link> variable is
+<emphasis>unset</emphasis>, i.e. the user doesn't want to see header
+fields while editing the message and doesn't pay enough attention to the
+compose menu's listing of attachments.
+</para>
+
+<para>
+For example, following a link like
+</para>
+
+<screen>
+mailto:joe@host?Attach=~/.gnupg/secring.gpg</screen>
+
+<para>
+will send out the user's private gnupg keyring to
+<literal>joe@host</literal> if the user doesn't follow the information
+on screen carefully enough.
+</para>
+
+</sect2>
+
+</sect1>
+
+<sect1 id="security-external">
+<title>External applications</title>
+
+<para>
+Mutt in many places has to rely on external applications or for
+convenience supports mechanisms involving external applications.
+</para>
+
+<sect2 id="security-external-mailcap">
+<title>mailcap</title>
+
+<para>
+One of these is the <literal>mailcap</literal> mechanism as defined by
+RfC1524. Mutt can be set up to <emphasis>automatically</emphasis>
+execute any given utility as listed in one of the mailcap files (see the
+<link linkend="mailcap-path">$mailcap_path</link> variable
+for details.)
+</para>
+
+<para>
+These utilities may have a variety of security vulnerabilities,
+including overwriting of arbitrary files, information leaks or other
+exploitable bugs. These vulnerabilities may go unnoticed by the user,
+especially when they are called automatically (and without interactive
+prompting) from the mailcap file(s). When using Mutt's autoview
+mechanism in combination with mailcap files, please be sure to...
+</para>
+
+<itemizedlist>
+<listitem>
+<para>
+manually select trustworth applications with a reasonable calling
+sequence
+</para>
+</listitem>
+<listitem>
+<para>
+periodically check the contents of mailcap files, especially after
+software installations or upgrades
+</para>
+</listitem>
+<listitem>
+<para>
+keep the software packages referenced in the mailcap file up to date
+</para>
+</listitem>
+<listitem>
+<para>
+leave the <link linkend="mailcap-sanitize">$mailcap-sanitize</link>
+variable with its default value to restrict mailcap expandos to a safe set of
+characters
+</para>
+</listitem>
+</itemizedlist>
+
+</sect2>
+
+<sect2 id="security-external-other">
+<title>Other</title>
+
+<para>
+Besides the mailcap mechanism, Mutt uses a number of other external
+utilities for operation, for example to provide crypto support, in
+backtick expansion in configuration files or format string filters. The
+same security considerations apply for these as for tools involved via
+mailcap.
+</para>
+
+</sect2>
+
+</sect1>
+
+</chapter>
+
+
<chapter id="tuning">
<title>Performance tuning</title>
| 0 | 10 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
829db35b1a61f9642e9c9857ecd0d0a9bfde6029
|
Use fgets_unlocked and fgetc_unlocked if available.
Since mutt does not use threads, there is no reason it should use the
locked variants of the FILE* IO functions. This checks if the unlocked
functions are available, and if so enables them globally via mutt.h.
Cuts load time for a 56k message, 1.8GB /var/mail mailbox from 14
seconds to ~6 seconds, since we avoid acquiring and releasing a mutex
for every character of input read.
Before: 0m14.376s
74.98% mutt libc-2.18.so [.] _IO_getc
11.87% mutt mutt [.] mbox_parse_mailbox
0.94% mutt [kernel.kallsyms] [k] copy_user_generic_string
0.83% mutt libc-2.18.so [.] __strchr_sse2
0.53% mutt libc-2.18.so [.] __memcpy_sse2
0.44% mutt libc-2.18.so [.] _int_malloc
After: 6 seconds
68.92% mutt mutt [.] mbox_parse_mailbox
2.25% mutt [kernel.kallsyms] [k] copy_user_generic_string
1.73% mutt libc-2.18.so [.] __strchr_sse2
1.24% mutt libc-2.18.so [.] __memcpy_sse2
1.17% mutt libc-2.18.so [.] _int_malloc
0.87% mutt libc-2.18.so [.] __strspn_sse42
|
commit 829db35b1a61f9642e9c9857ecd0d0a9bfde6029
Author: David Wilson <[email protected]>
Date: Wed Nov 8 13:40:34 2017 -0800
Use fgets_unlocked and fgetc_unlocked if available.
Since mutt does not use threads, there is no reason it should use the
locked variants of the FILE* IO functions. This checks if the unlocked
functions are available, and if so enables them globally via mutt.h.
Cuts load time for a 56k message, 1.8GB /var/mail mailbox from 14
seconds to ~6 seconds, since we avoid acquiring and releasing a mutex
for every character of input read.
Before: 0m14.376s
74.98% mutt libc-2.18.so [.] _IO_getc
11.87% mutt mutt [.] mbox_parse_mailbox
0.94% mutt [kernel.kallsyms] [k] copy_user_generic_string
0.83% mutt libc-2.18.so [.] __strchr_sse2
0.53% mutt libc-2.18.so [.] __memcpy_sse2
0.44% mutt libc-2.18.so [.] _int_malloc
After: 6 seconds
68.92% mutt mutt [.] mbox_parse_mailbox
2.25% mutt [kernel.kallsyms] [k] copy_user_generic_string
1.73% mutt libc-2.18.so [.] __strchr_sse2
1.24% mutt libc-2.18.so [.] __memcpy_sse2
1.17% mutt libc-2.18.so [.] _int_malloc
0.87% mutt libc-2.18.so [.] __strspn_sse42
diff --git a/configure.ac b/configure.ac
index a9c32068..8618ddc3 100644
--- a/configure.ac
+++ b/configure.ac
@@ -333,6 +333,7 @@ AC_CHECK_HEADERS(sys/time.h sys/resource.h)
AC_CHECK_HEADERS(unix.h)
AC_CHECK_FUNCS(setrlimit getsid)
+AC_CHECK_FUNCS(fgets_unlocked fgetc_unlocked)
AC_MSG_CHECKING(for sig_atomic_t in signal.h)
AC_EGREP_HEADER(sig_atomic_t,signal.h,
diff --git a/mutt.h b/mutt.h
index 54a807fa..9d318302 100644
--- a/mutt.h
+++ b/mutt.h
@@ -71,6 +71,14 @@
# define MB_LEN_MAX 16
#endif
+#ifdef HAVE_FGETS_UNLOCKED
+# define fgets fgets_unlocked
+#endif
+
+#ifdef HAVE_FGETC_UNLOCKED
+# define fgetc fgetc_unlocked
+#endif
+
/* nifty trick I stole from ELM 2.5alpha. */
#ifdef MAIN_C
#define WHERE
| 0 | 9 |
CVE-2005-2351
|
Mutt before 1.5.20 patch 7 allows an attacker to cause a denial of service via a series of requests to mutt temporary files.
|
muttmua/mutt
|
781acdf0601fca98aadf1bbfdaae743084cb5f88
|
With SASL, expect the server to prompt for additional auth data if
we have some to send (#129961, upstream #1845)
|
commit 781acdf0601fca98aadf1bbfdaae743084cb5f88
Author: Bill Nottingham <[email protected]>
Date: Thu Jan 27 18:48:41 2005 +0000
With SASL, expect the server to prompt for additional auth data if
we have some to send (#129961, upstream #1845)
diff --git a/mutt_sasl.c b/mutt_sasl.c
index aa41f2c8..efe7e146 100644
--- a/mutt_sasl.c
+++ b/mutt_sasl.c
@@ -190,7 +190,7 @@ int mutt_sasl_client_new (CONNECTION* conn, sasl_conn_t** saslconn)
service = "imap";
break;
case M_ACCT_TYPE_POP:
- service = "pop-3";
+ service = "pop";
break;
default:
dprint (1, (debugfile, "mutt_sasl_client_new: account type unset\n"));
| 0 | 4 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
e387b6df99b7ea797814a8b233ae48df12f68763
|
Added storeException() method that takes an ActionMessage instead of
ActionError.
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@50964 13f79535-47bb-0310-9956-ffa450edef68
|
commit e387b6df99b7ea797814a8b233ae48df12f68763
Author: David Graham <[email protected]>
Date: Sat Aug 16 17:50:10 2003 +0000
Added storeException() method that takes an ActionMessage instead of
ActionError.
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@50964 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/share/org/apache/struts/action/ExceptionHandler.java b/src/share/org/apache/struts/action/ExceptionHandler.java
index 163abda2f..c7e471b04 100644
--- a/src/share/org/apache/struts/action/ExceptionHandler.java
+++ b/src/share/org/apache/struts/action/ExceptionHandler.java
@@ -1,7 +1,7 @@
/*
- * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/ExceptionHandler.java,v 1.20 2003/08/07 00:39:05 dgraham Exp $
- * $Revision: 1.20 $
- * $Date: 2003/08/07 00:39:05 $
+ * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/ExceptionHandler.java,v 1.21 2003/08/16 17:50:10 dgraham Exp $
+ * $Revision: 1.21 $
+ * $Date: 2003/08/16 17:50:10 $
*
* ====================================================================
*
@@ -168,17 +168,45 @@ public class ExceptionHandler {
* @param error - The error generated from the exception mapping
* @param forward - The forward generated from the input path (from the form or exception mapping)
* @param scope - The scope of the exception mapping.
+ * @deprecated Use storeException(HttpServletRequest, String, ActionMessage, ActionForward, String)
+ * instead. This will be removed after Struts 1.2.
*/
- protected void storeException(HttpServletRequest request,
- String property,
- ActionError error,
- ActionForward forward,
- String scope) {
-
+ protected void storeException(
+ HttpServletRequest request,
+ String property,
+ ActionError error,
+ ActionForward forward,
+ String scope) {
+
+ this.storeException(request, property, error, forward, scope);
+ }
+
+ /**
+ * Default implementation for handling an <b>ActionMessage</b> generated
+ * from an Exception during <b>Action</b> delegation. The default
+ * implementation is to set an attribute of the request or session, as
+ * defined by the scope provided (the scope from the exception mapping). An
+ * <b>ActionErrors</b> instance is created, the error is added to the
+ * collection and the collection is set under the Globals.ERROR_KEY.
+ *
+ * @param request - The request we are handling
+ * @param property - The property name to use for this error
+ * @param error - The error generated from the exception mapping
+ * @param forward - The forward generated from the input path (from the form or exception mapping)
+ * @param scope - The scope of the exception mapping.
+ * @since Struts 1.2
+ */
+ protected void storeException(
+ HttpServletRequest request,
+ String property,
+ ActionMessage error,
+ ActionForward forward,
+ String scope) {
+
ActionErrors errors = new ActionErrors();
errors.add(property, error);
- if ("request".equals(scope)){
+ if ("request".equals(scope)) {
request.setAttribute(Globals.ERROR_KEY, errors);
} else {
request.getSession().setAttribute(Globals.ERROR_KEY, errors);
| 0 | 10 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
fa2d79ae6b60f7c3c7b3be2c2da0b0ea361ab5c9
|
STR-3004: Delete new copy; use svn copy to retain history
git-svn-id: https://svn.apache.org/repos/asf/struts/struts1/trunk@505772 13f79535-47bb-0310-9956-ffa450edef68
|
commit fa2d79ae6b60f7c3c7b3be2c2da0b0ea361ab5c9
Author: Paul C. Benedict Jr <[email protected]>
Date: Sat Feb 10 21:44:56 2007 +0000
STR-3004: Delete new copy; use svn copy to retain history
git-svn-id: https://svn.apache.org/repos/asf/struts/struts1/trunk@505772 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/core/src/main/resources/org/apache/struts/resources/struts-config_1_4.dtd b/core/src/main/resources/org/apache/struts/resources/struts-config_1_4.dtd
new file mode 100644
index 000000000..9935b24e6
--- /dev/null
+++ b/core/src/main/resources/org/apache/struts/resources/struts-config_1_4.dtd
@@ -0,0 +1,740 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!--
+ DTD for the Struts Application Configuration File
+
+ To support validation of your configuration file, include the following
+ DOCTYPE element at the beginning (after the "xml" declaration):
+
+ <!DOCTYPE struts-config PUBLIC
+ "-//Apache Software Foundation//DTD Struts Configuration 1.4//EN"
+ "http://struts.apache.org/dtds/struts-config_1_4.dtd">
+
+ $Id$
+-->
+
+
+<!-- ========== Defined Types ============================================= -->
+
+
+<!-- An "AttributeName" is the identifier of a page, request, session, or
+ application scope attribute.
+-->
+<!ENTITY % AttributeName "CDATA">
+
+
+<!-- A "BeanName" is the identifier of a JavaBean, such as a form bean,
+ and also serves as the name of the corresponding scripting variable
+ and the name of the JSP attribute under which the bean is accessed.
+ Therefore, it must conform to the rules for a Java identifier.
+-->
+<!ENTITY % BeanName "CDATA">
+
+
+<!-- A "Boolean" is the string representation of a boolean (true or false)
+ variable.
+-->
+<!ENTITY % Boolean "(true|false|yes|no)">
+
+
+<!-- A "ClassName" is the fully qualified name of a Java class that is
+ instantiated to provide the functionality of the enclosing element.
+-->
+<!ENTITY % ClassName "CDATA">
+
+
+<!-- An "Integer" is a character string consisting solely of numeric digits,
+ optionally preceeded by a minus sign, that can be converted to a
+ 32-bit integer.
+-->
+<!ENTITY % Integer "CDATA">
+
+
+<!-- A "Location" is a relative path, delimited by "/" characters, that
+ defines the location of a resource relative to the location of the
+ Struts configuration file itself.
+-->
+<!ENTITY % Location "#PCDATA">
+
+
+<!-- A "PropName" is the name of a JavaBeans property, and must begin with
+ a lower case letter and contain only characters that are legal in a
+ Java identifier.
+-->
+<!ENTITY % PropName "CDATA">
+
+
+<!-- A "RequestPath" is an module-relative URI path, beginning with a
+ slash, that identifies a mapped resource (such as a JSP page or a servlet)
+ within this web application.
+-->
+<!ENTITY % RequestPath "CDATA">
+
+
+<!-- The name of a JSP bean scope within which such a form bean may be
+ accessed.
+-->
+<!ENTITY % RequestScope "(request|session)">
+
+<!-- Defines possible values for automatic form bean population -->
+<!ENTITY % PopulateStrategy "(request|forward|request-forward|none)">
+
+<!-- ========== Top Level Elements ======================================== -->
+
+
+<!-- The "struts-config" element is the root of the configuration file
+ hierarchy, and contains nested elements for all of the other
+ configuration settings.
+-->
+<!ELEMENT struts-config (display-name?, description?, form-beans?, global-exceptions?, global-forwards?, action-mappings?, controller?, message-resources*, plug-in*)>
+<!ATTLIST struts-config id ID #IMPLIED>
+
+<!-- The "form-beans" element describes the set of form bean descriptors for this
+ module. The following attributes are defined:
+
+ type Fully qualified Java class to use when instantiating
+ ActionFormBean objects. If specified, the object must be a
+ subclass of the default class type.
+
+ WARNING: For Struts 1.0, this value is ignored. You
+ can set the default implementation class name with the
+ "formBean" initialization parameter to the Struts
+ controller servlet.
+-->
+<!ELEMENT form-beans (form-bean*)>
+<!ATTLIST form-beans id ID #IMPLIED>
+<!ATTLIST form-beans type %ClassName; #IMPLIED>
+
+
+<!-- The "form-bean" element describes an ActionForm subclass
+ [org.apache.struts.action.ActionForm] that can be referenced by an "action"
+ element.
+
+
+The "form-bean" element describes a particular form bean, which is a
+ JavaBean that implements the org.apache.struts.action.ActionForm
+ class. The following attributes are defined:
+
+ className The configuration bean for this form bean object. If
+ specified, the object must be a subclass of the default
+ configuration bean.
+ ["org.apache.struts.config.FormBeanConfig"]
+
+ extends The name of the form bean that this bean will
+ inherit configuration information from.
+
+ name The unique identifier for this form bean. Referenced by the
+ <action> element to specify which form bean to use with its
+ request.
+
+ type Fully qualified Java class name of the ActionForm subclass
+ to use with this form bean.
+
+ enhanced Reserved for future use.
+-->
+<!ELEMENT form-bean (icon?, display-name?, description?, set-property*, form-property*)>
+<!ATTLIST form-bean id ID #IMPLIED>
+<!ATTLIST form-bean className %ClassName; #IMPLIED>
+<!ATTLIST form-bean enhanced %Boolean; #IMPLIED>
+<!ATTLIST form-bean extends %BeanName; #IMPLIED>
+<!ATTLIST form-bean name %BeanName; #REQUIRED>
+<!ATTLIST form-bean type %ClassName; #IMPLIED>
+
+
+<!-- The "form-property" element describes a JavaBean property that can be used to
+ configure an instance of a DynaActionForm or a subclass thereof. This element
+ is only utilized when the "type" attribute of the enclosing "form-bean" element
+ is [org.apache.struts.action.DynaActionForm] or a subclass of DynaActionForm. If
+ a custom DynaActionForm subclass is used, then the "dynamic" attribute of the
+ enclosing <form-bean> element must be set to "true". Since Struts 1.1.
+
+ className The configuration bean for this form property object. If
+ specified, the object must be a subclass of the default
+ configuration bean.
+ ["org.apache.struts.config.FormPropertyConfig"]
+
+ initial String representation of the initial value for this property.
+ If not specified, primitives will be initialized to zero and
+ objects initialized to the zero-argument instantiation of that
+ object class. For example, Strings will be initialized to ""
+
+ name The name of the JavaBean property described by this element.
+
+ reset The flag that indicates when this property should be reset
+ to its "initial" value when the form's "reset()" method is
+ called. If this is set to "true", the property is always
+ reset when "reset()" is called. This can also be set to
+ one or more HTTP methods, such as GET or POST. In such a
+ case, the property will be reset only when the HTTP method
+ used for the request being processed is included in this
+ attribute's value(s). Multiple HTTP methods can be
+ specified by separating them with whitespace or commas.
+
+ size The number of array elements to create if the value of the
+ "type" attribute specifies an array, but there is no value
+ specified for the "initial" attribute.
+
+ type Fully qualified Java class name of the field underlying this
+ property, optionally followed by "[]" to indicate that the
+ field is indexed.
+-->
+<!ELEMENT form-property (set-property*)>
+<!ATTLIST form-property className %ClassName; #IMPLIED>
+<!ATTLIST form-property initial CDATA #IMPLIED>
+<!ATTLIST form-property name %PropName; #REQUIRED>
+<!ATTLIST form-property reset %Boolean; #IMPLIED>
+<!ATTLIST form-property size %Integer; #IMPLIED>
+<!ATTLIST form-property type %ClassName; #REQUIRED>
+
+
+<!-- The "global-exceptions" element describes a set of exceptions that might be
+ thrown by an Action object. The handling of individual exception types is
+ configured through nested exception elements. An <action> element may
+ override a global exception handler by registering a local exception handler
+ for the same exception type. Since Struts 1.1.
+-->
+<!ELEMENT global-exceptions (exception*)>
+<!ATTLIST global-exceptions id ID #IMPLIED>
+
+
+<!-- The "exception" element registers an ExceptionHandler for an exception type.
+ The following attributes are defined:
+
+ bundle Servlet context attribute for the message resources bundle
+ associated with this handler. The default attribute is the
+ value specified by the string constant declared at
+ Globals.MESSAGES_KEY.
+ [org.apache.struts.Globals.MESSAGES_KEY]
+
+ className The configuration bean for this ExceptionHandler object.
+ If specified, className must be a subclass of the default
+ configuration bean
+ ["org.apache.struts.config.ExceptionConfig"]
+
+ extends The name of the exception handler that this
+ will inherit configuration information from.
+
+ handler Fully qualified Java class name for this exception handler.
+ ["org.apache.struts.action.ExceptionHandler"]
+
+ key The key to use with this handler's message resource bundle
+ that will retrieve the error message template for this
+ exception.
+
+ path The module-relative URI to the resource that will complete
+ the request/response if this exception occurs.
+
+ scope The context ("request" or "session") that is used to access
+ the ActionMessage object
+ [org.apache.struts.action.ActionMessage] for this
+ exception.
+
+ type Fully qualified Java class name of the exception type to
+ register with this handler.
+-->
+<!ELEMENT exception (icon?, display-name?, description?, set-property*)>
+<!ATTLIST exception id ID #IMPLIED>
+<!ATTLIST exception bundle %AttributeName; #IMPLIED>
+<!ATTLIST exception className %ClassName; #IMPLIED>
+<!ATTLIST exception extends %ClassName; #IMPLIED>
+<!ATTLIST exception handler %ClassName; #IMPLIED>
+<!ATTLIST exception key CDATA #IMPLIED>
+<!ATTLIST exception path %RequestPath; #IMPLIED>
+<!ATTLIST exception scope CDATA #IMPLIED>
+<!ATTLIST exception type %ClassName; #REQUIRED>
+
+
+<!-- The "global-forwards" element describes a set of ActionForward objects
+ [org.apache.struts.action.ActionForward] that are available to all Action
+ objects as a return value. The individual ActionForwards are configured
+ through nested <forward> elements. An <action> element may override a global
+ forward by defining a local <forward> of the same name.
+
+ type Fully qualified Java class to use when instantiating
+ ActionForward objects. If specified, the object must be a
+ subclass of the default class type.
+
+ WARNING: For Struts 1.0, this value is ignored. You
+ can set the default implementation class name with the
+ "forward" initialization parameter to the Struts
+ controller servlet.
+-->
+<!ELEMENT global-forwards (forward*)>
+<!ATTLIST global-forwards id ID #IMPLIED>
+<!ATTLIST global-forwards type %ClassName; #IMPLIED>
+
+
+<!-- The "forward" element describes an ActionForward that is to be made
+ available to an Action as a return value. An ActionForward is referenced by
+ a logical name and encapsulates a URI. A "forward" element may be used to
+ describe both global and local ActionForwards. Global forwards are available
+ to all the Action objects in the module. Local forwards can be
+ nested within an <action> element and only available to an Action object
+ when it is invoked through that ActionMapping.
+
+ catalog The name of a commons-chain catalog in which to look up
+ a command to be executed as part of servicing this request.
+ Only meaningful if "command" is also specified.
+
+ className Fully qualified Java class name of ActionForward
+ subclass to use for this object.
+ ["org.apache.struts.action.ActionForward"]
+
+ command The name of a commons-chain command which should be looked up
+ and executed as part of servicing this request.
+
+ extends The name of the forward configuration that this
+ will inherit configuration information from.
+
+ module The module prefix to use with this path. This value should
+ begin with a slash ("/").
+
+ name The unique identifier for this forward. Referenced by the
+ Action object at runtime to select - by its logical name -
+ the resource that should complete the request/response.
+
+ path The module-relative path to the resources that is
+ encapsulated by the logical name of this ActionForward.
+ This value should begin with a slash ("/") character.
+
+ redirect Set to "true" if a redirect instruction should be issued to
+ the user-agent so that a new request is issued for this
+ forward's resource. If true, RequestDispatcher.Redirect is
+ called. If "false", RequestDispatcher.forward is called instead.
+ [false]
+-->
+<!ELEMENT forward (icon?, display-name?, description?, set-property*)>
+<!ATTLIST forward id ID #IMPLIED>
+<!ATTLIST forward catalog CDATA #IMPLIED>
+<!ATTLIST forward className %ClassName; #IMPLIED>
+<!ATTLIST forward command CDATA #IMPLIED>
+<!ATTLIST forward extends CDATA #IMPLIED>
+<!ATTLIST forward module %RequestPath; #IMPLIED>
+<!ATTLIST forward name CDATA #REQUIRED>
+<!ATTLIST forward path %RequestPath; #IMPLIED>
+<!ATTLIST forward redirect %Boolean; #IMPLIED>
+
+
+<!-- The "action-mappings" element describes a set of ActionMapping objects
+ [org.apache.struts.action.ActionMapping] that are available to process
+ requests matching the url-pattern our ActionServlet registered with the
+ container. The individual ActionMappings are configured through nested
+ <action> elements. The following attributes are defined:
+
+ type Fully qualified Java class to use when instantiating
+ ActionMapping objects. If specified, the object must be a
+ subclass of the default class type.
+
+ WARNING: For Struts 1.0, this value is ignored. You
+ can set the default implementation class name with the
+ "mapping" initialization parameter to the Struts
+ controller servlet.
+-->
+<!ELEMENT action-mappings (action*)>
+<!ATTLIST action-mappings id ID #IMPLIED>
+<!ATTLIST action-mappings type %ClassName; #IMPLIED>
+
+
+<!-- The "action" element describes an ActionMapping object that is to be used
+ to process a request for a specific module-relative URI. The following
+ attributes are defined:
+
+ attribute Name of the request-scope or session-scope attribute that
+ is used to access our ActionForm bean, if it is other than
+ the bean's specified "name". Optional if "name" is specified,
+ else not valid.
+
+ cancellable Set to "true" if the Action can be cancelled. By default,
+ when an Action is cancelled, validation is bypassed
+ and the Action should not execute the business operation.
+ If a request tries to cancel an Action when cancellable
+ is not set, a "InvalidCancelException" is thrown.
+ [false]
+
+ catalog The name of a commons-chain catalog in which to look up
+ a command to be executed as part of servicing this request.
+ Only meaningful if "command" is also specified.
+
+ className The fully qualified Java class name of the ActionMapping
+ subclass to use for this action mapping object. Defaults to
+ the type specified by the enclosing <action-mappings>
+ element or to "org.apache.struts.action.ActionMapping" if
+ not specified.
+ ["org.apache.struts.action.ActionMapping"]
+
+ command The name of a commons-chain command which should be looked up
+ and executed as part of servicing this request.
+
+ extends The path of the action mapping configuration that this
+ will inherit configuration information from.
+
+ forward Module-relative path of the servlet or other resource that
+ will process this request, instead of the Action class
+ specified by "type". The path WILL NOT be processed
+ through the "forwardPattern" attribute that is configured
+ on the "controller" element for this module.
+ Exactly one of "forward", "include", or "type" must be
+ specified.
+
+ include Module-relative path of the servlet or other resource that
+ will process this request, instead of the Action class
+ specified by "type". The path WILL NOT be processed
+ through the "forwardPattern" attribute that is configured
+ on the "controller" element for this module.
+ Exactly one of "forward", "include", or "type" must be
+ specified.
+
+ input Module-relative path of the action or other resource to
+ which control should be returned if a validation error is
+ encountered. Valid only when "name" is specified. Required
+ if "name" is specified and the input bean returns
+ validation errors. Optional if "name" is specified and the
+ input bean does not return validation errors.
+
+ name Name of the form bean, if any, that is associated with this
+ action mapping.
+
+ parameter General-purpose configuration parameter that can be used to
+ pass extra information to the Action object selected by
+ this action mapping.
+
+ path The module-relative path of the submitted request, starting
+ with a "/" character, and without the filename extension if
+ extension mapping is used.
+
+ NOTE: Do *not* include a period in your path name,
+ because it will look like a filename extension and
+ cause your Action to not be located.
+
+ prefix Prefix used to match request parameter names to ActionForm
+ property names, if any. Optional if "name" is specified,
+ else not allowed.
+
+ roles Comma-delimited list of security role names that are allowed
+ access to this ActionMapping object. Since Struts 1.1.
+
+ scope The context ("request" or "session") that is used to
+ access our ActionForm bean, if any. Optional if "name" is
+ specified, else not valid. [session]
+
+ suffix Suffix used to match request parameter names to ActionForm
+ bean property names, if any. Optional if "name" is
+ specified, else not valid.
+
+ type Fully qualified Java class name of the Action subclass
+ [org.apache.struts.action.Action] that will process requests
+ for this action mapping. Not valid if either the "forward"
+ or "include" attribute is specified. Exactly one of
+ "forward", "include", or "type" must be specified.
+
+ unknown Set to "true" if this object should be configured as the
+ default action mapping for this module. If a request does not
+ match another object, it will be passed to the ActionMapping
+ object with unknown set to "true". Only one ActionMapping
+ can be marked as "unknown" within a module.
+ [false]
+
+ validate Set to "true" if the validate method of the ActionForm bean
+ should be called prior to calling the Action object for this
+ action mapping, or set to "false" if you do not want the
+ validate method called.
+ [true]
+
+ reset Allows to specify conditions for automatic form reset.
+ Possible values: not specified, "request", "forward",
+ "request-forward" or "none".
+ [request-forward]
+
+ populate Allows to specify conditions for automatic form population
+ with HTTP request values. Possible values: not specified,
+ "request", "forward", "request-forward" or "none".
+ [request-forward]
+-->
+<!ELEMENT action (icon?, display-name?, description?, set-property*, exception*, forward*)>
+<!ATTLIST action id ID #IMPLIED>
+<!ATTLIST action attribute %BeanName; #IMPLIED>
+<!ATTLIST action cancellable %Boolean; #IMPLIED>
+<!ATTLIST action catalog CDATA #IMPLIED>
+<!ATTLIST action className %ClassName; #IMPLIED>
+<!ATTLIST action command CDATA #IMPLIED>
+<!ATTLIST action extends %RequestPath; #IMPLIED>
+<!ATTLIST action forward %RequestPath; #IMPLIED>
+<!ATTLIST action include %RequestPath; #IMPLIED>
+<!ATTLIST action input %RequestPath; #IMPLIED>
+<!ATTLIST action name %BeanName; #IMPLIED>
+<!ATTLIST action parameter CDATA #IMPLIED>
+<!ATTLIST action path %RequestPath; #REQUIRED>
+<!ATTLIST action populate %PopulateStrategy; #IMPLIED>
+<!ATTLIST action prefix CDATA #IMPLIED>
+<!ATTLIST action reset %PopulateStrategy; #IMPLIED>
+<!ATTLIST action roles CDATA #IMPLIED>
+<!ATTLIST action scope %RequestScope; #IMPLIED>
+<!ATTLIST action suffix CDATA #IMPLIED>
+<!ATTLIST action type %ClassName; #IMPLIED>
+<!ATTLIST action unknown %Boolean; #IMPLIED>
+<!ATTLIST action validate %Boolean; #IMPLIED>
+
+
+<!-- The "controller" element describes the ControllerConfig bean
+ [org.apache.struts.config.ControllerConfig] that encapsulates
+ a module's runtime configuration. The following
+ attributes are defined:
+
+ bufferSize The size of the input buffer used when processing
+ file uploads.
+ [4096]
+
+ catalog Name of the catalog to use when processing requests
+ for this module.
+ [struts]
+
+ className Fully qualified Java class name of the
+ ControllerConfig subclass for this controller object.
+ If specified, the object must be a subclass of the
+ default class.
+ ["org.apache.struts.config.ControllerConfig"]
+
+ command Name of the command to execute to process a request.
+ [servlet-standard]
+
+ contentType Default content type (and optional character encoding) to
+ be set on each response. May be overridden by the Action,
+ JSP, or other resource to which the request is forwarded.
+ ["text/html"]
+
+ forwardPattern Replacement pattern defining how the "path" attribute of a
+ <forward> element is mapped to a context-relative URL when
+ it starts with a slash (and when the contextRelative
+ property is false). This value may consist of any
+ combination of the following:
+ - "$M" - Replaced by the module prefix of this module
+ - "$P" - Replaced by the "path" attribute of the selected
+ "forward" element
+ - "$$" - Causes a literal dollar sign to be rendered
+ - "$x" - (Where "x" is any character not defined above)
+ Silently swallowed, reserved for future use
+ If not specified, the default forwardPattern is "$M$P",
+ which is consistent with the previous behavior of
+ forwards. Since Struts 1.1. ["$M$P"]
+
+ inputForward Set to "true" if you want the "input" attribute of
+ <action> elements to be the name of a local or global
+ ActionForward, which will then be used to calculate the
+ ultimate URL. Set to "false" (the default) to treat the
+ "input" parameter of <action> elements as a
+ module-relative path to the resource
+ to be used as the input form. Since Struts 1.1.
+ [false]
+
+ locale Set to "true" if you want a Locale object stored in the
+ user's session if not already present.
+ [true]
+
+ maxFileSize The maximum size (in bytes) of a file to be accepted as a
+ file upload. Can be expressed as a number followed by a
+ "K", "M", or "G", which are interpreted to mean kilobytes,
+ megabytes, or gigabytes, respectively.
+ ["250M"]
+
+ memFileSize The maximum size (in bytes) of a file whose contents will
+ be retained in memory after uploading. Files larger than
+ this threshold will be written to some alternative storage
+ medium, typically a hard disk. Can be expressed as a number
+ followed by a "K", "M", or "G", which are interpreted to
+ mean kilobytes, megabytes, or gigabytes, respectively.
+ ["256K"]
+
+ multipartClass The fully qualified Java class name of the multipart
+ request handler class to be used with this module.
+ ["org.apache.struts.upload.CommonsMultipartRequestHandler"]
+
+ nocache Set to "true" if you want the controller to add HTTP
+ headers for defeating caching to every response from
+ this module. [false]
+
+ pagePattern Replacement pattern defining how the "page" attribute of
+ custom tags using it is mapped to a context-relative URL
+ of the corresponding resource. This value may consist of
+ any combination of the following:
+ - "$M" - Replaced by the module prefix of this module
+ - "$P" - Replaced by the value of the "page" attribute
+ - "$$" - Causes a literal dollar sign to be rendered
+ - "$x" - (Where "x" is any character not defined above)
+ Silently swallowed, reserved for future use
+ If not specified, the default forwardPattern is
+ "$M$P", which is consistent with previous hard coded
+ behavior of URL evaluation for "page" attributes.
+ ["$M$P"]
+
+ processorClass The fully qualified Java class name of the
+ RequestProcessor subclass to be used with this module.
+ ["org.apache.struts.chain.ComposableRequestProcessor"]
+
+ tempDir Temporary working directory to use when processing
+ file uploads.
+ [{Directory provided by servlet container}]
+
+-->
+<!ELEMENT controller (set-property*)>
+<!ATTLIST controller id ID #IMPLIED>
+<!ATTLIST controller bufferSize %Integer; #IMPLIED>
+<!ATTLIST controller catalog CDATA #IMPLIED>
+<!ATTLIST controller className %ClassName; #IMPLIED>
+<!ATTLIST controller command CDATA #IMPLIED>
+<!ATTLIST controller contentType CDATA #IMPLIED>
+<!ATTLIST controller forwardPattern CDATA #IMPLIED>
+<!ATTLIST controller inputForward %Boolean; #IMPLIED>
+<!ATTLIST controller locale %Boolean; #IMPLIED>
+<!ATTLIST controller maxFileSize CDATA #IMPLIED>
+<!ATTLIST controller memFileSize CDATA #IMPLIED>
+<!ATTLIST controller multipartClass %ClassName; #IMPLIED>
+<!ATTLIST controller nocache %Boolean; #IMPLIED>
+<!ATTLIST controller pagePattern CDATA #IMPLIED>
+<!ATTLIST controller processorClass %ClassName; #IMPLIED>
+<!ATTLIST controller tempDir CDATA #IMPLIED>
+
+
+<!-- The "message-resources" element describes a MessageResources object with
+ message templates for this module. The following attributes are defined:
+
+ className The configuration bean for this message resources object.
+ If specified, the object must be a subclass of the default
+ configuration bean.
+ ["org.apache.struts.config.MessageResourcesConfig"]
+
+ factory Fully qualified Java class name of the
+ MessageResourcesFactory subclass to use for this message
+ resources object.
+ ["org.apache.struts.util.PropertyMessageResourcesFactory"]
+
+ key Servlet context attribute under which this message
+ resources bundle will be stored. The default attribute is
+ the value specified by the string constant at
+ [Globals.MESSAGES_KEY]. The module prefix (if
+ any) is appended to the key (${key}${prefix}).
+ [org.apache.struts.Globals.MESSAGES_KEY]
+
+ NOTE: The module prefix includes the leading
+ slash, so the default message resource bundle for a module
+ named "foo" is stored under
+ "org.apache.struts.action.MESSAGE/foo".
+
+ null Set to "true" if you want our message resources to return a
+ null string for unknown message keys, or "false" to return a
+ message with the bad key value.
+
+ parameter Configuration parameter to be passed to the createResources
+ method of our factory object.
+-->
+<!ELEMENT message-resources (set-property*)>
+<!ATTLIST message-resources id ID #IMPLIED>
+<!ATTLIST message-resources className %ClassName; #IMPLIED>
+<!ATTLIST message-resources factory %ClassName; #IMPLIED>
+<!ATTLIST message-resources key %AttributeName; #IMPLIED>
+<!ATTLIST message-resources null %Boolean; #IMPLIED>
+<!ATTLIST message-resources parameter CDATA #REQUIRED>
+
+
+<!-- The "plug-in" element specifies the fully qualified class name of a
+ general-purpose application plug-in module that receives notification of
+ application startup and shutdown events. An instance of the specified class
+ is created for each element, and can be configured with nested <set-property>
+ elements. The following attributes are supported:
+
+ className Fully qualified Java class name of the plug-in class; must
+ implement [org.apache.struts.action.PlugIn].
+-->
+<!ELEMENT plug-in (set-property*)>
+<!ATTLIST plug-in id ID #IMPLIED>
+<!ATTLIST plug-in className %ClassName; #REQUIRED>
+
+
+<!-- ========== Subordinate Elements ====================================== -->
+
+
+<!-- The "description" element contains descriptive (paragraph length) text
+ about the surrounding element, suitable for use in GUI tools.
+-->
+<!ELEMENT description (#PCDATA)>
+<!ATTLIST description id ID #IMPLIED>
+
+
+<!-- The "display-name" element contains a short (one line) description of
+ the surrounding element, suitable for use in GUI tools.
+-->
+<!ELEMENT display-name (#PCDATA)>
+<!ATTLIST display-name id ID #IMPLIED>
+
+
+<!-- The "icon" element contains a small-icon and large-icon element which
+ specify the location, relative to the Struts configuration file, for small
+ and large images used to represent the surrounding element in GUI tools.
+-->
+<!ELEMENT icon (small-icon?, large-icon?)>
+<!ATTLIST icon id ID #IMPLIED>
+
+
+<!-- The "large-icon" element specifies the location, relative to the Struts
+ configuration file, of a resource containing a large (32x32 pixel)
+ icon image.
+-->
+<!ELEMENT large-icon (%Location;)>
+<!ATTLIST large-icon id ID #IMPLIED>
+
+
+<!-- The "set-property" element specifies the method name and initial value of
+ an additional JavaBean configuration property. When the object representing
+ the surrounding element is instantiated, the accessor for the indicated
+ property is called and passed the indicated value. The "set-property"
+ element is especially useful when a custom subclass is used with
+ <forward>, <action>, or <plug-in> elements. The subclass
+ can be passed whatever other properties may be required to configure the
+ object without changing how the struts-config is parsed.
+
+ Since Struts 1.3, an alternate syntax is supported. By using
+ the "key" attribute instead of the "property" attribute, you can set
+ arbitrary string properties on the Config object which is populated
+ based on the containing element. NOTE: the "key" attribute is NOT
+ supported for <set-property> inside a <plug-in> element.
+
+ property Name of the JavaBeans property whose setter method
+ will be called. Exactly one of
+ "property" or "key" must be specified.
+
+ key Where supported, the key which will be used to store
+ the specified value in the given config object. Exactly one of
+ "property" or "key" must be specified.
+
+ value String representation of the value to which this
+ property will be set, after suitable type conversion
+
+-->
+<!ELEMENT set-property EMPTY>
+<!ATTLIST set-property id ID #IMPLIED>
+<!ATTLIST set-property property %PropName; #IMPLIED>
+<!ATTLIST set-property key CDATA #IMPLIED>
+<!ATTLIST set-property value CDATA #REQUIRED>
+
+
+<!-- The "small-icon" element specifies the location, relative to the Struts
+ configuration file, of a resource containing a small (16x16 pixel)
+ icon image.
+-->
+<!ELEMENT small-icon (%Location;)>
+<!ATTLIST small-icon id ID #IMPLIED>
+
| 0 | 2 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
dc188fbdf90d6210937dd25d03037018c5f41a87
|
Submitted by Ted Husted. Minor changes to hilight standard
ActionForm validate methods.
<snip>
<li>Generally, there will be very little input validation logic in an
<code>ActionForm</code> bean. The primary reason such beans exist
is to save the most recent values entered by the user for the
associated form -- even if errors are detected -- so that the same
page can be reproduced, along with a set of error messages, so the
user need only correct the fields that are wrong. Validation
of user input should be performed within <code>Action</code> classes
(if it is simple), or appropriate business logic beans.</li>
</snip>
<insert>
<li>The ActionForm object also offers a standard validation mechanism.
If you override a "stub" method, and provide error messages in the
standard application resource, Struts will automatically validate the
input from the form (using your method). If validation fails, Struts
can automatically return the user to the input form, re-populate
the form from the form bean, and display your error messages (via a
custom tag), all before the Action object is ever called. This is a
quick and easy way to get simple validation out of the way, but you
might also want to provide further "business logic" validation as
part of your Action object. (See "Action Form Validation" for details.)
Of course, you can also ignore the ActionForm validation and provide
your own in the Action object</li>
</insert>
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48018 13f79535-47bb-0310-9956-ffa450edef68
|
commit dc188fbdf90d6210937dd25d03037018c5f41a87
Author: Ted Nathan Husted <[email protected]>
Date: Wed Jan 10 22:39:27 2001 +0000
Submitted by Ted Husted. Minor changes to hilight standard
ActionForm validate methods.
<snip>
<li>Generally, there will be very little input validation logic in an
<code>ActionForm</code> bean. The primary reason such beans exist
is to save the most recent values entered by the user for the
associated form -- even if errors are detected -- so that the same
page can be reproduced, along with a set of error messages, so the
user need only correct the fields that are wrong. Validation
of user input should be performed within <code>Action</code> classes
(if it is simple), or appropriate business logic beans.</li>
</snip>
<insert>
<li>The ActionForm object also offers a standard validation mechanism.
If you override a "stub" method, and provide error messages in the
standard application resource, Struts will automatically validate the
input from the form (using your method). If validation fails, Struts
can automatically return the user to the input form, re-populate
the form from the form bean, and display your error messages (via a
custom tag), all before the Action object is ever called. This is a
quick and easy way to get simple validation out of the way, but you
might also want to provide further "business logic" validation as
part of your Action object. (See "Action Form Validation" for details.)
Of course, you can also ignore the ActionForm validation and provide
your own in the Action object</li>
</insert>
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48018 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/doc/userGuide/building_model.xml b/src/doc/userGuide/building_model.xml
index 1f9b2d009..f4bfde3a1 100644
--- a/src/doc/userGuide/building_model.xml
+++ b/src/doc/userGuide/building_model.xml
@@ -10,246 +10,250 @@
<body>
<chapter name="Building Model Components" href="building_model">
- <section name="2.1 Overview" href="overview">
-
- <p>
- The application requirements document that you are using will likely
- have focused on the user interface to be created. However, you should ensure
- that the processing required for each submitted request is also clearly
- defined. In general, the developer of the <i>Model</i> components will be
- focusing on the creation of JavaBeans classes that support all of the
- functional requirements. The precise nature of the beans required by a
- particular application will vary widely depending on those requirements,
- but they can generally be classified into several categories discussed
- below. However, a brief review of the concept of "scope" as it relates
- to beans is useful first.
- </p>
- </section>
-
- <section name="2.2 JavaBeans and Scope" href="javabeans">
-
- <p>
- Within a web-based application, JavaBeans can be stored in (and accessed
- from) a number of different collections of "attributes". Each collection
- has different rules for the lifetime of that collection, and the visibility
- of the beans stored there. Together, the rules defining lifetime and
- visibility are called the <i>scope</i> of those beans. The JavaServer
- Pages (JSP) Specification defines scope choices using the following terms
- (with the equivalent servlet API concept defined in parentheses):
- </p>
-
- <ul>
- <li><b>page</b> - Beans that are visible within a single JSP page,
- for the lifetime of the current request. (Local variables of
- the <code>service()</code> method)</li>
- <li><b>request</b> - Beans that are visible within a single JSP page,
- as well as to any page or servlet that is included in this page,
- or forwarded to by this page. (Request attributes)</li>
- <li><b>session</b> - Beans that are visible to all JSP pages and
- servlets that participate in a particular user session, across one
- or more requests. (Session attributes)</li>
- <li><b>application</b> - Beans that are visible to all JSP pages and
- servlets that are part of a web application. (Servlet context
- attributes)</li>
- </ul>
-
- <p>
- It is important to remember that JSP pages and servlets in the same
- web application share the same sets of bean collections. For example,
- a bean stored as a request attribute in a servlet like this:
- </p>
-
- <pre>
- MyCart mycart = new MyCart(...);
- request.setAttribute("cart", mycart);
- </pre>
-
- <p>
- is immediately visible to a JSP page which this servlet forwards to,
- using a standard action tag like this:
- </p>
-
- <pre>
- <jsp:useBean id="cart" scope="request"
- class="com.mycompany.MyApp.MyCart"/>
- </pre>
- </section>
-
- <section name="2.3 ActionForm Beans" href="actionform">
-
- <p>
- Note: ActionForm beans are actually closer to the <i>View</i>
- than the <i>Model</i>
- </p>
- <p>
- The Struts framework generally assumes that you have created an
- <code>ActionForm</code> bean (that is, a Java class extending the
- <code>ActionForm</code> class) for each input form required in your
- application. If you define such beans in your <code>ActionMapping</code>
- configuration file (see "Building the Controller Components"), the Struts
- controller servlet will automatically perform the following services for
- you, before invoking the appropriate <code>Action</code> method:
- </p>
-
- <ul>
- <li>Check in the user's session for an instance of a bean of the
- appropriate class, under the appropriate key.</li>
- <li>If there is no such session scope bean available, a new one is
- automatically created and added to the user's session.</li>
- <li>For every request parameter whose name corresponds to the name
- of a property in the bean, the corresponding setter method will
- be called. This operates in a manner similar to the standard
- JSP action <code><jsp:setProperty></code> when you use the
- asterisk wildcard to select all properties.</li>
- <li>The updated <code>ActionForm</code> bean will be passed to the
- Action Class <code>perform()</code> method when it is called,
- making these values immediately available.</li>
- </ul>
-
- <p>
- When you code your <code>ActionForm</code> beans, keep the following
- principles in mind:
- </p>
-
- <ul>
- <li>The <code>ActionForm</code> class itself requires no specific
- methods to be implemented. It is used to identify the role these
- particular beans play in the overall architecture. Typically, an
- <code>ActionForm</code> bean will have only property getter and
- property setter methods, with no business logic.</li>
- <li>Generally, there will be very little input validation logic in an
- <code>ActionForm</code> bean. The primary reason such beans exist
- is to save the most recent values entered by the user for the
- associated form -- even if errors are detected -- so that the same
- page can be reproduced, along with a set of error messages, so the
- user need only correct the fields that are wrong. Validation
- of user input should be performed within <code>Action</code> classes
- (if it is simple), or appropriate business logic beans.</li>
- <li>Define a property (with associated <code>getXxx()</code> and
- <code>setXxx()</code> methods) for each field that is present
- in the form. The field name and property name must match according
- to the usual JavaBeans conventions. For example, an input field named
- <code>username</code> will cause the <code>setUsername()</code> method
- to be called.</li>
- </ul>
-
- <p>
- You should note that a "form", in the sense discussed here, does not
- necessarily correspond to a single JSP page in the user interface. It is
- common in many applications to have a "form" (from the user's perspective)
- that extends over multiple pages. Think, for example, of the wizard style
- user interface that is commonly used when installing new applications. Struts
- encourages you to define a single <code>ActionForm</code> bean that contains
- properties for all of the fields, no matter which page the field is actually
- displayed on. Likewise, the various pages of the same form should all be
- submitted to the same Action Class. If you follow these suggestions, the
- page designers can rearrange the fields among the various pages, with no
- changes required to the processing logic in most cases.
- </p>
- </section>
-
- <section name="2.4 System State Beans" href="system_state">
-
- <p>
- The actual state of a system is normally represented as a set of one or
- more JavaBeans classes, whose properties define the current state. A
- shopping cart system, for example, will include a bean that represents the
- cart being maintained for each individual shopper, and will (among other
- things) include the set of items that the shopper has currently selected
- for purchase. Separately, the system will also include different beans
- for the user's profile information (including their credit card and ship-to
- addresses), as well as the catalog of available items and their current
- inventory levels.
- </p>
-
- <p>
- For small scale systems, or for state information that need not be kept
- for a long period of time, a set of system state beans may contain all the
- knowledge that the system ever has of these particular details. Or, as is
- often the case, the system state beans will represent information that is
- stored permanently in some external database (such as a CustomerBean object
- that corresponds to a particular row in the CUSTOMERS table), and are
- created or removed from the server's memory as needed. Entity Enterprise
- JavaBeans are also used for this purpose in large scale applications.
- </p>
- </section>
-
- <section name="2.5 Business Logic Beans" href="business_logic">
-
- <p>
- You should encapsulate the functional logic of your application as
- method calls on JavaBeans designed for this purpose. These methods may
- be part of the same classes used for the system state beans, or they may
- be in separate classes dedicated to performing the logic. In the latter
- case, you will usually need to pass the system state beans to be manipulated
- to these methods as arguments.
- </p>
-
- <p>
- For maximum code re-use, business logic beans should be designed and
- implemented so that they do <b>not</b> know they are being executed in a
- web application environment. If you find yourself having to import a
- <code>javax.servlet.*</code> class in your bean, you
- are tying this business logic to the web application environment. Consider
- rearranging things so that your <code>Action</code> classes (part of the
- Controller role, as described below) translate all required information
- from the HTTP request being processed into property setter calls on your
- business logic beans, after which a call to an <code>execute()</code> method
- can be made. Such a business logic class can be reused in environments
- other than the web application for which they were initially constructed.
- </p>
-
- <p>
- Depending on the complexity and scope of your application, business logic
- beans might be ordinary JavaBeans that interact with system state beans
- passed as arguments, or ordinary JavaBeans that access a database using
- JDBC calls. For larger applications, these beans will often be stateful
- or stateless Enterprise JavaBeans (EJBs) instead.
- </p>
- </section>
-
- <section name="2.6 Accessing Relational Databases" href="databases">
-
- <p>
- Struts contains in it's mapping config file the ability to specify data sources.
- See <a href="building_controller.html#config">The Action Mappings Configuration File</a>
- for information on how to set up a datasource. Do that first.
- </p>
-
- <p>
- After setting up your data source in the config file, most likely you'll want
- to retrieve a connection from it. This small example nested inside of an action's
- <code>perform()</code> method will show you how to do it:
- </p>
- <p>
- <pre>
- public ActionForward perform(ActionMapping mapping,
- ActionForm form,
- HttpServletRequest request,
- HttpServletResponse response) {
- try {
- javax.sql.DataSource dataSource =
- (DataSource) getServlet().getServletContext().getAttribute(Action.DATA_SOURCE_KEY);
-
- Connection myConnection = dataSource.getConnection();
- //do what you wish with myConnection
- }
- catch (SQLException sqle) {
- sqle.printStackTrace();
- }
- finally {
- //enclose this in a finally block to make
- //sure the connection is closed
- myConnection.close();
- }
- }
- </pre>
- </p>
-
- <p align="center">
- Next: <a href="building_view.html">Building View Components</a>
- </p>
- </section>
- </chapter>
- </body>
+ <section name="2.1 Overview" href="overview">
+
+ <p>
+ The application requirements document that you are using will likely
+ have focused on the user interface to be created. However, you should ensure
+ that the processing required for each submitted request is also clearly
+ defined. In general, the developer of the <i>Model</i> components will be
+ focusing on the creation of JavaBeans classes that support all of the
+ functional requirements. The precise nature of the beans required by a
+ particular application will vary widely depending on those requirements,
+ but they can generally be classified into several categories discussed
+ below. However, a brief review of the concept of "scope" as it relates
+ to beans is useful first.
+ </p>
+ </section>
+
+ <section name="2.2 JavaBeans and Scope" href="javabeans">
+
+ <p>
+ Within a web-based application, JavaBeans can be stored in (and accessed
+ from) a number of different collections of "attributes". Each collection
+ has different rules for the lifetime of that collection, and the visibility
+ of the beans stored there. Together, the rules defining lifetime and
+ visibility are called the <i>scope</i> of those beans. The JavaServer
+ Pages (JSP) Specification defines scope choices using the following terms
+ (with the equivalent servlet API concept defined in parentheses):
+ </p>
+
+ <ul>
+ <li><b>page</b> - Beans that are visible within a single JSP page,
+ for the lifetime of the current request. (Local variables of
+ the <code>service()</code> method)</li>
+ <li><b>request</b> - Beans that are visible within a single JSP page,
+ as well as to any page or servlet that is included in this page,
+ or forwarded to by this page. (Request attributes)</li>
+ <li><b>session</b> - Beans that are visible to all JSP pages and
+ servlets that participate in a particular user session, across one
+ or more requests. (Session attributes)</li>
+ <li><b>application</b> - Beans that are visible to all JSP pages and
+ servlets that are part of a web application. (Servlet context
+ attributes)</li>
+ </ul>
+
+ <p>
+ It is important to remember that JSP pages and servlets in the same
+ web application share the same sets of bean collections. For example,
+ a bean stored as a request attribute in a servlet like this:
+ </p>
+
+ <pre>
+ MyCart mycart = new MyCart(...);
+ request.setAttribute("cart", mycart);
+ </pre>
+
+ <p>
+ is immediately visible to a JSP page which this servlet forwards to,
+ using a standard action tag like this:
+ </p>
+
+ <pre>
+ <jsp:useBean id="cart" scope="request"
+ class="com.mycompany.MyApp.MyCart"/>
+ </pre>
+ </section>
+
+ <section name="2.3 ActionForm Beans" href="actionform">
+
+ <p>
+ Note: ActionForm beans are actually closer to the <i>View</i>
+ than the <i>Model</i>
+ </p>
+ <p>
+ The Struts framework generally assumes that you have created an
+ <code>ActionForm</code> bean (that is, a Java class extending the
+ <code>ActionForm</code> class) for each input form required in your
+ application. If you define such beans in your <code>ActionMapping</code>
+ configuration file (see "Building the Controller Components"), the Struts
+ controller servlet will automatically perform the following services for
+ you, before invoking the appropriate <code>Action</code> method:
+ </p>
+
+ <ul>
+ <li>Check in the user's session for an instance of a bean of the
+ appropriate class, under the appropriate key.</li>
+ <li>If there is no such session scope bean available, a new one is
+ automatically created and added to the user's session.</li>
+ <li>For every request parameter whose name corresponds to the name
+ of a property in the bean, the corresponding setter method will
+ be called. This operates in a manner similar to the standard
+ JSP action <code><jsp:setProperty></code> when you use the
+ asterisk wildcard to select all properties.</li>
+ <li>The updated <code>ActionForm</code> bean will be passed to the
+ Action Class <code>perform()</code> method when it is called,
+ making these values immediately available.</li>
+ </ul>
+
+ <p>
+ When you code your <code>ActionForm</code> beans, keep the following
+ principles in mind:
+ </p>
+
+ <ul>
+ <li>The <code>ActionForm</code> class itself requires no specific
+ methods to be implemented. It is used to identify the role these
+ particular beans play in the overall architecture. Typically, an
+ <code>ActionForm</code> bean will have only property getter and
+ property setter methods, with no business logic.</li>
+ <li>The ActionForm object also offers a standard validation mechanism.
+ If you override a "stub" method, and provide error messages in the
+ standard application resource, Struts will automatically validate the
+ input from the form (using your method). If validation fails, Struts
+ can automatically return the user to the input form, re-populate
+ the form from the form bean, and display your error messages (via a
+ custom tag), all before the Action object is ever called. This is a
+ quick and easy way to get simple validation out of the way, but you
+ might also want to provide further "business logic" validation as
+ part of your Action object. (See "Action Form Validation" for details.)
+ Of course, you can also ignore the ActionForm validation and provide
+ your own in the Action object</li>
+ <li>Define a property (with associated <code>getXxx()</code> and
+ <code>setXxx()</code> methods) for each field that is present
+ in the form. The field name and property name must match according
+ to the usual JavaBeans conventions. For example, an input field named
+ <code>username</code> will cause the <code>setUsername()</code> method
+ to be called.</li>
+ </ul>
+
+ <p>
+ You should note that a "form", in the sense discussed here, does not
+ necessarily correspond to a single JSP page in the user interface. It is
+ common in many applications to have a "form" (from the user's perspective)
+ that extends over multiple pages. Think, for example, of the wizard style
+ user interface that is commonly used when installing new applications. Struts
+ encourages you to define a single <code>ActionForm</code> bean that contains
+ properties for all of the fields, no matter which page the field is actually
+ displayed on. Likewise, the various pages of the same form should all be
+ submitted to the same Action Class. If you follow these suggestions, the
+ page designers can rearrange the fields among the various pages, with no
+ changes required to the processing logic in most cases.
+ </p>
+ </section>
+
+ <section name="2.4 System State Beans" href="system_state">
+
+ <p>
+ The actual state of a system is normally represented as a set of one or
+ more JavaBeans classes, whose properties define the current state. A
+ shopping cart system, for example, will include a bean that represents the
+ cart being maintained for each individual shopper, and will (among other
+ things) include the set of items that the shopper has currently selected
+ for purchase. Separately, the system will also include different beans
+ for the user's profile information (including their credit card and ship-to
+ addresses), as well as the catalog of available items and their current
+ inventory levels.
+ </p>
+
+ <p>
+ For small scale systems, or for state information that need not be kept
+ for a long period of time, a set of system state beans may contain all the
+ knowledge that the system ever has of these particular details. Or, as is
+ often the case, the system state beans will represent information that is
+ stored permanently in some external database (such as a CustomerBean object
+ that corresponds to a particular row in the CUSTOMERS table), and are
+ created or removed from the server's memory as needed. Entity Enterprise
+ JavaBeans are also used for this purpose in large scale applications.
+ </p>
+ </section>
+
+ <section name="2.5 Business Logic Beans" href="business_logic">
+
+ <p>
+ You should encapsulate the functional logic of your application as
+ method calls on JavaBeans designed for this purpose. These methods may
+ be part of the same classes used for the system state beans, or they may
+ be in separate classes dedicated to performing the logic. In the latter
+ case, you will usually need to pass the system state beans to be manipulated
+ to these methods as arguments.
+ </p>
+
+ <p>
+ For maximum code re-use, business logic beans should be designed and
+ implemented so that they do <b>not</b> know they are being executed in a
+ web application environment. If you find yourself having to import a
+ <code>javax.servlet.*</code> class in your bean, you
+ are tying this business logic to the web application environment. Consider
+ rearranging things so that your <code>Action</code> classes (part of the
+ Controller role, as described below) translate all required information
+ from the HTTP request being processed into property setter calls on your
+ business logic beans, after which a call to an <code>execute()</code> method
+ can be made. Such a business logic class can be reused in environments
+ other than the web application for which they were initially constructed.
+ </p>
+
+ <p>
+ Depending on the complexity and scope of your application, business logic
+ beans might be ordinary JavaBeans that interact with system state beans
+ passed as arguments, or ordinary JavaBeans that access a database using
+ JDBC calls. For larger applications, these beans will often be stateful
+ or stateless Enterprise JavaBeans (EJBs) instead.
+ </p>
+ </section>
+
+ <section name="2.6 Accessing Relational Databases" href="databases">
+
+ <p>
+ Struts contains in it's mapping config file the ability to specify data sources.
+ See <a href="building_controller.html#config">The Action Mappings Configuration File</a>
+ for information on how to set up a datasource. Do that first.
+ </p>
+
+ <p>
+ After setting up your data source in the config file, most likely you'll want
+ to retrieve a connection from it. This small example nested inside of an action's
+ <code>perform()</code> method will show you how to do it:
+ </p>
+ <p>
+ <pre>
+ public ActionForward perform(ActionMapping mapping,
+ ActionForm form,
+ HttpServletRequest request,
+ HttpServletResponse response) {
+ try {
+ javax.sql.DataSource dataSource =
+ (DataSource) getServlet().getServletContext().getAttribute(Action.DATA_SOURCE_KEY);
+
+ Connection myConnection = dataSource.getConnection();
+ //do what you wish with myConnection
+ }
+ catch (SQLException sqle) {
+ sqle.printStackTrace();
+ }
+ finally {
+ //enclose this in a finally block to make
+ //sure the connection is closed
+ myConnection.close();
+ }
+ }
+ </pre>
+ </p>
+
+ <p align="center">
+ Next: <a href="building_view.html">Building View Components</a>
+ </p>
+ </section>
+ </chapter>
+ </body>
</document>
\ No newline at end of file
| 0 | 9 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
7ac7d6d69ac64863983b2b673aab62241b33ce8f
|
Bring the release notes for beta-2 up to date with respect to recent changes.
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48341 13f79535-47bb-0310-9956-ffa450edef68
|
commit 7ac7d6d69ac64863983b2b673aab62241b33ce8f
Author: Craig R. McClanahan <[email protected]>
Date: Sun May 13 02:56:19 2001 +0000
Bring the release notes for beta-2 up to date with respect to recent changes.
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48341 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/doc/release-notes-1.0-b2.xml b/doc/release-notes-1.0-b2.xml
index 43fdb868b..8f8c54445 100644
--- a/doc/release-notes-1.0-b2.xml
+++ b/doc/release-notes-1.0-b2.xml
@@ -107,6 +107,12 @@
deprecated, and have been replaced (and considerably enhanced) in
the various individual tag libraries.</p>
+ <p>The build procedure for compiling the Struts source distribution
+ has been revised, and now depends on having <strong>Ant 1.2</strong>
+ (or later) installed, with the <code>$ANT_HOME/bin</code> directory
+ on your path. Further information can be found in the
+ <a href="installation.html">Installation</a> documentation.</p>
+
<p>The following new features have been added to the basic controller
framework (package <code>org.apache.struts.action</code>):</p>
<ul>
@@ -117,6 +123,23 @@
processing provided by the controller is still performed first, if you
have configured it, so the included resource can benefit from this
processing if it wishes to.</li>
+ <li>The <code>initDataSources()</code> method can now throw a
+ <code>ServletException</code> to report that an initialization error
+ has occurred. Previously, such errors were logged but otherwise
+ ignored.</li>
+ <li>It is now possible to integrate business logic that is already
+ encapsulated as a servlet or JSP page, via use of two new standard
+ actions: <code>org.apache.struts.actions.ForwardAction</code> and
+ <code>org.apache.struts.actions.IncludeAction</code> These actions
+ let you take advantage of the standard processing perfomed by the
+ controller servlet (including form bean population and calling the
+ <code>validate()</code> method), but not have to write Java code to
+ perform (or wrap) the required business logic.</li>
+ <li>A wrapper class has been added around the standard
+ <code>HttpServletRequest</code> for handling multipart requests as
+ identically as possible to standard requests, including processing
+ request parameters, populating form beans, transaction tokens, and
+ checking for cancellations.</li>
</ul>
<p>The following new features have been added to the
@@ -137,6 +160,17 @@
with a value of <code>true</code>.</li>
<li>The <code><html:options></code> tag now supports Enumeration
for the <code>collection</code> property.</li>
+ <li>The <code><html:form></code> tag now creates attributes for
+ the tag itself, and the form bean, in request scope instead of
+ page scope. Among other benefits, this allows you to nest the
+ fields of a form inside a separate page that is accessed via a
+ template or a <code><jsp:include></code> tag.</li>
+ <li>The <code>styleId</code> attribute has been added to all of the
+ tags where the corresponding <code>id</code> tag is relevant, to
+ identify a specific tag for the purposes of stylesheet references.</li>
+ <li>The <code><html:file></code> tag now supports the
+ <code>size</code> attribute to set the size of the file list
+ field.</li>
</ul>
<p>The following new features have been added to the
@@ -145,6 +179,9 @@
<ul>
<li>The <code><logic:iterate></code> tag now supports Enumeration
for the <code>collection</code> property.</li>
+ <li>The <code><logic:iterate></code> tag now exposes the current
+ iteration index to nested tags, through a call to the
+ <code>getIndex()</code> method.</li>
</ul>
<p>The following new features have been added to the
@@ -153,6 +190,10 @@
<ul>
<li>Attribute getter methods have been added to all of the custom
tag implementation classes to facilitate reuse.</li>
+ <li>The <code><template:get></code> tag now has an optional
+ "flush" attribute that causes the response to be commited prior
+ to performing the include, if set to "true". This allows working
+ around problems on broken servlet containers.</li>
</ul>
<p>The following new features have been added to the Struts Documentation
@@ -168,6 +209,23 @@
<section name="Changes and Bug Fixes" href="Changes">
+ <p>The following changes and bug fixes have occurred in the basic
+ controller framework (package <code>org.apache.struts.action</code>):</p>
+ <ul>
+ <li><code>DiskMultipartRequestHandler</code> now tries to retrieve the
+ temporary directory provided by the servlet container before all other
+ possible temporary directories.</li>
+ </ul>
+
+ <p>The following changes and bug fixes have occurred in the utilities
+ (package <code>org.apache.struts.util</code>):</p>
+ <ul>
+ <li>The <code>computeURL()</code> method now returns a
+ <code>MalformedURLException</code> if a URL cannot be created.
+ Previously, this case returned <code>null</code> with no error
+ message, making some problems difficult to track down.</li>
+ </ul>
+
<p>The following changes and bug fixes have occured in the
<em>struts-html</em> custom tag library (package
<code>org.apache.struts.taglib.html</code>):</p>
@@ -193,6 +251,21 @@
number if it is the default port for the current request scheme (80
for http, or 443 for https). Among other things, this corrects
session management behavior on the standard port numbers.</li>
+ <li>The <code>focus</code> attribute of the <code><html:form></code>
+ tag now works when the corresponding input field is a radio button,
+ or is otherwise indexed.</li>
+ <li>The <code>disabled</code> and <code>readonly</code> attributes have
+ been added to all HTML-rendering tags where they are relevant.</li>
+ </ul>
+
+ <p>The following changes and bug fixes have occurred in the
+ <em>struts-logic</em> custom tag library (package
+ <code>org.apache.struts.taglib.logic</code>):</p>
+ <ul>
+ <li>Hyperlink processing in the <code><logic:forward></code>
+ tag is now identical to that performed by the Struts Controller
+ Servlet when it processes an <code>ActionForward</code> that is
+ returned by an <code>Action</code>.</li>
</ul>
<p>The following changes and bug fixes to the Struts Documentation
@@ -206,7 +279,7 @@
<code>id</code> attribute with the same value in the same page.</li>
</ul>
- <p>The following changes and bug fixes to the Struts Example Applications
+ <p>The following changes and bug fixes to the Struts Example Application
have occurred:</p>
<ul>
<li>The Java source code of these applications is now included in the
@@ -215,8 +288,24 @@
have been eliminated.</li>
<li>Calls to the deprecated <code>BeanUtils.filter()</code> have been
replaced by calls to <code>ResponseUtils.filter()</code>.</li>
+ <li>Removed any attempt to save the pseudo-database at application
+ shutdown, because there is no portable mechanism to accomplish
+ this task.</li>
</ul>
+ <p>The following changes and bug fixes to the Struts Template Example
+ Application have occurred:</p>
+ <ul>
+ <li>Refactored the example pages to eliminate the creation of redundant
+ <code><html></code>, <code><head></code>, and
+ <code><body></code> tags.</li>
+ <li>If <code><template:get></code> or
+ <code><template:insert></code> throws an exception, do not
+ overwrite any "real" exception that has already been saved.</li>
+ <li>The text of the various pages in the example has been updated so
+ that they are not identical.</li>
+ </ul>
+
</section>
| 0 | 7 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
0c52833f19f85825e04d16a3a4b8aad3595ce0e6
|
Initial checkin of the "Declarative Exception Handling" feature (sorry
this took so long). I've incorporated it as presented, based on the
original configuration mechanism, to get it in play as quickly as possible.
It will next be integrated into the new ApplicationConfig approach so that
it works in sub-applications as well.
Submitted by: Laine Donlan <[email protected]>,
Dmitri Valdin <[email protected]>
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48766 13f79535-47bb-0310-9956-ffa450edef68
|
commit 0c52833f19f85825e04d16a3a4b8aad3595ce0e6
Author: Craig R. McClanahan <[email protected]>
Date: Mon Dec 31 01:14:36 2001 +0000
Initial checkin of the "Declarative Exception Handling" feature (sorry
this took so long). I've incorporated it as presented, based on the
original configuration mechanism, to get it in play as quickly as possible.
It will next be integrated into the new ApplicationConfig approach so that
it works in sub-applications as well.
Submitted by: Laine Donlan <[email protected]>,
Dmitri Valdin <[email protected]>
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48766 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/conf/share/struts-config_1_1.dtd b/conf/share/struts-config_1_1.dtd
index 9ee3702c4..33633d343 100644
--- a/conf/share/struts-config_1_1.dtd
+++ b/conf/share/struts-config_1_1.dtd
@@ -11,7 +11,7 @@
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
- $Id: struts-config_1_1.dtd,v 1.3 2001/12/27 16:20:59 cedric Exp $
+ $Id: struts-config_1_1.dtd,v 1.4 2001/12/31 01:14:36 craigmcc Exp $
-->
@@ -79,7 +79,7 @@
hierarchy, and contains nested elements for all of the other
configuration settings.
-->
-<!ELEMENT struts-config (data-sources?, form-beans?, global-forwards?, action-mappings?, controller?, message-resources?)>
+<!ELEMENT struts-config (data-sources?, form-beans?, global-exceptions?, global-forwards?, action-mappings?, controller?, message-resources?)>
<!ATTLIST struts-config id ID #IMPLIED>
@@ -157,6 +157,49 @@
<!ATTLIST data-source user CDATA #IMPLIED>
+<!-- The "global-exceptions" element configures the global handling of
+ exceptions thrown by Actions to mappable resources (identified by
+ context-relative URI paths). A global "exception" handler for a
+ particular exception class can be locally overridden by defining an
+ "exception" element with the same "type" attribute.
+-->
+<!ELEMENT global-exceptions (exception*)>
+<!ATTLIST global-exceptions id ID #IMPLIED>
+
+
+<!-- The "exception" element describes a mapping of an exception that may
+ occur during Action delegation and should be handled by the
+ ActionServlet.
+
+ handler Fully qualified Java class name of the exception handler
+ which should handle this exception.
+
+ hierarchical Determines if the exception's class hierarchy should be
+ used to determine the correct handler.
+
+ key Resource bundle key specifying the error message
+ associated with this exception.
+
+ path The context-relative path of the resource to
+ forward to if this exception occurs.
+
+ scope Identifier of the scope ("request" or "session")
+ within which the resulting ActionError will be
+ made accessible
+
+ type Fully qualified Java class name of the exception
+ that is to be handled.
+-->
+<!ELEMENT exception (icon?, display-name?, description?, set-property*)>
+<!ATTLIST exception id ID #IMPLIED>
+<!ATTLIST exception handler %ClassName; "org.apache.struts.action.ExceptionHandler">
+<!ATTLIST exception hierarchical %Boolean; #IMPLIED>
+<!ATTLIST exception key CDATA #IMPLIED>
+<!ATTLIST exception path %RequestPath; #IMPLIED>
+<!ATTLIST exception scope CDATA #IMPLIED>
+<!ATTLIST exception type %ClassName; #REQUIRED>
+
+
<!-- The "form-beans" element is the root of the set of form bean descriptors
for this application. The following attributes are defined:
@@ -327,7 +370,7 @@
should be called prior to calling this action, or set to
"false" if you do not want validation performed.
-->
-<!ELEMENT action (icon?, display-name?, description?, set-property*, forward*)>
+<!ELEMENT action (icon?, display-name?, description?, set-property*, exception*, forward*)>
<!ATTLIST action id ID #IMPLIED>
<!ATTLIST action attribute %BeanName; #IMPLIED>
<!ATTLIST action className %ClassName; #IMPLIED>
diff --git a/src/example/org/apache/struts/webapp/example/ApplicationResources.properties b/src/example/org/apache/struts/webapp/example/ApplicationResources.properties
index 088b07305..ce2a51bb6 100644
--- a/src/example/org/apache/struts/webapp/example/ApplicationResources.properties
+++ b/src/example/org/apache/struts/webapp/example/ApplicationResources.properties
@@ -2,6 +2,9 @@ button.cancel=Cancel
button.confirm=Confirm
button.reset=Reset
button.save=Save
+change.message=Your password has expired. Please ask the system administrator to change it.
+change.try=Try Again
+change.title=Password Has Expired
database.load=Cannot load database from {0}
error.database.missing=<li>User database is missing, cannot validate logon credentials</li>
error.fromAddress.format=<li>Invalid format for From Address</li>
diff --git a/src/example/org/apache/struts/webapp/example/ExpiredPasswordException.java b/src/example/org/apache/struts/webapp/example/ExpiredPasswordException.java
new file mode 100644
index 000000000..d39550a67
--- /dev/null
+++ b/src/example/org/apache/struts/webapp/example/ExpiredPasswordException.java
@@ -0,0 +1,87 @@
+/*
+ * $Header: /home/cvs/jakarta-struts/src/example/org/apache/struts/webapp/example/ExpiredPasswordException.java,v 1.1 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.1 $
+ * $Date: 2001/12/31 01:14:36 $
+ *
+ * ====================================================================
+ *
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 1999-2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Struts", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact [email protected].
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+
+package org.apache.struts.webapp.example;
+
+import org.apache.struts.util.AppException;
+
+/**
+ * Example of an application-specific exception for which a handler
+ * can be configured.
+ */
+
+
+public class ExpiredPasswordException extends AppException {
+
+
+ /**
+ * Construct a new instance of this exception for the specified username.
+ *
+ * @param username Username whose password has expired
+ */
+ public ExpiredPasswordException(String username) {
+ super("error.password.expired", username);
+ }
+
+
+}
+
diff --git a/src/example/org/apache/struts/webapp/example/LogonAction.java b/src/example/org/apache/struts/webapp/example/LogonAction.java
index 10d5cdb28..54d3b8f1c 100644
--- a/src/example/org/apache/struts/webapp/example/LogonAction.java
+++ b/src/example/org/apache/struts/webapp/example/LogonAction.java
@@ -1,7 +1,7 @@
/*
- * $Header: /home/cvs/jakarta-struts/src/example/org/apache/struts/webapp/example/LogonAction.java,v 1.2 2001/04/14 12:53:08 rleland Exp $
- * $Revision: 1.2 $
- * $Date: 2001/04/14 12:53:08 $
+ * $Header: /home/cvs/jakarta-struts/src/example/org/apache/struts/webapp/example/LogonAction.java,v 1.3 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.3 $
+ * $Date: 2001/12/31 01:14:36 $
*
* ====================================================================
*
@@ -78,6 +78,7 @@ import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
+import org.apache.struts.util.AppException;
import org.apache.struts.util.MessageResources;
@@ -85,7 +86,7 @@ import org.apache.struts.util.MessageResources;
* Implementation of <strong>Action</strong> that validates a user logon.
*
* @author Craig R. McClanahan
- * @version $Revision: 1.2 $ $Date: 2001/04/14 12:53:08 $
+ * @version $Revision: 1.3 $ $Date: 2001/12/31 01:14:36 $
*/
public final class LogonAction extends Action {
@@ -106,14 +107,13 @@ public final class LogonAction extends Action {
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
- * @exception IOException if an input/output error occurs
- * @exception ServletException if a servlet exception occurs
+ * @exception Exception if business logic throws an exception
*/
- public ActionForward perform(ActionMapping mapping,
+ public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
- throws IOException, ServletException {
+ throws Exception {
// Extract attributes we will need
Locale locale = getLocale(request);
@@ -130,7 +130,7 @@ public final class LogonAction extends Action {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.database.missing"));
else {
- user = (User) database.get(username);
+ user = getUser(database, username, password);
if ((user != null) && !user.getPassword().equals(password))
user = null;
if (user == null)
@@ -165,4 +165,36 @@ public final class LogonAction extends Action {
}
+ // ------------------------------------------------------ Protected Methods
+
+
+ /**
+ * Look up the user, throwing an exception to simulate business logic
+ * rule exceptions.
+ *
+ * @param database Database in which to look up the user
+ * @param username Username specified on the logon form
+ * @param password Password specified on the logon form
+ *
+ * @exception AppException if a business logic rule is violated
+ */
+ public User getUser(Hashtable database, String username, String password)
+ throws AppException {
+
+ // Force an ArithmeticException which can be handled explicitly
+ if ("arithmetic".equals(username)) {
+ int a = 10 / 0;
+ }
+
+ // Force an application-specific exception which can be handled
+ if ("expired".equals(username)) {
+ throw new ExpiredPasswordException(username);
+ }
+
+ // Look up and return the specified user
+ return ((User) database.get(username));
+
+ }
+
+
}
diff --git a/src/share/org/apache/struts/action/Action.java b/src/share/org/apache/struts/action/Action.java
index 24807dec8..efaf2c5ef 100755
--- a/src/share/org/apache/struts/action/Action.java
+++ b/src/share/org/apache/struts/action/Action.java
@@ -1,7 +1,7 @@
/*
- * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/Action.java,v 1.32 2001/12/29 19:37:28 craigmcc Exp $
- * $Revision: 1.32 $
- * $Date: 2001/12/29 19:37:28 $
+ * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/Action.java,v 1.33 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.33 $
+ * $Date: 2001/12/31 01:14:36 $
*
* ====================================================================
*
@@ -108,7 +108,7 @@ import org.apache.struts.upload.MultipartRequestHandler;
* by this Action.
*
* @author Craig R. McClanahan
- * @version $Revision: 1.32 $ $Date: 2001/12/29 19:37:28 $
+ * @version $Revision: 1.33 $ $Date: 2001/12/31 01:14:36 $
*/
public class Action {
@@ -320,6 +320,8 @@ public class Action {
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
+ *
+ * @deprecated Use the <code>execute()</code> method instead
*/
public ActionForward perform(ActionMapping mapping,
ActionForm form,
@@ -352,6 +354,8 @@ public class Action {
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
+ *
+ * @deprecated Use the <code>execute()</code> method instead
*/
public ActionForward perform(ActionMapping mapping,
ActionForm form,
@@ -364,6 +368,31 @@ public class Action {
}
+ /**
+ * Process the specified HTTP request, and create the corresponding HTTP
+ * response (or forward to another web component that will create it),
+ * with provision for handling exceptions thrown by the business logic.
+ *
+ * @param mapping The ActionMapping used to select this instance
+ * @param form The optional ActionForm bean for this request (if any)
+ * @param request The HTTP request we are processing
+ * @param response The HTTP response we are creating
+ *
+ * @exception Exception if the application business logic throws
+ * an exception
+ */
+ public ActionForward execute(ActionMapping mapping,
+ ActionForm form,
+ HttpServletRequest request,
+ HttpServletResponse response)
+ throws Exception {
+
+ // Call the deprecated method
+ return (perform(mapping, form, request, response));
+
+ }
+
+
// ---------------------------------------------------- Protected Methods
diff --git a/src/share/org/apache/struts/action/ActionException.java b/src/share/org/apache/struts/action/ActionException.java
new file mode 100644
index 000000000..f1cef6366
--- /dev/null
+++ b/src/share/org/apache/struts/action/ActionException.java
@@ -0,0 +1,265 @@
+/*
+ * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/Attic/ActionException.java,v 1.1 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.1 $
+ * $Date: 2001/12/31 01:14:36 $
+ *
+ * ====================================================================
+ *
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 1999-2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Struts", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact [email protected].
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.struts.action;
+
+import java.io.Serializable;
+
+/**
+ * An <strong>ActionException</strong> represents a potential exception
+ * that may occur during delegation to an Action class.
+ * Instances of this class may be configured in association
+ * with an <code>ActionMapping</code> instance for named lookup of potentially
+ * multiple destinations for a particular mapping instance.
+ * <p>
+ * An <code>ActionException</code> has the following minimal set of properties.
+ * Additional properties can be provided as needed by subclassses.
+ * <ul>
+ * <li><strong>type</strong> - The fully qualified class name of the
+ * exception to be associated to a particular <code>ActionMapping</code>.
+ * <li><strong>key</strong> - (Optional) Message key associated with the particular
+ * exception.
+ * <li><strong>path</strong> - (Optional) Context releative URI that should
+ * be redirected to as a result of the exception occuring. Will overide the
+ * input form of the associated ActionMapping if one is provided.
+ * <li><strong>scope</strong> - (Optional) The scope to store the exception in
+ * if a problem should occur - defaults to 'request'. Valid values are
+ * 'request' and 'session'.
+ * <li><strong>hierarchical</strong> - (Optional) Defines whether or not the
+ * Exception hierarchy should be used when determining if an occuring
+ * exception can be assigned to a mapping instance. Default is true.
+ * <li><strong>handler</strong> - (Optional) The fully qualified class name
+ * of the handler, which is responsible to handle this exception.
+ * Default is 'org.apache.struts.action.ExceptionHandler'.
+ * </ul>
+ *
+ * @author ldonlan
+ * @version $Revision: 1.1 $ $Date: 2001/12/31 01:14:36 $
+ */
+public class ActionException implements Serializable {
+
+ /** Holds value of property key. */
+ private String key;
+
+ /** Holds value of property type. */
+ private String type;
+
+ /** Holds value of property path. */
+ private String path;
+
+ /** Holds value of property exClass. */
+ private Class exClass;
+
+ /** Holds value of property hierachal. */
+ private boolean hierarchical = true;
+
+ /** Holds value of property scope. */
+ private String scope = "request";
+
+ /** Holds value of handler. */
+ private String handler;
+
+ /** Holds value of property handlerClass */
+ private Class handlerClass;
+
+ /** Creates new ActionException */
+ public ActionException() {
+
+ }
+
+ /**
+ * Returns the key associated with the exception.
+ * @return Value of property key.
+ */
+ public String getKey() {
+ return key;
+ }
+
+ /**
+ * Setter for property key.
+ * @param key New value of property key.
+ */
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ /**
+ * Returns the fully qualified type of the exception
+ * @return Value of property type.
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * Setter for property type.
+ * @param type New value of property type.
+ * @todo Need to clean up this logging, but don't want to die if
+ * an exception is mistyped, etc.
+ */
+ public void setType(String type){
+ this.type = type;
+ try{
+ exClass = Class.forName(type);
+ }catch(ClassNotFoundException ex){
+ System.out.println("[ActionException] - Could not instantiate: " +
+ ex.getClass() + " " + type);
+ exClass = null;
+ }
+
+ }
+
+ /**
+ * Returns the path associated with the exception.
+ * @return Value of property path.
+ */
+ public String getPath() {
+ return path;
+ }
+
+ /**
+ * Setter for property path.
+ * @param path New value of property path.
+ */
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ /**
+ * Getter for property exClass. Will be null if the type could not
+ * be used to create a class instance.
+ * @return Value of property exClass.
+ */
+ public Class getExClass() {
+ return exClass;
+ }
+
+ /** Getter for property hierachal.
+ * @return Value of property hierachal.
+ */
+ public boolean isHierarchical() {
+ return hierarchical;
+ }
+
+ /** Setter for property hierachal.
+ * @param hierarchical */
+ public void setHierarchical(boolean hierarchical) {
+ this.hierarchical = hierarchical;
+ }
+
+ /** Getter for property scope.
+ * @return Value of property scope.
+ */
+ public String getScope() {
+ return scope;
+ }
+
+ /** Setter for property scope.
+ * @param scope New value of property scope.
+ */
+ public void setScope(String scope) {
+ this.scope = scope;
+ }
+
+ /**
+ * Returns the fully qualified type of the exception handler
+ * @return Value of property handler.
+ */
+ public String getHandler() {
+ return handler;
+ }
+
+ /**
+ * Setter for property handler.
+ * @param type New value of property handler.
+ * @todo Need to clean up this logging, but don't want to die if
+ * an exception is mistyped, etc.
+ */
+ public void setHandler(String handler){
+ this.handler = handler;
+ try{
+ handlerClass = Class.forName(handler);
+ }catch(ClassNotFoundException ex){
+ System.out.println("[ActionException] - Could not instantiate: " +
+ ex.getClass() + " " + handler);
+ handlerClass = null;
+ }
+ }
+
+
+ /**
+ * Getter for property handler. Will be null if the handler could not
+ * be used to create a class instance.
+ * @return Value of property handlerClass.
+ */
+ public Class getHandlerClass() {
+ return handlerClass;
+ }
+
+ /**
+ *Returns an instance of an <b>ActionError</b> configured for
+ *this exception.
+ *@return ActionError
+ */
+ public ActionError getError() {
+ return new ActionError(this.key);
+ }
+
+}
diff --git a/src/share/org/apache/struts/action/ActionExceptions.java b/src/share/org/apache/struts/action/ActionExceptions.java
new file mode 100644
index 000000000..2b690a877
--- /dev/null
+++ b/src/share/org/apache/struts/action/ActionExceptions.java
@@ -0,0 +1,200 @@
+/*
+ * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/Attic/ActionExceptions.java,v 1.1 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.1 $
+ * $Date: 2001/12/31 01:14:36 $
+ *
+ * ====================================================================
+ *
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 1999-2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Struts", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact [email protected].
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.struts.action;
+
+import java.io.*;
+import java.util.*;
+import org.apache.commons.collections.FastHashMap;
+
+
+/**
+ * Encapsulate a collection of ActionException objects that can be
+ * administered and searched, while hiding the internal implementation.
+ *
+ * @author ldonlan
+ * @version $Revision: 1.1 $ $Date: 2001/12/31 01:14:36 $
+ */
+
+public class ActionExceptions implements Serializable{
+ private static final String APP_EXCEPTION_KEY =
+ "org.apache.struts.util.AppException";
+
+ private static final String APP_EXCEPTION_HANDLER_KEY =
+ "org.apache.struts.action.ExceptionHandler";
+
+ /** Creates new ActionExceptions */
+ public ActionExceptions() {
+ // Register an application exception.
+ addAppException();
+ }
+
+ // ----------------------------------------------------- Instance Variables
+
+
+ /**
+ * The collection of ActionForward instances, keyed by logical name.
+ */
+ private FastHashMap exceptions = new FastHashMap();
+
+
+ // ------------------------------------------------------------- Properties
+
+
+ /**
+ * Return the "fast" mode flag.
+ */
+ public boolean getFast() {
+
+ return (exceptions.getFast());
+
+ }
+
+
+ /**
+ * Set the "fast" mode flag.
+ *
+ * @param fast The new fast mode flag
+ */
+ public void setFast(boolean fast) {
+
+ exceptions.setFast(fast);
+
+ }
+
+ /**
+ * Register a logical exception that may occur processing the
+ * maping.
+ *
+ * @param exception The exception to be added
+ */
+ public void addException(ActionException ex){
+ exceptions.put(ex.getType(), ex);
+
+ }
+
+ /**
+ * Return the ActionException associated with the specified class name,
+ * if any; otherwise return <code>null</code>.<p>
+ * The search will consist of first looking for a specific match on
+ * the class provided. If one is not found, all <b>ActionException</b>
+ * objects will be examined. For all objects with the hierarchacal
+ * property set to true, a Class.isAssignableFrom() test will be performed.
+ * The first match to be made will be returned.
+ *
+ * @param name class name of the exception
+ */
+ public ActionException findException(Class type){
+ ActionException ex = null;
+
+ ex = (ActionException)exceptions.get(type.getName());
+
+ //If no exact match was made
+ if (ex == null){
+ //Look through all the A.E's
+ Iterator it = exceptions.values().iterator();
+
+ ActionException current = null;
+ while (it.hasNext()){
+ current = (ActionException)it.next();
+
+ //If there is a hierarchal match and the provided
+ //exception is assignable from it, then return it
+ if (current.isHierarchical()){
+ //Make sure that the class is not null - i.e the
+ //type could not be used to create a class.
+ if (current.getExClass() != null){
+ if (current.getExClass().isAssignableFrom(type)){
+ ex = current;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return ex;
+ }
+
+
+ /**
+ *Removes the ActionException with the specified type from the
+ *collection.
+ *
+ */
+ public ActionException remove(String type){
+ return (ActionException)exceptions.remove(type);
+ }
+
+
+ // -------------------------------------------------------- Private Methods
+
+ /**
+ * Register an application exception
+ */
+ private void addAppException() {
+ ActionException ae = new ActionException();
+ ae.setType(APP_EXCEPTION_KEY);
+ ae.setHandler(APP_EXCEPTION_HANDLER_KEY);
+ addException(ae);
+ }
+
+}
diff --git a/src/share/org/apache/struts/action/ActionMapping.java b/src/share/org/apache/struts/action/ActionMapping.java
index ad7fc9fa2..480c37790 100755
--- a/src/share/org/apache/struts/action/ActionMapping.java
+++ b/src/share/org/apache/struts/action/ActionMapping.java
@@ -1,7 +1,7 @@
/*
- * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/ActionMapping.java,v 1.20 2001/11/04 07:42:21 martinc Exp $
- * $Revision: 1.20 $
- * $Date: 2001/11/04 07:42:21 $
+ * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/ActionMapping.java,v 1.21 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.21 $
+ * $Date: 2001/12/31 01:14:36 $
*
* ====================================================================
*
@@ -130,7 +130,7 @@ import java.io.Serializable;
* </ul>
*
* @author Craig R. McClanahan
- * @version $Revision: 1.20 $ $Date: 2001/11/04 07:42:21 $
+ * @version $Revision: 1.21 $ $Date: 2001/12/31 01:14:36 $
*/
public class ActionMapping implements Serializable {
@@ -146,6 +146,12 @@ public class ActionMapping implements Serializable {
protected String attribute = null;
+ /**
+ * The set of ActionException objects associated with this mapping.
+ */
+ protected ActionExceptions exceptions = new ActionExceptions();
+
+
/**
* The context relative path of the servlet or JSP resource (to be called
* via <code>RequestDispatcher.forward()</code>) that will process this
@@ -594,6 +600,18 @@ public class ActionMapping implements Serializable {
// --------------------------------------------------------- Public Methods
+ /**
+ * Add a new <code>ActionException</code> associated with this mapping.
+ *
+ * @param exception The ActionException to be added
+ */
+ public void addException(ActionException exception) {
+
+ exceptions.addException(exception);
+
+ }
+
+
/**
* Add a new <code>ActionForward</code> associated with this mapping.
*
@@ -606,6 +624,35 @@ public class ActionMapping implements Serializable {
}
+ /**
+ * Return the <code>ActionException</code> handler for exceptions of the
+ * specified type.
+ *
+ * @param type Exception class for which to find a handler
+ */
+ public ActionException findException(Class type) {
+
+ // First, check our locally defined exceptions
+ ActionException ex = exceptions.findException(type);
+ if (ex != null) {
+ return (ex);
+ }
+
+ // Second, check the globally defined exceptions
+ ActionMappings mappings = getMappings();
+ if (mappings == null) {
+ return (null);
+ }
+ ActionServlet servlet = mappings.getServlet();
+ if (servlet == null) {
+ return (null);
+ } else {
+ return (servlet.findException(type));
+ }
+
+ }
+
+
/**
* Return the <code>ActionForward</code> with the specified name,
* if any; otherwise return <code>null</code>. If there is no locally
diff --git a/src/share/org/apache/struts/action/ActionServlet.java b/src/share/org/apache/struts/action/ActionServlet.java
index 638d2f51d..61508006f 100755
--- a/src/share/org/apache/struts/action/ActionServlet.java
+++ b/src/share/org/apache/struts/action/ActionServlet.java
@@ -1,7 +1,7 @@
/*
- * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/ActionServlet.java,v 1.81 2001/12/29 19:35:32 craigmcc Exp $
- * $Revision: 1.81 $
- * $Date: 2001/12/29 19:35:32 $
+ * $Header: /home/cvs/jakarta-struts/src/share/org/apache/struts/action/ActionServlet.java,v 1.82 2001/12/31 01:14:36 craigmcc Exp $
+ * $Revision: 1.82 $
+ * $Date: 2001/12/31 01:14:36 $
*
* ====================================================================
*
@@ -238,7 +238,7 @@ import org.xml.sax.SAXException;
*
* @author Craig R. McClanahan
* @author Ted Husted
- * @version $Revision: 1.81 $ $Date: 2001/12/29 19:35:32 $
+ * @version $Revision: 1.82 $ $Date: 2001/12/31 01:14:36 $
*/
public class ActionServlet
@@ -307,6 +307,20 @@ public class ActionServlet
protected final Locale defaultLocale = Locale.getDefault();
+ /**
+ * The Java class name of the <code>ActionException</code> implementation
+ * class to use.
+ */
+ protected String exceptionClass =
+ "org.apache.struts.action.ActionException";
+
+
+ /**
+ * The global exceptions registered with this handler.
+ */
+ protected ActionExceptions exceptions = new ActionExceptions();
+
+
/**
* The Java class name of the <code>MessageResourcesFactory</code>
* class for the application message resources bundle.
@@ -567,6 +581,20 @@ public class ActionServlet
}
+ /**
+ * Add a global exception to the set configured for this servlet.
+ *
+ * @param exception The exception to be added
+ *
+ * @deprecated Will no longer be required with multi-application support
+ */
+ public void addException(ActionException exception) {
+
+ exceptions.addException(exception);
+
+ }
+
+
/**
* Register a form bean definition to the set configured for this servlet.
*
@@ -678,6 +706,21 @@ public class ActionServlet
}
+ /**
+ * Return the exception handler for an exception of the specified
+ * class, if any; otherwise return <code>null</code>.
+ *
+ * @param ex Exception class for which to find a handler
+ *
+ * @deprecated Will no longer be required with multi-application support
+ */
+ public ActionException findException(Class ex) {
+
+ return (exceptions.findException(ex));
+
+ }
+
+
/**
* Return the forwarding associated with the specified logical name,
* if any; otherwise return <code>null</code>.
@@ -1575,6 +1618,16 @@ public class ActionServlet
"addForward",
"org.apache.struts.action.ActionForward");
+ digester.addObjectCreate
+ ("struts-config/action-mappings/action/exception",
+ exceptionClass, "className");
+ digester.addSetProperties
+ ("struts-config/action-mappings/action/exception");
+ digester.addSetNext
+ ("struts-config/action-mappings/action/exception",
+ "addException",
+ "org.apache.struts.action.ActionException");
+
digester.addSetProperty
("struts-config/action-mappings/action/forward/set-property",
"property", "value");
@@ -1590,6 +1643,17 @@ public class ActionServlet
("struts-config/form-beans/form-bean/set-property",
"property", "value");
+ digester.addObjectCreate("struts-config/global-exceptions/exception",
+ exceptionClass, "className");
+ digester.addSetProperties("struts-config/global-exceptions/exception");
+ digester.addSetNext("struts-config/global-exceptions/exception",
+ "addException",
+ "org.apache.struts.action.ActionException");
+
+ digester.addSetProperty
+ ("struts-config/global-exceptions/exception/set-property",
+ "property", "value");
+
digester.addObjectCreate("struts-config/global-forwards/forward",
forwardClass, "className");
digester.addSetProperties("struts-config/global-forwards/forward");
@@ -2160,9 +2224,24 @@ public class ActionServlet
HttpServletResponse response)
throws IOException, ServletException {
- ActionForward forward =
- action.perform(mapping, formInstance, request, response);
- return (forward);
+ // ActionForward forward =
+ // action.perform(mapping, formInstance, request, response);
+ // return (forward);
+
+ ActionError error = null;
+ Throwable cause = null;
+ try {
+ ActionForward forward =
+ action.execute(mapping, formInstance, request, response);
+ return (forward);
+ } catch (Exception ex) {
+ if (debug >= 1) {
+ log("Exception occurred", ex);
+ }
+ return (processException(ex, mapping, formInstance,
+ request, response));
+ }
+
}
@@ -2182,6 +2261,56 @@ public class ActionServlet
}
+ /**
+ * Ask our exception handler to handle the exception. Return the
+ * <code>ActionForward</code> instance (if any) returned by the called
+ * <code>ExceptionHandler</code>.
+ *
+ * @param ex The exception to handle
+ * @param maping The ActionMapping we are processing
+ * @param form The ActionForm we are processing (if any)
+ * @param request The servlet request we are processing
+ * @param response The servlet response we are processing
+ *
+ * @exception ServletException if a servlet exception occurs
+ */
+ protected ActionForward processException(Exception ex,
+ ActionMapping mapping,
+ ActionForm form,
+ HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException {
+
+ // Look for an exception mapping
+ ActionException ae = mapping.findException(ex.getClass());
+
+ // If one is found, place it in the scope defined
+ if (ae != null) {
+ Class handlerClass = ae.getHandlerClass();
+ try {
+ // Ask handler to handle the exception
+ ExceptionHandler handler = (ExceptionHandler)
+ handlerClass.newInstance();
+ return (handler.execute(ex, ae, mapping, form,
+ request, response));
+ } catch (Exception e) {
+ // Yuck - the exception handler thew an exception
+ throw new ServletException(e);
+ }
+ } else {
+ if (debug >= 1) {
+ log(internal.getMessage("unhandledException", ex.getClass()));
+ }
+ if (ex instanceof ServletException) {
+ throw (ServletException) ex;
+ }
+ throw new ServletException(ex);
+ }
+
+ }
+
+
+
/**
* Process a forward requested by this mapping, if any. Return
* <code>true</code> if processing of this request should continue (i.e.
diff --git a/src/share/org/apache/struts/action/ExceptionHandler.java b/src/share/org/apache/struts/action/ExceptionHandler.java
new file mode 100644
index 000000000..d38ade9ac
--- /dev/null
+++ b/src/share/org/apache/struts/action/ExceptionHandler.java
@@ -0,0 +1,158 @@
+/*
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 1999-2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Struts", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact [email protected].
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.struts.action;
+
+import java.util.Locale;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.struts.action.Action;
+import org.apache.struts.action.ActionError;
+import org.apache.struts.action.ActionErrors;
+import org.apache.struts.action.ActionException;
+import org.apache.struts.action.ActionForm;
+import org.apache.struts.action.ActionForward;
+import org.apache.struts.action.ActionMapping;
+import org.apache.struts.util.AppException;
+
+
+public class ExceptionHandler {
+ /**
+ * Handle the exception.
+ * Return the <code>ActionForward</code> instance (if any) returned by
+ * the called <code>ExceptionHandler</code>.
+ *
+ * @param ex The exception to handle
+ * @param ae The ActionException corresponding to the exception
+ * @param mapping The ActionMapping we are processing
+ * @param formInstance The ActionForm we are processing
+ * @param request The servlet request we are processing
+ * @param response The servlet response we are creating
+ *
+ * @exception ServletException if a servlet exception occurs
+ */
+ protected ActionForward execute(Exception ex,
+ ActionException ae,
+ ActionMapping mapping,
+ ActionForm formInstance,
+ HttpServletRequest request,
+ HttpServletResponse response)
+ throws ServletException {
+
+ ActionForward forward = null;
+ ActionError error = null;
+ String property = null;
+
+ String path;
+
+ // Build the forward from the exception mapping if it exists
+ // or from the form input
+ if (ae.getPath() != null) {
+ path = ae.getPath();
+ } else {
+ path = mapping.getInput();
+ }
+
+ // Generate the forward
+ forward = new ActionForward(path);
+
+ // Figure out the error
+ if (ex instanceof AppException) {
+ error = ((AppException) ex).getError();
+ property = ((AppException) ex).getProperty();
+ } else {
+ error = ae.getError();
+ property = error.getKey();
+ }
+
+ // Store the exception
+ storeException(request, property, error, forward, ae.getScope());
+
+ return forward;
+ }
+
+ /**
+ * Default implementation for handling an <b>ActionError</b> generated
+ * from an Exception during <b>Action</b> delegation. The default
+ * implementation is to set an attribute of the request or session, as
+ * defined by the scope provided (the scope from the exception mapping). An
+ * <b>ActionErrors</b> instance is created, the error is added to the collection
+ * and the collection is set under the Action.ERROR_KEY.
+ *
+ * @param request
+ * @param error - The error generated from the exception mapping
+ * @param input - The forward generated from the input path (from the form or exception mapping)
+ * @param scope - The scope of the exception mapping.
+ *
+ */
+ protected void storeException(HttpServletRequest request,
+ String property,
+ ActionError error,
+ ActionForward forward,
+ String scope) {
+ ActionErrors errors = new ActionErrors();
+ errors.add(property, error);
+
+ if ("request".equals(scope)){
+ request.setAttribute(Action.ERROR_KEY, errors);
+ } else {
+ request.getSession().setAttribute(Action.ERROR_KEY, errors);
+ }
+ }
+
+}
+
diff --git a/src/share/org/apache/struts/util/AppException.java b/src/share/org/apache/struts/util/AppException.java
new file mode 100644
index 000000000..8b2f29f68
--- /dev/null
+++ b/src/share/org/apache/struts/util/AppException.java
@@ -0,0 +1,154 @@
+/*
+ * The Apache Software License, Version 1.1
+ *
+ * Copyright (c) 1999-2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution, if
+ * any, must include the following acknowlegement:
+ * "This product includes software developed by the
+ * Apache Software Foundation (http://www.apache.org/)."
+ * Alternately, this acknowlegement may appear in the software itself,
+ * if and wherever such third-party acknowlegements normally appear.
+ *
+ * 4. The names "The Jakarta Project", "Struts", and "Apache Software
+ * Foundation" must not be used to endorse or promote products derived
+ * from this software without prior written permission. For written
+ * permission, please contact [email protected].
+ *
+ * 5. Products derived from this software may not be called "Apache"
+ * nor may "Apache" appear in their names without prior written
+ * permission of the Apache Group.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
+ * ITS CONTRIBUTORS 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.struts.util;
+
+import java.util.Locale;
+
+import org.apache.struts.action.ActionError;
+
+
+public class AppException extends Exception {
+ private String property = null;
+ private ActionError error = null;
+
+ // ----------------------------------------------------------- Constructors
+
+
+ /**
+ * Construct an application exception with no replacement values.
+ *
+ * @param key Message key for this error message
+ */
+ public AppException(String key) {
+ super(key);
+ error = new ActionError(key);
+ }
+
+ /**
+ * Construct an application exception with the specified replacement values.
+ *
+ * @param key Message key for this error message
+ * @param value0 First replacement value
+ */
+ public AppException(String key, Object value) {
+ super(key);
+ error = new ActionError(key, value);
+ }
+
+ /**
+ * Construct an application exception with the specified replacement values.
+ *
+ * @param key Message key for this error message
+ * @param value0 First replacement value
+ * @param value1 Second replacement value
+ */
+ public AppException(String key, Object value0, Object value1) {
+ super(key);
+ error = new ActionError(key, value0, value1);
+ }
+
+ /**
+ * Construct an application exception with the specified replacement values.
+ *
+ * @param key Message key for this error message
+ * @param value0 First replacement value
+ * @param value1 Second replacement value
+ * @param value2 Third replacement value
+ */
+ public AppException(String key, Object value0, Object value1, Object value2) {
+ super(key);
+ error = new ActionError(key, value0, value1, value2);
+ }
+
+ /**
+ * Construct an application exception with the specified replacement values.
+ *
+ * @param key Message key for this error message
+ * @param value0 First replacement value
+ * @param value1 Second replacement value
+ * @param value2 Third replacement value
+ * @param value3 Fourth replacement value
+ */
+ public AppException(String key, Object value0, Object value1, Object value2, Object value3) {
+ super(key);
+ error = new ActionError(key, value0, value1, value2, value3);
+ }
+
+ // -------------------------------------------------------- Public Methods
+
+ /**
+ * Returns the property associated with the exception.
+ * @return Value of property.
+ */
+ public String getProperty() {
+ return (property != null) ? property : error.getKey();
+ }
+
+ /**
+ * Set the property associated with the exception.
+ * It can be a name of the edit field, which 'caused' the exception.
+ */
+ public void setProperty(String property) {
+ this.property = property;
+ }
+
+ /**
+ * Returns the error associated with the exception.
+ * @return Value of property error.
+ */
+ public ActionError getError() {
+ return error;
+ }
+}
diff --git a/web/example/WEB-INF/struts-config.xml b/web/example/WEB-INF/struts-config.xml
index c2def6d44..51e77de75 100644
--- a/web/example/WEB-INF/struts-config.xml
+++ b/web/example/WEB-INF/struts-config.xml
@@ -103,6 +103,9 @@
name="logonForm"
scope="request"
input="/logon.jsp">
+ <exception
+ type="org.apache.struts.webapp.example.ExpiredPasswordException"
+ path="/changePassword.jsp"/>
</action>
<!-- Save user registration -->
diff --git a/web/example/changePassword.jsp b/web/example/changePassword.jsp
new file mode 100644
index 000000000..cf1b4d460
--- /dev/null
+++ b/web/example/changePassword.jsp
@@ -0,0 +1,18 @@
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
+<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
+
+<html:html locale="true">
+<head>
+<title><bean:message key="change.title"/></title>
+<html:base/>
+</head>
+<body bgcolor="white">
+
+<bean:message key="change.message"/>
+<html:link page="/logon.jsp">
+ <bean:message key="change.try"/>
+</html:link>
+
+</body>
+</html:html>
| 0 | 4 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
bbacb93047499aa5694058ec5379ed7b68420662
|
Moved ssl page from taglib to core.
git-svn-id: https://svn.apache.org/repos/asf/struts/core/trunk@332197 13f79535-47bb-0310-9956-ffa450edef68
|
commit bbacb93047499aa5694058ec5379ed7b68420662
Author: Wendy Smoak <[email protected]>
Date: Thu Nov 10 02:11:47 2005 +0000
Moved ssl page from taglib to core.
git-svn-id: https://svn.apache.org/repos/asf/struts/core/trunk@332197 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/xdocs/ssl.xml b/xdocs/ssl.xml
new file mode 100644
index 000000000..6cf6264b9
--- /dev/null
+++ b/xdocs/ssl.xml
@@ -0,0 +1,157 @@
+<?xml version="1.0"?>
+<!--
+Copyright 1999-2005 The Apache Software Foundation
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<!--
+// ======================================================================== 78
+-->
+<document>
+
+<properties>
+ <title>Secure Socket Layer and Web Applications </title>
+</properties>
+
+<body>
+
+<section href="ssl" name="Secure Socket Layer and Web Applications">
+
+<a name="overview"/>
+<subsection name="Overview">
+
+<p>
+Many web applications, especially those deployed for e-commerce, necessitate the
+transmission of sensitive data between the web server and the client browser. This data
+may include passwords, credit card numbers, bank account numbers or any other
+information that users would not want to divulge to the general public. To protect
+sensitive data during transmission, application developers typically use the Secure
+Sockets Layer (SSL) and its companion protocol, HTTP over Secure Sockets Layer
+(HTTPS). HTTPS employs SSL to protect data by encrypting it at the source, be it the
+server or the client, and decrypting it at the destination. This prevents anyone monitoring
+Internet data transmissions from easily capturing this data. The client and server
+exchange public keys to enable encryption and decryption to occur.
+</p>
+
+<p>
+The encryption/decryption process comes at a performance price, however. The
+throughput of data for a web server transmitting via HTTPS is often as little as one-tenth
+that of data transmission via HTTP. For this reason, it is undesirable to deploy an entire
+web application under SSL. For fastest performance, it is best to deploy a web
+application under HTTP and employ HTTPS only for those pages and processes that
+transmit sensitive data.
+</p>
+
+</subsection>
+
+<a name="mixing"/>
+<subsection name="Mixing Protocols in Web Applications">
+
+<p>
+Switching back and forth between the two protocols can require hard-coding the protocol
+and full URL in every link to each resource in the web application. This creates an
+ongoing maintenance headache for developers each time a server name changes or secure
+protocol requirements change for resources in the web app.
+</p>
+
+<p>
+Another significant hazard is that there is nothing to prevent a user from specifying the
+wrong protocol by manually entering a URL into the browser. The penalty for manually
+specifying HTTPS for a page or servlet that does not require HTTPS is reduced
+performance. Far worse is the penalty for manually specifying HTTP for non-secure
+access of a page that does require HTTPS: public exposure of sensitive data.
+</p>
+
+</subsection>
+
+<a name="help"/>
+<subsection name="Help from Deployment Descriptor">
+
+<p>
+To help overcome the problem of non-secure access of sensitive data, the Java Servlet
+Specification (versions 2.2 and 2.3) defines the transport-guarantee element of the
+web.xml deployment descriptor file. The transport-guarantee element must specify one
+of three types of protection for communication between client and server: NONE,
+INTEGRAL, or CONFIDENTIAL. For most containers a specification of INTEGRAL
+or CONFIDENTIAL is treated as a requirement for SSL usage. Web application
+containers will prevent users from accessing web resources over HTTP if they have been
+so specified.
+</p>
+
+<p>
+The implementation for blocking HTTP access to web resources specified as INTEGRAL
+or CONFIDENTIAL varies from container to container. If a user attempts to access such
+a resource over HTTP, some containers will present that user with an error message
+instructing them to use the HTTPS protocol for accessing the requested resource. Other
+containers will actually redirect the request using the HTTPS protocol, but then continue
+using the HTTPS protocol for all subsequent requests, even those for resources with a
+transport-guarantee specification of NONE.
+</p>
+
+</subsection>
+
+<a name="sslext"/>
+<subsection name="The sslext Struts Extension">
+
+<p>
+An extension to Struts 1.1, named sslext, helps solve many of these issues for Struts
+developers. It extends the ActionConfig class, RequestProcessor, and Plugin classes to
+define a framework where developers may specify the transmission protocol behavior for
+Struts applications. Within the Struts configuration file, developers specify which action
+requests require HTTPS transmission and which should use HTTP. Developers can also
+specify whether to redirect "improperly-protocoled" requests to the correct protocol.
+</p>
+
+<p>
+In addition to these extensions, the <html:link> and the <html:form> tags have been
+extended. In these extensions, the Struts actions specified in either of these tags are
+analyzed to determine the protocol that should be used in requesting that action. The
+HTML generated by these tags will specify the proper protocol. An additional custom
+tag is defined for allowing users to specify the transmission protocol for an individual
+JSP. This is most often used for form-based authentication pages.
+</p>
+
+<p>
+The sslext library may be obtained from <a href="http://sslext.sourceforge.net">
+http://sslext.sourceforge.net</a>
+</p>
+
+</subsection>
+
+<a name="legacy"/>
+<subsection name="Legacy Browser Issue">
+
+<p>
+One additional complication faced by developers of web applications is that some
+browsers (e.g. pre-6.0 versions of Netscape Navigator) will treat requests to different
+protocols and ports on the same server as requests to different domains. This causes
+these browsers to initiate a new session each time a different protocol or port is specified
+in a request. This problem can only be solved at the container level. Some containers
+have a "session domain" or "cookie domain" configuration parameter to allow the session
+to be shared across different servers in the same domain. As an example, the Weblogic
+Server has a "CookieDomain" property configured in its weblogic.xml deployment
+descriptor. Thankfully, the effects of this problem are diminishing as people upgrade
+their browsers to the current versions.
+</p>
+
+</subsection>
+
+<a name="containers"/>
+<subsection name="Configuring Containers for SSL">
+
+The procedure for configuring SSL for a container will be specific to that container. The
+procedure for enabling SSL for Tomcat can be found
+<a href="http://jakarta.apache.org/tomcat/tomcat-4.1-doc/ssl-howto.html">here</a>.
+
+</subsection>
+
+</section></body></document>
| 0 | 8 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
5b26c0cd85dc51f47ef8496ce8f9d73c651196e8
|
Submitted by Ted Husted. Updated "presentation tags" segment to include present/notPresent, and omit 0.5 versions. Updated beginning of "Automatic Form Validation" section to omit non-HTTP version (beyond scope of users guide).
<section name="3.3.3 Other Useful Presentation Tags" href="presentation_tags">
<p>
There are several tags useful for creating presentations, consult the documentation
on each specific tag library, along with the Tag Developers Guides, for more
information:
</p>
<ul>
<li><a href="struts-logic.html#iterate">iterate</a> repeats its tag body once
for each element of a specified collection (which can be an Enumeration,
a Hashtable, a Vector, or an array of objects).</li>
<li><a href="struts-logic.html#present">present</a> depending on which attribute
is specified, this tag checks the current request, and evaluates the nested
body content of this tag only if the specified value is present. Only one of
the attributes may be used in one occurrence of this tag, unless you use the
property attribute, in which case the name attribute is also required. The
attributes include cookie, header, name, parameter, property, role, scope,
and user.
</li>
<li><a href="struts-logic.html#notPresent">notPresent</a> the companion tag to
present, notPresent provides the same functionality when the specified attribute
is not present.
<li><a href="struts-html.html#link">link</a> generates a HTML <a> element
as an anchor definition or a hyperlink to the specified URL, and automatically
applies URL encoding to maintain session state in the absence of
cookie support.</li>
<li><a href="struts-bean.html#parameter">parameter</a> retrieves the value of the
specified request parameter, and defines the result as a page scope attribute of
type String or String[].</li>
</ul>
</section>
<section name="3.3.4 Automatic Form Validation" href="form_validation">
<snip>
<p>
In addition to the form and bean interactions described above, Struts
offers an additional facility to validate the input
fields it has received. To utilize this feature, override either of the following
methods, depending on your servlet environment, in your ActionForm class:
<pre>
public ActionErrors validate(ActionMapping mapping,
ServletRequest request)
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request)
</pre>
</p>
</snip>
<insert>
<p>
In addition to the form and bean interactions described above, Struts
offers an additional facility to validate the input fields it has received.
To utilize this feature, override the following method in your ActionForm
class:
<pre>
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request)
</pre>
</p>
</insert>
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48024 13f79535-47bb-0310-9956-ffa450edef68
|
commit 5b26c0cd85dc51f47ef8496ce8f9d73c651196e8
Author: Ted Nathan Husted <[email protected]>
Date: Thu Jan 11 00:20:03 2001 +0000
Submitted by Ted Husted. Updated "presentation tags" segment to include present/notPresent, and omit 0.5 versions. Updated beginning of "Automatic Form Validation" section to omit non-HTTP version (beyond scope of users guide).
<section name="3.3.3 Other Useful Presentation Tags" href="presentation_tags">
<p>
There are several tags useful for creating presentations, consult the documentation
on each specific tag library, along with the Tag Developers Guides, for more
information:
</p>
<ul>
<li><a href="struts-logic.html#iterate">iterate</a> repeats its tag body once
for each element of a specified collection (which can be an Enumeration,
a Hashtable, a Vector, or an array of objects).</li>
<li><a href="struts-logic.html#present">present</a> depending on which attribute
is specified, this tag checks the current request, and evaluates the nested
body content of this tag only if the specified value is present. Only one of
the attributes may be used in one occurrence of this tag, unless you use the
property attribute, in which case the name attribute is also required. The
attributes include cookie, header, name, parameter, property, role, scope,
and user.
</li>
<li><a href="struts-logic.html#notPresent">notPresent</a> the companion tag to
present, notPresent provides the same functionality when the specified attribute
is not present.
<li><a href="struts-html.html#link">link</a> generates a HTML <a> element
as an anchor definition or a hyperlink to the specified URL, and automatically
applies URL encoding to maintain session state in the absence of
cookie support.</li>
<li><a href="struts-bean.html#parameter">parameter</a> retrieves the value of the
specified request parameter, and defines the result as a page scope attribute of
type String or String[].</li>
</ul>
</section>
<section name="3.3.4 Automatic Form Validation" href="form_validation">
<snip>
<p>
In addition to the form and bean interactions described above, Struts
offers an additional facility to validate the input
fields it has received. To utilize this feature, override either of the following
methods, depending on your servlet environment, in your ActionForm class:
<pre>
public ActionErrors validate(ActionMapping mapping,
ServletRequest request)
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request)
</pre>
</p>
</snip>
<insert>
<p>
In addition to the form and bean interactions described above, Struts
offers an additional facility to validate the input fields it has received.
To utilize this feature, override the following method in your ActionForm
class:
<pre>
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request)
</pre>
</p>
</insert>
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48024 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/doc/userGuide/building_view.xml b/src/doc/userGuide/building_view.xml
index 70fb0fb96..175d77612 100644
--- a/src/doc/userGuide/building_view.xml
+++ b/src/doc/userGuide/building_view.xml
@@ -10,573 +10,571 @@
<body>
<chapter name="Building View Components" href="building_view">
- <section name="3.1 Overview" href="overview">
-
- <p>
- This chapter focuses on the task of building the <i>View</i> components
- of the application, which will primarily be created using JavaServer Pages
- (JSP) technology. In particular, Struts provides support for building
- internationalized applications, as well as for interacting with input forms.
- Several other topics related to the View components are briefly discussed.
- </p>
-
- </section>
-
- <section name="3.2 Internationalized Messages" href="i18n">
-
- <p>
- A few years ago, application developers could count on having to support
- only residents of their own country, who are used to only one (or sometimes
- two) languages, and one way to represent numeric quantities like dates,
- numbers, and monetary values. However, the explosion of application
- development based on web technologies, as well as the deployment of such
- applications on the Internet and other broadly accessible networks, have
- rendered national boundaries invisible in many cases. This has translated
- (if you will pardon the pun) into a need for applications to support
- <i>internationalization</i> (often called "i18n" because 18 is the number of
- letters in between the "i" and the "n") and <i>localization</i>.
- </p>
-
- <p>
- Struts builds upon the Java platform to provide assistance
- for building internationalized and localized applications. The key concepts
- to become familiar with are:
- </p>
-
- <ul>
- <li><b>Locale</b> - The fundamental Java class that supports
- internationalization is <code>java.util.Locale</code>. Each
- <code>Locale</code> represents a particular choice of country and
- language (plus an optional language variant), and also a set of
- formatting assumptions for things like numbers and dates.</li>
- <li><b>ResourceBundle</b> - The <code>java.util.ResourceBundle</code> class
- provides the fundmental tools for supporting messages in multiple
- languages. See the Javadocs for the <code>ResourceBundle</code> class,
- and the information on Internationalization in the documentation bundle
- for your JDK release, for more information.</li>
- <li><b>PropertyResourceBundle</b> - One of the standard implementations of
- <code>ResourceBundle</code> allows you to define resources using the
- same "name=value" syntax used to initialize properties files. This is
- very convenient for preparing resource bundles with messages that are
- used in a web application, because these messages are generally text
- oriented.</li>
- <li><b>MessageFormat</b> - The <code>java.text.MessageFormat</code> class
- allows you to replace portions of a message string (in this case,
- one retrieved from a resource bundle) with arguments specified at
- run time. This is useful in cases where you are creating a sentence,
- but the words would appear in a different order in different languages.
- The placeholder string <code>{0}</code> in the message is replaced by
- the first runtime argument, <code>{1}</code> is replaced by the second
- argument, and so on.</li>
- <li><b>MessageResources</b> - The Struts class
- <code>org.apache.struts.util.MessageResources</code> lets you treat
- a set of resource bundles like a database, and allows you to request
- a particular message string for a particular Locale (normally one
- associated with the current user) instead of for the default Locale
- the server itself is running in.</li>
- </ul>
-
- <p>
- For an internationalized application, follow the steps described in
- the Internationalization document in the JDK documentation bundle for your
- platform to create a properties file containing the messages for each
- language. An example will illustrate this further.
- </p>
-
- <p>
- Assume that your source code is created in package
- <code>com.mycompany.mypackage</code>, so it is stored in a directory
- (relative to your source directory) named
- <code>com/mycompany/mypackage</code>. To create a resource bundle called
- <code>com.mycompany.mypackage.MyResources</code>, you would create the
- following files in the <code>com/mycompany/mypackage</code> directory:
- </p>
-
- <ul>
- <li><b>MyResources.properties</b> - Contains the messages in the default
- language for your server. If your default language is English, you
- might have an entry like this:
- <pre>
- prompt.hello=Hello
- </pre></li>
- <li><b>MyResources_xx.properties</b> - Contains the same messages in the
- language whose ISO language code is "xx" (See the ResourceBundle
- Javadoc page for a link to the current list). For a French version
- of the message shown above, you would have this entry:
- <pre>
- prompt.hello=Bonjour
- </pre>
- You can have resource bundle files for as many languages as you need.</li>
- </ul>
-
- <p>
- When you configue the controller servlet in the web application
- deployment descriptor, one of the things you will need to define in
- an initialization parameter is the base name of the resource bundle
- for the application. In the case described above, it would be
- <code>com.mycompany.mypackage.MyResources</code>.
- </p>
- </section>
+ <section name="3.1 Overview" href="overview">
+
+ <p>
+ This chapter focuses on the task of building the <i>View</i> components
+ of the application, which will primarily be created using JavaServer Pages
+ (JSP) technology. In particular, Struts provides support for building
+ internationalized applications, as well as for interacting with input forms.
+ Several other topics related to the View components are briefly discussed.
+ </p>
+
+ </section>
+
+ <section name="3.2 Internationalized Messages" href="i18n">
+
+ <p>
+ A few years ago, application developers could count on having to support
+ only residents of their own country, who are used to only one (or sometimes
+ two) languages, and one way to represent numeric quantities like dates,
+ numbers, and monetary values. However, the explosion of application
+ development based on web technologies, as well as the deployment of such
+ applications on the Internet and other broadly accessible networks, have
+ rendered national boundaries invisible in many cases. This has translated
+ (if you will pardon the pun) into a need for applications to support
+ <i>internationalization</i> (often called "i18n" because 18 is the number of
+ letters in between the "i" and the "n") and <i>localization</i>.
+ </p>
+
+ <p>
+ Struts builds upon the Java platform to provide assistance
+ for building internationalized and localized applications. The key concepts
+ to become familiar with are:
+ </p>
+
+ <ul>
+ <li><b>Locale</b> - The fundamental Java class that supports
+ internationalization is <code>java.util.Locale</code>. Each
+ <code>Locale</code> represents a particular choice of country and
+ language (plus an optional language variant), and also a set of
+ formatting assumptions for things like numbers and dates.</li>
+ <li><b>ResourceBundle</b> - The <code>java.util.ResourceBundle</code> class
+ provides the fundmental tools for supporting messages in multiple
+ languages. See the Javadocs for the <code>ResourceBundle</code> class,
+ and the information on Internationalization in the documentation bundle
+ for your JDK release, for more information.</li>
+ <li><b>PropertyResourceBundle</b> - One of the standard implementations of
+ <code>ResourceBundle</code> allows you to define resources using the
+ same "name=value" syntax used to initialize properties files. This is
+ very convenient for preparing resource bundles with messages that are
+ used in a web application, because these messages are generally text
+ oriented.</li>
+ <li><b>MessageFormat</b> - The <code>java.text.MessageFormat</code> class
+ allows you to replace portions of a message string (in this case,
+ one retrieved from a resource bundle) with arguments specified at
+ run time. This is useful in cases where you are creating a sentence,
+ but the words would appear in a different order in different languages.
+ The placeholder string <code>{0}</code> in the message is replaced by
+ the first runtime argument, <code>{1}</code> is replaced by the second
+ argument, and so on.</li>
+ <li><b>MessageResources</b> - The Struts class
+ <code>org.apache.struts.util.MessageResources</code> lets you treat
+ a set of resource bundles like a database, and allows you to request
+ a particular message string for a particular Locale (normally one
+ associated with the current user) instead of for the default Locale
+ the server itself is running in.</li>
+ </ul>
+
+ <p>
+ For an internationalized application, follow the steps described in
+ the Internationalization document in the JDK documentation bundle for your
+ platform to create a properties file containing the messages for each
+ language. An example will illustrate this further.
+ </p>
+
+ <p>
+ Assume that your source code is created in package
+ <code>com.mycompany.mypackage</code>, so it is stored in a directory
+ (relative to your source directory) named
+ <code>com/mycompany/mypackage</code>. To create a resource bundle called
+ <code>com.mycompany.mypackage.MyResources</code>, you would create the
+ following files in the <code>com/mycompany/mypackage</code> directory:
+ </p>
+
+ <ul>
+ <li><b>MyResources.properties</b> - Contains the messages in the default
+ language for your server. If your default language is English, you
+ might have an entry like this:
+ <pre>
+ prompt.hello=Hello
+ </pre></li>
+ <li><b>MyResources_xx.properties</b> - Contains the same messages in the
+ language whose ISO language code is "xx" (See the ResourceBundle
+ Javadoc page for a link to the current list). For a French version
+ of the message shown above, you would have this entry:
+ <pre>
+ prompt.hello=Bonjour
+ </pre>
+ You can have resource bundle files for as many languages as you need.</li>
+ </ul>
+
+ <p>
+ When you configue the controller servlet in the web application
+ deployment descriptor, one of the things you will need to define in
+ an initialization parameter is the base name of the resource bundle
+ for the application. In the case described above, it would be
+ <code>com.mycompany.mypackage.MyResources</code>.
+ </p>
+ </section>
- <section name="3.3 Forms and FormBean Interactions" href="form_beans">
-
- <p>
- At one time or another, most web developers have built forms using
- the standard capabilities of HTML, such as the <code><input></code>
- tag. Users have come to expect interactive applications to have certain
- behaviors, and one of these expectations relates to error handling -- if
- the user makes an error, the application should allow them to fix just what
- needs to be changed -- without having to re-enter any of the rest of the
- information on the current page or form.
- </p>
-
- <p>
- Fulfilling this expectation is tedious and cumbersome when coding with
- standard HTML and JSP pages. For example, an input element for a
- <code>username</code> field might look like this (in JSP)
-
-
- <pre>
- <input type="text" name="username"
- value="<%= loginBean.getUsername() %>">
- </pre>
-
-
- which is difficult to type correctly, confuses HTML developers who are
- not knowledgeable about programming concepts, and can cause problems with
- HTML editors. Instead, Struts provides a comprehensive facility for
- building forms, based on the Custom Tag Library facility of JSP 1.1.
- The case above would be rendered like this using Struts:
-
- <pre>
- <html:text name="username"/>
- </pre>
-
- with no need to explicitly refer to the JavaBean from which the initial
- value is retrieved. That is handled automatically by the framework.
- </p>
- <p>
- Another problem with coding forms is how to handle the multipart form,
- a form with <input type="file"> elements. Struts also handles this
- in a way identical to building normal forms.
- </p>
-
- <section name="3.3.1 Building Forms With Struts" href="forms">
-
- <p>
- A complete example of a login form will illustrate how Struts
- makes dealing with forms much less painful than using straight HTML
- and standard JSP facilities. Consider the following page (from the
- example application included with Struts) named <code>logon.jsp</code>:
- </p>
-
- <pre>
- <%@ page language="java" %>
- <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
- <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
+ <section name="3.3 Forms and FormBean Interactions" href="form_beans">
+
+ <p>
+ At one time or another, most web developers have built forms using
+ the standard capabilities of HTML, such as the <code><input></code>
+ tag. Users have come to expect interactive applications to have certain
+ behaviors, and one of these expectations relates to error handling -- if
+ the user makes an error, the application should allow them to fix just what
+ needs to be changed -- without having to re-enter any of the rest of the
+ information on the current page or form.
+ </p>
+
+ <p>
+ Fulfilling this expectation is tedious and cumbersome when coding with
+ standard HTML and JSP pages. For example, an input element for a
+ <code>username</code> field might look like this (in JSP)
+
+
+ <pre>
+ <input type="text" name="username"
+ value="<%= loginBean.getUsername() %>">
+ </pre>
+
+
+ which is difficult to type correctly, confuses HTML developers who are
+ not knowledgeable about programming concepts, and can cause problems with
+ HTML editors. Instead, Struts provides a comprehensive facility for
+ building forms, based on the Custom Tag Library facility of JSP 1.1.
+ The case above would be rendered like this using Struts:
+
+ <pre>
+ <html:text name="username"/>
+ </pre>
+
+ with no need to explicitly refer to the JavaBean from which the initial
+ value is retrieved. That is handled automatically by the framework.
+ </p>
+ <p>
+ HTML forms are sometimes used to upload other files. Most browsers
+ support this through a <input type="file"> element, that generates
+ a file browse button, but it's up to the developer to handle the incoming
+ files. Struts handles these "multipart" forms in a way identical to
+ building normal forms. In the next section, we will cover using Struts to
+ create a simple login form, and also a simple mulitpart form.
+ </p>
+
+ <section name="3.3.1 Building Forms With Struts" href="forms">
+
+ <p>
+ A complete example of a login form will illustrate how Struts
+ makes dealing with forms much less painful than using straight HTML
+ and standard JSP facilities. Consider the following page (from the
+ example application included with Struts) named <code>logon.jsp</code>:
+ </p>
+
+ <pre>
+ <%@ page language="java" %>
+ <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
+ <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
-
- <html>
- <head>
- <title><bean:message key="logon.title"/></title>
- <body bgcolor="white">
-
- <html:errors/>
-
- <html:form action="logon.do">
- <table border="0" width="100%">
- <tr>
- <th align="right">
- <html:message key="prompt.username"/>
- </th>
- <td align="left">
- <html:text name="username" size="16"/>
- </td>
- </tr>
- <tr>
- <th align="right">
- <html:message key="prompt.password"/>
- </th>
- <td align="left">
- <html:password name="password" size="16"/>
- </td>
- </tr>
- <tr>
- <td align="right">
- <struts:submit>
- <bean:message key="button.submit"/>
- </struts:submit>
- </td>
- <td align="right">
- <html:reset>
- <bean:message key="button.reset"/>
- </html:reset>
- </td>
- </tr>
- </table>
- </html:form>
-
- </body>
- </html>
- </pre>
-
- <p>
- The following items illustrate the key features of form handling in Struts,
- based on this example:
- </p>
-
- <ul>
- <li>The <code>taglib</code> directive tells the JSP page compiler where to
- find the <i>tag library descriptor</i> for the Struts tag library. In
- this case, we are using <code>bean</code> as the prefix that identifies
- tags from the struts-bean library, and "html" as the prefix that identifies
- tags from the struts-html library. Any desired prefix can be used.</li>
- <li>This page uses several occurrences of the
- message tag to look up internationalized
- message strings from a <code>MessageResources</code> object containing
- all the resources for this application. For this page to work, the
- following message keys must be defined in these resources:
- <ul>
- <li><b>logon.title</b> - Title of the logon page</li>
- <li><b>prompt.username</b> - A "Username:" prompt string</li>
- <li><b>prompt.password</b> - A "Password:" prompt string</li>
- <li><b>button.submit</b> - "Submit" for the button label</li>
- <li><b>button.reset</b> - "Reset" for the button label</li>
- </ul>
- When the user logs on, the application can store a <code>Locale</code>
- object in the user's session. This <code>Locale</code> will be used
- to select messages in the appropriate language. This makes it easy to
- implement giving the user an option to switch languages -- simply change
- the stored <code>Locale</code> object, and all messages are switched
- automatically.</li>
- <li>The errors tag displays any error
- messages that have been stored by a business logic component, or nothing
- if no errors have been stored. This tag will be described further
- below.</li>
- <li>The form tag renders an HTML
- <code><form></code> element, based on the specified attributes.
- It also associates all of the fields within this form with a session
- scoped FormBean that is stored under the key <code>logonForm</code>.
- This bean is used to provide initial values for all of the input
- fields that have names matching the property names of the bean.
- If an appropriate bean is not found, a new one will be created
- automatically, using the specified Java class name.</li>
- <li>The text tag renders an HTML
- <code><input></code> element of type "text". In this case,
- the number of character positions to occupy on the browser's screen
- has been specified as well. When this page is executed, the current
- value of the <code>username</code> property of the corresponding bean
- (that is, the value returned by <code>getUsername()</code>).</li>
- <li>The password tag is used similarly.
- The difference is that the browser will echo asterisk characters,
- instead of the input value, as the user types their password.</li>.
- <li>The submit and
- reset tags generate the corresponding
- buttons at the bottom of the form. The text labels for each button
- are created using message tags,
- as with the prompts, so that these values are internationalized.</li>
- </ul>
-
- <p>
- Handling multipart forms is also easy. Obviously when you create a multipart
- form you're creating a form that has at least one input of type "file". The first step to
- creating a multipart form is to utilize the struts-html taglib to create the presentation
- page:
- </p>
-
- <p>
- <pre>
- <%@page language="java">
-
- <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html">
-
- <html:form action="uploadAction.do">
- Please Input Text: <html:text property="myText"><br />
- Please Input The File You Wish to Upload:<br />
- <html:file property="myFile"><br />
- <html:submit />
- </html:form>
- </pre>
- </p>
- <p>
- The next step is to create your ActionForm bean:
- </p>
- <p>
- <pre>
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionMapping;
- import org.apache.struts.upload.FormFile;
-
- public class UploadForm extends ActionForm {
-
- protected String myText;
- protected FormFile myFile;
-
- public void setMyText(String text) {
- myText = text;
- }
-
- public String getMyText() {
- return myText;
- }
-
- public void setMyFile(FormFile file) {
- myFile = file;
- }
-
- public FormFile getMyFile() {
- return myFile;
- }
- }
- </pre>
- </p>
-
- <p>
- Look at the <a href="api/index.html">javadocs</a> for FormFile to see the
- methods it exposes to manipulate files in file uploading. Also look at the
- javadocs for ActionServlet and ActionMapping for the various parameters
- you can specify to change how files are uploaded. Basically in your
- peform() method in your action class you would call <code>((UploadForm) form).getMyFile()</code>
- to retrieve the FormFile and do what you want with it.
- </p>
-
- </section>
-
- <section name="3.3.2 Input Field Types Supported" href="form_input">
-
- <p>
- Struts defines tags for all of the following types of input fields,
- with hyperlinks to the corresponding reference information.
- </p>
-
- <ul>
- <li><a href="struts-html.html#checkbox">checkboxes</a></li>
- <li><a href="struts-html.html#hidden">hidden</a> fields</li>
- <li><a href="struts-html.html#password">password</a> input fields</li>
- <li><a href="struts-html.html#radio">radio</a> buttons</li>
- <li><a href="struts-html.html#reset">reset</a> buttons</li>
- <li><a href="struts-html.html#select">select</a> lists with embedded</li>
- <li><a href="struts-html.html#option">options</a></li>
- <li><a href="struts-html.html#submit">submit</a> buttons</li>
- <li><a href="struts-html.html#text">text</a> input fields</li>
- <li><a href="struts-html.html#textarea">textareas</a></li>
- </ul>
-
- <p>
- In every
- case, a field tag must be nested within a <code>form</code> tag, so that
- the field knows what bean to use for initializing displayed values.
- </p>
- </section>
-
- <section name="3.3.3 Other Useful Presentation Tags" href="presentation_tags">
-
- <p>
- There are several tags useful for creating presentations, consult the documentation
- on each specific tag library for more information:
- </p>
-
- <ul>
- <li><a href="struts-logic.html#iterate">iterate</a> repeats its tag body once
- for each element of a specified collection (which can be an Enumeration,
- a Hashtable, a Vector, or an array of objects).</li>
- <li><a href="struts-logic.html#ifAttributeExists">ifAttributeExists</a> evaluates
- its tag body only if a specified attribute exists in a specified scope.
- </li>
- <li><a href="struts-logic.html#ifAttributeMissing">ifAttributeMissing</a> evaluates
- its tag body only if a specified attribute does not exist in a
- specified scope.</li>
- <li><a href="struts-logic.html#ifParameterEquals">ifParameterEquals</a> evaluates
- its tag body only if a specified request parameter has a specified
- value.</li>
- <li><a href="struts-logic.html#ifParameterNotEquals">ifParameterNotEquals</a>
- evaluates its tag body only if a specified request parameter does not
- have a specified value, or is not present.</li>
- <li><a href="struts-logic.html#ifParameterNotNull">ifParameterNotNull</a>
- evaluates its tag body only if a specified request parameter is included
- in this request, and has a length greater than zero.</li>
- <li><a href="struts-logic.html#ifParameterNull">ifParameterNull</a> evaluates its
- tag body only if a specified request parameter is not included in this
- request, or if it is included with zero length.</li>
- <li><a href="struts-html.html#link">link</a> generates a hyperlink, and automatically
- applies URL encoding to maintain session state in the absence of
- cookie support.</li>
- <li><a href="struts-bean.html#parameter">parameter</a> renders the specified
- request parameter's value or exposes it as a scripting variable.I can also be
- filtered for characters that are sensitive in HTML.</li>
- </ul>
- </section>
-
- <section name="3.3.4 Automatic Form Validation" href="form_validation">
-
- <p>
- In addition to the form and bean interactions described above, Struts
- offers an additional facility to validate the input
- fields it has received. To utilize this feature, override either of the following
- methods, depending on your servlet environment, in your ActionForm class:
- <pre>
- public ActionErrors validate(ActionMapping mapping,
- ServletRequest request)
+
+ <html>
+ <head>
+ <title><bean:message key="logon.title"/></title>
+ <body bgcolor="white">
+
+ <html:errors/>
+
+ <html:form action="logon.do">
+ <table border="0" width="100%">
+ <tr>
+ <th align="right">
+ <html:message key="prompt.username"/>
+ </th>
+ <td align="left">
+ <html:text name="username" size="16"/>
+ </td>
+ </tr>
+ <tr>
+ <th align="right">
+ <html:message key="prompt.password"/>
+ </th>
+ <td align="left">
+ <html:password name="password" size="16"/>
+ </td>
+ </tr>
+ <tr>
+ <td align="right">
+ <struts:submit>
+ <bean:message key="button.submit"/>
+ </struts:submit>
+ </td>
+ <td align="right">
+ <html:reset>
+ <bean:message key="button.reset"/>
+ </html:reset>
+ </td>
+ </tr>
+ </table>
+ </html:form>
+
+ </body>
+ </html>
+ </pre>
+
+ <p>
+ The following items illustrate the key features of form handling in Struts,
+ based on this example:
+ </p>
+
+ <ul>
+ <li>The <code>taglib</code> directive tells the JSP page compiler where to
+ find the <i>tag library descriptor</i> for the Struts tag library. In
+ this case, we are using <code>bean</code> as the prefix that identifies
+ tags from the struts-bean library, and "html" as the prefix that identifies
+ tags from the struts-html library. Any desired prefix can be used.</li>
+ <li>This page uses several occurrences of the
+ message tag to look up internationalized
+ message strings from a <code>MessageResources</code> object containing
+ all the resources for this application. For this page to work, the
+ following message keys must be defined in these resources:
+ <ul>
+ <li><b>logon.title</b> - Title of the logon page</li>
+ <li><b>prompt.username</b> - A "Username:" prompt string</li>
+ <li><b>prompt.password</b> - A "Password:" prompt string</li>
+ <li><b>button.submit</b> - "Submit" for the button label</li>
+ <li><b>button.reset</b> - "Reset" for the button label</li>
+ </ul>
+ When the user logs on, the application can store a <code>Locale</code>
+ object in the user's session. This <code>Locale</code> will be used
+ to select messages in the appropriate language. This makes it easy to
+ implement giving the user an option to switch languages -- simply change
+ the stored <code>Locale</code> object, and all messages are switched
+ automatically.</li>
+ <li>The errors tag displays any error
+ messages that have been stored by a business logic component, or nothing
+ if no errors have been stored. This tag will be described further
+ below.</li>
+ <li>The form tag renders an HTML
+ <code><form></code> element, based on the specified attributes.
+ It also associates all of the fields within this form with a session
+ scoped FormBean that is stored under the key <code>logonForm</code>.
+ This bean is used to provide initial values for all of the input
+ fields that have names matching the property names of the bean.
+ If an appropriate bean is not found, a new one will be created
+ automatically, using the specified Java class name.</li>
+ <li>The text tag renders an HTML
+ <code><input></code> element of type "text". In this case,
+ the number of character positions to occupy on the browser's screen
+ has been specified as well. When this page is executed, the current
+ value of the <code>username</code> property of the corresponding bean
+ (that is, the value returned by <code>getUsername()</code>).</li>
+ <li>The password tag is used similarly.
+ The difference is that the browser will echo asterisk characters,
+ instead of the input value, as the user types their password.</li>.
+ <li>The submit and
+ reset tags generate the corresponding
+ buttons at the bottom of the form. The text labels for each button
+ are created using message tags,
+ as with the prompts, so that these values are internationalized.</li>
+ </ul>
+
+ <p>
+ Handling multipart forms is also easy. Obviously when you create a multipart
+ form you're creating a form that has at least one input of type "file". The first step to
+ creating a multipart form is to utilize the struts-html taglib to create the presentation
+ page:
+ </p>
+
+ <p>
+ <pre>
+ <%@page language="java">
+
+ <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html">
+
+ <html:form action="uploadAction.do">
+ Please Input Text: <html:text property="myText"><br />
+ Please Input The File You Wish to Upload:<br />
+ <html:file property="myFile"><br />
+ <html:submit />
+ </html:form>
+ </pre>
+ </p>
+ <p>
+ The next step is to create your ActionForm bean:
+ </p>
+ <p>
+ <pre>
+ import javax.servlet.http.HttpServletRequest;
+ import javax.servlet.http.HttpServletResponse;
+ import org.apache.struts.action.ActionForm;
+ import org.apache.struts.action.ActionMapping;
+ import org.apache.struts.upload.FormFile;
+
+ public class UploadForm extends ActionForm {
+
+ protected String myText;
+ protected FormFile myFile;
+
+ public void setMyText(String text) {
+ myText = text;
+ }
+
+ public String getMyText() {
+ return myText;
+ }
+
+ public void setMyFile(FormFile file) {
+ myFile = file;
+ }
+
+ public FormFile getMyFile() {
+ return myFile;
+ }
+ }
+ </pre>
+ </p>
+
+ <p>
+ Look at the <a href="api/index.html">javadocs</a> for FormFile to see the
+ methods it exposes to manipulate files in file uploading. Also look at the
+ javadocs for ActionServlet and ActionMapping for the various parameters
+ you can specify to change how files are uploaded. Basically in your
+ peform() method in your action class you would call <code>((UploadForm) form).getMyFile()</code>
+ to retrieve the FormFile and do what you want with it.
+ </p>
+
+ </section>
+
+ <section name="3.3.2 Input Field Types Supported" href="form_input">
+
+ <p>
+ Struts defines tags for all of the following types of input fields,
+ with hyperlinks to the corresponding reference information.
+ </p>
+
+ <ul>
+ <li><a href="struts-html.html#checkbox">checkboxes</a></li>
+ <li><a href="struts-html.html#hidden">hidden</a> fields</li>
+ <li><a href="struts-html.html#password">password</a> input fields</li>
+ <li><a href="struts-html.html#radio">radio</a> buttons</li>
+ <li><a href="struts-html.html#reset">reset</a> buttons</li>
+ <li><a href="struts-html.html#select">select</a> lists with embedded</li>
+ <li><a href="struts-html.html#option">options</a></li>
+ <li><a href="struts-html.html#submit">submit</a> buttons</li>
+ <li><a href="struts-html.html#text">text</a> input fields</li>
+ <li><a href="struts-html.html#textarea">textareas</a></li>
+ </ul>
+
+ <p>
+ In every
+ case, a field tag must be nested within a <code>form</code> tag, so that
+ the field knows what bean to use for initializing displayed values.
+ </p>
+ </section>
+
+ <section name="3.3.3 Other Useful Presentation Tags" href="presentation_tags">
+
+ <p>
+ There are several tags useful for creating presentations, consult the documentation
+ on each specific tag library, along with the Tag Developers Guides, for more
+ information:
+ </p>
+
+ <ul>
+
+ <li><a href="struts-logic.html#iterate">iterate</a> repeats its tag body once
+ for each element of a specified collection (which can be an Enumeration,
+ a Hashtable, a Vector, or an array of objects).</li>
+ <li><a href="struts-logic.html#present">present</a> depending on which attribute
+ is specified, this tag checks the current request, and evaluates the nested
+ body content of this tag only if the specified value is present. Only one of
+ the attributes may be used in one occurrence of this tag, unless you use the
+ property attribute, in which case the name attribute is also required. The
+ attributes include cookie, header, name, parameter, property, role, scope,
+ and user.
+ </li>
+ <li><a href="struts-logic.html#notPresent">notPresent</a> the companion tag to
+ present, notPresent provides the same functionality when the specified attribute
+ is not present.
+ <li><a href="struts-html.html#link">link</a> generates a HTML <a> element
+ as an anchor definition or a hyperlink to the specified URL, and automatically
+ applies URL encoding to maintain session state in the absence of
+ cookie support.</li>
+ <li><a href="struts-bean.html#parameter">parameter</a> retrieves the value of the
+ specified request parameter, and defines the result as a page scope attribute of
+ type String or String[].</li>
+ </ul>
+
+ </section>
+
+ <section name="3.3.4 Automatic Form Validation" href="form_validation">
+
+ <p>
+ In addition to the form and bean interactions described above, Struts
+ offers an additional facility to validate the input fields it has received.
+ To utilize this feature, override the following method in your ActionForm
+ class:
+ <pre>
public ActionErrors validate(ActionMapping mapping,
- HttpServletRequest request)
+ HttpServletRequest request)
</pre>
- </p>
-
- <p>
- The validate() method is called by the controller servlet after the bean
- properties have been populated, but before the corresponding action class's
- <code>perform()</code> method is invoked. The <code>validate()</code> method
- has the following options:
- </p>
-
- <ul>
- <li>Perform the appropriate validations and find no problems -- Return either
- <code>null</code> or a zero-length ActionErrors instance, and the controller servlet
- will proceed to call the <code>perform()</code> method of the appropriate
- <code>Action</code> class.</li>
- <li>Perform the appropriate validations and find problems -- Return an ActionErrors
- instance containing <code>ActionError</code>'s, which are classes that contain
- the error message keys (into the application's
- <code>MessageResources</code> bundle) that should be displayed. The
- controller servlet will store this array as a request attribute suitable
- for use by the <code><html:errors></code> tag, and will forward
- control back to the input form (identified by the <code>inputForm</code>
- property for this <code>ActionMapping</code>.</li>
- </ul>
-
- <p>
- As mentioned earlier, this feature is entirely optional. The default implementation
- of the validate() method returns <code>null</code>, and the controller servlet
- will assume that any required validation is done by the action class.
- </p>
- </section>
- </section>
-
- <section name="3.4 Other Presentation Techniques" href="other_presentations">
-
- <p>
- Although the look and feel of your application can be completely constructed
- based on the standard capabilities of JSP and the Struts custom tag library,
- you should consider employing other techniques that will improve component
- reuse, reduce maintenance efforts, and/or reduce errors. Several options
- are discussed in the following sections.
- </p>
-
- <section name="3.4.1 Application-Specific Custom Tags" href="custom_tags">
-
- <p>
- Beyond using the custom tags provided by the Struts library, it is easy
- to create tags that are specific to the application you are building, to
- assist in creating the user interface. The example application included with
- Struts illustrates this principle by creating the following tags unique to
- the implementation of this application:
- </p>
-
- <ul>
- <li><code>checkLogon</code> - Checks for the existence of a particular session
- object, and forwards control to the logon page if it is missing. This is
- used to catch cases where a user has bookmarked a page in the middle of
- your application and tries to bypass logging on, or if the user's session
- has been timed out.</li>
- <li><code>linkSubscription</code> - Generates a hyperlink to a details page
- for a Subscription, which passes the required primary key values as
- request attributes. This is used when listing the subscriptions associated
- with a user, and providing links to edit or delete them.</li>
- <li><code>linkUser</code> - Generates a hyperlink to a details page
- for a User, which passes the required primary key values as
- request attributes.</li>
- </ul>
-
- <p>
- The source code for these tags is in the <code>src/example</code> directory,
- in package <code>org.apache.struts.example</code>, along with the other Java
- classes that are used in this application.
- </p>
- </section>
-
- <section name="3.4.2 Page Composition With Includes" href="includes">
-
- <p>
- Creating the entire presentation of a page in one JSP file (with custom
- tags and beans to access the required dynamic data) is a very common design
- approach, and was employed in the example application included with Struts.
- However, many applications require the display of multiple logically distinct
- portions of your application together on a single page.</p>
-
- <p>
- For example, a portal application might have some or all of the following
- functional capabilities available on the portal's "home" page:
- </p>
-
- <ul>
- <li>Access to a search engine for this portal.</li>
- <li>One or more "news feed" displays, with the topics of interest customized
- from the user's registration profile.</li>
- <li>Access to discussion topics related to this portal.</li>
- <li>A "mail waiting" indicator if your portal provides free email
- accounts.</li>
- </ul>
-
- <p>
- The development of the various segments of this site is easier if you
- can divide up the work, and assign different developers to the different
- segments. Then, you can use the <i>include</i> capability of JavaServer Pages
- technology to combine the results into a single result page, or use the include tag
- provided with Struts. There are three
- types of <i>include</i> available, depending on when you want the combination
- of output to occur:
- </p>
-
- <ul>
- <li>The include <i>directive</i> (<code><%@ include file="xxxxx"
- %></code>) is processed when the JSP page is compiled. It is
- useful when you are including HTML code that will not need to change
- at request time. It treats the text being included as static text,
- much like the <code>#include</code> directive in C or C++.</li>
- <li>The include <i>action</i> (<code><jsp:include page="xxxxx"
- flush="true" /></code>) is processed at request time, and is handled
- transparently by the server. Among other things, that means you
- can conditionally perform the include by nesting it within a tag
- like <a href="struts-logic.html#ifParameterEquals">ifParameterEquals</a>.</li>
- <li>The <a href="struts-bean.html#include">bean:include</a> tag takes either a
- an argument "forward" representing a logical name mapped to the jsp to include,
- or the "id" argument, which represents a page context String variable to print
- out to the jsp page.</li>
- </ul>
- </section>
+ </p>
+
+ <p>
+ The validate() method is called by the controller servlet after the bean
+ properties have been populated, but before the corresponding action class's
+ <code>perform()</code> method is invoked. The <code>validate()</code> method
+ has the following options:
+ </p>
+
+ <ul>
+ <li>Perform the appropriate validations and find no problems -- Return either
+ <code>null</code> or a zero-length ActionErrors instance, and the controller servlet
+ will proceed to call the <code>perform()</code> method of the appropriate
+ <code>Action</code> class.</li>
+ <li>Perform the appropriate validations and find problems -- Return an ActionErrors
+ instance containing <code>ActionError</code>'s, which are classes that contain
+ the error message keys (into the application's
+ <code>MessageResources</code> bundle) that should be displayed. The
+ controller servlet will store this array as a request attribute suitable
+ for use by the <code><html:errors></code> tag, and will forward
+ control back to the input form (identified by the <code>inputForm</code>
+ property for this <code>ActionMapping</code>.</li>
+ </ul>
+
+ <p>
+ As mentioned earlier, this feature is entirely optional. The default implementation
+ of the validate() method returns <code>null</code>, and the controller servlet
+ will assume that any required validation is done by the action class.
+ </p>
+ </section>
+ </section>
+
+ <section name="3.4 Other Presentation Techniques" href="other_presentations">
+
+ <p>
+ Although the look and feel of your application can be completely constructed
+ based on the standard capabilities of JSP and the Struts custom tag library,
+ you should consider employing other techniques that will improve component
+ reuse, reduce maintenance efforts, and/or reduce errors. Several options
+ are discussed in the following sections.
+ </p>
+
+ <section name="3.4.1 Application-Specific Custom Tags" href="custom_tags">
+
+ <p>
+ Beyond using the custom tags provided by the Struts library, it is easy
+ to create tags that are specific to the application you are building, to
+ assist in creating the user interface. The example application included with
+ Struts illustrates this principle by creating the following tags unique to
+ the implementation of this application:
+ </p>
+
+ <ul>
+ <li><code>checkLogon</code> - Checks for the existence of a particular session
+ object, and forwards control to the logon page if it is missing. This is
+ used to catch cases where a user has bookmarked a page in the middle of
+ your application and tries to bypass logging on, or if the user's session
+ has been timed out.</li>
+ <li><code>linkSubscription</code> - Generates a hyperlink to a details page
+ for a Subscription, which passes the required primary key values as
+ request attributes. This is used when listing the subscriptions associated
+ with a user, and providing links to edit or delete them.</li>
+ <li><code>linkUser</code> - Generates a hyperlink to a details page
+ for a User, which passes the required primary key values as
+ request attributes.</li>
+ </ul>
+
+ <p>
+ The source code for these tags is in the <code>src/example</code> directory,
+ in package <code>org.apache.struts.example</code>, along with the other Java
+ classes that are used in this application.
+ </p>
+ </section>
+
+ <section name="3.4.2 Page Composition With Includes" href="includes">
+
+ <p>
+ Creating the entire presentation of a page in one JSP file (with custom
+ tags and beans to access the required dynamic data) is a very common design
+ approach, and was employed in the example application included with Struts.
+ However, many applications require the display of multiple logically distinct
+ portions of your application together on a single page.</p>
+
+ <p>
+ For example, a portal application might have some or all of the following
+ functional capabilities available on the portal's "home" page:
+ </p>
+
+ <ul>
+ <li>Access to a search engine for this portal.</li>
+ <li>One or more "news feed" displays, with the topics of interest customized
+ from the user's registration profile.</li>
+ <li>Access to discussion topics related to this portal.</li>
+ <li>A "mail waiting" indicator if your portal provides free email
+ accounts.</li>
+ </ul>
+
+ <p>
+ The development of the various segments of this site is easier if you
+ can divide up the work, and assign different developers to the different
+ segments. Then, you can use the <i>include</i> capability of JavaServer Pages
+ technology to combine the results into a single result page, or use the include tag
+ provided with Struts. There are three
+ types of <i>include</i> available, depending on when you want the combination
+ of output to occur:
+ </p>
+
+ <ul>
+ <li>The include <i>directive</i> (<code><%@ include file="xxxxx"
+ %></code>) is processed when the JSP page is compiled. It is
+ useful when you are including HTML code that will not need to change
+ at request time. It treats the text being included as static text,
+ much like the <code>#include</code> directive in C or C++.</li>
+ <li>The include <i>action</i> (<code><jsp:include page="xxxxx"
+ flush="true" /></code>) is processed at request time, and is handled
+ transparently by the server. Among other things, that means you
+ can conditionally perform the include by nesting it within a tag
+ like <a href="struts-logic.html#ifParameterEquals">ifParameterEquals</a>.</li>
+ <li>The <a href="struts-bean.html#include">bean:include</a> tag takes either a
+ an argument "forward" representing a logical name mapped to the jsp to include,
+ or the "id" argument, which represents a page context String variable to print
+ out to the jsp page.</li>
+ </ul>
+ </section>
- <section name="3.4.3 Image Rendering Components" href="image_rendering">
-
- <p>
- Some applications require dynamically generated images, like the price
- charts on a stock reporting site. Two different approaches are commonly used
- to meet these requirements:
- </p>
-
- <ul>
- <li>Render a hyperlink with a URL that executes a servlet request. The
- servlet will use a graphics library to render the graphical image,
- set the content type appropriately (such as to <code>image/gif</code>),
- and send back the bytes of that image to the browser, which will display
- them just as if it had received a static file.</li>
- <li>Render the HTML code necessary to download a Java applet that creates
- the required graph. You can configure the graph by setting appropriate
- initialization parameters for the applet in the rendered code, or you
- can have the applet make its own connection to the server to receive
- these parameters.</li>
- </ul>
-
- <p align="center">
- Next: <a href="building_controller.html">Building Controller Components</a>
- </p>
- </section>
- </section>
- </chapter>
- </body>
-</document>
-
+ <section name="3.4.3 Image Rendering Components" href="image_rendering">
+
+ <p>
+ Some applications require dynamically generated images, like the price
+ charts on a stock reporting site. Two different approaches are commonly used
+ to meet these requirements:
+ </p>
+
+ <ul>
+ <li>Render a hyperlink with a URL that executes a servlet request. The
+ servlet will use a graphics library to render the graphical image,
+ set the content type appropriately (such as to <code>image/gif</code>),
+ and send back the bytes of that image to the browser, which will display
+ them just as if it had received a static file.</li>
+ <li>Render the HTML code necessary to download a Java applet that creates
+ the required graph. You can configure the graph by setting appropriate
+ initialization parameters for the applet in the rendered code, or you
+ can have the applet make its own connection to the server to receive
+ these parameters.</li>
+ </ul>
+
+ <p align="center">
+ Next: <a href="building_controller.html">Building Controller Components</a>
+ </p>
+ </section>
+ </section>
+ </chapter>
+ </body>
+</document>
+
| 0 | 1 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
942be4854f1ddf98a64e4dee7bb14fcb40d23d25
|
Submitted by Ted Husted. Minor stylistic changes to introduction. Refactor section 1.2 to segue from 1.1 and 1.3.
[1.1]
Good Thing.
Java code.
in-and-of itself
resolve /the/ flow control issues
under the Sun ...
released, and IOHO, Java Model 2 development will never be quite the same.
<strike>If you are new ... </strike>
--
[1.2]
In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, which act as an adapter between the request and the Model. The Model represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an applicaton significantly easier to create and maintain.
--
[1.3]
See the ASF license < http://www.apache.org/LICENSE-1.1 > for specifics.
--
[2.3]
Model.
object.
+ You may also place a bean instance on your form, and use nested property references. For example, you might have a "customer" bean on your Action Form, and then refer to the property "customer.name" in your JSP view. This would correspond to the methods customer.getName() and customer.setName(string Name) on your customer bean. See the Tag Library Developer Guides for more about nested syntax.
--
[2.6]
Struts can define the datasources for an application form within its standard configuration file. A simple JDBC connection pool is also provided. See The Action Mappings Configuration File section and the Utilities Developer Guide for details.
After the datasource is defined, here is an example of establishing a connection from within a Action perform method.
DataSource datasource = servlet.findDataSource(null);
--
[3.3]
../api
--
[3.3.1]
(based on
<html:form action="logon.do" name="logonForm">
using the specified Java class name. (The form bean name can also be specified in the Struts configuration file, and then omitted here. See "The Action Mappings Configuration File" for details.)
--
[3.3.4]
ActionMapping).
--
[3.4.2 Page Composition With Includes]
Another approach to this would be to use the Struts Template Tag library. See the Developer's Guide for details.
--
[4.2]
Most people would only use the "HttpServletRequest" version.
MVC/Model-2
--
[4.4
../api
--
[4.5.1]
You can also find these details in the Javadocs for the ActionServlet class.
../api
--
[Resources]
mailto:Thor
mailto:david
Change <u>'s to <b>'s
Make one "master" link to Husted dot Com.
Add mail-archive.com
--
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48049 13f79535-47bb-0310-9956-ffa450edef68
|
commit 942be4854f1ddf98a64e4dee7bb14fcb40d23d25
Author: Ted Nathan Husted <[email protected]>
Date: Sun Jan 21 12:57:51 2001 +0000
Submitted by Ted Husted. Minor stylistic changes to introduction. Refactor section 1.2 to segue from 1.1 and 1.3.
[1.1]
Good Thing.
Java code.
in-and-of itself
resolve /the/ flow control issues
under the Sun ...
released, and IOHO, Java Model 2 development will never be quite the same.
<strike>If you are new ... </strike>
--
[1.2]
In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, which act as an adapter between the request and the Model. The Model represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an applicaton significantly easier to create and maintain.
--
[1.3]
See the ASF license < http://www.apache.org/LICENSE-1.1 > for specifics.
--
[2.3]
Model.
object.
+ You may also place a bean instance on your form, and use nested property references. For example, you might have a "customer" bean on your Action Form, and then refer to the property "customer.name" in your JSP view. This would correspond to the methods customer.getName() and customer.setName(string Name) on your customer bean. See the Tag Library Developer Guides for more about nested syntax.
--
[2.6]
Struts can define the datasources for an application form within its standard configuration file. A simple JDBC connection pool is also provided. See The Action Mappings Configuration File section and the Utilities Developer Guide for details.
After the datasource is defined, here is an example of establishing a connection from within a Action perform method.
DataSource datasource = servlet.findDataSource(null);
--
[3.3]
../api
--
[3.3.1]
(based on
<html:form action="logon.do" name="logonForm">
using the specified Java class name. (The form bean name can also be specified in the Struts configuration file, and then omitted here. See "The Action Mappings Configuration File" for details.)
--
[3.3.4]
ActionMapping).
--
[3.4.2 Page Composition With Includes]
Another approach to this would be to use the Struts Template Tag library. See the Developer's Guide for details.
--
[4.2]
Most people would only use the "HttpServletRequest" version.
MVC/Model-2
--
[4.4
../api
--
[4.5.1]
You can also find these details in the Javadocs for the ActionServlet class.
../api
--
[Resources]
mailto:Thor
mailto:david
Change <u>'s to <b>'s
Make one "master" link to Husted dot Com.
Add mail-archive.com
--
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48049 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/doc/userGuide/building_controller.xml b/src/doc/userGuide/building_controller.xml
index 217d99d42..9d2f0450f 100644
--- a/src/doc/userGuide/building_controller.xml
+++ b/src/doc/userGuide/building_controller.xml
@@ -10,347 +10,350 @@
<body>
<chapter name="Building Controller Components" href="building_controller">
- <section name="4.1 Overview" href="overview">
-
- <p>
- Now that we understand how to construct the Model and View components
- of your application, it is time to focus on the <code>Controller</code>
- components. Struts includes a servlet that implements the primary function
- of mapping a request URI to an <code>Action</code> class. Therefore, your
- primary responsibilities related to the Controller are:
- </p>
-
- <ul>
- <li>Write an <code>Action</code> class (that is, an extension of the
- <code>Action</code> class) for each logical request
- that may be received.</li>
- <li>[Optionally] Write an <code>ActionMapping</code> class (that is, an
- extension of the <code>ActionMapping</code> class) that defines the class
- names and other information associated with each possible mapping.</li>
- <li>Write the action mapping configuration file (in XML) that is used
- to configure the controller servlet.</li>
- <li>Update the web application deployment descriptor file (in XML)
- for your application to include the necessary Struts components.</li>
- <li>Add the appropriate Struts components to your application.</li>
- </ul>
- </section>
-
- <section name="4.2 Action Classes" href="action_classes">
-
- <p>The <code>Action</code> class defines two methods that could be
- executed depending on your servlet environment:
+ <section name="4.1 Overview" href="overview">
+
+ <p>
+ Now that we understand how to construct the Model and View components
+ of your application, it is time to focus on the <code>Controller</code>
+ components. Struts includes a servlet that implements the primary function
+ of mapping a request URI to an <code>Action</code> class. Therefore, your
+ primary responsibilities related to the Controller are:
+ </p>
+
+ <ul>
+ <li>Write an <code>Action</code> class (that is, an extension of the
+ <code>Action</code> class) for each logical request
+ that may be received.</li>
+ <li>[Optionally] Write an <code>ActionMapping</code> class (that is, an
+ extension of the <code>ActionMapping</code> class) that defines the class
+ names and other information associated with each possible mapping.</li>
+ <li>Write the action mapping configuration file (in XML) that is used
+ to configure the controller servlet.</li>
+ <li>Update the web application deployment descriptor file (in XML)
+ for your application to include the necessary Struts components.</li>
+ <li>Add the appropriate Struts components to your application.</li>
+ </ul>
+ </section>
+
+ <section name="4.2 Action Classes" href="action_classes">
+
+ <p>The <code>Action</code> class defines two methods that could be
+ executed depending on your servlet environment:
<pre>
public ActionForward perform(ActionMapping mapping,
- ActionForm form,
- HttpServletRequest request,
- HttpServletResponse response)
- throws IOException, ServletException
-
+ ActionForm form,
+ ServletRequest request,
+ ServletResponse response)
+ throws IOException, ServletException
+
public ActionForward perform(ActionMapping mapping,
- ActionForm form,
- ServletRequest request,
- ServletResponse response)
- throws IOException, ServletException
+ ActionForm form,
+ HttpServletRequest request,
+ HttpServletResponse response)
+ throws IOException, ServletException
</pre>
- </p>
-
- <p>
- The goal of an <code>Action</code> class is to process this request,
- and then to return an <code>ActionForward</code> object that identifies
- the JSP page (if any) to which control should be forwarded to generate
- the corresponding response. In the <i>Model-1</i> design pattern,
- a typical <code>Action</code> class will implement the following
- logic in its <code>perform()</code> method:
- </p>
- <ul>
- <li>Validate the current state of the user's session (for example, checking
- that the user has successfully logged on). If the <code>Action</code>
- class finds that no logon exists, the request should be forwarded to
- the JSP page that displays the username and password prompts for
- logging on. This could occur because a user tried to enter your
- application "in the middle" (say, from a bookmark), or because the
- session has timed out, and the servlet container created a new one.</li>
- <li>If validation has not yet occurred,
- validate the form bean properties as necessary. If a problem is found,
- store the appropriate error message keys as a request attribute, and
- forward control back to the input form so that the errors can be
- corrected.</li>
- <li>Perform the processing required to deal with this request (such as
- saving a row into a database). This can be done by code embedded within
- the <code>Action</code> class itself, but should generally be performed
- by calling an appropriate method of a business logic bean.</li>
- <li>Update the server-side objects that will be used to create the next
- page of the user interface (typically request scope or session scope
- beans, depending on how long you need to keep these items available).</li>
- <li>Return an appropriate <code>ActionForward</code> object that identifies
- the JSP page to be used to generate this response, based on the newly
- updated beans. Typically, you will acquire a reference to such an
- object by calling <code>findForward()</code> on either the
- <code>ActionMapping</code> object you received (if you are using a
- logical name local to this mapping), or on the controller servlet
- itself (if you are using a logical name global to the application).</li>
- </ul>
-
- <p>
- Design issues to remember when coding <code>Action</code> classes
- include the following:
- </p>
-
- <ul>
- <li>The controller servlet creates only one instance of your
- <code>Action</code> class, and uses it for all requests. Thus,
- you need to code your <code>Action</code> class so that it operates
- correctly in a multi-threaded environment, just as you must code a
- servlet's <code>service()</code> method safely.</li>
- <li>The most important principle that aids in thread-safe coding is to
- use only local variables, not instance variables, in your
- <code>Action</code> class. Local variables are created on a
- stack that is assigned (by your JVM) to each request thread, so
- there is no need to worry about sharing them.</li>
- <li>The beans that represent the Model of your system may throw exceptions
- due to problems accessing databases or other resources.
- You should trap all such exceptions
- in the logic of your <code>perform()</code> method, and log them to the
- application logfile (along with the corresponding stack trace) by
- calling:
- <pre>
- servlet.log("Error message text", exception);
- </pre></li>
- <li>As a general rule, allocating scarce resources and keeping them across
- requests from the same user (in the user's session) can cause
- scalability problems. You should strive to release such resources
- (such as database connections) prior to forwarding control to the
- appropriate View component -- even if a bean method you have called
- throws an exception.</li>
- </ul>
-
- <p>
- In addition, you will want to guard against <code>Action</code> classes
- that are too large. The easiest way for this to happen is to embed your
- functional logic in the <code>Action</code> class itself, rather than
- coding it in separate business logic beans. Besides making the
- <code>Action</code> class itself hard to understand and maintain, this
- approach also makes it harder to re-use the business logic code, because
- it is embedded inside a component (the <code>Action</code> class) that
- is tied to being executed in a web application environment.
- </p>
-
- <p>
- The example application included with Struts stretches this design
- principle somewhat, because the business logic itself is embedded in the
- <code>Action</code> classes. This should be considered something of a
- bug in the design of the sample application, rather than an intrinsic
- feature of the Struts architecture, or an approach to be emulated.
- </p>
- </section>
-
- <section name="4.3 The ActionMapping Implementation" href="actionmapping">
-
- <p>
- In order to operate successfully, the Struts controller servlet needs
- to know several things about how each request URI should be mapped to an
- appropriate <code>Action</code> class. The required knowledge has been
- encapsulated in a Java interface named <code>ActionMapping</code>, the most
- important properties are as follows:
- </p>
-
- <ul>
- <li><b>type</b> - Fully qualified Java class name of the
- <code>Action</code> implementation class used by this mapping.</li>
- <li><b>name</b> - The name of the form bean defined in the config file
- that this action will use</li>
- <li><b>path</b> - The request URI path that is matched to select this
- mapping. See below for examples of how matching works.</li>
-
- <li><b>unknown</b> - Set to <code>true</code> if this action
- should be configured as the default for this application, to handle
- all requests not handled by another action. Only one action can be
- defined as a default within a single application.</li>
- <li><b>validate</b> - Set to <code>true</code> if the
- <code>validate()</code> method of the action associated
- with this mapping should be called.</li>
- </ul>
-
-
- <p>
- In the example application included with Struts, this feature is used to
- define two additional properties:
- </p>
-
- <ul>
- <li><b>failure</b> - The context-relative URI to which control should be
- forwarded if the Action class detects some sort of problem with the
- input fields it received. This will typically be the name of the
- JSP page from which the request was sent, which will cause the form
- to be redisplayed (with the error messages set by the Action Class
- and the most recent input values from the ActionForm bean).</li>
- <li><b>success</b> - The context-relative URI to which control should be
- forwarded if the Action class successfully performs the required
- function. This will typically be the name of a JSP page that prepares
- the next page of the conversation flow for this application.</li>
- </ul>
-
- <p>
- Using these two extra properties, the <code>Action</code> classes in the
- example application are almost totally independent of the actual names of
- the JSP pages that are used by the page designers. The pages can be renamed
- (for example) during a redesign, with negligible impact on the
- <code>Action</code> classes themselves. If the names of the "next" JSP
- pages were hard coded into the <code>Action</code> classes, all of these
- classes would also need to be modified.
- </p>
- </section>
-
- <section name="4.4 The Action Mappings Configuration File" href="config">
-
- <p>
- How does the controller servlet learn about the mappings you want? It
- would be possible (but tedious) to write a small Java class that simply
- instantiated new <code>ActionMapping</code> instances, and called all of
- the appropriate setter methods. To make this process easier, Struts includes
- a Digester module that is capable of reading an XML-based description of
- the desired mappings, creating the appropriate objects along the way.
- See the <a href="api/index.html">API documentation</a> for more information
- about Digester.
- </p>
-
- <p>
- The developer's responsibility is to create an XML file named
- <code>struts-config.xml</code>, and place it in the WEB-INF directory of your
- application. This format of this document is constrained by it's definition in
- "struts-config_1_0.dtd". The outermost XML element must be <code><struts-config></code>.
- </p>
-
- <p>
- Inside of the <struts-config> element, there two important elements that use
- to describe your actions:
-
- <blockquote>
- <b><form-beans></b><br />
- This section contains your form bean definitions. You use a <form-bean> element
- for each form bean, which has the following important attributes:
- <ul>
- <li>
- <b>name</b>: The name of the request or session level attribute that this form
- bean will be stored as
- </li>
- <li>
- <b>type</b>: The fully-qualified Java classname of your form bean
- </li>
- </ul>
- </blockquote>
- <blockquote>
- <b><action-mappings></b><br />
- This section contains your action definitions. You use an <action> element
- for each of your actions you would like to define. Each action element has requires
- the follwing attributes to be defined:
-
- <ul>
- <li>
- <b>path</b>: The application context-relative path to the action
- </li>
- <li>
- <b>type</b>: The fully qualified java classname of your Action class
- </li>
- <li>
- <b>name</b>: The name of your <form-bean> element to use with this action
- </li>
- </ul>
- </blockquote>
- </p>
-
- <p>
- The <code>struts-config.xml</code> file from the example application includes
- the following mapping entry for the "log on" function, which we will use
- to illustrate the requirements. Note that the entries for all the other actions
- are left out:
- </p>
+ </p>
+
+ <p>
+ Most people would only use the "HttpServletRequest" version.
+ </p>
+ <p>
+ The goal of an <code>Action</code> class is to process this request,
+ and then to return an <code>ActionForward</code> object that identifies
+ the JSP page (if any) to which control should be forwarded to generate
+ the corresponding response. In the <i>MVC/Model 2</i> design pattern,
+ a typical <code>Action</code> class will implement the following
+ logic in its <code>perform()</code> method:
+ </p>
+ <ul>
+ <li>Validate the current state of the user's session (for example, checking
+ that the user has successfully logged on). If the <code>Action</code>
+ class finds that no logon exists, the request should be forwarded to
+ the JSP page that displays the username and password prompts for
+ logging on. This could occur because a user tried to enter your
+ application "in the middle" (say, from a bookmark), or because the
+ session has timed out, and the servlet container created a new one.</li>
+ <li>If validation has not yet occurred,
+ validate the form bean properties as necessary. If a problem is found,
+ store the appropriate error message keys as a request attribute, and
+ forward control back to the input form so that the errors can be
+ corrected.</li>
+ <li>Perform the processing required to deal with this request (such as
+ saving a row into a database). This can be done by code embedded within
+ the <code>Action</code> class itself, but should generally be performed
+ by calling an appropriate method of a business logic bean.</li>
+ <li>Update the server-side objects that will be used to create the next
+ page of the user interface (typically request scope or session scope
+ beans, depending on how long you need to keep these items available).</li>
+ <li>Return an appropriate <code>ActionForward</code> object that identifies
+ the JSP page to be used to generate this response, based on the newly
+ updated beans. Typically, you will acquire a reference to such an
+ object by calling <code>findForward()</code> on either the
+ <code>ActionMapping</code> object you received (if you are using a
+ logical name local to this mapping), or on the controller servlet
+ itself (if you are using a logical name global to the application).</li>
+ </ul>
+
+ <p>
+ Design issues to remember when coding <code>Action</code> classes
+ include the following:
+ </p>
+
+ <ul>
+ <li>The controller servlet creates only one instance of your
+ <code>Action</code> class, and uses it for all requests. Thus,
+ you need to code your <code>Action</code> class so that it operates
+ correctly in a multi-threaded environment, just as you must code a
+ servlet's <code>service()</code> method safely.</li>
+ <li>The most important principle that aids in thread-safe coding is to
+ use only local variables, not instance variables, in your
+ <code>Action</code> class. Local variables are created on a
+ stack that is assigned (by your JVM) to each request thread, so
+ there is no need to worry about sharing them.</li>
+ <li>The beans that represent the Model of your system may throw exceptions
+ due to problems accessing databases or other resources.
+ You should trap all such exceptions
+ in the logic of your <code>perform()</code> method, and log them to the
+ application logfile (along with the corresponding stack trace) by
+ calling:
+ <pre>
+ servlet.log("Error message text", exception);
+ </pre></li>
+ <li>As a general rule, allocating scarce resources and keeping them across
+ requests from the same user (in the user's session) can cause
+ scalability problems. You should strive to release such resources
+ (such as database connections) prior to forwarding control to the
+ appropriate View component -- even if a bean method you have called
+ throws an exception.</li>
+ </ul>
+
+ <p>
+ In addition, you will want to guard against <code>Action</code> classes
+ that are too large. The easiest way for this to happen is to embed your
+ functional logic in the <code>Action</code> class itself, rather than
+ coding it in separate business logic beans. Besides making the
+ <code>Action</code> class itself hard to understand and maintain, this
+ approach also makes it harder to re-use the business logic code, because
+ it is embedded inside a component (the <code>Action</code> class) that
+ is tied to being executed in a web application environment.
+ </p>
+
+ <p>
+ The example application included with Struts stretches this design
+ principle somewhat, because the business logic itself is embedded in the
+ <code>Action</code> classes. This should be considered something of a
+ bug in the design of the sample application, rather than an intrinsic
+ feature of the Struts architecture, or an approach to be emulated.
+ </p>
+ </section>
+
+ <section name="4.3 The ActionMapping Implementation" href="actionmapping">
+
+ <p>
+ In order to operate successfully, the Struts controller servlet needs
+ to know several things about how each request URI should be mapped to an
+ appropriate <code>Action</code> class. The required knowledge has been
+ encapsulated in a Java interface named <code>ActionMapping</code>, the most
+ important properties are as follows:
+ </p>
+
+ <ul>
+ <li><b>type</b> - Fully qualified Java class name of the
+ <code>Action</code> implementation class used by this mapping.</li>
+ <li><b>name</b> - The name of the form bean defined in the config file
+ that this action will use</li>
+ <li><b>path</b> - The request URI path that is matched to select this
+ mapping. See below for examples of how matching works.</li>
+
+ <li><b>unknown</b> - Set to <code>true</code> if this action
+ should be configured as the default for this application, to handle
+ all requests not handled by another action. Only one action can be
+ defined as a default within a single application.</li>
+ <li><b>validate</b> - Set to <code>true</code> if the
+ <code>validate()</code> method of the action associated
+ with this mapping should be called.</li>
+ </ul>
+
+
+ <p>
+ In the example application included with Struts, this feature is used to
+ define two additional properties:
+ </p>
+
+ <ul>
+ <li><b>failure</b> - The context-relative URI to which control should be
+ forwarded if the Action class detects some sort of problem with the
+ input fields it received. This will typically be the name of the
+ JSP page from which the request was sent, which will cause the form
+ to be redisplayed (with the error messages set by the Action Class
+ and the most recent input values from the ActionForm bean).</li>
+ <li><b>success</b> - The context-relative URI to which control should be
+ forwarded if the Action class successfully performs the required
+ function. This will typically be the name of a JSP page that prepares
+ the next page of the conversation flow for this application.</li>
+ </ul>
+
+ <p>
+ Using these two extra properties, the <code>Action</code> classes in the
+ example application are almost totally independent of the actual names of
+ the JSP pages that are used by the page designers. The pages can be renamed
+ (for example) during a redesign, with negligible impact on the
+ <code>Action</code> classes themselves. If the names of the "next" JSP
+ pages were hard coded into the <code>Action</code> classes, all of these
+ classes would also need to be modified.
+ </p>
+ </section>
+
+ <section name="4.4 The Action Mappings Configuration File" href="config">
+
+ <p>
+ How does the controller servlet learn about the mappings you want? It
+ would be possible (but tedious) to write a small Java class that simply
+ instantiated new <code>ActionMapping</code> instances, and called all of
+ the appropriate setter methods. To make this process easier, Struts includes
+ a Digester module that is capable of reading an XML-based description of
+ the desired mappings, creating the appropriate objects along the way.
+ See the <a href="../api/index.html">API documentation</a> for more information
+ about Digester.
+ </p>
+
+ <p>
+ The developer's responsibility is to create an XML file named
+ <code>struts-config.xml</code>, and place it in the WEB-INF directory of your
+ application. This format of this document is constrained by it's definition in
+ "struts-config_1_0.dtd". The outermost XML element must be <code><struts-config></code>.
+ </p>
+
+ <p>
+ Inside of the <struts-config> element, there two important elements that use
+ to describe your actions:
+
+ <blockquote>
+ <b><form-beans></b><br />
+ This section contains your form bean definitions. You use a <form-bean> element
+ for each form bean, which has the following important attributes:
+ <ul>
+ <li>
+ <b>name</b>: The name of the request or session level attribute that this form
+ bean will be stored as
+ </li>
+ <li>
+ <b>type</b>: The fully-qualified Java classname of your form bean
+ </li>
+ </ul>
+ </blockquote>
+ <blockquote>
+ <b><action-mappings></b><br />
+ This section contains your action definitions. You use an <action> element
+ for each of your actions you would like to define. Each action element has requires
+ the follwing attributes to be defined:
+
+ <ul>
+ <li>
+ <b>path</b>: The application context-relative path to the action
+ </li>
+ <li>
+ <b>type</b>: The fully qualified java classname of your Action class
+ </li>
+ <li>
+ <b>name</b>: The name of your <form-bean> element to use with this action
+ </li>
+ </ul>
+ </blockquote>
+ </p>
+
+ <p>
+ The <code>struts-config.xml</code> file from the example application includes
+ the following mapping entry for the "log on" function, which we will use
+ to illustrate the requirements. Note that the entries for all the other actions
+ are left out:
+ </p>
<pre>
<struts-config>
- <form-beans>
- <form-bean name="logonForm"
- type="org.apache.struts.example.LogonForm">
- </form-beans>
-
- <global-forwards type="org.apache.struts.action.ActionForward">
- <forward name="logon" path="/logon.jsp" redirect="false" />
- </global-forwards>
-
- <action-mappings>
-
- <action path="/logon"
- type="org.apache.struts.example.LogonAction"
- name="logonForm"
- scope="request"
- input="/logon.jsp"
- unknown="false"
- validate="true" />
- </action-mappings>
+ <form-beans>
+ <form-bean name="logonForm"
+ type="org.apache.struts.example.LogonForm">
+ </form-beans>
+
+ <global-forwards type="org.apache.struts.action.ActionForward">
+ <forward name="logon" path="/logon.jsp" redirect="false" />
+ </global-forwards>
+
+ <action-mappings>
+
+ <action path="/logon"
+ type="org.apache.struts.example.LogonAction"
+ name="logonForm"
+ scope="request"
+ input="/logon.jsp"
+ unknown="false"
+ validate="true" />
+ </action-mappings>
</struts-config>
</pre>
-
- <p>
- First the form bean is defined. A basic bean of class "org.apache.struts.example.LogonForm"
- is mapped to the logical name "logonForm". This name is used as a session or request attribute
- name for the form bean.
- </p>
- <p>
- The "global-forwards" section is used to create logical name mappings between commonly used
- jsp pages. Each of these forwards is available through a call to your action mapping instance,
- i.e. actionMappingInstace.findForward("logicalName")
- </p>
- <p>
- As you can see, this mapping matches the path <code>/logon</code> (actually,
- because the example application uses extension mapping, the request URI you
- specify in a JSP page would end in <code>/logon.do</code>). When a request
- that matches this path is received, an instance of the <code>LogonAction</code>
- class will be created (the first time only) and used. The controller servlet
- will look for a session scoped bean under key <code>logonForm</code>, creating
- and saving a bean of the specified class if needed.
- </p>
-
- <p>
- One more section of good use is the <code><data-sources></code> section, which
- specifies data sources that your application can use.This is how you would specify a basic data source for your application inside
- of struts-config.xml:
- </p>
- <p>
+
+ <p>
+ First the form bean is defined. A basic bean of class "org.apache.struts.example.LogonForm"
+ is mapped to the logical name "logonForm". This name is used as a session or request attribute
+ name for the form bean.
+ </p>
+ <p>
+ The "global-forwards" section is used to create logical name mappings between commonly used
+ jsp pages. Each of these forwards is available through a call to your action mapping instance,
+ i.e. actionMappingInstace.findForward("logicalName")
+ </p>
+ <p>
+ As you can see, this mapping matches the path <code>/logon</code> (actually,
+ because the example application uses extension mapping, the request URI you
+ specify in a JSP page would end in <code>/logon.do</code>). When a request
+ that matches this path is received, an instance of the <code>LogonAction</code>
+ class will be created (the first time only) and used. The controller servlet
+ will look for a session scoped bean under key <code>logonForm</code>, creating
+ and saving a bean of the specified class if needed.
+ </p>
+
+ <p>
+ One more section of good use is the <code><data-sources></code> section, which
+ specifies data sources that your application can use.This is how you would specify a basic data source for your application inside
+ of struts-config.xml:
+ </p>
+ <p>
<pre>
- <struts-config>
- <data-sources>
- <data-source autoCommit="false"
- description="Example Data Source Description"
- driverClass="org.postgresql.Driver"
- maxCount="4"
- minCount="2"
- password="mypassword"
- url="jdbc:postgresql://localhost/mydatabase"
- user="myusername"/>
- </data-sources>
- </struts-config>
+ <struts-config>
+ <data-sources>
+ <data-source autoCommit="false"
+ description="Example Data Source Description"
+ driverClass="org.postgresql.Driver"
+ maxCount="4"
+ minCount="2"
+ password="mypassword"
+ url="jdbc:postgresql://localhost/mydatabase"
+ user="myusername"/>
+ </data-sources>
+ </struts-config>
</pre>
- </p>
- <p>
- For information on how to retrieve the data source, see the
- <a href="building_model.html#databases">Accessing Relational Databases</a> section.
- </p>
- </section>
-
- <section name="4.5 The Web Application Deployment Descriptor" href="dd_config">
-
- <p>
- The final step in setting up the application is to configure the application
- deployment descriptor (stored in file <code>WEB-INF/web.xml</code>) to include
- all the Struts components that are required. Using the deployment descriptor
- for the example application as a guide, we see that the following entries need
- to be created or modified.
- </p>
-
- <section name="4.5.1 Configure the Action Servlet Instance" href="dd_config_servlet">
-
- <p>
- Add an entry defining the action servlet itself, along with the appropriate
- initialization parameters. Such an entry might look like this:
+ </p>
+ <p>
+ For information on how to retrieve the data source, see the
+ <a href="building_model.html#databases">Accessing Relational Databases</a> section.
+ </p>
+ </section>
+
+ <section name="4.5 The Web Application Deployment Descriptor" href="dd_config">
+
+ <p>
+ The final step in setting up the application is to configure the application
+ deployment descriptor (stored in file <code>WEB-INF/web.xml</code>) to include
+ all the Struts components that are required. Using the deployment descriptor
+ for the example application as a guide, we see that the following entries need
+ to be created or modified.
+ </p>
+
+ <section name="4.5.1 Configure the Action Servlet Instance" href="dd_config_servlet">
+
+ <p>
+ Add an entry defining the action servlet itself, along with the appropriate
+ initialization parameters. Such an entry might look like this:
<pre>
<servlet>
<servlet-name>action</servlet-name>
@@ -374,178 +377,178 @@
<load-on-startup>2</load-on-startup>
</servlet>
</pre>
- </p>
-
- <p>
- The initialization parameters supported by the controller servlet are
- described below, which is copied from the <a href="api/index.html">Javadocs</a>
- for the <code>ActionServlet</code> class. Square brackets describe the
- default values that are assumed if you do not provide a value for that
- initialization parameter.
- </p>
- <ul>
-
- <li><strong>application</strong> - Java class name of the application
- resources bundle base class. [NONE]</li>
- <li><strong>bufferSize</strong> - The size of the input buffer used when
- processing file uploads. [4096]</li>
- <li><strong>config</strong> - Context-relative path to the XML resource
- containing our configuration information.
- [/WEB-INF/struts-config.xml]</li>
- <li><strong>content</strong> - Default content type and character encoding
- to be set on each response; may be overridden by a forwarded-to
- servlet or JSP page. [text/html]</li>
- <li><strong>debug</strong> - The debugging detail level for this
- servlet, which controls how much information is logged. [0]</li>
- <li><strong>detail</strong> - The debugging detail level for the Digester
- we utilize in <code>initMapping()</code>, which logs to System.out
- instead of the servlet log. [0]</li>
- <li><strong>factory</strong> - The Java class name of the
- <code>MessageResourcesFactory</code> used to create the application
- <code>MessageResources</code> object.</li>
- <li><strong>formBean</strong> - The Java class name of the ActionFormBean
- implementation to use [org.apache.struts.action.ActionFormBean].</li>
- <li><strong>forward</strong> - The Java class name of the ActionForward
- implementation to use [org.apache.struts.action.ActionForward].
- Two convenient classes you may wish to use are:
- <ul>
- <li><em>org.apache.struts.action.ForwardingActionForward</em> -
- Subclass of <code>org.apache.struts.action.ActionForward</code>
- that defaults the <code>redirect</code> property to
- <code>false</code> (same as the ActionForward default value).</li>
- <li><em>org.apache.struts.action.RedirectingActionForward</em> -
- Subclass of <code>org.apache.struts.action.ActionForward</code>
- that defaults the <code>redirect</code> property to
- <code>true</code>.</li>
- </ul></li>
- <li><strong>locale</strong> - If set to <code>true</code>, and there is a
- user session, identify and store an appropriate
- <code>java.util.Locale</code> object (under the standard key
- identified by <code>Action.LOCALE_KEY</code>) in the user's session
- if there is not a Locale object there already.</li>
- <li><strong>mapping</strong> - The Java class name of the ActionMapping
- implementation to use [org.apache.struts.action.ActionMapping].
- Two convenient classes you may wish to use are:
- <ul>
- <li><em>org.apache.struts.action.RequestActionMapping</em> - Subclass
- of <code>org.apache.struts.action.ActionMapping</code> that
- defaults the <code>scope</code> property to "request".</li>
- <li><em>org.apache.struts.action.SessionActionMapping</em> - Subclass
- of <code>org.apache.struts.action.ActionMapping</code> that
- defaults the <code>scope</code> property to "session". (Same
- as the ActionMapping default value).</li>
- </ul></li>
- <li><strong>maxFileSize</strong> - The maximum size (in bytes) of a file
- to be accepted as a file upload. Can be expressed as a number followed
- by a "K" "M", or "G", which are interpreted to mean kilobytes,
- megabytes, or gigabytes, respectively. [250M]</li>
- <li><strong>multipartClass</strong> - The fully qualified name of the
- MultiplartRequestHandler implementation class to be used for processing
- file uploads. [org.apache.struts.upload.DiskMultipartRequestHandler]
- </li>
- <li><strong>nocache</strong> - If set to <code>true</code>, add HTTP headers
- to every response intended to defeat browser caching of any response we
- generate or forward to. [false]</li>
- <li><strong>null</strong> - If set to <code>true</code>, set our application
- resources to return <code>null</code> if an unknown message key is used.
- Otherwise, an error message including the offending message key will
- be returned. [true]</li>
- <li><strong>tempDir</strong> - The temporary working directory to use when
- processing file uploads. [The working directory provided to this web
- application as a servlet context attribute]</li>
- <li><strong>validate</strong> - Are we using the new configuration file
- format? [true]</li>
- </ul>
- </section>
-
- <section name="4.5.2 Configure the Action Servlet Mapping" href="dd_config_mapping">
-
- <p>
- There are two common approaches to defining the URLs that will
- be processed by the controller servlet -- prefix matching and extension
- matching. An appropriate mapping entry for each approach will be
- described below.
- </p>
-
- <p>
- Prefix matching means that you want all URLs that start (after the context
- path part) with a particular value to be passed to this servlet. Such an
- entry might look like this:
- </p>
+ </p>
+
+ <p>
+ The initialization parameters supported by the controller servlet are
+ described below. (You can also find these details in the <a
+ href="../api/index.html">Javadocs</a> for the ActionServlet class.) Square brackets
+ describe the default values that are assumed if you do not provide a value for
+ that initialization parameter.
+ </p>
+ <ul>
+
+ <li><strong>application</strong> - Java class name of the application
+ resources bundle base class. [NONE]</li>
+ <li><strong>bufferSize</strong> - The size of the input buffer used when
+ processing file uploads. [4096]</li>
+ <li><strong>config</strong> - Context-relative path to the XML resource
+ containing our configuration information.
+ [/WEB-INF/struts-config.xml]</li>
+ <li><strong>content</strong> - Default content type and character encoding
+ to be set on each response; may be overridden by a forwarded-to
+ servlet or JSP page. [text/html]</li>
+ <li><strong>debug</strong> - The debugging detail level for this
+ servlet, which controls how much information is logged. [0]</li>
+ <li><strong>detail</strong> - The debugging detail level for the Digester
+ we utilize in <code>initMapping()</code>, which logs to System.out
+ instead of the servlet log. [0]</li>
+ <li><strong>factory</strong> - The Java class name of the
+ <code>MessageResourcesFactory</code> used to create the application
+ <code>MessageResources</code> object.</li>
+ <li><strong>formBean</strong> - The Java class name of the ActionFormBean
+ implementation to use [org.apache.struts.action.ActionFormBean].</li>
+ <li><strong>forward</strong> - The Java class name of the ActionForward
+ implementation to use [org.apache.struts.action.ActionForward].
+ Two convenient classes you may wish to use are:
+ <ul>
+ <li><em>org.apache.struts.action.ForwardingActionForward</em> -
+ Subclass of <code>org.apache.struts.action.ActionForward</code>
+ that defaults the <code>redirect</code> property to
+ <code>false</code> (same as the ActionForward default value).</li>
+ <li><em>org.apache.struts.action.RedirectingActionForward</em> -
+ Subclass of <code>org.apache.struts.action.ActionForward</code>
+ that defaults the <code>redirect</code> property to
+ <code>true</code>.</li>
+ </ul></li>
+ <li><strong>locale</strong> - If set to <code>true</code>, and there is a
+ user session, identify and store an appropriate
+ <code>java.util.Locale</code> object (under the standard key
+ identified by <code>Action.LOCALE_KEY</code>) in the user's session
+ if there is not a Locale object there already.</li>
+ <li><strong>mapping</strong> - The Java class name of the ActionMapping
+ implementation to use [org.apache.struts.action.ActionMapping].
+ Two convenient classes you may wish to use are:
+ <ul>
+ <li><em>org.apache.struts.action.RequestActionMapping</em> - Subclass
+ of <code>org.apache.struts.action.ActionMapping</code> that
+ defaults the <code>scope</code> property to "request".</li>
+ <li><em>org.apache.struts.action.SessionActionMapping</em> - Subclass
+ of <code>org.apache.struts.action.ActionMapping</code> that
+ defaults the <code>scope</code> property to "session". (Same
+ as the ActionMapping default value).</li>
+ </ul></li>
+ <li><strong>maxFileSize</strong> - The maximum size (in bytes) of a file
+ to be accepted as a file upload. Can be expressed as a number followed
+ by a "K" "M", or "G", which are interpreted to mean kilobytes,
+ megabytes, or gigabytes, respectively. [250M]</li>
+ <li><strong>multipartClass</strong> - The fully qualified name of the
+ MultiplartRequestHandler implementation class to be used for processing
+ file uploads. [org.apache.struts.upload.DiskMultipartRequestHandler]
+ </li>
+ <li><strong>nocache</strong> - If set to <code>true</code>, add HTTP headers
+ to every response intended to defeat browser caching of any response we
+ generate or forward to. [false]</li>
+ <li><strong>null</strong> - If set to <code>true</code>, set our application
+ resources to return <code>null</code> if an unknown message key is used.
+ Otherwise, an error message including the offending message key will
+ be returned. [true]</li>
+ <li><strong>tempDir</strong> - The temporary working directory to use when
+ processing file uploads. [The working directory provided to this web
+ application as a servlet context attribute]</li>
+ <li><strong>validate</strong> - Are we using the new configuration file
+ format? [true]</li>
+ </ul>
+ </section>
+
+ <section name="4.5.2 Configure the Action Servlet Mapping" href="dd_config_mapping">
+
+ <p>
+ There are two common approaches to defining the URLs that will
+ be processed by the controller servlet -- prefix matching and extension
+ matching. An appropriate mapping entry for each approach will be
+ described below.
+ </p>
+
+ <p>
+ Prefix matching means that you want all URLs that start (after the context
+ path part) with a particular value to be passed to this servlet. Such an
+ entry might look like this:
+ </p>
<pre>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/execute/*</url-pattern>
</servlet-mapping>
</pre>
-
- <p>
- which means that a request URI to match the <code>/logon</code> path
- described earlier might look like this:
- <pre>
- http://www.mycompany.com/myapplication/execute/logon
- </pre>
- </p>
-
- <p>
- where <code>/myapplication</code> is the context path under which your
- application is deployed.
- </p>
-
- <p>
- Extension mapping, on the other hand, matches request URIs to the action
- servlet based on the fact that the URI ends with a period followed by a
- defined set of characters. For example, the JSP processing servlet is mapped
- to the <code>*.jsp</code> pattern so that it is called to process every
- JSP page that is requested. To use the <code>*.do</code> extension (which
- implies "do something"), the mapping entry would look like this:
+
+ <p>
+ which means that a request URI to match the <code>/logon</code> path
+ described earlier might look like this:
+ <pre>
+ http://www.mycompany.com/myapplication/execute/logon
+ </pre>
+ </p>
+
+ <p>
+ where <code>/myapplication</code> is the context path under which your
+ application is deployed.
+ </p>
+
+ <p>
+ Extension mapping, on the other hand, matches request URIs to the action
+ servlet based on the fact that the URI ends with a period followed by a
+ defined set of characters. For example, the JSP processing servlet is mapped
+ to the <code>*.jsp</code> pattern so that it is called to process every
+ JSP page that is requested. To use the <code>*.do</code> extension (which
+ implies "do something"), the mapping entry would look like this:
<pre>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</pre>
- </p>
-
- <p>
- and a request URI to match the <code>/logon</code> path described
- earlier might look like this:
- <pre>
- http://www.mycompany.com/myapplication/logon.do
- </pre>
- </p>
- </section>
-
- <section name="4.5.3 Configure the Struts Tag Library" href="dd_config_taglib">
-
- <p>
- Next, you must add an entry defining the Struts tag library. There are currently four
- taglibs that struts is packaged with.
- </p>
- <p>
- The struts-bean taglib contains tags useful in accessing
- beans and their properties, as well as defining new beans (based on these accesses) that are
- accessible to the remainder of the page via scripting variables and page scope attributes.
- Convenient mechanisms to create new beans based on the value of request cookies, headers,
- and parameters are also provided.
- </p>
- <p>
- The struts-html taglib contains tags used to create struts input forms, as well as other
- tags generally useful in the creation of HTML-based user interfaces.
- </p>
- <p>
- The struts-logic taglib contains tags that are useful in managing conditional generation
- of output text, looping over object collections for repetitive generation of output text,
- and application flow management.
- </p>
- <p>
- The struts-template taglib contains tags that define a template mechanism.
- </p>
-
- <p>
- Below is how you would define all taglibs for use within your application,
- in reality you would only specify the taglib's that your application will use:
-
+ </p>
+
+ <p>
+ and a request URI to match the <code>/logon</code> path described
+ earlier might look like this:
+ <pre>
+ http://www.mycompany.com/myapplication/logon.do
+ </pre>
+ </p>
+ </section>
+
+ <section name="4.5.3 Configure the Struts Tag Library" href="dd_config_taglib">
+
+ <p>
+ Next, you must add an entry defining the Struts tag library. There are currently four
+ taglibs that struts is packaged with.
+ </p>
+ <p>
+ The struts-bean taglib contains tags useful in accessing
+ beans and their properties, as well as defining new beans (based on these accesses) that are
+ accessible to the remainder of the page via scripting variables and page scope attributes.
+ Convenient mechanisms to create new beans based on the value of request cookies, headers,
+ and parameters are also provided.
+ </p>
+ <p>
+ The struts-html taglib contains tags used to create struts input forms, as well as other
+ tags generally useful in the creation of HTML-based user interfaces.
+ </p>
+ <p>
+ The struts-logic taglib contains tags that are useful in managing conditional generation
+ of output text, looping over object collections for repetitive generation of output text,
+ and application flow management.
+ </p>
+ <p>
+ The struts-template taglib contains tags that define a template mechanism.
+ </p>
+
+ <p>
+ Below is how you would define all taglibs for use within your application,
+ in reality you would only specify the taglib's that your application will use:
+
<pre>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
@@ -564,28 +567,28 @@
<taglib-location>/WEB-INF/struts-template.tld</taglib-location>
</taglib>
</pre>
- </p>
-
- <p>
- This tells the JSP system where to find the tag library descriptor
- for this library (in your application's WEB-INF directory, instead of
- out on the Internet somewhere).
- </p>
- </section>
-
- <section name="4.5.4 Add Struts Components To Your Application" href="config_add">
-
- <p>
- To use struts, you must copy the .tld files that you require into your
- WEB-INF directory, and copy struts.jar into your WEB-INF/lib directory.
- </p>
+ </p>
+
+ <p>
+ This tells the JSP system where to find the tag library descriptor
+ for this library (in your application's WEB-INF directory, instead of
+ out on the Internet somewhere).
+ </p>
+ </section>
+
+ <section name="4.5.4 Add Struts Components To Your Application" href="config_add">
+
+ <p>
+ To use struts, you must copy the .tld files that you require into your
+ WEB-INF directory, and copy struts.jar into your WEB-INF/lib directory.
+ </p>
<p>
Next: <a href="resources.html">Struts Resources</a>
</p>
- </section>
- </section>
- </chapter>
- </body>
+ </section>
+ </section>
+ </chapter>
+ </body>
</document>
-
-
+
+
diff --git a/src/doc/userGuide/building_model.xml b/src/doc/userGuide/building_model.xml
index 91018f85d..55377c2c1 100644
--- a/src/doc/userGuide/building_model.xml
+++ b/src/doc/userGuide/building_model.xml
@@ -60,8 +60,8 @@
</p>
<pre>
- MyCart mycart = new MyCart(...);
- request.setAttribute("cart", mycart);
+ MyCart mycart = new MyCart(...);
+ request.setAttribute("cart", mycart);
</pre>
<p>
@@ -79,16 +79,17 @@
<p>
Note: ActionForm beans are actually closer to the <i>View</i>
- than the <i>Model</i>
+ than the <i>Model</i>.
</p>
<p>
The Struts framework generally assumes that you have created an
<code>ActionForm</code> bean (that is, a Java class extending the
<code>ActionForm</code> class) for each input form required in your
application. If you define such beans in your <code>ActionMapping</code>
- configuration file (see "Building the Controller Components"), the Struts
- controller servlet will automatically perform the following services for
- you, before invoking the appropriate <code>Action</code> method:
+ configuration file (see "<a href="building_controller.html#config">
+ Building the Controller Components</a>"), the Struts controller servlet
+ will automatically perform the following services for you, before
+ invoking the appropriate <code>Action</code> method:
</p>
<ul>
@@ -128,13 +129,19 @@
might also want to provide further "business logic" validation as
part of your Action object. (See "Action Form Validation" for details.)
Of course, you can also ignore the ActionForm validation and provide
- your own in the Action object</li>
+ your own in the Action object.</li>
<li>Define a property (with associated <code>getXxx()</code> and
<code>setXxx()</code> methods) for each field that is present
in the form. The field name and property name must match according
to the usual JavaBeans conventions. For example, an input field named
<code>username</code> will cause the <code>setUsername()</code> method
to be called.</li>
+ <li>You may also place a bean instance on your form, and use nested property
+ references. For example, you might have a "customer" bean on your Action
+ Form, and then refer to the property "customer.name" in your JSP view.
+ This would correspond to the methods customer.getName() and
+ customer.setName(string Name) on your customer bean. See the Tag Library
+ Developer Guides for more about nested syntax.</li>
</ul>
<p>
@@ -215,15 +222,14 @@
<section name="2.6 Accessing Relational Databases" href="databases">
<p>
- Struts contains in it's mapping config file the ability to specify data sources.
- See <a href="building_controller.html#config">The Action Mappings Configuration File</a>
- for information on how to set up a datasource. Do that first.
+ Struts can define the datasources for an application from within its standard
+ configuration file. A simple JDBC connection pool is also provided. See <a
+ href="building_controller.html#config">The Action Mappings Configuration File</a>
+ section and the Utilities Developer Guide for details.
</p>
-
<p>
- After setting up your data source in the config file, most likely you'll want
- to retrieve a connection from it. This small example nested inside of an action's
- <code>perform()</code> method will show you how to do it:
+ After the datasource is defined, here is an example of establishing a connection
+ from within a Action perform method.
</p>
<p>
<pre>
@@ -232,7 +238,7 @@
HttpServletRequest request,
HttpServletResponse response) {
try {
- javax.sql.DataSource dataSource = getServlet().findDataSource(null);
+ DataSource dataSource = servlet.findDataSource(null);
Connection myConnection = dataSource.getConnection();
//do what you wish with myConnection
diff --git a/src/doc/userGuide/building_view.xml b/src/doc/userGuide/building_view.xml
index c17db3ce9..55e067c5c 100644
--- a/src/doc/userGuide/building_view.xml
+++ b/src/doc/userGuide/building_view.xml
@@ -169,7 +169,7 @@
<p>
A complete example of a login form will illustrate how Struts
makes dealing with forms much less painful than using straight HTML
- and standard JSP facilities. Consider the following page (from the
+ and standard JSP facilities. Consider the following page (based on the
example application included with Struts) named <code>logon.jsp</code>:
</p>
@@ -186,7 +186,7 @@
<html:errors/>
-<html:form action="logon.do">
+<html:form name="logonForm" action="logon.do">
<table border="0" width="100%">
<tr>
<th align="right">
@@ -263,7 +263,10 @@
This bean is used to provide initial values for all of the input
fields that have names matching the property names of the bean.
If an appropriate bean is not found, a new one will be created
- automatically, using the specified Java class name.</li>
+ automatically, using the specified Java class name. (The form bean name
+ can also be specified in the Struts configuration file, and then omitted
+ here. See "<a href="building_controller.html#config">The Action Mappings
+ Configuration File</a>" for details.)</li>
<li>The text tag renders an HTML
<code><input></code> element of type "text". In this case,
the number of character positions to occupy on the browser's screen
@@ -337,7 +340,7 @@ public class UploadForm extends ActionForm {
</p>
<p>
- Look at the <a href="api/index.html">javadocs</a> for FormFile to see the
+ Look at the <a href="../api/index.html">javadocs</a> for FormFile to see the
methods it exposes to manipulate files in file uploading. Also look at the
javadocs for ActionServlet and ActionMapping for the various parameters
you can specify to change how files are uploaded. Basically in your
@@ -425,7 +428,7 @@ public class UploadForm extends ActionForm {
<p>
The validate() method is called by the controller servlet after the bean
properties have been populated, but before the corresponding action class's
- <code>perform()</code> method is invoked. The <code>validate()</code> method
+ <code>perform()</code> method is invoked. The <code>validate()</code> method
has the following options:
</p>
@@ -437,11 +440,11 @@ public class UploadForm extends ActionForm {
<li>Perform the appropriate validations and find problems -- Return an ActionErrors
instance containing <code>ActionError</code>'s, which are classes that contain
the error message keys (into the application's
- <code>MessageResources</code> bundle) that should be displayed. The
+ <code>MessageResources</code> bundle) that should be displayed. The
controller servlet will store this array as a request attribute suitable
for use by the <code><html:errors></code> tag, and will forward
control back to the input form (identified by the <code>inputForm</code>
- property for this <code>ActionMapping</code>.</li>
+ property for this <code>ActionMapping</code>).</li>
</ul>
<p>
@@ -529,10 +532,10 @@ public class UploadForm extends ActionForm {
<ul>
<li>An <code><%@ include file="xxxxx" %></code> directive can include a file that contains
- java code or jsp tags. The code in the included file can even reference
- variables declared earlier in the outer jsp page. The code is inlined into
- the other jsp before it is compiled so it can definately contain more than
- just HTML.</li>
+ java code or jsp tags. The code in the included file can even reference
+ variables declared earlier in the outer jsp page. The code is inlined into
+ the other jsp before it is compiled so it can definately contain more than
+ just HTML.</li>
<li>The include <i>action</i> (<code><jsp:include page="xxxxx"
flush="true" /></code>) is processed at request time, and is handled
transparently by the server. Among other things, that means you
@@ -544,6 +547,10 @@ public class UploadForm extends ActionForm {
or the "id" argument, which represents a page context String variable to print
out to the jsp page.</li>
</ul>
+ <p>
+ Another approach to this would be to use the Struts Template Tag library. See the
+ Developer's Guide for details.
+ </p>
</section>
<section name="3.4.3 Image Rendering Components" href="image_rendering">
diff --git a/src/doc/userGuide/introduction.xml b/src/doc/userGuide/introduction.xml
index fc2d9a0f5..951ce7561 100644
--- a/src/doc/userGuide/introduction.xml
+++ b/src/doc/userGuide/introduction.xml
@@ -13,303 +13,298 @@
<chapter name="1. Introduction" href="introduction">
- <section name="1.1 Preface: Forward into the Past! (or a brief history of Struts)" href="preface">
+ <section name="1.1 Preface: Forward into the Past! (or a brief history of Struts)" href="preface">
- <p>
- When Java servlets were first invented, many programmers quickly realized that they were a
- Good Thing! They were faster and more powerful that standard CGI, portable, and infinitely
- extensible.
- </p>
-
- <p>
- But writing HTML to send to the browser in endless println() statements was tiresome and
- problematic. The answer to that was JavaServer Pages, which turned servlet writing inside-out.
- Now developers could easily mix HTML with Java Code, and have all the advantages of servlets.
- The sky was the limit!
- </p>
-
- <p>
- Java web applications quickly became "JSP-centric". This in and of itself was not a Bad
- Thing, but it did little to resolve the flow control and other problems endemic to web
- applications.
- </p>
-
- <p>Another model was clearly needed ...</p>
-
- <p>
- Many clever developers realized that JavaServer Pages AND servlets could be used <b>
- together</b> to deploy web applications. The servlets could help with the control-flow, and the
- JSPs could focus on the nasty business of writing HTML. In due course, using JSPs and servlets
- together became known as Model 2 (where using JSPs alone was Model 1).
- </p>
-
- <p>
- Of course, there is nothing new under the sun .. and many have been quick to point out that
- JSP's Model 2 follows SmallTalk's classic Model-View-Controller design pattern. It is now
- commonplace to use the terms Model 2 and MVC interchangeably.
- </p>
-
- <p>
- The Struts project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC
- framework to the Java community. In January 2001, Struts 1.0 was released ... Welcome to the
- future of Java development!
- </p>
-
- <p>
- If you are new to MVC and Model 2, be sure to read the Framework Overview in the next
- section. If you are an old hand, you might want to skim forward to "Mapping MVC Concepts to
- Stuts Components".
- </p>
- </section>
-
- <section name="1.2 The Model-View-Controller ('MVC') Design Pattern" href="mvc">
-
- <p>
- In the MVC design pattern, the application flow is controlled by a central <i>Controller</i>,
- which utilizes an implementation of the Mediator design pattern to delegate requests to the
- appropriate handler, which is tied with a <i>Model</i>. The Model is responsible for containing the
- application logic. The control is then forwarded to the appropriate <i>View</i> back through the
- Controller. The appropriate View which to forward the request to is acquired by resolving,
- from a configuration file or database, the logical name passed to the Controller. This provides
- a loose coupling of the View and Model within the application. The MVC implementation in Struts
- is sometimes also called "Model-2".
- </p>
-
- </section>
-
+ <p>
+ When Java servlets were first invented, many programmers quickly realized that they were a
+ Good Thing. They were faster and more powerful that standard CGI, portable, and infinitely
+ extensible.
+ </p>
+
+ <p>
+ But writing HTML to send to the browser in endless println() statements was tiresome and
+ problematic. The answer to that was JavaServer Pages, which turned servlet writing inside-out.
+ Now developers could easily mix HTML with Java code, and have all the advantages of servlets.
+ The sky was the limit!
+ </p>
+
+ <p>
+ Java web applications quickly became "JSP-centric". This in-and-of itself was not a Bad
+ Thing, but it did little to resolve flow control issues and other problems endemic to web
+ applications.
+ </p>
+
+ <p>Another model was clearly needed ...</p>
+
+ <p>
+ Many clever developers realized that JavaServer Pages AND servlets could be used <b>
+ together</b> to deploy web applications. The servlets could help with the control-flow, and the
+ JSPs could focus on the nasty business of writing HTML. In due course, using JSPs and servlets
+ together became known as Model 2 (where using JSPs alone was Model 1).
+ </p>
+
+ <p>
+ Of course, there is nothing new under the Sun ... and many have been quick to point out that
+ JSP's Model 2 follows SmallTalk's classic Model-View-Controller design pattern. It is now
+ commonplace to use the terms Model 2 and MVC interchangeably.
+ </p>
+
+ <p>
+ The Struts project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC
+ framework to the Java community. In January 2001, Struts 1.0 was released, and IOHO, Java
+ Model 2 development will never be quite the same.
+ </p>
+
+ </section>
+
+ <section name="1.2 The Model-View-Controller ('MVC') Design Pattern" href="mvc">
+
+ <p>
+ In the MVC design pattern, application flow is mediated by a central Controller. The
+ Controller delegates requests to an appropriate handler. The handlers are tied to a Model,
+ which act as an adapter between the request and the Model. The Model represents, or
+ encapsulates, an application's business logic or state. Control is usually then forwarded
+ back through the Controller to the appropriate View. The forwarding can be determined by
+ consulting a set of mappings, usually loaded from a database or configuration file. This
+ provides a loose coupling between the View and Model, which can make an application
+ significantly easier to create and maintain.
+ </p>
+
+ </section>
+
<section name="1.3 Struts Framework Overview" href="overview">
- <p>
- True to the Model-View-Controller design pattern, Struts applications have three
- major components: a servlet controller, JavaServer pages, and the application's
- business logic (or the "model"). Let's step through how this all fits together.</p>
- <p>
- The controller bundles and routes HTTP requests to other objects in the framework,
- including JavaServer Pages. When initialized, the controller parses a configuration
- resource file. The configuration resource defines (among other things) the action
- mappings for the application. The controller uses these mappings to turn HTTP
- requests into application actions.
- </p>
-
- <p>
- At a minimum, a mapping must specify (1) a request path and (2) the object
- type to act upon the request. The action object can handle the request and respond
- to the client (usually a Web browser), or indicate that control should be forwarded
- to another action. For example, if a login succeeds, a loginAction object may wish
- to forward control to a mainMenu action.
- </p>
-
- <p>
- Action objects are linked to the application's controller, and so have access
- to that servlet's methods. When forwarding control, an object can indirectly
- forward one or more shared objects, including JavaBeans, by placing them in one
- of the standard collections shared by Java servlets.
- </p>
-
- <p>
- An action object can create a shopping cart bean, add an item to the
- cart, place the bean in the session collection, and then forward control to
- another action -- that may use a JSP to display the contents of the user's cart.
- Since each client has their own session, they will each also have their own
- shopping cart. In a Struts application, most of the business logic can be
- represented using JavaBeans.
- </p>
-
- <p>
- JavaBeans can also be used to manage input forms. A key problem in designing
- Web applications is retaining and validating what a user has entered between
- requests. With Struts, you can easily store the data for a input form in a form
- bean. The bean is saved in one of the standard, shared context collections,
- so that it can be used by other objects, especially the action object.
- </p>
-
- <p>
- The form bean can be used by a JSP to collect data from the user ... by an
- action object to validate the user entered ... and then by the JSP again to
- re-populate the form fields. In the case of validation errors, Struts has a
- shared mechanism for raising and displaying error messages.
- </p>
-
- <p>
- A Struts form bean is defined in the configuration resource and linked to an action
- mapping using a common property name. When a request calls for an action that uses
- a form bean, the controller servlet either retrieves or creates the form bean, and
- passes it to the action object. The action object can then check the contents of
- the form bean before its input form is displayed, and also queue messages to be
- handled by the form. When ready, the action object can return control with a
- forwarding to its input form, usually a JSP. The controller can then respond to
- the HTTP request and direct the client to the Java Server Page.
- </p>
-
- <p>
- The Struts framework includes custom tags that can automatically populate
- fields from a form bean. The only thing most JavaServer Pages need to know
- about the rest of the framework is the proper field names and where to submit
- the form. Components like the messages set by the action object can be output
- using a single custom tag. Other application-specific tags can also be defined
- to hide implementation details from the JSPs.
- </p>
-
- <p>
- The custom tags in the Struts framework are designed to use the
- internationalization features built into the Java platform. All the field labels
- and messages can be retrieved from a message resource, and Java can
- automatically provide the correct resource for a client's country and language.
- To provide messages for another language, simply add another resource file.
- </p>
-
- <p>
- Internationalism aside, other benefits to this approach are consistent labeling
- between forms, and the ability to review all labels and messages from a central
- location.
- </p>
-
- <p>
- For the simplest applications, an action object can handle the business logic
- associated with a request. However, in most cases, an action object should pass
- the request to another object, usually a JavaBean. To allow resuse on other
- platforms, business-logic JavaBeans should not refer to any Web application
- objects. The action object should translate needed details from the HTTP request
- and pass those along to the business-logic beans as regular Java variables.
- </p>
-
- <p>
- In a database application, the business-logic beans might connect to and
- query the database and return the result set back to the action's servlet ... to
- be stored in a form bean ... and then displayed by the JSP. Neither the action's
- servlet nor the JSP need to know (or care) where the result set comes from.
- </p>
-
- <p>
- The rest of this Users Guide explains the various Struts components in greater
- detail. The Struts release also includes several Developer Guides covering
- various aspects of the frameworks, along with sample applications,
- the standard JavaDoc API, and, of course, the complete source code!
- </p>
-
- <p>
- Struts is distributed under the Apache Software Foundation license. The code
- is copyrighted, but is free to use in any application. See the ASF license for
- other specifics.
- </p>
-
- </section>
+ <p>
+ True to the Model-View-Controller design pattern, Struts applications have three
+ major components: a servlet controller, JavaServer pages, and the application's
+ business logic (or the "model"). Let's step through how this all fits together.</p>
+ <p>
+ The controller bundles and routes HTTP requests to other objects in the framework,
+ including JavaServer Pages. When initialized, the controller parses a configuration
+ resource file. The configuration resource defines (among other things) the action
+ mappings for the application. The controller uses these mappings to turn HTTP
+ requests into application actions.
+ </p>
+
+ <p>
+ At a minimum, a mapping must specify (1) a request path and (2) the object
+ type to act upon the request. The action object can handle the request and respond
+ to the client (usually a Web browser), or indicate that control should be forwarded
+ to another action. For example, if a login succeeds, a loginAction object may wish
+ to forward control to a mainMenu action.
+ </p>
+
+ <p>
+ Action objects are linked to the application's controller, and so have access
+ to that servlet's methods. When forwarding control, an object can indirectly
+ forward one or more shared objects, including JavaBeans, by placing them in one
+ of the standard collections shared by Java servlets.
+ </p>
+
+ <p>
+ An action object can create a shopping cart bean, add an item to the
+ cart, place the bean in the session collection, and then forward control to
+ another action -- that may use a JSP to display the contents of the user's cart.
+ Since each client has their own session, they will each also have their own
+ shopping cart. In a Struts application, most of the business logic can be
+ represented using JavaBeans.
+ </p>
+
+ <p>
+ JavaBeans can also be used to manage input forms. A key problem in designing
+ Web applications is retaining and validating what a user has entered between
+ requests. With Struts, you can easily store the data for a input form in a form
+ bean. The bean is saved in one of the standard, shared context collections,
+ so that it can be used by other objects, especially the action object.
+ </p>
+
+ <p>
+ The form bean can be used by a JSP to collect data from the user ... by an
+ action object to validate the user entered ... and then by the JSP again to
+ re-populate the form fields. In the case of validation errors, Struts has a
+ shared mechanism for raising and displaying error messages.
+ </p>
+
+ <p>
+ A Struts form bean is defined in the configuration resource and linked to an action
+ mapping using a common property name. When a request calls for an action that uses
+ a form bean, the controller servlet either retrieves or creates the form bean, and
+ passes it to the action object. The action object can then check the contents of
+ the form bean before its input form is displayed, and also queue messages to be
+ handled by the form. When ready, the action object can return control with a
+ forwarding to its input form, usually a JSP. The controller can then respond to
+ the HTTP request and direct the client to the Java Server Page.
+ </p>
+
+ <p>
+ The Struts framework includes custom tags that can automatically populate
+ fields from a form bean. The only thing most JavaServer Pages need to know
+ about the rest of the framework is the proper field names and where to submit
+ the form. Components like the messages set by the action object can be output
+ using a single custom tag. Other application-specific tags can also be defined
+ to hide implementation details from the JSPs.
+ </p>
+
+ <p>
+ The custom tags in the Struts framework are designed to use the
+ internationalization features built into the Java platform. All the field labels
+ and messages can be retrieved from a message resource, and Java can
+ automatically provide the correct resource for a client's country and language.
+ To provide messages for another language, simply add another resource file.
+ </p>
+
+ <p>
+ Internationalism aside, other benefits to this approach are consistent labeling
+ between forms, and the ability to review all labels and messages from a central
+ location.
+ </p>
+
+ <p>
+ For the simplest applications, an action object can handle the business logic
+ associated with a request. However, in most cases, an action object should pass
+ the request to another object, usually a JavaBean. To allow resuse on other
+ platforms, business-logic JavaBeans should not refer to any Web application
+ objects. The action object should translate needed details from the HTTP request
+ and pass those along to the business-logic beans as regular Java variables.
+ </p>
+
+ <p>
+ In a database application, the business-logic beans might connect to and
+ query the database and return the result set back to the action's servlet ... to
+ be stored in a form bean ... and then displayed by the JSP. Neither the action's
+ servlet nor the JSP need to know (or care) where the result set comes from.
+ </p>
+
+ <p>
+ The rest of this Users Guide explains the various Struts components in greater
+ detail. The Struts release also includes several Developer Guides covering
+ various aspects of the frameworks, along with sample applications,
+ the standard JavaDoc API, and, of course, the complete source code!
+ </p>
+
+ <p>
+ Struts is distributed under the Apache Software Foundation license. The code
+ is copyrighted, but is free to use in any application. See the
+ <a href="http://www.apache.org/LICENSE-1.1">ASF license</a> for specifics.
+ </p>
+
+ </section>
- <section name="1.4 The Model: System State and Business Logic JavaBeans" href="modelConcepts">
-
- <p>
- The <i>Model</i> portion of an MVC-based system can be subdivided into
- concepts -- the internal state of the system, and the actions that can be
- taken to change that state. In grammatical terms, we might think about
- state information as <i>nouns</i> (things) and actions as <i>verbs</i>
- (changes to the state of those things).
- </p>
-
- <p>
- Generally, your application will represent the internal state of the
- system as a set of one or more JavaBeans, with properties that represent
- the details of the state. Depending on your application's complexity,
- these beans may be self contained (and know how to save their state
- information persistently somehow), or they may be facades that know
- how to retrieve information from external sources (such as a database)
- when it is requested. Entity Enterprise JavaBeans (EJBs) are also commonly
- used to represent internal state.
- </p>
-
- <p>
- Large-scale applications will often represent the business logic actions
- that are possible in a system as methods that can be called on the beans
- maintaining the state information. For example, you might have a shopping
- cart bean, stored in session scope for each current user, with properties
- that represent the current set of items that the user has decided to
- purchase. This bean might also have a <code>checkOut()</code> method
- that authorizes the user's credit card, and sends the order to the
- warehouse to be picked and shipped. Other systems will represent the
- available actions separately, perhaps as Session Enterprise JavaBeans
- (EJBs).
- </p>
-
- <p>
- In some smaller scale applications, on the other hand, the available
- actions might be embedded within the <code>Action</code> classes that are
- part of the Controller role. This is appropriate when the logic is very
- simple, or where reuse of the business logic in other environments is not
- contemplated. The Struts framework supports any of these approaches, but
- recommends separating the business logic ("what to do") from the role that
- <code>Action</code> classes play ("deciding what to do").
- </p>
- </section>
+ <section name="1.4 The Model: System State and Business Logic JavaBeans" href="modelConcepts">
+
+ <p>
+ The <i>Model</i> portion of an MVC-based system can be subdivided into
+ concepts -- the internal state of the system, and the actions that can be
+ taken to change that state. In grammatical terms, we might think about
+ state information as <i>nouns</i> (things) and actions as <i>verbs</i>
+ (changes to the state of those things).
+ </p>
+
+ <p>
+ Generally, your application will represent the internal state of the
+ system as a set of one or more JavaBeans, with properties that represent
+ the details of the state. Depending on your application's complexity,
+ these beans may be self contained (and know how to save their state
+ information persistently somehow), or they may be facades that know
+ how to retrieve information from external sources (such as a database)
+ when it is requested. Entity Enterprise JavaBeans (EJBs) are also commonly
+ used to represent internal state.
+ </p>
+
+ <p>
+ Large-scale applications will often represent the business logic actions
+ that are possible in a system as methods that can be called on the beans
+ maintaining the state information. For example, you might have a shopping
+ cart bean, stored in session scope for each current user, with properties
+ that represent the current set of items that the user has decided to
+ purchase. This bean might also have a <code>checkOut()</code> method
+ that authorizes the user's credit card, and sends the order to the
+ warehouse to be picked and shipped. Other systems will represent the
+ available actions separately, perhaps as Session Enterprise JavaBeans
+ (EJBs).
+ </p>
+
+ <p>
+ In some smaller scale applications, on the other hand, the available
+ actions might be embedded within the <code>Action</code> classes that are
+ part of the Controller role. This is appropriate when the logic is very
+ simple, or where reuse of the business logic in other environments is not
+ contemplated. The Struts framework supports any of these approaches, but
+ recommends separating the business logic ("what to do") from the role that
+ <code>Action</code> classes play ("deciding what to do").
+ </p>
+ </section>
- <section name="1.5 The View: JSP Pages and Presentation Components" href="presentationConcepts">
-
- <p>
- The <i>View</i> portion of a Struts-based application is generally
- constructed using JavaServer Pages (JSP) technology. JSP pages can
- contain static HTML (or XML) text called "template text", plus the
- ability to insert dynamic content based on the interpretation (at page
- request time) of special action tags. The JSP environment includes a
- set of standard action tags, such as <code><jsp:useBean></code>
- whose purpose is described in the JavaServer Pages Specification. In
- addition, there is a standard facility to define your own tags, which
- are organized into "custom tag libraries."
- </p>
-
- <p>
- Struts includes an extensive custom tag library that facilitates
- creating user interfaces that are fully internationalized, and that
- interact gracefully with <code>ActionForm</code> beans that are part
- of the <i>Model</i> portion of the system. The use of these tags is
- discussed in detail later.
- </p>
-
- <p>
- In addition to JSP pages and the action and custom tags they contain,
- it is often necessary for business objects to be able to render
- themselves in HTML (or XML), based on their current state at request time.
- The rendered output from such objects can be easily included in a
- resulting JSP page by using the <code><jsp:include></code>
- standard action tag.
- </p>
- </section>
-
- <section name="1.6 The Controller: ActionServlet and ActionMapping" href="controllerConcepts">
-
- <p>
- The <i>Controller</i> portion of the application is focused on receiving
- requests from the client (typically a user running a web browser), deciding
- what business logic function is to be performed, and then delegating
- responsibility for producing the next phase of the user interface to
- an appropriate View component. In Struts, the primary component of the
- Controller is a servlet of class <code>ActionServlet</code>. This servlet
- is configured by defining a set of mappings (described by a Java class
- <code>ActionMapping</code>). Each mapping defines a <code>path</code>
- that is matched against the request URI of the incoming request, and the
- fully qualified class name of an <code>Action</code> class (that is, a
- Java class extending the <code>Action</code> class) which is
- responsible for performing the desired business logic, and then dispatching
- control to the appropriate View component to create the response.
- </p>
-
- <p>
- Struts also supports the ability to use <code>ActionMapping</code>
- classes that have additional properties beyond the standard ones required
- to operate the framework. This allows you to store additional information
- specific to your application, but still utilize the remaining features of
- the framework. In addition, Struts lets you define logical "names" to which
- control should be forwarded so that an action method can ask for the
- "Main Menu" page (for example), without knowing what the actual name of the
- corresponding JSP page is. These features greatly assist you in separating
- the control logic (what do I do next) with the view logic (what is the name
- of the corresponding page).
- </p>
-
- <p align="center">
- Next: <a href="building_model.html">Building Model Components</a>
- </p>
- </section>
-
-
- </chapter>
- </body>
+ <section name="1.5 The View: JSP Pages and Presentation Components" href="presentationConcepts">
+
+ <p>
+ The <i>View</i> portion of a Struts-based application is generally
+ constructed using JavaServer Pages (JSP) technology. JSP pages can
+ contain static HTML (or XML) text called "template text", plus the
+ ability to insert dynamic content based on the interpretation (at page
+ request time) of special action tags. The JSP environment includes a
+ set of standard action tags, such as <code><jsp:useBean></code>
+ whose purpose is described in the JavaServer Pages Specification. In
+ addition, there is a standard facility to define your own tags, which
+ are organized into "custom tag libraries."
+ </p>
+
+ <p>
+ Struts includes an extensive custom tag library that facilitates
+ creating user interfaces that are fully internationalized, and that
+ interact gracefully with <code>ActionForm</code> beans that are part
+ of the <i>Model</i> portion of the system. The use of these tags is
+ discussed in detail later.
+ </p>
+
+ <p>
+ In addition to JSP pages and the action and custom tags they contain,
+ it is often necessary for business objects to be able to render
+ themselves in HTML (or XML), based on their current state at request time.
+ The rendered output from such objects can be easily included in a
+ resulting JSP page by using the <code><jsp:include></code>
+ standard action tag.
+ </p>
+ </section>
+
+ <section name="1.6 The Controller: ActionServlet and ActionMapping" href="controllerConcepts">
+
+ <p>
+ The <i>Controller</i> portion of the application is focused on receiving
+ requests from the client (typically a user running a web browser), deciding
+ what business logic function is to be performed, and then delegating
+ responsibility for producing the next phase of the user interface to
+ an appropriate View component. In Struts, the primary component of the
+ Controller is a servlet of class <code>ActionServlet</code>. This servlet
+ is configured by defining a set of mappings (described by a Java class
+ <code>ActionMapping</code>). Each mapping defines a <code>path</code>
+ that is matched against the request URI of the incoming request, and the
+ fully qualified class name of an <code>Action</code> class (that is, a
+ Java class extending the <code>Action</code> class) which is
+ responsible for performing the desired business logic, and then dispatching
+ control to the appropriate View component to create the response.
+ </p>
+
+ <p>
+ Struts also supports the ability to use <code>ActionMapping</code>
+ classes that have additional properties beyond the standard ones required
+ to operate the framework. This allows you to store additional information
+ specific to your application, but still utilize the remaining features of
+ the framework. In addition, Struts lets you define logical "names" to which
+ control should be forwarded so that an action method can ask for the
+ "Main Menu" page (for example), without knowing what the actual name of the
+ corresponding JSP page is. These features greatly assist you in separating
+ the control logic (what do I do next) with the view logic (what is the name
+ of the corresponding page).
+ </p>
+
+ <p align="center">
+ Next: <a href="building_model.html">Building Model Components</a>
+ </p>
+ </section>
+
+
+ </chapter>
+ </body>
</document>
diff --git a/src/doc/userGuide/resources.xml b/src/doc/userGuide/resources.xml
index 1b36906b0..19f8e4069 100644
--- a/src/doc/userGuide/resources.xml
+++ b/src/doc/userGuide/resources.xml
@@ -8,59 +8,51 @@
<body>
- <chapter name="Struts Resources" href="resources">
-
- <section name="Struts Tutorials" href="tutorials">
-
- <p>
- <u>Welcome to the Struts Framework</u>, <a href="http://www.bluestone.com">Bluestone Software</a><br />
- <a href="http://developer.bluestone.com/scripts/SaISAPI.dll/Gallery.class/demos/trailMaps/index.jsp">http://developer.bluestone.com/scripts/SaISAPI.dll/Gallery.class/demos/trailMaps/index.jsp</a>
- </p>
-
- <p>
- <u>A Walking Tour of the Struts Example Application</u>, <a href="mailto:[email protected]">Ted Husted</a><br />
- <a href="http://www.husted.com/about/struts/tour.htm">http://www.husted.com/about/struts/tour.htm</a>
- </p>
-
- <p>
- <u>Struts with a Fruit Glaze</u>, <a href="mailto:[email protected]">Ted Husted</a><br />
- <a href="http://www.husted.com/about/struts/husted-coreservlets-jdbc.zip">http://www.husted.com/about/struts/husted-coreservlets-jdbc.zip</a>
- </p>
-
- <p>
- <u>About Struts - Husted dot Com</u>, <a href="mailto:[email protected]">Ted Husted</a><br />
- <a href="http://www.husted.com/about/struts/">Struts Resources</a>
- </p>
- </section>
-
- <section name="Struts Articles" href="articles">
-
- <p>
- <u>Strut Your Stuff With JSP Tags</u>, <a href="[email protected]">Thor Kristmundsson</a><br />
- <a href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1201-struts.html">http://www.javaworld.com/javaworld/jw-12-2000/jw-1201-struts.html</a>
- </p>
-
- <p>
- <u>Using the Struts Framework to Develop a Message Board</u>, Maneesh Sahu<br />
- <a href="http://informit.com/books/authors/author_template/index.asp?authorid={A08A00B0-71BB-42DB-9B29-08879A9A7ABE}&t={94AE5B48-1D7D-462A-A4A6-83CE19EC0705}&n={4641FAF9-E21F-4902-8F6E-0C8FAF114C62}">Author Page (article requires registration with informit.com)</a>
- </p>
+ <chapter name="Struts Resources" href="resources">
+
+ <section name="Struts Tutorials" href="tutorials">
+
+ <p>
+ <b>Welcome to the Struts Framework</b>, <a href="http://www.bluestone.com">Bluestone Software</a><br />
+ <a href="http://developer.bluestone.com/scripts/SaISAPI.dll/Gallery.class/demos/trailMaps/index.jsp">http://developer.bluestone.com/scripts/SaISAPI.dll/Gallery.class/demos/trailMaps/index.jsp</a>
+ </p>
+
+ <p>
+ <b>About Struts</b>, <a href="mailto:[email protected]">Husted dot Com</a><br />
+ <a href="http://www.husted.com/about/struts/">http://www.husted.com/about/struts/</a>
+ </p>
+ </section>
+
+ <section name="Struts Articles" href="articles">
+
+ <p>
+ <b>Strut Your Stuff With JSP Tags</b>, <a href="mailto:[email protected]">Thor Kristmundsson</a><br />
+ <a href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1201-struts.html">http://www.javaworld.com/javaworld/jw-12-2000/jw-1201-struts.html</a>
+ </p>
+
+ <p>
+ <b>Using the Struts Framework to Develop a Message Board</b>, Maneesh Sahu<br />
+ <a href="http://informit.com/books/authors/author_template/index.asp?authorid={A08A00B0-71BB-42DB-9B29-08879A9A7ABE}&t={94AE5B48-1D7D-462A-A4A6-83CE19EC0705}&n={4641FAF9-E21F-4902-8F6E-0C8FAF114C62}">Author Page (article requires registration with informit.com)</a>
+ </p>
+
+ <p>
+ <b>JSP templates</b>, <a href="mailto:[email protected]">David Geary</a><br />
+ <a href="http://www.javaworld.com/javaworld/jw-09-2000/jw-0915-jspweb_p.html">http://www.javaworld.com/javaworld/jw-09-2000/jw-0915-jspweb_p.html</a>
+ </p>
- <p>
- <u>JSP templates</u>, <a href="[email protected]">David Geary</a><br />
- <a href="http://www.javaworld.com/javaworld/jw-09-2000/jw-0915-jspweb_p.html">http://www.javaworld.com/javaworld/jw-09-2000/jw-0915-jspweb_p.html</a>
- </p>
- </section>
-
- <section name="Struts Mailing List Archives" href="archives">
-
- <p>
- <u>covalent.net</u>, <a href="http://archive.covalent.net/">http://archive.covalent.net</a>
- </p>
- </section>
-
-
- </chapter>
-
-
+ </section>
+
+ <section name="Struts Mailing List Archives" href="archives">
+
+ <p>
+ <a href="http://archive.covalent.net/"><b>covalent.net</b></a><br />
+ <a href="http://mail-archive.com/"><b>mail-archive.com</b></a>
+ </p>
+ </section>
+
+
+ </chapter>
+
+
</body>
</document>
\ No newline at end of file
| 0 | 3 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
8056f6ea913ff717dcbdcca6d5fcb8f0946c10a0
|
Fix line ends, in preparation for other changes.
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48660 13f79535-47bb-0310-9956-ffa450edef68
|
commit 8056f6ea913ff717dcbdcca6d5fcb8f0946c10a0
Author: Martin Cooper <[email protected]>
Date: Fri Oct 19 05:15:16 2001 +0000
Fix line ends, in preparation for other changes.
git-svn-id: https://svn.apache.org/repos/asf/struts/trunk@48660 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/doc/userGuide/introduction.xml b/doc/userGuide/introduction.xml
index 7b9cc2612..69e4a5867 100644
--- a/doc/userGuide/introduction.xml
+++ b/doc/userGuide/introduction.xml
@@ -1,311 +1,311 @@
-<?xml version="1.0"?>
-<document url="./introduction.xml">
-
- <properties>
- <author>Craig R. McClanahan</author>
- <author>Mike Schachter</author>
- <author>Larry McCay</author>
- <author>Ted Husted</author>
- <title>The Struts User's Guide - Introduction</title>
- </properties>
-
- <body>
-
- <chapter name="1. Introduction" href="introduction">
-
- <section name="1.1 Preface: Forward into the Past! (or a brief history of Struts)" href="preface">
-
- <p>
- When Java servlets were first invented, many programmers quickly realized that they were a
- Good Thing. They were faster and more powerful that standard CGI, portable, and infinitely
- extensible.
- </p>
-
- <p>
- But writing HTML to send to the browser in endless println() statements was tiresome and
- problematic. The answer to that was JavaServer Pages, which turned servlet writing inside-out.
- Now developers could easily mix HTML with Java code, and have all the advantages of servlets.
- The sky was the limit!
- </p>
-
- <p>
- Java web applications quickly became "JSP-centric". This in-and-of itself was not a Bad
- Thing, but it did little to resolve flow control issues and other problems endemic to web
- applications.
- </p>
-
- <p>Another model was clearly needed ...</p>
-
- <p>
- Many clever developers realized that JavaServer Pages AND servlets could be used <b>
- together</b> to deploy web applications. The servlets could help with the control-flow, and the
- JSPs could focus on the nasty business of writing HTML. In due course, using JSPs and servlets
- together became known as Model 2 (where using JSPs alone was Model 1).
- </p>
-
- <p>
- Of course, there is nothing new under the Sun ... and many have been quick to point out that
- JSP's Model 2 follows SmallTalk's classic Model-View-Controller design pattern. It is now
- commonplace to use the terms Model 2 and MVC interchangeably.
- </p>
-
- <p>
- The Struts project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC
- framework to the Java community. In July 2001, Struts 1.0 was released, and IOHO, Java
- Model 2 development will never be quite the same.
- </p>
-
- </section>
-
- <section name="1.2 The Model-View-Controller ('MVC') Design Pattern" href="mvc">
-
- <p>
- In the MVC design pattern, application flow is mediated by a central Controller. The
- Controller delegates requests to an appropriate handler. The handlers are tied to a Model,
- which act as an adapter between the request and the Model. The Model represents, or
- encapsulates, an application's business logic or state. Control is usually then forwarded
- back through the Controller to the appropriate View. The forwarding can be determined by
- consulting a set of mappings, usually loaded from a database or configuration file. This
- provides a loose coupling between the View and Model, which can make an application
- significantly easier to create and maintain.
- </p>
-
- </section>
-
-
- <section name="1.3 Struts Framework Overview" href="overview">
-
- <p>
- True to the Model-View-Controller design pattern, Struts applications have three
- major components: a servlet controller, JavaServer pages (the "view"), and the
- application's business logic (or the "model"). Let's step through how this all
- fits together.</p>
- <p>
- The controller bundles and routes HTTP requests to other objects in the framework,
- including JavaServer Pages. When initialized, the controller parses a configuration
- resource file. The configuration resource defines (among other things) the action
- mappings for the application. The controller uses these mappings to turn HTTP
- requests into application actions.
- </p>
-
- <p>
- At a minimum, a mapping must specify (1) a request path and (2) the object
- type to act upon the request. The action object can handle the request and respond
- to the client (usually a Web browser), or indicate that control should be forwarded
- to another action. For example, if a login succeeds, a loginAction object may wish
- to forward control to a mainMenu action.
- </p>
-
- <p>
- Action objects are linked to the application's controller, and so have access
- to that servlet's methods. When forwarding control, an object can indirectly
- forward one or more shared objects, including JavaBeans, by placing them in one
- of the standard collections shared by Java servlets.
- </p>
-
- <p>
- An action object can create a shopping cart bean, add an item to the
- cart, place the bean in the session collection, and then forward control to
- another action -- that may use a JSP to display the contents of the user's cart.
- Since each client has their own session, they will each also have their own
- shopping cart. In a Struts application, most of the business logic can be
- represented using JavaBeans.
- </p>
-
- <p>
- JavaBeans can also be used to manage input forms. A key problem in designing
- Web applications is retaining and validating what a user has entered between
- requests. With Struts, you can easily store the data for a input form in a form
- bean. The bean is saved in one of the standard, shared context collections,
- so that it can be used by other objects, especially the action object.
- </p>
-
- <p>
- The form bean can be used by a JSP to collect data from the user ... by an
- action object to validate the user-entered data ... and then by the JSP again to
- re-populate the form fields. In the case of validation errors, Struts has a
- shared mechanism for raising and displaying error messages.
- </p>
-
- <p>
- A Struts form bean is defined in the configuration resource and linked to an action
- mapping using a common property name. When a request calls for an action that uses
- a form bean, the controller servlet either retrieves or creates the form bean, and
- passes it to the action object. The action object can then check the contents of
- the form bean before its input form is displayed, and also queue messages to be
- handled by the form. When ready, the action object can return control with a
- forwarding to its input form, usually a JSP. The controller can then respond to
- the HTTP request and direct the client to the Java Server Page.
- </p>
-
- <p>
- The Struts framework includes custom tags that can automatically populate
- fields from a form bean. The only thing most JavaServer Pages need to know
- about the rest of the framework is the proper field names and where to submit
- the form. Components like the messages set by the action object can be output
- using a single custom tag. Other application-specific tags can also be defined
- to hide implementation details from the JSPs.
- </p>
-
- <p>
- The custom tags in the Struts framework are designed to use the
- internationalization features built into the Java platform. All the field labels
- and messages can be retrieved from a message resource, and Java can
- automatically provide the correct resource for a client's country and language.
- To provide messages for another language, simply add another resource file.
- </p>
-
- <p>
- Internationalism aside, other benefits to this approach are consistent labeling
- between forms, and the ability to review all labels and messages from a central
- location.
- </p>
-
- <p>
- For the simplest applications, an action object can handle the business logic
- associated with a request. However, in most cases, an action object should pass
- the request to another object, usually a JavaBean. To allow reuse on other
- platforms, business-logic JavaBeans should not refer to any Web application
- objects. The action object should translate needed details from the HTTP request
- and pass those along to the business-logic beans as regular Java variables.
- </p>
-
- <p>
- In a database application, the business-logic beans might connect to and
- query the database and return the result set back to the action's servlet ... to
- be stored in a form bean ... and then displayed by the JSP. Neither the action's
- servlet nor the JSP need to know (or care) where the result set comes from.
- </p>
-
- <p>
- The rest of this Users Guide explains the various Struts components in greater
- detail. The Struts release also includes several Developer Guides covering
- various aspects of the frameworks, along with sample applications,
- the standard JavaDoc API, and, of course, the complete source code!
- </p>
-
- <p>
- Struts is distributed under the Apache Software Foundation license. The code
- is copyrighted, but is free to use in any application. See the
- <a href="http://www.apache.org/LICENSE-1.1">ASF license</a> for specifics.
- </p>
-
- </section>
-
- <section name="1.4 The Model: System State and Business Logic JavaBeans" href="modelConcepts">
-
- <p>
- The <i>Model</i> portion of an MVC-based system can be subdivided into
- concepts -- the internal state of the system, and the actions that can be
- taken to change that state. In grammatical terms, we might think about
- state information as <i>nouns</i> (things) and actions as <i>verbs</i>
- (changes to the state of those things).
- </p>
-
- <p>
- Generally, your application will represent the internal state of the
- system as a set of one or more JavaBeans, with properties that represent
- the details of the state. Depending on your application's complexity,
- these beans may be self contained (and know how to save their state
- information persistently somehow), or they may be facades that know
- how to retrieve information from external sources (such as a database)
- when it is requested. Entity Enterprise JavaBeans (EJBs) are also commonly
- used to represent internal state.
- </p>
-
- <p>
- Large-scale applications will often represent the business logic actions
- that are possible in a system as methods that can be called on the beans
- maintaining the state information. For example, you might have a shopping
- cart bean, stored in session scope for each current user, with properties
- that represent the current set of items that the user has decided to
- purchase. This bean might also have a <code>checkOut()</code> method
- that authorizes the user's credit card, and sends the order to the
- warehouse to be picked and shipped. Other systems will represent the
- available actions separately, perhaps as Session Enterprise JavaBeans
- (EJBs).
- </p>
-
- <p>
- In some smaller scale applications, on the other hand, the available
- actions might be embedded within the <code>Action</code> classes that are
- part of the Controller role. This is appropriate when the logic is very
- simple, or where reuse of the business logic in other environments is not
- contemplated. The Struts framework supports any of these approaches, but
- recommends separating the business logic ("what to do") from the role that
- <code>Action</code> classes play ("deciding what to do").
- </p>
- </section>
-
- <section name="1.5 The View: JSP Pages and Presentation Components" href="presentationConcepts">
-
- <p>
- The <i>View</i> portion of a Struts-based application is generally
- constructed using JavaServer Pages (JSP) technology. JSP pages can
- contain static HTML (or XML) text called "template text", plus the
- ability to insert dynamic content based on the interpretation (at page
- request time) of special action tags. The JSP environment includes a
- set of standard action tags, such as <code><jsp:useBean></code>
- whose purpose is described in the JavaServer Pages Specification. In
- addition, there is a standard facility to define your own tags, which
- are organized into "custom tag libraries."
- </p>
-
- <p>
- Struts includes an extensive custom tag library that facilitates
- creating user interfaces that are fully internationalized, and that
- interact gracefully with <code>ActionForm</code> beans that are part
- of the <i>Model</i> portion of the system. The use of these tags is
- discussed in detail later.
- </p>
-
- <p>
- In addition to JSP pages and the action and custom tags they contain,
- it is often necessary for business objects to be able to render
- themselves in HTML (or XML), based on their current state at request time.
- The rendered output from such objects can be easily included in a
- resulting JSP page by using the <code><jsp:include></code>
- standard action tag.
- </p>
- </section>
-
- <section name="1.6 The Controller: ActionServlet and ActionMapping" href="controllerConcepts">
-
- <p>
- The <i>Controller</i> portion of the application is focused on receiving
- requests from the client (typically a user running a web browser), deciding
- what business logic function is to be performed, and then delegating
- responsibility for producing the next phase of the user interface to
- an appropriate View component. In Struts, the primary component of the
- Controller is a servlet of class <code>ActionServlet</code>. This servlet
- is configured by defining a set of mappings (described by a Java class
- <code>ActionMapping</code>). Each mapping defines a <code>path</code>
- that is matched against the request URI of the incoming request, and the
- fully qualified class name of an <code>Action</code> class (that is, a
- Java class extending the <code>Action</code> class) which is
- responsible for performing the desired business logic, and then dispatching
- control to the appropriate View component to create the response.
- </p>
-
- <p>
- Struts also supports the ability to use <code>ActionMapping</code>
- classes that have additional properties beyond the standard ones required
- to operate the framework. This allows you to store additional information
- specific to your application, but still utilize the remaining features of
- the framework. In addition, Struts lets you define logical "names" to which
- control should be forwarded so that an action method can ask for the
- "Main Menu" page (for example), without knowing what the actual name of the
- corresponding JSP page is. These features greatly assist you in separating
- the control logic (what do I do next) with the view logic (what is the name
- of the corresponding page).
- </p>
-
- <p align="center">
- Next: <a href="building_model.html">Building Model Components</a>
- </p>
- </section>
-
-
- </chapter>
- </body>
-</document>
+<?xml version="1.0"?>
+<document url="./introduction.xml">
+
+ <properties>
+ <author>Craig R. McClanahan</author>
+ <author>Mike Schachter</author>
+ <author>Larry McCay</author>
+ <author>Ted Husted</author>
+ <title>The Struts User's Guide - Introduction</title>
+ </properties>
+
+ <body>
+
+ <chapter name="1. Introduction" href="introduction">
+
+ <section name="1.1 Preface: Forward into the Past! (or a brief history of Struts)" href="preface">
+
+ <p>
+ When Java servlets were first invented, many programmers quickly realized that they were a
+ Good Thing. They were faster and more powerful that standard CGI, portable, and infinitely
+ extensible.
+ </p>
+
+ <p>
+ But writing HTML to send to the browser in endless println() statements was tiresome and
+ problematic. The answer to that was JavaServer Pages, which turned servlet writing inside-out.
+ Now developers could easily mix HTML with Java code, and have all the advantages of servlets.
+ The sky was the limit!
+ </p>
+
+ <p>
+ Java web applications quickly became "JSP-centric". This in-and-of itself was not a Bad
+ Thing, but it did little to resolve flow control issues and other problems endemic to web
+ applications.
+ </p>
+
+ <p>Another model was clearly needed ...</p>
+
+ <p>
+ Many clever developers realized that JavaServer Pages AND servlets could be used <b>
+ together</b> to deploy web applications. The servlets could help with the control-flow, and the
+ JSPs could focus on the nasty business of writing HTML. In due course, using JSPs and servlets
+ together became known as Model 2 (where using JSPs alone was Model 1).
+ </p>
+
+ <p>
+ Of course, there is nothing new under the Sun ... and many have been quick to point out that
+ JSP's Model 2 follows SmallTalk's classic Model-View-Controller design pattern. It is now
+ commonplace to use the terms Model 2 and MVC interchangeably.
+ </p>
+
+ <p>
+ The Struts project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC
+ framework to the Java community. In July 2001, Struts 1.0 was released, and IOHO, Java
+ Model 2 development will never be quite the same.
+ </p>
+
+ </section>
+
+ <section name="1.2 The Model-View-Controller ('MVC') Design Pattern" href="mvc">
+
+ <p>
+ In the MVC design pattern, application flow is mediated by a central Controller. The
+ Controller delegates requests to an appropriate handler. The handlers are tied to a Model,
+ which act as an adapter between the request and the Model. The Model represents, or
+ encapsulates, an application's business logic or state. Control is usually then forwarded
+ back through the Controller to the appropriate View. The forwarding can be determined by
+ consulting a set of mappings, usually loaded from a database or configuration file. This
+ provides a loose coupling between the View and Model, which can make an application
+ significantly easier to create and maintain.
+ </p>
+
+ </section>
+
+
+ <section name="1.3 Struts Framework Overview" href="overview">
+
+ <p>
+ True to the Model-View-Controller design pattern, Struts applications have three
+ major components: a servlet controller, JavaServer pages (the "view"), and the
+ application's business logic (or the "model"). Let's step through how this all
+ fits together.</p>
+ <p>
+ The controller bundles and routes HTTP requests to other objects in the framework,
+ including JavaServer Pages. When initialized, the controller parses a configuration
+ resource file. The configuration resource defines (among other things) the action
+ mappings for the application. The controller uses these mappings to turn HTTP
+ requests into application actions.
+ </p>
+
+ <p>
+ At a minimum, a mapping must specify (1) a request path and (2) the object
+ type to act upon the request. The action object can handle the request and respond
+ to the client (usually a Web browser), or indicate that control should be forwarded
+ to another action. For example, if a login succeeds, a loginAction object may wish
+ to forward control to a mainMenu action.
+ </p>
+
+ <p>
+ Action objects are linked to the application's controller, and so have access
+ to that servlet's methods. When forwarding control, an object can indirectly
+ forward one or more shared objects, including JavaBeans, by placing them in one
+ of the standard collections shared by Java servlets.
+ </p>
+
+ <p>
+ An action object can create a shopping cart bean, add an item to the
+ cart, place the bean in the session collection, and then forward control to
+ another action -- that may use a JSP to display the contents of the user's cart.
+ Since each client has their own session, they will each also have their own
+ shopping cart. In a Struts application, most of the business logic can be
+ represented using JavaBeans.
+ </p>
+
+ <p>
+ JavaBeans can also be used to manage input forms. A key problem in designing
+ Web applications is retaining and validating what a user has entered between
+ requests. With Struts, you can easily store the data for a input form in a form
+ bean. The bean is saved in one of the standard, shared context collections,
+ so that it can be used by other objects, especially the action object.
+ </p>
+
+ <p>
+ The form bean can be used by a JSP to collect data from the user ... by an
+ action object to validate the user-entered data ... and then by the JSP again to
+ re-populate the form fields. In the case of validation errors, Struts has a
+ shared mechanism for raising and displaying error messages.
+ </p>
+
+ <p>
+ A Struts form bean is defined in the configuration resource and linked to an action
+ mapping using a common property name. When a request calls for an action that uses
+ a form bean, the controller servlet either retrieves or creates the form bean, and
+ passes it to the action object. The action object can then check the contents of
+ the form bean before its input form is displayed, and also queue messages to be
+ handled by the form. When ready, the action object can return control with a
+ forwarding to its input form, usually a JSP. The controller can then respond to
+ the HTTP request and direct the client to the Java Server Page.
+ </p>
+
+ <p>
+ The Struts framework includes custom tags that can automatically populate
+ fields from a form bean. The only thing most JavaServer Pages need to know
+ about the rest of the framework is the proper field names and where to submit
+ the form. Components like the messages set by the action object can be output
+ using a single custom tag. Other application-specific tags can also be defined
+ to hide implementation details from the JSPs.
+ </p>
+
+ <p>
+ The custom tags in the Struts framework are designed to use the
+ internationalization features built into the Java platform. All the field labels
+ and messages can be retrieved from a message resource, and Java can
+ automatically provide the correct resource for a client's country and language.
+ To provide messages for another language, simply add another resource file.
+ </p>
+
+ <p>
+ Internationalism aside, other benefits to this approach are consistent labeling
+ between forms, and the ability to review all labels and messages from a central
+ location.
+ </p>
+
+ <p>
+ For the simplest applications, an action object can handle the business logic
+ associated with a request. However, in most cases, an action object should pass
+ the request to another object, usually a JavaBean. To allow reuse on other
+ platforms, business-logic JavaBeans should not refer to any Web application
+ objects. The action object should translate needed details from the HTTP request
+ and pass those along to the business-logic beans as regular Java variables.
+ </p>
+
+ <p>
+ In a database application, the business-logic beans might connect to and
+ query the database and return the result set back to the action's servlet ... to
+ be stored in a form bean ... and then displayed by the JSP. Neither the action's
+ servlet nor the JSP need to know (or care) where the result set comes from.
+ </p>
+
+ <p>
+ The rest of this Users Guide explains the various Struts components in greater
+ detail. The Struts release also includes several Developer Guides covering
+ various aspects of the frameworks, along with sample applications,
+ the standard JavaDoc API, and, of course, the complete source code!
+ </p>
+
+ <p>
+ Struts is distributed under the Apache Software Foundation license. The code
+ is copyrighted, but is free to use in any application. See the
+ <a href="http://www.apache.org/LICENSE-1.1">ASF license</a> for specifics.
+ </p>
+
+ </section>
+
+ <section name="1.4 The Model: System State and Business Logic JavaBeans" href="modelConcepts">
+
+ <p>
+ The <i>Model</i> portion of an MVC-based system can be subdivided into
+ concepts -- the internal state of the system, and the actions that can be
+ taken to change that state. In grammatical terms, we might think about
+ state information as <i>nouns</i> (things) and actions as <i>verbs</i>
+ (changes to the state of those things).
+ </p>
+
+ <p>
+ Generally, your application will represent the internal state of the
+ system as a set of one or more JavaBeans, with properties that represent
+ the details of the state. Depending on your application's complexity,
+ these beans may be self contained (and know how to save their state
+ information persistently somehow), or they may be facades that know
+ how to retrieve information from external sources (such as a database)
+ when it is requested. Entity Enterprise JavaBeans (EJBs) are also commonly
+ used to represent internal state.
+ </p>
+
+ <p>
+ Large-scale applications will often represent the business logic actions
+ that are possible in a system as methods that can be called on the beans
+ maintaining the state information. For example, you might have a shopping
+ cart bean, stored in session scope for each current user, with properties
+ that represent the current set of items that the user has decided to
+ purchase. This bean might also have a <code>checkOut()</code> method
+ that authorizes the user's credit card, and sends the order to the
+ warehouse to be picked and shipped. Other systems will represent the
+ available actions separately, perhaps as Session Enterprise JavaBeans
+ (EJBs).
+ </p>
+
+ <p>
+ In some smaller scale applications, on the other hand, the available
+ actions might be embedded within the <code>Action</code> classes that are
+ part of the Controller role. This is appropriate when the logic is very
+ simple, or where reuse of the business logic in other environments is not
+ contemplated. The Struts framework supports any of these approaches, but
+ recommends separating the business logic ("what to do") from the role that
+ <code>Action</code> classes play ("deciding what to do").
+ </p>
+ </section>
+
+ <section name="1.5 The View: JSP Pages and Presentation Components" href="presentationConcepts">
+
+ <p>
+ The <i>View</i> portion of a Struts-based application is generally
+ constructed using JavaServer Pages (JSP) technology. JSP pages can
+ contain static HTML (or XML) text called "template text", plus the
+ ability to insert dynamic content based on the interpretation (at page
+ request time) of special action tags. The JSP environment includes a
+ set of standard action tags, such as <code><jsp:useBean></code>
+ whose purpose is described in the JavaServer Pages Specification. In
+ addition, there is a standard facility to define your own tags, which
+ are organized into "custom tag libraries."
+ </p>
+
+ <p>
+ Struts includes an extensive custom tag library that facilitates
+ creating user interfaces that are fully internationalized, and that
+ interact gracefully with <code>ActionForm</code> beans that are part
+ of the <i>Model</i> portion of the system. The use of these tags is
+ discussed in detail later.
+ </p>
+
+ <p>
+ In addition to JSP pages and the action and custom tags they contain,
+ it is often necessary for business objects to be able to render
+ themselves in HTML (or XML), based on their current state at request time.
+ The rendered output from such objects can be easily included in a
+ resulting JSP page by using the <code><jsp:include></code>
+ standard action tag.
+ </p>
+ </section>
+
+ <section name="1.6 The Controller: ActionServlet and ActionMapping" href="controllerConcepts">
+
+ <p>
+ The <i>Controller</i> portion of the application is focused on receiving
+ requests from the client (typically a user running a web browser), deciding
+ what business logic function is to be performed, and then delegating
+ responsibility for producing the next phase of the user interface to
+ an appropriate View component. In Struts, the primary component of the
+ Controller is a servlet of class <code>ActionServlet</code>. This servlet
+ is configured by defining a set of mappings (described by a Java class
+ <code>ActionMapping</code>). Each mapping defines a <code>path</code>
+ that is matched against the request URI of the incoming request, and the
+ fully qualified class name of an <code>Action</code> class (that is, a
+ Java class extending the <code>Action</code> class) which is
+ responsible for performing the desired business logic, and then dispatching
+ control to the appropriate View component to create the response.
+ </p>
+
+ <p>
+ Struts also supports the ability to use <code>ActionMapping</code>
+ classes that have additional properties beyond the standard ones required
+ to operate the framework. This allows you to store additional information
+ specific to your application, but still utilize the remaining features of
+ the framework. In addition, Struts lets you define logical "names" to which
+ control should be forwarded so that an action method can ask for the
+ "Main Menu" page (for example), without knowing what the actual name of the
+ corresponding JSP page is. These features greatly assist you in separating
+ the control logic (what do I do next) with the view logic (what is the name
+ of the corresponding page).
+ </p>
+
+ <p align="center">
+ Next: <a href="building_model.html">Building Model Components</a>
+ </p>
+ </section>
+
+
+ </chapter>
+ </body>
+</document>
| 0 | 6 |
CVE-2005-3745
|
Cross-site scripting (XSS) vulnerability in Apache Struts 1.2.7, and possibly other versions allows remote attackers to inject arbitrary web script or HTML via the query string, which is not properly quoted or filtered when the request handler generates an error message.
|
apache/struts1
|
577746b34784c7acbc0920567580b848114452e5
|
Oops, meant to copy this in r279152, but I moved it instead.
git-svn-id: https://svn.apache.org/repos/asf/struts/core/trunk@279968 13f79535-47bb-0310-9956-ffa450edef68
|
commit 577746b34784c7acbc0920567580b848114452e5
Author: Ted Nathan Husted <[email protected]>
Date: Sat Sep 10 08:07:48 2005 +0000
Oops, meant to copy this in r279152, but I moved it instead.
git-svn-id: https://svn.apache.org/repos/asf/struts/core/trunk@279968 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/xdocs/building_view.xml b/xdocs/building_view.xml
new file mode 100644
index 000000000..5a6281a0e
--- /dev/null
+++ b/xdocs/building_view.xml
@@ -0,0 +1,896 @@
+<?xml version="1.0"?>
+<document url="building_view.html">
+
+<!--
+// ======================================================================== 78
+-->
+
+<properties>
+ <title>The Struts User's Guide - Building View Components</title>
+</properties>
+
+<body>
+<section name="3. Building View Components">
+
+<subsection name="3.1 Overview">
+
+ <p>
+ This chapter focuses on the task of building the <em>View</em> components
+ for use with the Struts framework.
+ Many applications rely on JavaServer Pages (JSP) technology to create the
+ presentation layer.
+ The Struts distribution includes a comprehensive JSP tag library that
+ provides support for building internationalized applications, as well as
+ for interacting with input forms.
+ Several other topics related to the View components are briefly discussed.
+ </p>
+
+</subsection>
+
+<subsection name="3.2 Internationalized Messages">
+
+ <p>
+ A few years ago, application developers could count on having to support
+ only residents of their own country, who are used to only one (or
+ sometimes two) languages, and one way to represent numeric quantities like
+ dates, numbers, and monetary values.
+ However, the explosion of application development based on web
+ technologies, as well as the deployment of such applications on the
+ Internet and other broadly accessible networks, have rendered national
+ boundaries invisible in many cases.
+ This has translated (if you will pardon the pun) into a need for
+ applications to support <em>internationalization</em> (often called "i18n"
+ because 18 is the number of letters in between the "i" and the "n") and
+ <em>localization</em>.
+ </p>
+
+ <p>
+ Struts builds upon the standard classes available on the Java platform to
+ build internationalized and localized applications.
+ The key concepts to become familiar with are:
+ </p>
+
+ <ul>
+
+ <li>
+ <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/util/Locale.html">
+ <strong>Locale</strong></a> - The fundamental Java class that supports
+ internationalization is <code>Locale</code>.
+ Each <code>Locale</code> represents a particular choice of country and
+ language (plus an optional language variant), and also a set of
+ formatting assumptions for things like numbers and dates.
+ </li>
+
+ <li>
+ <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/util/ResourceBundle.html">
+ <strong>ResourceBundle</strong></a> - The <code>java.util.ResourceBundle</code>
+ class provides the fundamental tools for supporting messages in
+ multiple languages.
+ See the Javadocs for the <code>ResourceBundle</code> class, and the
+ information on Internationalization in the documentation bundle for your
+ JDK release, for more information.
+ </li>
+
+ <li>
+ <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/util/PropertyResourceBundle.html">
+ <strong>PropertyResourceBundle</strong></a> - One of the standard
+ implementations of <code>ResourceBundle</code> allows you to define
+ resources using the same "name=value" syntax used to initialize
+ properties files.
+ This is very convenient for preparing resource bundles with messages
+ that are used in a web application, because these messages are
+ generally text oriented.
+ </li>
+
+ <li>
+ <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/text/MessageFormat.html">
+ <strong>MessageFormat</strong></a> - The <code>java.text.MessageFormat</code>
+ class allows you to replace portions of a message string (in this
+ case, one retrieved from a resource bundle) with arguments specified
+ at run time.
+ This is useful in cases where you are creating a sentence, but the
+ words would appear in a different order in different languages.
+ The placeholder string <code>{0}</code> in the message is replaced by
+ the first runtime argument, <code>{1}</code> is replaced by the
+ second argument, and so on.
+ </li>
+
+ <li>
+ <a href="../struts-core/apidocs/org/apache/struts/util/MessageResources.html">
+ <strong>MessageResources</strong></a> - The Struts class
+ <code>org.apache.struts.util.MessageResources</code> lets you treat
+ a set of resource bundles like a database, and allows you to request
+ a particular message string for a particular Locale (normally one
+ associated with the current user) instead of for the default Locale
+ the server itself is running in.
+ </li>
+
+ </ul>
+
+ <p>
+ Please note that the i18n support in a framework like Struts is limited to
+ the <strong>presentation</strong> of internationalized text and images to the user.
+ Support for Locale specific <strong>input methods</strong> (used with languages
+ such as Japanese, Chinese, and Korean) is left up to the client device,
+ whichis usually a web browser.
+ </p>
+
+ <p>
+ For an internationalized application, follow the steps described in
+ the Internationalization document in the JDK documentation bundle for your
+ platform to create a properties file containing the messages for each
+ language.
+ An example will illustrate this further:
+ </p>
+
+ <p>
+ Assume that your source code is created in package
+ <code>com.mycompany.mypackage</code>, so it is stored in a directory
+ (relative to your source directory) named
+ <code>com/mycompany/mypackage</code>.
+ To create a resource bundle called
+ <code>com.mycompany.mypackage.MyApplication</code>, you would create the
+ following files in the <code>com/mycompany/mypackage</code> directory:
+ </p>
+
+ <ul>
+
+ <li>
+ <strong>MyApplication.properties</strong> - Contains the messages in the default
+ language for your server.
+ If your default language is English, you might have an entry like
+ this: <code>prompt.hello=Hello</code>
+ </li>
+
+ <li>
+ <strong>MyApplication_xx.properties</strong> - Contains the same messages in the
+ language whose ISO language code is "xx" (See the
+ <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/util/ResourceBundle.html">
+ ResourceBundle Javadoc</a> page for a link to the current list).
+ For a French version of the message shown above, you would have this
+ entry: <code>prompt.hello=Bonjour</code>
+ You can have resource bundle files for as many languages as you need.
+ </li>
+
+ </ul>
+
+ <p>
+ When you configure the controller servlet in the web application
+ deployment descriptor, one of the things you will need to define in
+ an initialization parameter is the base name of the resource bundle
+ for the application.
+ In the case described above, it would be
+ <code>com.mycompany.mypackage.MyApplication</code>.
+ </p>
+
+<source><![CDATA[
+<servlet>
+<servlet-name>action</servlet-name>
+<servlet-class>
+org.apache.struts.action.ActionServlet
+</servlet-class>
+<init-param>
+<param-name>application</param-name>
+<param-value>
+ com.mycompany.mypackage.MyResources
+</param-value>
+</init-param>
+<!-- ... -->
+</servlet>
+]]></source>
+
+ <p>
+ The important thing is for the resource bundle to be found on the
+ class path for your application.
+ Another approach is to store the <code>MyResources.properties</code>
+ file in your application's <code>classes</code> folder.
+ You can then simply specify "myResources" as the application value.
+ Just be careful it is not deleted if your build script deletes
+ classes as part of a "clean" target.
+ </p>
+
+ <p>
+ If it does, here is an Ant task to run when compiling your application
+ that copies the contents of a <code>src/conf</code>
+ directory to the <code>classes</code> directory:
+ </p>
+
+<source><![CDATA[
+<!-- Copy any configuration files -->
+<copy todir="classes">
+<fileset dir="src/conf"/>
+</copy>
+]]></source>
+
+</subsection>
+
+<subsection name="3.3 Forms and FormBean Interactions">
+
+<p>
+ <strong>Note:</strong> While the examples given here use JSP and custom tags,
+ the ActionForm beans and the other Struts controller components are
+ View neutral.
+ Struts can be used with Velocity Templates, XSL, and any other
+ presentation technology that can be rendered via a Java servlet.
+</p>
+
+ <p>
+ At one time or another, most web developers have built forms using
+ the standard capabilities of HTML, such as the <code><input></code>
+ tag.
+ Users have come to expect interactive applications to have certain
+ behaviors, and one of these expectations relates to error handling -- if
+ the user makes an error, the application should allow them to fix just
+ what needs to be changed -- without having to re-enter any of the rest
+ of the information on the current page or form.
+ </p>
+
+ <p>
+ Fulfilling this expectation is tedious and cumbersome when coding with
+ standard HTML and JSP pages.
+ For example, an input element for a <code>username</code> field might
+ look like this (in JSP):
+ </p>
+
+<source><![CDATA[
+<input type="text" name="username"
+value="<%= loginBean.getUsername() >"/>
+]]></source>
+
+ <p>
+ which is difficult to type correctly, confuses HTML developers who are
+ not knowledgeable about programming concepts, and can cause problems with
+ HTML editors.
+ Instead, Struts provides a comprehensive facility for building forms,
+ based on the Custom Tag Library facility of JSP 1.1.
+ The case above would be rendered like this using Struts:
+ </p>
+
+<source><![CDATA[
+<html:text property="username"/>;
+]]></source>
+
+ <p>
+ with no need to explicitly refer to the JavaBean from which the initial
+ value is retrieved. That is handled automatically by the JSP tag, using
+ facilities provided by the framework.
+ </p>
+
+ <p>
+ HTML forms are sometimes used to upload other files.
+ Most browsers support this through a <input type="file"> element,
+ that generates a file browse button, but it's up to the developer to
+ handle the incoming files.
+ Struts handles these "multipart" forms in a way identical to building
+ normal forms.
+ </p>
+
+ <p>
+ For an example of using Struts to create a simple login form,
+ see the "<a href="../faqs/actionForm.html">
+ Buiding an ActionForm Howto</a>".
+ </p>
+
+</subsection>
+
+
+<subsection name="3.3.1 Indexed and Mapped Properties">
+
+ <p>
+ Property references in JSP pages using the Struts framework can reference
+ Java Bean properties as described in the JavaBeans specification.
+ Most of these references refer to "scalar" bean properties, referring to
+ primitive or single Object properties.
+ However, Struts, along with the Jakarta Commons Beanutils library, allow
+ you to use property references which refer to individual items in an array,
+ collection, or map, which are represented by bean methods using
+ well-defined naming and signature schemes.
+ </p>
+
+<p>
+ Documentation on the Beanutils package can be found at
+ <a href="http://jakarta.apache.org/commons/beanutils/api/index.html">
+ http://jakarta.apache.org/commons/beanutils/api/index.html</a>.
+ More information about using indexed and mapped properties in Struts can
+ be found in the FAQ describing <a
+ href="../faqs/indexedprops.html"><em>Indexed Properties, Mapped Properties,
+ and Indexed Tags</em></a>.
+</p>
+</subsection>
+
+<subsection name="3.3.2 Input Field Types Supported">
+
+ <p>
+ Struts defines HTML tags for all of the following types of input fields,
+ with hyperlinks to the corresponding reference information.
+ </p>
+
+ <ul>
+
+ <li>
+ <a href="struts-html.html#checkbox">checkboxes</a>
+ </li>
+
+ <li>
+ <a href="struts-html.html#hidden">hidden</a> fields
+ </li>
+
+ <li>
+ <a href="struts-html.html#password">password</a> input fields
+ </li>
+
+ <li>
+ <a href="struts-html.html#radio">radio</a> buttons
+ </li>
+
+ <li>
+ <a href="struts-html.html#reset">reset</a> buttons
+ </li>
+
+ <li>
+ <a href="struts-html.html#select">select</a> lists with embedded
+ option or options items
+ </li>
+
+ <li>
+ <a href="struts-html.html#option">option</a>
+ </li>
+
+ <li>
+ <a href="struts-html.html#options">options</a>
+ </li>
+
+ <li>
+ <a href="struts-html.html#submit">submit</a> buttons
+ </li>
+
+ <li>
+ <a href="struts-html.html#text">text</a> input fields
+ </li>
+
+ <li>
+ <a href="struts-html.html#textarea">textareas</a>
+ </li>
+
+ </ul>
+
+ <p>
+ In every
+ case, a field tag must be nested within a <code>form</code> tag, so that
+ the field knows what bean to use for initializing displayed values.
+ </p>
+
+</subsection>
+
+<subsection name="3.3.3 Other Useful Presentation Tags">
+
+ <p>
+ There are several tags useful for creating presentations, consult the
+ documentation on each specific tag library, along with the Tag Developers
+ Guides, for more information:
+ </p>
+
+ <ul>
+
+ <li>
+ [logic] <a href="struts-logic.html#iterate">iterate</a> repeats its
+ tag body once for each element of a specified collection (which can be an
+ Enumeration, a Hashtable, a Vector, or an array of objects).
+ </li>
+
+ <li>
+ [logic] <a href="struts-logic.html#present">present</a> depending on
+ which attribute is specified, this tag checks the current request, and
+ evaluates the nested body content of this tag only if the specified value
+ is present.
+ Only one of the attributes may be used in one occurrence of this tag,
+ unless you use the property attribute, in which case the name attribute
+ is also required.
+ The attributes include cookie, header, name, parameter, property, role,
+ scope, and user.
+ </li>
+
+ <li>
+ [logic] <a href="struts-logic.html#notPresent">notPresent</a> the
+ companion tag to present, notPresent provides the same functionality when
+ the specified attribute is not present.
+ </li>
+
+ <li>
+ [html] <a href="struts-html.html#link">link</a> generates a HTML
+ <a> element as an anchor definition or a hyperlink to the specified
+ URL, and automatically applies URL encoding to maintain session state in
+ the absence of cookie support.
+ </li>
+
+ <li>
+ [html] <a href="struts-html.html#img">img</a> generates a HTML
+ <img> element with the ability to dynamically modify the URLs
+ specified by the "src" and "lowsrc" attributes in the same manner that
+ <html:link> can.
+ </li>
+
+ <li>
+ [bean] <a href="struts-bean.html#parameter">parameter</a>
+ retrieves the value of the specified request parameter, and defines the
+ result as a page scope attribute of type String or String[].
+ </li>
+
+ </ul>
+
+</subsection>
+
+<subsection name="3.3.4 Automatic Form Validation">
+
+ <p>
+ In addition to the form and bean interactions described above, Struts
+ offers an additional facility to validate the input fields it has received.
+ To utilize this feature, override the following method in your ActionForm
+ class:
+ </p>
+
+<source><![CDATA[
+validate(ActionMapping mapping,
+HttpServletRequest request);
+]]></source>
+
+ <p>
+ The <code>validate</code> method is called by the controller servlet after
+ the bean properties have been populated, but before the corresponding
+ action class's <code>execute</code> method is invoked.
+ The <code>validate</code> method has the following options:
+ </p>
+
+ <ul>
+
+ <li>
+ Perform the appropriate validations and find no problems -- Return
+ either <code>null</code> or a zero-length ActionErrors instance,
+ and the controller servlet will proceed to call the
+ <code>perform</code> method of the appropriate <code>Action</code> class.
+ </li>
+
+ <li>
+ Perform the appropriate validations and find problems -- Return an
+ ActionErrors instance containing <code>ActionMessage</code>'s, which
+ are classes that contain the error message keys (into the
+ application's <code>MessageResources</code> bundle) that should be
+ displayed.
+ The controller servlet will store this array as a request attribute
+ suitable for use by the <code><html:errors></code> tag, and
+ will forward control back to the input form (identified by the
+ <code>input</code> property for this <code>ActionMapping</code>).
+ </li>
+
+ </ul>
+
+ <p>
+ As mentioned earlier, this feature is entirely optional.
+ The default implementation of the <code>validate</code> method returns
+ <code>null</code>, and the controller servlet will assume that any
+ required validation is done by the action class.
+ </p>
+
+ <p>
+ One common approach is to perform simple, prima facia validations using
+ the ActionForm <code>validate</code> method, and then handle the
+ "business logic" validation from the Action.
+ </p>
+
+ <p>
+ The Struts Validator, covered in the next section, may be used to easily
+ validate ActionForms.
+ </p>
+
+</subsection>
+
+<subsection name="3.3.5 The Struts Validator">
+
+ <p>
+ Configuring the Validator to perform form validation is easy.
+ </p>
+ <ol>
+
+ <li>
+ The ActionForm bean must extend ValidatorForm
+ </li>
+ <li>
+ The form's JSP must include the
+ <a href="struts-html.html"><html:javascript></a> tag for client
+ side validation.
+ </li>
+ <li>
+ You must define the validation rules in an xml file like this:
+
+<source><![CDATA[
+<form-validation>
+<formset>
+<form name="logonForm">
+ <field property="username" depends="required">
+ <msg name="required" key="error.username"/>
+ </field>
+</form>
+</formset>
+</form-validation>
+]]></source>
+The msg element points to the message resource key to use when generating the error message.
+</li>
+<li>Lastly, you must enable the ValidatorPlugin in the struts-config.xml file like this:
+<source><![CDATA[
+<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
+<set-property
+property="pathnames"
+value="/WEB-INF/validator-rules.xml,
+ /WEB-INF/validation.xml"/>
+</plug-in>
+]]></source>
+
+ </li>
+ </ol>
+
+ <p>
+ <strong>Note:</strong> If your required form property is one of the Java object representations of
+ primitive types (ie. java.lang.Integer), you must set the ActionServlet's convertNull init.
+ parameter to true. Failing to do this will result in the required validation not being performed
+ on that field because it will default to 0.
+ </p>
+
+ <p>
+ For more about the Struts Validator, see the
+ <a href="./dev_validator.html">Developers Guide</a>.
+ </p>
+
+</subsection>
+
+<subsection name="3.4 Other Presentation Techniques">
+
+ <p>
+ Although the look and feel of your application can be completely
+ constructed based on the standard capabilities of JSP and the Struts
+ custom tag library, you should consider employing other techniques that
+ will improve component reuse, reduce maintenance efforts, and/or reduce
+ errors.
+ Several options are discussed in the following sections.
+ </p>
+
+</subsection>
+
+<subsection name="3.4.1 Application-Specific Custom Tags">
+
+ <p>
+ Beyond using the custom tags provided by the Struts library, it is easy
+ to create tags that are specific to the application you are building, to
+ assist in creating the user interface. The MailReader example application included with
+ Struts illustrates this principle by creating the following tags unique to
+ the implementation of this application:
+ </p>
+
+ <ul>
+ <li><strong>checkLogon</strong> - Checks for the existence of a particular session
+ object, and forwards control to the logon page if it is missing. This is
+ used to catch cases where a user has bookmarked a page in the middle of
+ your application and tries to bypass logging on, or if the user's session
+ has been timed out. (Note that there are better ways to authenticate users; the
+ checkLogon tag is simply meant to demonstrate writing your own custom tags.) </li>
+ <li><strong>linkSubscription</strong> - Generates a hyperlink to a details page
+ for a Subscription, which passes the required primary key values as
+ request attributes. This is used when listing the subscriptions associated
+ with a user, and providing links to edit or delete them.</li>
+ <li><strong>linkUser</strong> - Generates a hyperlink to a details page
+ for a User, which passes the required primary key values as
+ request attributes.</li>
+ </ul>
+
+ <p>
+ The source code for these tags is in the <code>src/example</code> directory,
+ in package <code>org.apache.struts.example</code>, along with the other Java
+ classes that are used in this application.
+ </p>
+</subsection>
+
+<subsection name="3.4.2 Page Composition With Includes">
+
+ <p>
+ Creating the entire presentation of a page in one JSP file (with custom
+ tags and beans to access the required dynamic data) is a very common
+ design approach, and was employed in the example application included
+ with Struts.
+ However, many applications require the display of multiple logically
+ distinct portions of your application together on a single page.
+ </p>
+
+ <p>
+ For example, a portal application might have some or all of the following
+ functional capabilities available on the portal's "home" page:
+ </p>
+
+ <ul>
+
+ <li>
+ Access to a search engine for this portal.
+ </li>
+
+ <li>
+ One or more "news feed" displays, with the topics of interest
+ customizedfrom the user's registration profile.
+ </li>
+
+ <li>
+ Access to discussion topics related to this portal.
+ </li>
+
+ <li>
+ A "mail waiting" indicator if your portal provides free email
+ accounts.
+ </li>
+
+ </ul>
+
+ <p>
+ The development of the various segments of this site is easier if you
+ can divide up the work, and assign different developers to the different
+ segments.
+ Then, you can use the <em>include</em> capability of JavaServer Pages
+ technology to combine the results into a single result page, or use the
+ include tag provided with Struts.
+ There are three types of <em>include</em> available, depending on when you w
+ ant the combination of output to occur:
+ </p>
+
+ <ul>
+
+ <li>
+ An <code><%@ include file="xxxxx" %></code> directive can
+ include a file that contains Java code or JSP tags.
+ The code in the included file can even reference variables declared
+ earlier in the outer jsp page.
+ The code is inlined into the other JavaServer Page before it is
+ compiled so it can definitely contain more than just HTML.
+ </li>
+
+ <li>
+ The include <em>action</em> (<code><jsp:include page="xxxxx"
+ flush="true" /></code>) is processed at request time, and is
+ handled transparently by the server.
+ Among other things, that means you can conditionally perform the
+ include by nesting it within a tag like
+ <a href="struts-logic.html#equal">equal</a> by using it's
+ parameter attribute.
+ </li>
+
+ <li>
+ The <a href="struts-bean.html#include">bean:include</a>
+ tag takes either a an argument "forward" representing a logical name
+ mapped to the jsp to include, or the "id" argument, which represents a
+ page context String variable to print out to the jsp page.
+ </li>
+
+ </ul>
+
+</subsection>
+
+<subsection name="3.4.3 Page Composition With Tiles">
+
+ <p>
+ Tiles is a powerful templating library that allows you to construct views
+ by combining various "tiles".
+ Here's a quick setup guide:
+ </p>
+
+ <ol>
+ <li>
+ Create a /layout/layout.jsp file that contains your app's common look and
+ feel:
+
+<source><![CDATA[
+<html>
+<body>
+<tiles:insert attribute="body"/>
+</body>
+</html>
+]]></source>
+ </li>
+
+ <li>
+ Create your /index.jsp homepage file:
+
+<source><![CDATA[
+<h1>This is my homepage</h1>
+]]></source>
+
+ </li>
+
+ <li>
+ Create a /WEB-INF/tiles-defs.xml file that looks like this:
+
+<source><![CDATA[
+<tiles-definitions>
+<definition
+ name="layout"
+ path="/layout/layout.jsp">
+ <put name="body" value=""/>
+</definition>
+<definition name="homepage" extends="layout">
+ <put
+ name="body"
+ value="/index.jsp"/>
+</definition>
+<tiles-definitions>
+]]></source>
+ </li>
+
+ <li>
+ Setup the TilesPlugin in the struts-config.xml file:
+
+<source><![CDATA[
+<plug-in
+ className="org.apache.struts.tiles.TilesPlugin">
+ <set-property
+ property="definitions-config"
+ value="/WEB-INF/tiles-defs.xml"/>
+</plug-in>
+]]></source>
+ </li>
+
+ <li>
+ Setup an action mapping in struts-config.xml to point to your
+ homepage tile:
+
+<source><![CDATA[
+<action
+path="/index"
+type="org.apache.struts.actions.ForwardAction"
+parameter="homepage"/>
+]]></source>
+ </li>
+ </ol>
+
+ <p>
+ The TilesPlugin configures a special RequestProcessor that determines
+ if the requested view is a tile and processes it accordingly.
+ Note that we made the homepage tile extend our root layout tile and
+ changed the body attribute.
+ Tiles inserts the file named in the body attribute into the main
+ layout.
+ </p>
+
+ <p>
+ See the tiles-documentation webapp for in-depth examples.
+ </p>
+
+ </subsection>
+
+ <subsection name="3.4.4 Image Rendering Components">
+
+ <p>
+ Some applications require dynamically generated images, like the
+ price charts on a stock reporting site.
+ Two different approaches are commonly used to meet these
+ requirements:
+ </p>
+
+ <ul>
+
+ <li>
+ Render a hyperlink with a URL that executes a servlet request.
+ The servlet will use a graphics library to render the graphical image,
+ set the content type appropriately (such as to
+ <code>image/gif</code>), and send back the bytes of that image to the
+ browser, which will display them just as if it had received a static
+ file.
+ </li>
+
+ <li>
+ Render the HTML code necessary to download a Java applet that
+ creates the required graph.
+ You can configure the graph by setting appropriate initialization
+ parameters for the applet in the rendered code, or you can have the
+ applet make its own connection to the server to receive
+ these parameters.
+ </li>
+
+ </ul>
+
+ </subsection>
+
+ <subsection name="3.4.5 Rendering Text">
+
+ <p>
+ Some applications require dynamically generated text or markup,
+ such as XML.
+ If a complete page is being rendered, and can be output using a
+ PrintWriter, this is very easy to do from an Action:
+ </p>
+
+<source><![CDATA[
+response.setContentType("text/plain"); // or text/xml
+PrintWriter writer = response.getWriter();
+// use writer to render text
+return(null);
+]]></source>
+
+</subsection>
+
+ <subsection name="3.4.6 The Struts-EL Tag Library">
+
+ <p>
+ The <strong>Struts-EL</strong> tag library is a contributed library in
+ the Struts distribution.
+ It represents an integration of the Struts tag library with the JavaServer
+ Pages Standard Tag Library, or at least the "expression evaluation"
+ engine that is used by the JSTL.
+ </p>
+
+ <p>
+ The base Struts tag library contains tags which rely on the evaluation
+ of "rtexprvalue"s (runtime scriptlet expressions) to evaluate dynamic
+ attribute values. For instance, to print a message from a properties
+ file based on a resource key, you would use the
+ <code>bean:write</code> tag, perhaps like this:</p>
+ <source>
+ <![CDATA[<bean:message key='<%= stringvar %>'/>]]>
+ </source>
+
+ <p>
+ This assumes that <code>stringvar</code> exists as a JSP scripting
+ variable. If you're using the <strong>Struts-EL</strong> library, the
+ reference looks very similar, but slightly different, like this:</p>
+ <source>
+ <![CDATA[<bean-el:message key="${stringvar}"/>]]>
+ </source>
+
+ <p>
+ If you want to know how to properly use the <strong>Struts-EL</strong>
+ tag library, there are two important things you need to know:
+ </p>
+
+ <ul>
+
+ <li>
+ The Struts tag library
+ </li>
+
+ <li>
+ The JavaServer Pages Standard tag library
+ </li>
+
+ </ul>
+
+
+ <p>
+ Once you understand how to use these two, consider Struts tag
+ attribute values being evaluated the same way the JSTL tag attribute
+ values are.
+ Past that, there is very little else you need to know to effectively use
+ the <strong>Struts-EL</strong> tag library.
+ </p>
+
+ <p>
+ Although the <strong>Struts-EL</strong> tag library is a direct "port"
+ of the tags from the Struts tag library, not all of the tags in the
+ Struts tag library were implemented in the <strong>Struts-EL</strong>
+ tag library.
+ This was the case if it was clear that the functionality of a particular
+ Struts tag could be entirely fulfilled by a tag in the JSTL.
+ It is assumed that developers will want to use the
+ <strong>Struts-EL</strong> tag library along with the JSTL, so it is
+ reasonable to assume that they will use tags from the JSTL if they
+ fill their needs.
+ </p>
+
+ <p>
+ For more see, <a href="../faqs/struts-el.html">Struts-El Extension</a> in the FAQ/HOWTO section.
+ </p>
+
+</subsection>
+
+<subsection>
+ <p class="right">
+ Next: <a href="building_controller.html">Building Controller
+ Components</a>
+ </p>
+</subsection>
+
+</section>
+</body>
+</document>
| 0 | 5 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
8a592984cb69669bb05cabf29a54cffcd744ab9d
|
Fix (partial?) for #373. Fixes staticFilter.
|
commit 8a592984cb69669bb05cabf29a54cffcd744ab9d
Author: Robert Brewer <[email protected]>
Date: Fri Oct 28 00:14:53 2005 +0000
Fix (partial?) for #373. Fixes staticFilter.
diff --git a/cherrypy/lib/filter/staticfilter.py b/cherrypy/lib/filter/staticfilter.py
index a1bafcad..de7e8c33 100644
--- a/cherrypy/lib/filter/staticfilter.py
+++ b/cherrypy/lib/filter/staticfilter.py
@@ -41,10 +41,12 @@ class StaticFilter(BaseFilter):
if not config.get('staticFilter.on', False):
return
+ path = request.objectPath or request.path
+
regex = config.get('staticFilter.match', '')
if regex:
import re
- if not re.search(regex, request.path):
+ if not re.search(regex, path):
return
filename = config.get('staticFilter.file')
@@ -54,7 +56,7 @@ class StaticFilter(BaseFilter):
if section == 'global':
section = "/"
section = section.rstrip(r"\/")
- extraPath = request.path[len(section) + 1:]
+ extraPath = path[len(section) + 1:]
extraPath = extraPath.lstrip(r"\/")
extraPath = urllib.unquote(extraPath)
filename = os.path.join(staticDir, extraPath)
| 0 | 8 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
f71d502fcb5c77fa80ad8e305de5fdf13e2bad7f
|
Trunk fix for #744 (Malicious cookies may allow access to files outside the session directory).
|
commit f71d502fcb5c77fa80ad8e305de5fdf13e2bad7f
Author: Robert Brewer <[email protected]>
Date: Sat Oct 27 17:15:58 2007 +0000
Trunk fix for #744 (Malicious cookies may allow access to files outside the session directory).
diff --git a/cherrypy/lib/sessions.py b/cherrypy/lib/sessions.py
index 8b1c3760..810b8c7e 100644
--- a/cherrypy/lib/sessions.py
+++ b/cherrypy/lib/sessions.py
@@ -282,7 +282,10 @@ class FileSession(Session):
setup = classmethod(setup)
def _get_file_path(self):
- return os.path.join(self.storage_path, self.SESSION_PREFIX + self.id)
+ f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id)
+ if not os.path.normpath(f).startswith(self.storage_path):
+ raise cherrypy.HTTPError(400, "Invalid session id in cookie.")
+ return f
def _load(self, path=None):
if path is None:
| 0 | 7 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
85a2984b3dfa29b2ce9c03abe9a7bb4a385b22c4
|
Replaced request.remote_addr, remote_port, and remote_host with a single "remote" attribute, an instance of lib.http.Host, which has "ip", "port" and "name" attributes. Added a similar request.local attribute. Changed request() signature to (local, remote, scheme). This allows requests run behind multiple HTTP servers to know the address info for their particular connection.
|
commit 85a2984b3dfa29b2ce9c03abe9a7bb4a385b22c4
Author: Robert Brewer <[email protected]>
Date: Mon Aug 7 02:48:57 2006 +0000
Replaced request.remote_addr, remote_port, and remote_host with a single "remote" attribute, an instance of lib.http.Host, which has "ip", "port" and "name" attributes. Added a similar request.local attribute. Changed request() signature to (local, remote, scheme). This allows requests run behind multiple HTTP servers to know the address info for their particular connection.
diff --git a/cherrypy/__init__.py b/cherrypy/__init__.py
index 46e57df6..72e44c78 100644
--- a/cherrypy/__init__.py
+++ b/cherrypy/__init__.py
@@ -95,7 +95,7 @@ def logtime():
def log_access():
"""Default method for logging access"""
tmpl = '%(h)s %(l)s %(u)s [%(t)s] "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
- s = tmpl % {'h': request.remote_host,
+ s = tmpl % {'h': request.remote.name or request.remote.ip,
'l': '-',
'u': getattr(request, "login", None) or "-",
't': logtime(),
diff --git a/cherrypy/_cpengine.py b/cherrypy/_cpengine.py
index 05b1ee2a..674a3c87 100644
--- a/cherrypy/_cpengine.py
+++ b/cherrypy/_cpengine.py
@@ -38,6 +38,7 @@ except ValueError, _signal_exc:
if _signal_exc.args[0] != "signal only works in main thread":
raise
+
class Engine(object):
"""The application engine, which exposes a request interface to (HTTP) servers."""
@@ -173,13 +174,11 @@ class Engine(object):
ready = property(_is_ready, doc="Return True if the engine is ready to"
" receive requests, False otherwise.")
- def request(self, client_address, remote_host, scheme="http"):
+ def request(self, local_host, remote_host, scheme="http"):
"""Obtain an HTTP Request object.
- client_address: the (IP address, port) of the client
- remote_host should be the client's host name. If not available
- (because no reverse DNS lookup is performed), the client
- IP should be provided.
+ local_host should be an http.Host object with the server info.
+ remote_host should be an http.Host object with the client info.
scheme: either "http" or "https"; defaults to "http"
"""
if self.state == STOPPED:
@@ -195,8 +194,7 @@ class Engine(object):
for func in self.on_start_thread_list:
func(i)
- r = self.request_class(client_address[0], client_address[1],
- remote_host, scheme)
+ r = self.request_class(local_host, remote_host, scheme)
cherrypy.serving.request = r
cherrypy.serving.response = self.response_class()
return r
diff --git a/cherrypy/_cpmodpy.py b/cherrypy/_cpmodpy.py
index a4168847..dfef13d6 100644
--- a/cherrypy/_cpmodpy.py
+++ b/cherrypy/_cpmodpy.py
@@ -3,6 +3,7 @@
from mod_python import apache
import cherrypy
from cherrypy._cperror import format_exc, bare_error
+from cherrypy.lib import http
def setup(req):
@@ -46,10 +47,13 @@ def handler(req):
_isSetUp = True
# Obtain a Request object from CherryPy
- clientAddress = req.connection.remote_addr
- remoteHost = clientAddress[0]
+ local = req.connection.local_addr
+ local = http.Host(local[0], local[1], req.connection.local_host or "")
+ remote = req.connection.remote_addr
+ remote = http.Host(remote[0], remote[1], req.connection.remote_host or "")
+
scheme = req.parsed_uri[0] or 'http'
- request = cherrypy.engine.request(clientAddress, remoteHost, scheme)
+ request = cherrypy.engine.request(local, remote, scheme)
req.get_basic_auth_pw()
request.login = req.user
diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py
index 66ecdb8f..2dc3bfd3 100644
--- a/cherrypy/_cprequest.py
+++ b/cherrypy/_cprequest.py
@@ -52,10 +52,9 @@ class HookMap(object):
class Request(object):
"""An HTTP request."""
- # Conversation attributes
- remote_addr = "localhost"
- remote_port = 1111
- remote_host = "localhost"
+ # Conversation/connection attributes
+ local = http.Host("localhost", 80)
+ remote = http.Host("localhost", 1111)
scheme = "http"
base = ""
@@ -90,19 +89,15 @@ class Request(object):
'before_error_response', 'after_error_response']
hooks = HookMap(hookpoints)
- def __init__(self, remote_addr, remote_port, remote_host, scheme="http"):
+ def __init__(self, local_host, remote_host, scheme="http"):
"""Populate a new Request object.
- remote_addr should be the client IP address.
- remote_port should be the client Port.
- remote_host should be the client's host name. If not available
- (because no reverse DNS lookup is performed), the client
- IP should be provided.
+ local_host should be an http.Host object with the server info.
+ remote_host should be an http.Host object with the client info.
scheme should be a string, either "http" or "https".
"""
- self.remote_addr = remote_addr
- self.remote_port = remote_port
- self.remote_host = remote_host
+ self.local = local_host
+ self.remote = remote_host
self.scheme = scheme
self.closed = False
@@ -271,7 +266,7 @@ class Request(object):
raise cherrypy.HTTPError(400, msg)
host = dict.__getitem__(headers, 'Host')
if not host:
- host = cherrypy.config.get('server.socket_host', '')
+ host = self.local.name or self.local.ip
self.base = "%s://%s" % (self.scheme, host)
def get_resource(self, path):
diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py
index 2c76c46d..e6727a40 100644
--- a/cherrypy/_cpwsgi.py
+++ b/cherrypy/_cpwsgi.py
@@ -30,9 +30,12 @@ def _wsgi_callable(environ, start_response, app=None):
request = None
try:
env = environ.get
- clientAddr = (env('REMOTE_ADDR', ''), int(env('REMOTE_PORT', -1)))
- request = cherrypy.engine.request(clientAddr, env('REMOTE_ADDR', ''),
- environ['wsgi.url_scheme'])
+ local = http.Host('', int(env('SERVER_PORT', 80)),
+ env('SERVER_NAME', ''))
+ remote = http.Host(env('REMOTE_ADDR', ''),
+ int(env('REMOTE_PORT', -1)),
+ env('REMOTE_HOST', ''))
+ request = cherrypy.engine.request(local, remote, env('wsgi.url_scheme'))
# LOGON_USER is served by IIS, and is the name of the
# user after having been mapped to a local account.
diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py
index 8b9b9b6c..baef0865 100644
--- a/cherrypy/lib/cptools.py
+++ b/cherrypy/lib/cptools.py
@@ -75,8 +75,8 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For'):
request = cherrypy.request
if base is None:
- port = str(cherrypy.config.get('server.socket_port', '80'))
- if port == "80":
+ port = cherrypy.local.port
+ if port == 80:
base = 'http://localhost'
else:
base = 'http://localhost:%s' % port
@@ -96,7 +96,7 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For'):
if remote == 'X-Forwarded-For':
# See http://bob.pythonmac.org/archives/2005/09/23/apache-x-forwarded-for-caveat/
xff = xff.split(',')[-1].strip()
- request.remote_host = xff
+ request.remote.name = xff
def response_headers(headers=None):
diff --git a/cherrypy/lib/http.py b/cherrypy/lib/http.py
index 42bc0372..d9c96ba8 100644
--- a/cherrypy/lib/http.py
+++ b/cherrypy/lib/http.py
@@ -437,3 +437,21 @@ class SizeCheckWrapper(object):
## raise StopIteration()
return data
+
+class Host(object):
+ """An internet address.
+
+ name should be the client's host name. If not available (because no DNS
+ lookup is performed), the IP address should be used instead.
+ """
+
+ ip = "0.0.0.0"
+ port = 80
+ name = "unknown.tld"
+
+ def __init__(self, ip, port, name=None):
+ self.ip = ip
+ self.port = port
+ if name is None:
+ name = ip
+ self.name = name
diff --git a/cherrypy/lib/wsgiapp.py b/cherrypy/lib/wsgiapp.py
index 87e9fac8..4003d7ac 100644
--- a/cherrypy/lib/wsgiapp.py
+++ b/cherrypy/lib/wsgiapp.py
@@ -31,12 +31,11 @@ def make_environ():
environ["PATH_INFO"] = cherrypy.request.path_info
environ["QUERY_STRING"] = cherrypy.request.query_string
environ["SERVER_PROTOCOL"] = cherrypy.request.protocol
- server_name = getattr(cherrypy.server.httpserver, 'server_name', "None")
- environ["SERVER_NAME"] = server_name
- environ["SERVER_PORT"] = cherrypy.config.get('server.socket_port')
- environ["REMOTE_HOST"] = cherrypy.request.remote_host
- environ["REMOTE_ADDR"] = cherrypy.request.remote_addr
- environ["REMOTE_PORT"] = cherrypy.request.remote_port
+ environ["SERVER_NAME"] = cherrypy.request.local.name
+ environ["SERVER_PORT"] = cherrypy.request.local.port
+ environ["REMOTE_HOST"] = cherrypy.request.remote.name
+ environ["REMOTE_ADDR"] = cherrypy.request.remote.ip
+ environ["REMOTE_PORT"] = cherrypy.request.remote.port
# then all the http headers
headers = cherrypy.request.headers
environ["CONTENT_TYPE"] = headers.get("Content-type", "")
diff --git a/cherrypy/test/benchmark.py b/cherrypy/test/benchmark.py
index 74a09f29..8a6bb95d 100644
--- a/cherrypy/test/benchmark.py
+++ b/cherrypy/test/benchmark.py
@@ -81,7 +81,7 @@ cherrypy.tree.mount(Root(), SCRIPT_NAME, appconf)
class NullRequest:
"""A null HTTP request class, returning 204 and an empty body."""
- def __init__(self, remote_addr, remote_port, remote_host, scheme="http"):
+ def __init__(self, local, remote, scheme="http"):
pass
def close(self):
diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py
index 4c511a49..6d6e0435 100644
--- a/cherrypy/test/test_core.py
+++ b/cherrypy/test/test_core.py
@@ -275,7 +275,7 @@ def setup_server():
hMap['content-length'] = 18
hMap['server'] = 'CherryPy headertest'
hMap['location'] = ('%s://127.0.0.1:%s/headers/'
- % (cherrypy.request.remote_port,
+ % (cherrypy.request.remote.port,
cherrypy.request.scheme))
# Set a rare header for fun
diff --git a/cherrypy/test/test_proxy.py b/cherrypy/test/test_proxy.py
index aff65d9d..186207d4 100644
--- a/cherrypy/test/test_proxy.py
+++ b/cherrypy/test/test_proxy.py
@@ -11,7 +11,7 @@ def setup_server():
index.exposed = True
def remotehost(self):
- return cherrypy.request.remote_host
+ return cherrypy.request.remote.name
remotehost.exposed = True
def xhost(self):
| 0 | 9 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
b673abd4486e5776130be58204cbef59473cb18f
|
Fix for #404, #417 (index files and staticfilter). New "static_filter.index" config entry.
|
commit b673abd4486e5776130be58204cbef59473cb18f
Author: Robert Brewer <[email protected]>
Date: Thu Dec 29 23:03:46 2005 +0000
Fix for #404, #417 (index files and staticfilter). New "static_filter.index" config entry.
diff --git a/cherrypy/filters/staticfilter.py b/cherrypy/filters/staticfilter.py
index 33c34f76..b82ae989 100644
--- a/cherrypy/filters/staticfilter.py
+++ b/cherrypy/filters/staticfilter.py
@@ -33,9 +33,12 @@ class StaticFilter(BaseFilter):
extraPath = path[len(section) + 1:]
extraPath = extraPath.lstrip(r"\/")
extraPath = urllib.unquote(extraPath)
+ # If extraPath is "", filename will end in a slash
filename = os.path.join(staticDir, extraPath)
# If filename is relative, make absolute using "root".
+ # Note that, if "root" isn't defined, we still may send
+ # a relative path to serveFile.
if not os.path.isabs(filename):
root = config.get('static_filter.root', '').rstrip(r"\/")
if root:
@@ -45,8 +48,16 @@ class StaticFilter(BaseFilter):
cptools.serveFile(filename)
request.execute_main = False
except cherrypy.NotFound:
- # if we didn't find the static file, continue
- # handling the request. we might find a dynamic
- # handler instead.
- pass
+ # If we didn't find the static file, continue handling the
+ # request. We might find a dynamic handler instead.
+
+ # But first check for an index file if a folder was requested.
+ if filename[-1:] in ("/", "\\"):
+ idx = config.get('static_filter.index', '')
+ if idx:
+ try:
+ cptools.serveFile(os.path.join(filename, idx))
+ request.execute_main = False
+ except cherrypy.NotFound:
+ pass
diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py
index 18b09f67..d22dfa8e 100644
--- a/cherrypy/lib/cptools.py
+++ b/cherrypy/lib/cptools.py
@@ -94,6 +94,10 @@ def serveFile(path, contentType=None, disposition=None, name=None):
cherrypy.log(" NOT FOUND file: %s" % path, "DEBUG")
raise cherrypy.NotFound()
+ if os.path.isdir(path):
+ # Let the caller deal with it as they like.
+ raise cherrypy.NotFound()
+
if contentType is None:
# Set content-type based on filename extension
ext = ""
diff --git a/cherrypy/test/test_static_filter.py b/cherrypy/test/test_static_filter.py
index 8f66d31b..9e82ca55 100644
--- a/cherrypy/test/test_static_filter.py
+++ b/cherrypy/test/test_static_filter.py
@@ -1,14 +1,22 @@
import test
test.prefer_parent_path()
-import cherrypy
import os
+curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
+
+import cherrypy
+from cherrypy.lib import cptools
-class Root: pass
+class Root:
+ pass
class Static:
+ def index(self):
+ return 'You want the Baron? You can have the Baron!'
+ index.exposed = True
+
def dynamic(self):
return "This is a DYNAMIC page"
dynamic.exposed = True
@@ -33,8 +41,9 @@ cherrypy.config.update({
},
'/docroot': {
'static_filter.on': True,
- 'static_filter.root': os.path.join(os.getcwd(), os.path.dirname(__file__)),
+ 'static_filter.root': curdir,
'static_filter.dir': 'static',
+ 'static_filter.index': 'index.html',
},
})
@@ -70,18 +79,26 @@ class StaticFilterTest(helper.CPWebCase):
# we just check the content
self.assertMatchesBody('^Dummy stylesheet')
- # Check a directory (should currently fail--no provision for it)
- ignore = helper.webtest.ignored_exceptions
- ignore.append(IOError)
- try:
- self.getPage("/static/")
- self.assertErrorPage(500)
- finally:
- ignore.pop()
-
# Test that NotFound will then try dynamic handlers (see [878]).
self.getPage("/static/dynamic")
self.assertBody("This is a DYNAMIC page")
+
+ # Check a directory via fall-through to dynamic handler.
+ self.getPage("/static/")
+ self.assertStatus('200 OK')
+ self.assertHeader('Content-Type', 'text/html')
+ self.assertBody('You want the Baron? You can have the Baron!')
+
+ # Check a directory via "static_filter.index".
+ self.getPage("/docroot/")
+ self.assertStatus('200 OK')
+ self.assertHeader('Content-Type', 'text/html')
+ self.assertBody('Hello, world\r\n')
+ # The same page should be returned even if redirected.
+ self.getPage("/docroot")
+ self.assertStatus('200 OK')
+ self.assertHeader('Content-Type', 'text/html')
+ self.assertBody('Hello, world\r\n')
if __name__ == "__main__":
| 0 | 4 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
2d1f9c0b09420909a3ee8540e901d62b7b7d2cd0
|
A more inclusive, os-level check for staticfilter uplevel attacks.
|
commit 2d1f9c0b09420909a3ee8540e901d62b7b7d2cd0
Author: Robert Brewer <[email protected]>
Date: Tue Jan 10 21:47:24 2006 +0000
A more inclusive, os-level check for staticfilter uplevel attacks.
diff --git a/cherrypy/filters/staticfilter.py b/cherrypy/filters/staticfilter.py
index c0c34fc1..c885fbea 100644
--- a/cherrypy/filters/staticfilter.py
+++ b/cherrypy/filters/staticfilter.py
@@ -23,8 +23,11 @@ class StaticFilter(BaseFilter):
if not re.search(regex, path):
return
+ root = config.get('static_filter.root', '').rstrip(r"\/")
filename = config.get('static_filter.file')
- if not filename:
+ if filename:
+ staticDir = None
+ else:
staticDir = config.get('static_filter.dir')
if not staticDir:
msg = ("StaticFilter requires either static_filter.file "
@@ -38,22 +41,29 @@ class StaticFilter(BaseFilter):
extraPath = extraPath.lstrip(r"\/")
extraPath = urllib.unquote(extraPath)
# If extraPath is "", filename will end in a slash
- if '..' in extraPath:
- # Disallow '..' (security flaw)
- raise cherrypy.HTTPError(403) # Forbidden
filename = os.path.join(staticDir, extraPath)
# If filename is relative, make absolute using "root".
# Note that, if "root" isn't defined, we still may send
# a relative path to serveFile.
if not os.path.isabs(filename):
- root = config.get('static_filter.root', '').rstrip(r"\/")
if not root:
msg = ("StaticFilter requires an absolute final path. "
"Make static_filter.dir, .file, or .root absolute.")
raise cherrypy.WrongConfigValue(msg)
filename = os.path.join(root, filename)
+ # If we used static_filter.dir, then there's a chance that the
+ # extraPath pulled from the URL might have ".." or similar uplevel
+ # attacks in it. Check that the final file is a child of staticDir.
+ # Note that we do not check static_filter.file--that can point
+ # anywhere (since it does not use the request URL).
+ if staticDir:
+ if not os.path.isabs(staticDir):
+ staticDir = os.path.join(root, staticDir)
+ if not os.path.normpath(filename).startswith(os.path.normpath(staticDir)):
+ raise cherrypy.HTTPError(403) # Forbidden
+
try:
cptools.serveFile(filename)
request.execute_main = False
| 0 | 1 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
7e6187ee19a90ebe7f8597296bfa942cd1eb1864
|
Patch for serious security flaw in staticfilter
|
commit 7e6187ee19a90ebe7f8597296bfa942cd1eb1864
Author: Remi Delon <[email protected]>
Date: Tue Jan 10 15:40:43 2006 +0000
Patch for serious security flaw in staticfilter
diff --git a/cherrypy/_cputil.py b/cherrypy/_cputil.py
index 0ba12570..a0be071b 100644
--- a/cherrypy/_cputil.py
+++ b/cherrypy/_cputil.py
@@ -154,12 +154,13 @@ def _cp_log_message(msg, context = '', severity = 0):
f.close()
-_HTTPErrorTemplate = '''<html>
+_HTTPErrorTemplate = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>%(status)s</title>
<style type="text/css">
- #poweredBy {
+ #powered_by {
margin-top: 20px;
border-top: 2px solid black;
font-style: italic;
@@ -174,7 +175,7 @@ _HTTPErrorTemplate = '''<html>
<h2>%(status)s</h2>
<p>%(message)s</p>
<pre id="traceback">%(traceback)s</pre>
- <div id="poweredBy">
+ <div id="powered_by">
<span>Powered by <a href="http://www.cherrypy.org">CherryPy %(version)s</a></span>
</div>
</body>
diff --git a/cherrypy/filters/staticfilter.py b/cherrypy/filters/staticfilter.py
index a4235f37..f1637d51 100644
--- a/cherrypy/filters/staticfilter.py
+++ b/cherrypy/filters/staticfilter.py
@@ -38,6 +38,9 @@ class StaticFilter(BaseFilter):
extraPath = extraPath.lstrip(r"\/")
extraPath = urllib.unquote(extraPath)
# If extraPath is "", filename will end in a slash
+ if '..' in extraPath:
+ # Disallow '..' (secutiry flaw)
+ raise cherrypy.HTTPError(403) # Forbidden
filename = os.path.join(staticDir, extraPath)
# If filename is relative, make absolute using "root".
| 1 | 3 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
f9a56a72a69d9ecc62d745141735aee8bd4eade3
|
Fix for #402 (staticfilter errors if .on but no .file nor .dir).
|
commit f9a56a72a69d9ecc62d745141735aee8bd4eade3
Author: Robert Brewer <[email protected]>
Date: Fri Dec 30 07:04:41 2005 +0000
Fix for #402 (staticfilter errors if .on but no .file nor .dir).
diff --git a/cherrypy/filters/staticfilter.py b/cherrypy/filters/staticfilter.py
index b82ae989..a4235f37 100644
--- a/cherrypy/filters/staticfilter.py
+++ b/cherrypy/filters/staticfilter.py
@@ -26,6 +26,10 @@ class StaticFilter(BaseFilter):
filename = config.get('static_filter.file')
if not filename:
staticDir = config.get('static_filter.dir')
+ if not staticDir:
+ msg = ("StaticFilter requires either static_filter.file "
+ "or static_filter.dir (%s)" % request.path)
+ raise cherrypy.WrongConfigValue(msg)
section = config.get('static_filter.dir', return_section=True)
if section == 'global':
section = "/"
diff --git a/cherrypy/test/test_static_filter.py b/cherrypy/test/test_static_filter.py
index 9e82ca55..3dba5b5c 100644
--- a/cherrypy/test/test_static_filter.py
+++ b/cherrypy/test/test_static_filter.py
@@ -45,6 +45,10 @@ cherrypy.config.update({
'static_filter.dir': 'static',
'static_filter.index': 'index.html',
},
+ '/error': {
+ 'static_filter.on': True,
+ 'server.show_tracebacks': True,
+ },
})
import helper
@@ -99,6 +103,13 @@ class StaticFilterTest(helper.CPWebCase):
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html')
self.assertBody('Hello, world\r\n')
+
+ # Check that we get a WrongConfigValue error if no .file or .dir
+ self.getPage("/error/thing.html")
+ self.assertErrorPage(500)
+ self.assertInBody("WrongConfigValue: StaticFilter requires either "
+ "static_filter.file or static_filter.dir "
+ "(/error/thing.html)")
if __name__ == "__main__":
| 0 | 5 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
c1de1a99373fb76b287636a47c3c2e57b690c7df
|
Test for staticfilter uplevel security, plus a more-informative error if staticfilter can't obtain an absolute path.
|
commit c1de1a99373fb76b287636a47c3c2e57b690c7df
Author: Robert Brewer <[email protected]>
Date: Tue Jan 10 19:13:07 2006 +0000
Test for staticfilter uplevel security, plus a more-informative error if staticfilter can't obtain an absolute path.
diff --git a/cherrypy/filters/staticfilter.py b/cherrypy/filters/staticfilter.py
index f1637d51..c0c34fc1 100644
--- a/cherrypy/filters/staticfilter.py
+++ b/cherrypy/filters/staticfilter.py
@@ -39,7 +39,7 @@ class StaticFilter(BaseFilter):
extraPath = urllib.unquote(extraPath)
# If extraPath is "", filename will end in a slash
if '..' in extraPath:
- # Disallow '..' (secutiry flaw)
+ # Disallow '..' (security flaw)
raise cherrypy.HTTPError(403) # Forbidden
filename = os.path.join(staticDir, extraPath)
@@ -48,8 +48,11 @@ class StaticFilter(BaseFilter):
# a relative path to serveFile.
if not os.path.isabs(filename):
root = config.get('static_filter.root', '').rstrip(r"\/")
- if root:
- filename = os.path.join(root, filename)
+ if not root:
+ msg = ("StaticFilter requires an absolute final path. "
+ "Make static_filter.dir, .file, or .root absolute.")
+ raise cherrypy.WrongConfigValue(msg)
+ filename = os.path.join(root, filename)
try:
cptools.serveFile(filename)
diff --git a/cherrypy/test/test_static_filter.py b/cherrypy/test/test_static_filter.py
index fd6cec37..692b2d4d 100644
--- a/cherrypy/test/test_static_filter.py
+++ b/cherrypy/test/test_static_filter.py
@@ -111,6 +111,10 @@ class StaticFilterTest(helper.CPWebCase):
self.assertInBody("WrongConfigValue: StaticFilter requires either "
"static_filter.file or static_filter.dir "
"(/error/thing.html)")
+
+ # Test up-level security
+ self.getPage("/static/../style.css")
+ self.assertStatus('403 Forbidden')
if __name__ == "__main__":
| 0 | 2 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
09f4d4b6c3c1db6949eb4cdab195b7485a90e600
|
fix which now allows us to serve static content directly alongside dynamic content. staticFilter won't take over the entire request if it doesn't find the file
|
commit 09f4d4b6c3c1db6949eb4cdab195b7485a90e600
Author: Peter Hunt <none@none>
Date: Tue Dec 20 02:03:58 2005 +0000
fix which now allows us to serve static content directly alongside dynamic content. staticFilter won't take over the entire request if it doesn't find the file
diff --git a/cherrypy/filters/staticfilter.py b/cherrypy/filters/staticfilter.py
index 67a9d585..06613a6f 100644
--- a/cherrypy/filters/staticfilter.py
+++ b/cherrypy/filters/staticfilter.py
@@ -40,7 +40,13 @@ class StaticFilter(BaseFilter):
root = config.get('static_filter.root', '').rstrip(r"\/")
if root:
filename = os.path.join(root, filename)
-
- cptools.serveFile(filename)
- request.executeMain = False
+ try:
+ cptools.serveFile(filename)
+ request.executeMain = False
+ except cherrypy.NotFound:
+ # if we didn't find the static file, continue
+ # handling the request. we might find a dynamic
+ # handler instead.
+ pass
+
\ No newline at end of file
| 0 | 6 |
CVE-2006-0847
|
Directory traversal vulnerability in the staticfilter component in CherryPy before 2.1.1 allows remote attackers to read arbitrary files via ".." sequences in unspecified vectors.
|
cherrypy/cherrypy
|
3fcc339cb6cd8a633f6be06220a3db5188069e24
|
X-Forwarded-For should overwrite remote.ip, not remote.name.
|
commit 3fcc339cb6cd8a633f6be06220a3db5188069e24
Author: Robert Brewer <[email protected]>
Date: Fri Aug 11 16:55:20 2006 +0000
X-Forwarded-For should overwrite remote.ip, not remote.name.
diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py
index ef25c1a9..e570e1cf 100644
--- a/cherrypy/lib/cptools.py
+++ b/cherrypy/lib/cptools.py
@@ -70,6 +70,11 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For'):
you must explicitly set base to the full base path, and ALSO set 'local'
to '', so that the X-Forwarded-Host request header (which never includes
path info) does not override it.
+
+ cherrypy.request.remote.ip (the IP address of the client) will be
+ rewritten if the header specified by the 'remote' arg is valid.
+ By default, 'remote' is set to 'X-Forwarded-For'. If you do not
+ want to rewrite remote.ip, set the 'remote' arg to an empty string.
"""
request = cherrypy.request
@@ -96,7 +101,7 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For'):
if remote == 'X-Forwarded-For':
# See http://bob.pythonmac.org/archives/2005/09/23/apache-x-forwarded-for-caveat/
xff = xff.split(',')[-1].strip()
- request.remote.name = xff
+ request.remote.ip = xff
def response_headers(headers=None):
diff --git a/cherrypy/lib/encoding.py b/cherrypy/lib/encoding.py
index 5496936d..8aa44156 100644
--- a/cherrypy/lib/encoding.py
+++ b/cherrypy/lib/encoding.py
@@ -5,7 +5,7 @@ import cherrypy
def decode(encoding=None, default_encoding='utf-8'):
- """Decode cherrypy.request.params ."""
+ """Decode cherrypy.request.params."""
if not encoding:
ct = cherrypy.request.headers.elements("Content-Type")
if ct:
diff --git a/cherrypy/test/test_proxy.py b/cherrypy/test/test_proxy.py
index 186207d4..c7da7911 100644
--- a/cherrypy/test/test_proxy.py
+++ b/cherrypy/test/test_proxy.py
@@ -10,9 +10,9 @@ def setup_server():
raise cherrypy.HTTPRedirect('dummy')
index.exposed = True
- def remotehost(self):
- return cherrypy.request.remote.name
- remotehost.exposed = True
+ def remoteip(self):
+ return cherrypy.request.remote.ip
+ remoteip.exposed = True
def xhost(self):
raise cherrypy.HTTPRedirect('blah')
@@ -44,10 +44,10 @@ class ProxyTest(helper.CPWebCase):
self.assertHeader('Location', "http://www.yetanother.com/dummy")
# Test X-Forwarded-For (Apache2)
- self.getPage("/remotehost",
+ self.getPage("/remoteip",
headers=[('X-Forwarded-For', '192.168.0.20')])
self.assertBody("192.168.0.20")
- self.getPage("/remotehost",
+ self.getPage("/remoteip",
headers=[('X-Forwarded-For', '67.15.36.43, 192.168.0.20')])
self.assertBody("192.168.0.20")
| 0 | 10 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
29c436886cc019e72eeb39fe6ef99af1f70bd86c
|
Merge pull request #43 from victor-homyakov/patch-5
Fix PDoc.
|
commit 29c436886cc019e72eeb39fe6ef99af1f70bd86c (from 7b09d807dad9f1be0d3e56125ecdc991996fec0b)
Merge: 7b09d80 308917b
Author: Andrew Dupont <[email protected]>
Date: Fri Mar 30 12:50:21 2012 -0700
Merge pull request #43 from victor-homyakov/patch-5
Fix PDoc.
diff --git a/src/prototype/lang/string.js b/src/prototype/lang/string.js
index 7b58b5c..a8807d3 100644
--- a/src/prototype/lang/string.js
+++ b/src/prototype/lang/string.js
@@ -177,7 +177,7 @@ Object.extend(String.prototype, (function() {
* ##### Examples
*
* 'apple, pear & orange'.scan(/\w+/, alert);
- * // -> 'apple pear orange' (and displays 'apple', 'pear' and 'orange' in three successive alert dialogs)
+ * // -> 'apple pear & orange' (and displays 'apple', 'pear' and 'orange' in three successive alert dialogs)
*
* Can be used to populate an array:
*
@@ -382,11 +382,9 @@ Object.extend(String.prototype, (function() {
* }
*
* (You can leave off the `window.` part of that, but it's bad form.)
- * Evaluates the content of any `script` block present in the string. Returns
- * an array containing the value returned by each script.
**/
function evalScripts() {
- return this.extractScripts().map(function(script) { return eval(script) });
+ return this.extractScripts().map(function(script) { return eval(script); });
}
/** related to: String#unescapeHTML
@@ -451,7 +449,7 @@ Object.extend(String.prototype, (function() {
* 'section=blog&id=45'.toQueryParams();
* // -> {section: 'blog', id: '45'}
*
- * 'section=blog;id=45'.toQueryParams();
+ * 'section=blog;id=45'.toQueryParams(';');
* // -> {section: 'blog', id: '45'}
*
* 'http://www.example.com?section=blog&id=45#comments'.toQueryParams();
commit 29c436886cc019e72eeb39fe6ef99af1f70bd86c (from 308917bac21e310954f620f46562f321064fd36a)
Merge: 7b09d80 308917b
Author: Andrew Dupont <[email protected]>
Date: Fri Mar 30 12:50:21 2012 -0700
Merge pull request #43 from victor-homyakov/patch-5
Fix PDoc.
diff --git a/src/prototype/dom/dom.js b/src/prototype/dom/dom.js
index 9dc93e0..7e0b792 100644
--- a/src/prototype/dom/dom.js
+++ b/src/prototype/dom/dom.js
@@ -521,7 +521,7 @@
var LINK_ELEMENT_INNERHTML_BUGGY = (function() {
try {
var el = document.createElement('div');
- el.innerHTML = "<link>";
+ el.innerHTML = "<link />";
var isBuggy = (el.childNodes.length === 0);
el = null;
return isBuggy;
@@ -1125,7 +1125,7 @@
}
if (workaround) {
- div.innerHTML = ' ' + t[0] + html + t[1];
+ div.innerHTML = ' ' + t[0] + html + t[1];
div.removeChild(div.firstChild);
for (var i = t[2]; i--; )
div = div.firstChild;
@@ -1545,6 +1545,30 @@
return selector.match(element);
}
+
+ // Internal method for optimizing traversal. Works like
+ // `recursivelyCollect`, except it stops at the first match and doesn't
+ // extend any elements except for the returned element.
+ function _recursivelyFind(element, property, expression, index) {
+ element = $(element), expression = expression || 0, index = index || 0;
+ if (Object.isNumber(expression)) {
+ index = expression, expression = null;
+ }
+
+ while (element = element[property]) {
+ // Skip any non-element nodes.
+ if (element.nodeType !== 1) continue;
+ // Skip any nodes that don't match the expression, if there is one.
+ if (expression && !Prototype.Selector.match(element, expression))
+ continue;
+ // Skip the first `index` matches we find.
+ if (--index >= 0) continue;
+
+ return Element.extend(element);
+ }
+ }
+
+
/**
* Element.up(@element[, expression[, index = 0]]) -> Element
* Element.up(@element[, index = 0]) -> Element
@@ -1648,14 +1672,11 @@
**/
function up(element, expression, index) {
element = $(element);
-
+
if (arguments.length === 1) return $(element.parentNode);
-
- var ancestors = Element.ancestors(element);
- return Object.isNumber(expression) ? ancestors[expression] :
- Prototype.Selector.find(ancestors, expression, index);
+ return _recursivelyFind(element, 'parentNode', expression, index);
}
-
+
/**
* Element.down(@element[, expression[, index = 0]]) -> Element
* Element.down(@element[, index = 0]) -> Element
@@ -1754,38 +1775,15 @@
* // -> undefined
**/
function down(element, expression, index) {
- element = $(element);
+ element = $(element), expression = expression || 0, index = index || 0;
- if (arguments.length === 1) return firstDescendant(element);
+ if (Object.isNumber(expression))
+ index = expression, expression = '*';
- return Object.isNumber(expression) ? Element.descendants(element)[expression] :
- Element.select(element, expression)[index || 0];
- }
-
-
- function _descendants(element) {
- var nodes = element.getElementsByTagName('*'), results = [];
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.tagName !== "!") // Filter out comment nodes.
- results.push(node);
- return results;
- }
-
- // We optimize Element#down for IE so that it does not call
- // Element#descendants (and therefore extend all nodes).
- function down_IE(element, expression, index) {
- element = $(element);
- if (arguments.length === 1)
- return Element.firstDescendant(element);
-
- var node = Object.isNumber(expression) ? _descendants(element)[expression] :
- Element.select(element, expression)[index || 0];
+ var node = Prototype.Selector.select(expression, element)[index];
return Element.extend(node);
}
-
- if (!Prototype.BrowserFeatures.ElementExtensions)
- down = down_IE;
-
+
/**
* Element.previous(@element[, expression[, index = 0]]) -> Element
* Element.previous(@element[, index = 0]) -> Element
@@ -1886,16 +1884,7 @@
* // -> undefined
**/
function previous(element, expression, index) {
- element = $(element);
- if (Object.isNumber(expression))
- index = expression, expression = false;
- if (!Object.isNumber(index)) index = 0;
-
- if (expression) {
- return Prototype.Selector.find(previousSiblings(element), expression, index);
- } else {
- return recursivelyCollect(element, 'previousSibling', index + 1)[index];
- }
+ return _recursivelyFind(element, 'previousSibling', expression, index);
}
/**
@@ -1998,16 +1987,7 @@
* // -> undefined
**/
function next(element, expression, index) {
- element = $(element);
- if (Object.isNumber(expression))
- index = expression, expression = false;
- if (!Object.isNumber(index)) index = 0;
-
- if (expression) {
- return Prototype.Selector.find(nextSiblings(element), expression, index);
- } else {
- return recursivelyCollect(element, 'nextSibling', index + 1)[index];
- }
+ return _recursivelyFind(element, 'nextSibling', expression, index);
}
/**
diff --git a/src/prototype/dom/event.js b/src/prototype/dom/event.js
index 4151938..ccfff53 100644
--- a/src/prototype/dom/event.js
+++ b/src/prototype/dom/event.js
@@ -220,6 +220,13 @@
* });
**/
function element(event) {
+ // The public version of `Event.element` is a thin wrapper around the
+ // private `_element` method below. We do this so that we can use it
+ // internally as `_element` without having to extend the node.
+ return Element.extend(_element(event));
+ }
+
+ function _element(event) {
event = Event.extend(event);
var node = event.target, type = event.type,
@@ -268,13 +275,11 @@
* });
**/
function findElement(event, expression) {
- var element = Event.element(event);
-
- if (!expression) return element;
+ var element = _element(event), match = Prototype.Selector.match;
+ if (!expression) return Element.extend(element);
while (element) {
- if (Object.isElement(element) && Prototype.Selector.match(element, expression)) {
+ if (Object.isElement(element) && match(element, expression))
return Element.extend(element);
- }
element = element.parentNode;
}
}
diff --git a/src/prototype/dom/layout.js b/src/prototype/dom/layout.js
index 9b7b78f..811868a 100644
--- a/src/prototype/dom/layout.js
+++ b/src/prototype/dom/layout.js
@@ -111,9 +111,7 @@
// 50% of its offset parent. If it's `position: fixed` instead, we know
// it's 50% of the viewport. And so on.
context = context || element.parentNode;
- var decimal = toDecimal(value);
- var whole = null;
- var position = element.getStyle('position');
+ var decimal = toDecimal(value), whole = null;
var isHorizontal = property.include('left') || property.include('right') ||
property.include('width');
@@ -151,7 +149,6 @@
// Shortcut for figuring out if an element is `display: none` or not.
function isDisplayed(element) {
- var originalElement = element;
while (element && element.parentNode) {
var display = element.getStyle('display');
if (display === 'none') {
diff --git a/src/prototype/lang/array.js b/src/prototype/lang/array.js
index d45bac4..71b7e3d 100644
--- a/src/prototype/lang/array.js
+++ b/src/prototype/lang/array.js
@@ -358,7 +358,7 @@ Array.from = $A;
**/
function intersect(array) {
return this.uniq().findAll(function(item) {
- return array.detect(function(value) { return item === value });
+ return array.indexOf(item) !== -1;
});
}
@@ -423,27 +423,74 @@ Array.from = $A;
* // -> -1 (not found, 1 !== '1')
**/
function indexOf(item, i) {
- i || (i = 0);
- var length = this.length;
- if (i < 0) i = length + i;
- for (; i < length; i++)
- if (this[i] === item) return i;
+ if (this == null) throw new TypeError();
+
+ var array = Object(this), length = array.length >>> 0;
+ if (length === 0) return -1;
+
+ // The rules for the `fromIndex` argument are tricky. Let's follow the
+ // spec line-by-line.
+ i = Number(i);
+ if (isNaN(i)) {
+ i = 0;
+ } else if (i !== 0 && isFinite(i)) {
+ // Equivalent to ES5's `ToInteger` operation.
+ i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i));
+ }
+
+ // If the search index is greater than the length of the array,
+ // return -1.
+ if (i > length) return -1;
+
+ // If the search index is negative, take its absolute value, subtract it
+ // from the length, and make that the new search index. If it's still
+ // negative, make it 0.
+ var k = i >= 0 ? i : Math.max(length - Math.abs(i), 0);
+ for (; k < length; k++)
+ if (k in array && array[k] === item) return k;
return -1;
}
+
/** related to: Array#indexOf
* Array#lastIndexOf(item[, offset]) -> Number
* - item (?): A value that may or may not be in the array.
- * - offset (Number): The number of items at the end to skip before beginning
- * the search.
+ * - offset (Number): The number of items at the end to skip before
+ * beginning the search.
*
- * Returns the position of the last occurrence of `item` within the array — or
- * `-1` if `item` doesn't exist in the array.
+ * Returns the position of the last occurrence of `item` within the
+ * array — or `-1` if `item` doesn't exist in the array.
**/
function lastIndexOf(item, i) {
- i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
- var n = this.slice(0, i).reverse().indexOf(item);
- return (n < 0) ? n : i - n - 1;
+ if (this == null) throw new TypeError();
+
+ var array = Object(this), length = array.length >>> 0;
+ if (length === 0) return -1;
+
+ // The rules for the `fromIndex` argument are tricky. Let's follow the
+ // spec line-by-line.
+ if (!Object.isUndefined(i)) {
+ i = Number(i);
+ if (isNaN(i)) {
+ i = 0;
+ } else if (i !== 0 && isFinite(i)) {
+ // Equivalent to ES5's `ToInteger` operation.
+ i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i));
+ }
+ } else {
+ i = length;
+ }
+
+ // If fromIndex is positive, clamp it to the last index in the array;
+ // if it's negative, subtract its absolute value from the array's length.
+ var k = i >= 0 ? Math.min(i, length - 1) :
+ length - Math.abs(i);
+
+ // (If fromIndex is still negative, it'll bypass this loop altogether and
+ // return -1.)
+ for (; k >= 0; k--)
+ if (k in array && array[k] === item) return k;
+ return -1;
}
// Replaces a built-in function. No PDoc needed.
diff --git a/src/prototype/lang/object.js b/src/prototype/lang/object.js
index 0c5a4f2..92e1d03 100644
--- a/src/prototype/lang/object.js
+++ b/src/prototype/lang/object.js
@@ -161,9 +161,7 @@
}
function Str(key, holder, stack) {
- var value = holder[key],
- type = typeof value;
-
+ var value = holder[key];
if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
@@ -183,7 +181,7 @@
case false: return 'false';
}
- type = typeof value;
+ var type = typeof value;
switch (type) {
case 'string':
return value.inspect(true);
diff --git a/src/prototype/prototype.js b/src/prototype/prototype.js
index 7ce3270..ef5b046 100644
--- a/src/prototype/prototype.js
+++ b/src/prototype/prototype.js
@@ -139,7 +139,7 @@ var Prototype = {
})()
},
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
+ ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script\\s*>',
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
/**
diff --git a/test/unit/array_test.js b/test/unit/array_test.js
index d1f11c3..7e553fc 100644
--- a/test/unit/array_test.js
+++ b/test/unit/array_test.js
@@ -96,6 +96,21 @@ new Test.Unit.Runner({
this.assertEqual(0, [1,2,1].indexOf(1));
this.assertEqual(2, [1,2,1].indexOf(1, -1));
this.assertEqual(1, [undefined,null].indexOf(null));
+
+ // ES5 compatibility tests.
+ var undef;
+ var array = [1, 2, 3, 4, 5, undef, 6, 7, 1, 2, 3];
+
+ this.assertEqual(2, array.indexOf(3, -47),
+ "large negative value for fromIndex");
+ this.assertEqual(10, array.indexOf(3, 4));
+ this.assertEqual(10, array.indexOf(3, -5))
+ this.assertEqual(2, array.indexOf(3, {}),
+ "nonsensical value for fromIndex");
+ this.assertEqual(2, array.indexOf(3, ""),
+ "nonsensical value for fromIndex");
+ this.assertEqual(-1, array.indexOf(3, 41),
+ "fromIndex value larger than the length of the array");
},
testLastIndexOf: function(){
@@ -131,6 +146,7 @@ new Test.Unit.Runner({
testIntersect: function(){
this.assertEnumEqual([1,3], [1,1,3,5].intersect([1,2,3]));
+ this.assertEnumEqual([0,1], [0,1,2].intersect([0,1]));
this.assertEnumEqual([1], [1,1].intersect([1,1]));
this.assertEnumEqual([], [1,1,3,5].intersect([4]));
this.assertEnumEqual([], [1].intersect(['1']));
@@ -187,18 +203,37 @@ new Test.Unit.Runner({
this.assertIdentical(1, Array.prototype.concat.length);
- this.assertEnumEqual([0, 1], [0, 1].concat());
- this.assertIdentical(2, [0, 1].concat().length);
+ this.assertEnumEqual(
+ [0, 1],
+ [0, 1].concat(),
+ "test 2"
+ );
+ this.assertIdentical(2, [0, 1].concat().length, "test 3");
- this.assertEnumEqual([0, 1, 2, 3, 4], [].concat([0, 1], [2, 3, 4]));
- this.assertIdentical(5, [].concat([0, 1], [2, 3, 4]).length);
+ this.assertEnumEqual(
+ [0, 1, 2, 3, 4],
+ [].concat([0, 1], [2, 3, 4]),
+ "test 4"
+ );
+ this.assertIdentical(5, [].concat([0, 1], [2, 3, 4]).length, "test 5");
- this.assertEnumEqual([0, x, 1, 2, true, "NaN"], [0].concat(x, [1, 2], true, "NaN"));
- this.assertIdentical(6, [0].concat(x, [1, 2], true, "NaN").length);
+ this.assertEnumEqual([0, x, 1, 2, true, "NaN"], [0].concat(x, [1, 2], true, "NaN"), "test 6");
+ this.assertIdentical(6, [0].concat(x, [1, 2], true, "NaN").length, "test 7");
+
+ // These tests will fail in older IE because of the trailing comma.
+ // Nothing we can do about that, so just skip them and let the user know.
+ if ([,].length === 2) {
+ this.info("NOTE: Old versions of IE don't like trailing commas in " +
+ "arrays. Skipping some tests.");
+ } else {
+ this.assertEnumEqual([undefined, 1, undefined], [,1].concat([], [,]),
+ "concatenation behavior with a trailing comma (1)");
+ this.assertIdentical(3, [,1].concat([], [,]).length,
+ "concatenation behavior with a trailing comma (2)");
+ }
+
- this.assertEnumEqual([undefined, 1, undefined], [,1].concat([], [,]));
- this.assertIdentical(3, [,1].concat([], [,]).length);
- this.assertEnumEqual([1], Object.keys([,1].concat([], [,])));
+ this.assertEnumEqual([1], Object.keys([,1].concat([], [,])), "test 10");
// Check that Array.prototype.concat can be used in a generic way
x.concat = Array.prototype.concat;
diff --git a/test/unit/string_test.js b/test/unit/string_test.js
index 2851950..d729f2b 100644
--- a/test/unit/string_test.js
+++ b/test/unit/string_test.js
@@ -215,6 +215,9 @@ new Test.Unit.Runner({
this.assertEqual('foo bar', 'foo bar'.stripScripts());
this.assertEqual('foo bar', ('foo <script>boo();<'+'/script>bar').stripScripts());
this.assertEqual('foo bar', ('foo <script type="text/javascript">boo();\nmoo();<'+'/script>bar').stripScripts());
+
+ this.assertEqual('foo bar', ('foo <script>boo();<'+'/script >bar').stripScripts(),
+ 'should properly handle whitespace in closing tag');
},
testExtractScripts: function() {
| 0 | 8 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
093c0cce4bbb89b88b0af20356faa83906b3aafa
|
Optimize retrieving of top|left|right|bottom properties. Add some documentation. Disable setting of properties for now.
|
commit 093c0cce4bbb89b88b0af20356faa83906b3aafa
Author: Andrew Dupont <[email protected]>
Date: Mon Nov 2 23:54:25 2009 -0600
Optimize retrieving of top|left|right|bottom properties. Add some documentation. Disable setting of properties for now.
diff --git a/src/dom/layout.js b/src/dom/layout.js
index 854f566..3152ed6 100644
--- a/src/dom/layout.js
+++ b/src/dom/layout.js
@@ -96,8 +96,115 @@
*
* A set of key/value pairs representing measurements of various
* dimensions of an element.
+ *
+ * <h4>Overview</h4>
+ *
+ * The `Element.Layout` class is a specialized way to measure elements.
+ * It helps mitigate:
+ *
+ * * The convoluted steps often needed to get common measurements for
+ * elements.
+ * * The tendency of browsers to report measurements in non-pixel units.
+ * * The quirks that lead some browsers to report inaccurate measurements.
+ * * The difficulty of measuring elements that are hidden.
+ *
+ * <h4>Usage</h4>
+ *
+ * Instantiate an `Element.Layout` class by passing an element into the
+ * constructor:
+ *
+ * var layout = new Element.Layout(someElement);
+ *
+ * You can also use [[Element.getLayout]], if you prefer.
+ *
+ * Once you have a layout object, retrieve properties using [[Hash]]'s
+ * familiar `get` and `set` syntax.
+ *
+ * layout.get('width'); //-> 400
+ * layout.get('top'); //-> 180
+ *
+ * The following are the CSS-related properties that can be retrieved.
+ * Nearly all of them map directly to their property names in CSS. (The
+ * only exception is for borders — e.g., `border-width` instead of
+ * `border-left-width`.)
+ *
+ * * `height`
+ * * `width`
+ * * `top`
+ * * `left`
+ * * `right`
+ * * `bottom`
+ * * `border-left`
+ * * `border-right`
+ * * `border-top`
+ * * `border-bottom`
+ * * `padding-left`
+ * * `padding-right`
+ * * `padding-top`
+ * * `padding-bottom`
+ * * `margin-top`
+ * * `margin-bottom`
+ * * `margin-left`
+ * * `margin-right`
+ *
+ * In addition, these "composite" properties can be retrieved:
+ *
+ * * `padding-box-width` (width of the content area, from the beginning of
+ * the left padding to the end of the right padding)
+ * * `padding-box-height` (height of the content area, from the beginning
+ * of the top padding to the end of the bottom padding)
+ * * `border-box-width` (width of the content area, from the outer edge of
+ * the left border to the outer edge of the right border)
+ * * `border-box-height` (height of the content area, from the outer edge
+ * of the top border to the outer edge of the bottom border)
+ * * `margin-box-width` (width of the content area, from the beginning of
+ * the left margin to the end of the right margin)
+ * * `margin-box-height` (height of the content area, from the beginning
+ * of the top margin to the end of the bottom margin)
+ *
+ * <h4>Caching</h4>
+ *
+ * Because these properties can be costly to retrieve, `Element.Layout`
+ * behaves differently from an ordinary [[Hash]].
+ *
+ * First: by default, values are "lazy-loaded" — they aren't computed
+ * until they're retrieved. To measure all properties at once, pass
+ * a second argument into the constructor:
+ *
+ * var layout = new Element.Layout(someElement, true);
+ *
+ * Second: once a particular value is computed, it's cached. Asking for
+ * the same property again will return the original value without
+ * re-computation. This means that **an instance of `Element.Layout`
+ * becomes stale when the element's dimensions change**. When this
+ * happens, obtain a new instance.
+ *
+ * <h4>Hidden elements<h4>
+ *
+ * Because it's a common case to want the dimensions of a hidden element
+ * (e.g., for animations), it's possible to measure elements that are
+ * hidden with `display: none`.
+ *
+ * However, **it's only possible to measure a hidden element if its parent
+ * is visible**. If its parent (or any other ancestor) is hidden, any
+ * width and height measurements will return `0`, as will measurements for
+ * `top|bottom|left|right`.
+ *
**/
Element.Layout = Class.create(Hash, {
+ /**
+ * new Element.Layout(element[, preCompute])
+ * - element (Element): The element to be measured.
+ * - preCompute (Boolean): Whether to compute all values at once.
+ *
+ * Declare a new layout hash.
+ *
+ * The `preCompute` argument determines whether measurements will be
+ * lazy-loaded or not. If you plan to use many different measurements,
+ * it's often more performant to pre-compute, as it minimizes the
+ * amount of overhead needed to measure. If you need only one or two
+ * measurements, it's probably not worth it.
+ **/
initialize: function($super, element, preCompute) {
$super();
this.element = $(element);
@@ -125,14 +232,25 @@
return Hash.prototype.set.call(this, property, value);
},
+
+ // TODO: Investigate.
set: function(property, value) {
- if (Element.Layout.COMPOSITE_PROPERTIES.include(property)) {
- throw "Cannot set a composite property.";
- }
-
- return this._set(property, toCSSPixels(value));
+ throw "Properties of Element.Layout are read-only.";
+ // if (Element.Layout.COMPOSITE_PROPERTIES.include(property)) {
+ // throw "Cannot set a composite property.";
+ // }
+ //
+ // return this._set(property, toCSSPixels(value));
},
+ /**
+ * Element.Layout#get(property) -> Number
+ * - property (String): One of the properties defined in
+ * [[Element.Layout.PROPERTIES]].
+ *
+ * Retrieve the measurement specified by `property`. Will throw an error
+ * if the property is invalid.
+ **/
get: function($super, property) {
// Try to fetch from the cache.
var value = $super(property);
@@ -228,9 +346,20 @@
Object.extend(Element.Layout, {
// All measurable properties.
+ /**
+ * Element.Layout.PROPERTIES = Array
+ *
+ * A list of all measurable properties.
+ **/
PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'),
- // Sums of other properties. Can be read but not written.
+ /**
+ * Element.Layout.COMPOSITE_PROPERTIES = Array
+ *
+ * A list of all composite properties. Composite properties don't map
+ * directly to CSS properties — they're combinations of other
+ * properties.
+ **/
COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'),
COMPUTATIONS: {
@@ -313,19 +442,37 @@
},
'top': function(element) {
- return getPixelValue(element, 'top');
+ var offset = element.positionedOffset();
+ return offset.top;
},
'bottom': function(element) {
- return getPixelValue(element, 'bottom');
+ var offset = element.positionedOffset(),
+ parent = element.getOffsetParent(),
+ pHeight = parent.measure('height');
+
+ var mHeight = this.get('border-box-height');
+
+ return pHeight - mHeight - offset.top;
+ //
+ // return getPixelValue(element, 'bottom');
},
'left': function(element) {
- return getPixelValue(element, 'left');
+ var offset = element.positionedOffset();
+ return offset.left;
},
'right': function(element) {
- return getPixelValue(element, 'right');
+ var offset = element.positionedOffset(),
+ parent = element.getOffsetParent(),
+ pWidth = parent.measure('width');
+
+ var mWidth = this.get('border-box-width');
+
+ return pWidth - mWidth - offset.left;
+ //
+ // return getPixelValue(element, 'right');
},
'padding-top': function(element) {
@@ -382,6 +529,27 @@
}
});
+ // An easier way to compute right and bottom offsets.
+ if ('getBoundingClientRect' in document.documentElement) {
+ Object.extend(Element.Layout.COMPUTATIONS, {
+ 'right': function(element) {
+ var parent = hasLayout(element.getOffsetParent());
+ var rect = element.getBoundingClientRect(),
+ pRect = parent.getBoundingClientRect();
+
+ return (pRect.right - rect.right).round();
+ },
+
+ 'bottom': function(element) {
+ var parent = hasLayout(element.getOffsetParent());
+ var rect = element.getBoundingClientRect(),
+ pRect = parent.getBoundingClientRect();
+
+ return (pRect.bottom - rect.bottom).round();
+ }
+ });
+ }
+
/**
* class Element.Offset
*
| 0 | 9 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
c2c47da6aa4e41d2cb45255ad8f3c95eb26f8b44
|
Optimize retrieving of top|left|right|bottom properties. Add some documentation. Disable setting of properties for now.
|
commit c2c47da6aa4e41d2cb45255ad8f3c95eb26f8b44
Author: Andrew Dupont <[email protected]>
Date: Mon Nov 2 23:54:25 2009 -0600
Optimize retrieving of top|left|right|bottom properties. Add some documentation. Disable setting of properties for now.
diff --git a/src/dom/layout.js b/src/dom/layout.js
index 854f566..3152ed6 100644
--- a/src/dom/layout.js
+++ b/src/dom/layout.js
@@ -96,8 +96,115 @@
*
* A set of key/value pairs representing measurements of various
* dimensions of an element.
+ *
+ * <h4>Overview</h4>
+ *
+ * The `Element.Layout` class is a specialized way to measure elements.
+ * It helps mitigate:
+ *
+ * * The convoluted steps often needed to get common measurements for
+ * elements.
+ * * The tendency of browsers to report measurements in non-pixel units.
+ * * The quirks that lead some browsers to report inaccurate measurements.
+ * * The difficulty of measuring elements that are hidden.
+ *
+ * <h4>Usage</h4>
+ *
+ * Instantiate an `Element.Layout` class by passing an element into the
+ * constructor:
+ *
+ * var layout = new Element.Layout(someElement);
+ *
+ * You can also use [[Element.getLayout]], if you prefer.
+ *
+ * Once you have a layout object, retrieve properties using [[Hash]]'s
+ * familiar `get` and `set` syntax.
+ *
+ * layout.get('width'); //-> 400
+ * layout.get('top'); //-> 180
+ *
+ * The following are the CSS-related properties that can be retrieved.
+ * Nearly all of them map directly to their property names in CSS. (The
+ * only exception is for borders — e.g., `border-width` instead of
+ * `border-left-width`.)
+ *
+ * * `height`
+ * * `width`
+ * * `top`
+ * * `left`
+ * * `right`
+ * * `bottom`
+ * * `border-left`
+ * * `border-right`
+ * * `border-top`
+ * * `border-bottom`
+ * * `padding-left`
+ * * `padding-right`
+ * * `padding-top`
+ * * `padding-bottom`
+ * * `margin-top`
+ * * `margin-bottom`
+ * * `margin-left`
+ * * `margin-right`
+ *
+ * In addition, these "composite" properties can be retrieved:
+ *
+ * * `padding-box-width` (width of the content area, from the beginning of
+ * the left padding to the end of the right padding)
+ * * `padding-box-height` (height of the content area, from the beginning
+ * of the top padding to the end of the bottom padding)
+ * * `border-box-width` (width of the content area, from the outer edge of
+ * the left border to the outer edge of the right border)
+ * * `border-box-height` (height of the content area, from the outer edge
+ * of the top border to the outer edge of the bottom border)
+ * * `margin-box-width` (width of the content area, from the beginning of
+ * the left margin to the end of the right margin)
+ * * `margin-box-height` (height of the content area, from the beginning
+ * of the top margin to the end of the bottom margin)
+ *
+ * <h4>Caching</h4>
+ *
+ * Because these properties can be costly to retrieve, `Element.Layout`
+ * behaves differently from an ordinary [[Hash]].
+ *
+ * First: by default, values are "lazy-loaded" — they aren't computed
+ * until they're retrieved. To measure all properties at once, pass
+ * a second argument into the constructor:
+ *
+ * var layout = new Element.Layout(someElement, true);
+ *
+ * Second: once a particular value is computed, it's cached. Asking for
+ * the same property again will return the original value without
+ * re-computation. This means that **an instance of `Element.Layout`
+ * becomes stale when the element's dimensions change**. When this
+ * happens, obtain a new instance.
+ *
+ * <h4>Hidden elements<h4>
+ *
+ * Because it's a common case to want the dimensions of a hidden element
+ * (e.g., for animations), it's possible to measure elements that are
+ * hidden with `display: none`.
+ *
+ * However, **it's only possible to measure a hidden element if its parent
+ * is visible**. If its parent (or any other ancestor) is hidden, any
+ * width and height measurements will return `0`, as will measurements for
+ * `top|bottom|left|right`.
+ *
**/
Element.Layout = Class.create(Hash, {
+ /**
+ * new Element.Layout(element[, preCompute])
+ * - element (Element): The element to be measured.
+ * - preCompute (Boolean): Whether to compute all values at once.
+ *
+ * Declare a new layout hash.
+ *
+ * The `preCompute` argument determines whether measurements will be
+ * lazy-loaded or not. If you plan to use many different measurements,
+ * it's often more performant to pre-compute, as it minimizes the
+ * amount of overhead needed to measure. If you need only one or two
+ * measurements, it's probably not worth it.
+ **/
initialize: function($super, element, preCompute) {
$super();
this.element = $(element);
@@ -125,14 +232,25 @@
return Hash.prototype.set.call(this, property, value);
},
+
+ // TODO: Investigate.
set: function(property, value) {
- if (Element.Layout.COMPOSITE_PROPERTIES.include(property)) {
- throw "Cannot set a composite property.";
- }
-
- return this._set(property, toCSSPixels(value));
+ throw "Properties of Element.Layout are read-only.";
+ // if (Element.Layout.COMPOSITE_PROPERTIES.include(property)) {
+ // throw "Cannot set a composite property.";
+ // }
+ //
+ // return this._set(property, toCSSPixels(value));
},
+ /**
+ * Element.Layout#get(property) -> Number
+ * - property (String): One of the properties defined in
+ * [[Element.Layout.PROPERTIES]].
+ *
+ * Retrieve the measurement specified by `property`. Will throw an error
+ * if the property is invalid.
+ **/
get: function($super, property) {
// Try to fetch from the cache.
var value = $super(property);
@@ -228,9 +346,20 @@
Object.extend(Element.Layout, {
// All measurable properties.
+ /**
+ * Element.Layout.PROPERTIES = Array
+ *
+ * A list of all measurable properties.
+ **/
PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'),
- // Sums of other properties. Can be read but not written.
+ /**
+ * Element.Layout.COMPOSITE_PROPERTIES = Array
+ *
+ * A list of all composite properties. Composite properties don't map
+ * directly to CSS properties — they're combinations of other
+ * properties.
+ **/
COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'),
COMPUTATIONS: {
@@ -313,19 +442,37 @@
},
'top': function(element) {
- return getPixelValue(element, 'top');
+ var offset = element.positionedOffset();
+ return offset.top;
},
'bottom': function(element) {
- return getPixelValue(element, 'bottom');
+ var offset = element.positionedOffset(),
+ parent = element.getOffsetParent(),
+ pHeight = parent.measure('height');
+
+ var mHeight = this.get('border-box-height');
+
+ return pHeight - mHeight - offset.top;
+ //
+ // return getPixelValue(element, 'bottom');
},
'left': function(element) {
- return getPixelValue(element, 'left');
+ var offset = element.positionedOffset();
+ return offset.left;
},
'right': function(element) {
- return getPixelValue(element, 'right');
+ var offset = element.positionedOffset(),
+ parent = element.getOffsetParent(),
+ pWidth = parent.measure('width');
+
+ var mWidth = this.get('border-box-width');
+
+ return pWidth - mWidth - offset.left;
+ //
+ // return getPixelValue(element, 'right');
},
'padding-top': function(element) {
@@ -382,6 +529,27 @@
}
});
+ // An easier way to compute right and bottom offsets.
+ if ('getBoundingClientRect' in document.documentElement) {
+ Object.extend(Element.Layout.COMPUTATIONS, {
+ 'right': function(element) {
+ var parent = hasLayout(element.getOffsetParent());
+ var rect = element.getBoundingClientRect(),
+ pRect = parent.getBoundingClientRect();
+
+ return (pRect.right - rect.right).round();
+ },
+
+ 'bottom': function(element) {
+ var parent = hasLayout(element.getOffsetParent());
+ var rect = element.getBoundingClientRect(),
+ pRect = parent.getBoundingClientRect();
+
+ return (pRect.bottom - rect.bottom).round();
+ }
+ });
+ }
+
/**
* class Element.Offset
*
| 0 | 10 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
36a9f70687b0a1b0d93349d9e1ba7061059399f9
|
Merge pull request #27 from rlineweaver/master
Avoid an infinite loop in `String#gsub` when there is a zero-length match.
|
commit 36a9f70687b0a1b0d93349d9e1ba7061059399f9 (from c8a6942a0cd0537ed4168f837cd1aa99dcacc17e)
Merge: c8a6942 075625c
Author: Andrew Dupont <[email protected]>
Date: Mon Aug 27 15:10:48 2012 -0700
Merge pull request #27 from rlineweaver/master
Avoid an infinite loop in `String#gsub` when there is a zero-length match.
diff --git a/src/prototype/lang/string.js b/src/prototype/lang/string.js
index a8807d3..558db32 100644
--- a/src/prototype/lang/string.js
+++ b/src/prototype/lang/string.js
@@ -100,7 +100,8 @@ Object.extend(String.prototype, (function() {
}
while (source.length > 0) {
- if (match = source.match(pattern)) {
+ match = source.match(pattern)
+ if (match && match[0].length > 0) {
result += source.slice(0, match.index);
result += String.interpret(replacement(match));
source = source.slice(match.index + match[0].length);
diff --git a/test/unit/string_test.js b/test/unit/string_test.js
index d729f2b..5b274b2 100644
--- a/test/unit/string_test.js
+++ b/test/unit/string_test.js
@@ -66,7 +66,6 @@ new Test.Unit.Runner({
testGsubWithTroublesomeCharacters: function() {
this.assertEqual('ab', 'a|b'.gsub('|', ''));
- //'ab'.gsub('', ''); // freeze
this.assertEqual('ab', 'ab(?:)'.gsub('(?:)', ''));
this.assertEqual('ab', 'ab()'.gsub('()', ''));
this.assertEqual('ab', 'ab'.gsub('^', ''));
@@ -77,6 +76,12 @@ new Test.Unit.Runner({
this.assertEqual('ab', 'a.b'.gsub('.', ''));
},
+ testGsubWithZeroLengthMatch: function() {
+ this.assertEqual('ab', 'ab'.gsub('', ''));
+ this.assertEqual('a', 'a'.gsub(/b*/, 'c'));
+ this.assertEqual('abc', 'abc'.gsub(/b{0}/, ''));
+ },
+
testSubWithReplacementFunction: function() {
var source = 'foo boo boz';
commit 36a9f70687b0a1b0d93349d9e1ba7061059399f9 (from 075625c037f1201a227c6ee2ab2b628c25bf8cb1)
Merge: c8a6942 075625c
Author: Andrew Dupont <[email protected]>
Date: Mon Aug 27 15:10:48 2012 -0700
Merge pull request #27 from rlineweaver/master
Avoid an infinite loop in `String#gsub` when there is a zero-length match.
diff --git a/CHANGELOG b/CHANGELOG
index 702a20b..796e908 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,8 @@
+-----------------------------------------------------------------------------
+NOTE: This changelog is no longer updated. Consult the commit history for a
+list of changes from version to version.
+-----------------------------------------------------------------------------
+
*1.7* (November 16, 2010)
* Ensure `Element#update` works with string content that includes a LINK tag in Internet Explorer. [#264 state:resolved] (Tobias H. Michaelsen, Andrew Dupont)
diff --git a/Rakefile b/Rakefile
index c2b744c..aeab195 100755
--- a/Rakefile
+++ b/Rakefile
@@ -157,10 +157,19 @@ EOF
end
def self.get_selector_engine(name)
- return if name == DEFAULT_SELECTOR_ENGINE || !name
+ return if !name
+ # If the submodule exists, we should use it, even if we're using the
+ # default engine; the user might have fetched it manually, and thus would
+ # want to build a distributable with the most recent version of that
+ # engine.
submodule_path = File.join(ROOT_DIR, "vendor", name)
return submodule_path if File.exist?(File.join(submodule_path, "repository", ".git"))
return submodule_path if name === "legacy_selector"
+
+ # If it doesn't exist, we should fetch it, _unless_ it's the default
+ # engine. We've already got a known version of the default engine in our
+ # load path.
+ return if name == DEFAULT_SELECTOR_ENGINE
get_submodule('the required selector engine', "#{name}/repository")
unless File.exist?(submodule_path)
puts "The selector engine you required isn't available at vendor/#{name}.\n\n"
diff --git a/src/constants.yml b/src/constants.yml
index e3db1ba..c85abf6 100644
--- a/src/constants.yml
+++ b/src/constants.yml
@@ -1 +1 @@
-PROTOTYPE_VERSION: 1.7
+PROTOTYPE_VERSION: 1.7.1
diff --git a/src/prototype/ajax.js b/src/prototype/ajax.js
index 137be07..55f2375 100644
--- a/src/prototype/ajax.js
+++ b/src/prototype/ajax.js
@@ -63,6 +63,13 @@
* * `requestHeaders` ([[Object]]): A set of key-value pairs, with properties
* representing header names.
* * `evalJS` ([[Boolean]] | [[String]]; default `true`): Automatically `eval`s
+ * the content of [[Ajax.Response#responseText]] if the `Content-type` returned
+ * by the server is set to one of `text/javascript`, `application/ecmascript`
+ * (matches expression `(text|application)\/(x-)?(java|ecma)script`).
+ * If the request doesn't obey same-origin policy, the content is not evaluated.
+ * If you need to force evalutation, pass `'force'`. To prevent it altogether,
+ * pass `false`.
+ * * `evalJSON` ([[Boolean]] | [[String]]; default `true`): Automatically `eval`s
* the content of [[Ajax.Response#responseText]] and populates
* [[Ajax.Response#responseJSON]] with it if the `Content-type` returned by
* the server is set to `application/json`. If the request doesn't obey
diff --git a/src/prototype/ajax/request.js b/src/prototype/ajax/request.js
index f50ece6..b264249 100644
--- a/src/prototype/ajax/request.js
+++ b/src/prototype/ajax/request.js
@@ -49,7 +49,7 @@
* status-specific callback is defined, it gets invoked. Otherwise, if
* `onSuccess` is defined and the response is deemed a success (see below), it
* is invoked. Otherwise, if `onFailure` is defined and the response is *not*
- * deemed a sucess, it is invoked. Only after that potential first callback is
+ * deemed a success, it is invoked. Only after that potential first callback is
* `onComplete` called.
*
* ##### A note on portability
diff --git a/src/prototype/ajax/responders.js b/src/prototype/ajax/responders.js
index daa9326..0f5611e 100644
--- a/src/prototype/ajax/responders.js
+++ b/src/prototype/ajax/responders.js
@@ -69,8 +69,8 @@
Ajax.Responders = {
responders: [],
- _each: function(iterator) {
- this.responders._each(iterator);
+ _each: function(iterator, context) {
+ this.responders._each(iterator, context);
},
/**
diff --git a/src/prototype/ajax/response.js b/src/prototype/ajax/response.js
index 5054909..7b70092 100644
--- a/src/prototype/ajax/response.js
+++ b/src/prototype/ajax/response.js
@@ -151,7 +151,23 @@ Ajax.Response = Class.create({
_getHeaderJSON: function() {
var json = this.getHeader('X-JSON');
if (!json) return null;
- json = decodeURIComponent(escape(json));
+
+ try {
+ // Browsers expect HTTP headers to be ASCII and nothing else. Running
+ // them through `decodeURIComponent` processes them with the page's
+ // specified encoding.
+ json = decodeURIComponent(escape(json));
+ } catch(e) {
+ // Except Chrome doesn't seem to need this, and calling
+ // `decodeURIComponent` on text that's already in the proper encoding
+ // will throw a `URIError`. The ugly solution is to assume that a
+ // `URIError` raised here signifies that the text is, in fact, already
+ // in the correct encoding, and treat the failure as a good sign.
+ //
+ // This is ugly, but so too is sending extended characters in an HTTP
+ // header with no spec to back you up.
+ }
+
try {
return json.evalJSON(this.request.options.sanitizeJSON ||
!this.request.isSameOrigin());
diff --git a/src/prototype/deprecated.js b/src/prototype/deprecated.js
index 4f48677..26351b7 100644
--- a/src/prototype/deprecated.js
+++ b/src/prototype/deprecated.js
@@ -156,10 +156,10 @@ Element.ClassNames.prototype = {
this.element = $(element);
},
- _each: function(iterator) {
+ _each: function(iterator, context) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
- })._each(iterator);
+ })._each(iterator, context);
},
set: function(className) {
diff --git a/src/prototype/dom.js b/src/prototype/dom.js
index 6003cd0..a93263e 100644
--- a/src/prototype/dom.js
+++ b/src/prototype/dom.js
@@ -8,6 +8,7 @@
/**
* == DOM ==
+ *
* Extensions to DOM elements, plus other utilities for DOM traversal
* and modification.
*
diff --git a/src/prototype/dom/dom.js b/src/prototype/dom/dom.js
index a068c29..5a02d0e 100644
--- a/src/prototype/dom/dom.js
+++ b/src/prototype/dom/dom.js
@@ -1,12 +1,16 @@
(function(GLOBAL) {
- var UNDEFINED = void 0;
+ var UNDEFINED;
var SLICE = Array.prototype.slice;
// Try to reuse the same created element as much as possible. We'll use
// this DIV for capability checks (where possible) and for normalizing
// HTML content.
var DIV = document.createElement('div');
+
+ /** section: DOM
+ * class Element
+ **/
/** section: DOM, related to: Element
* $(id) -> Element
@@ -184,12 +188,12 @@
*
* ##### Examples
*
- * Hide the element
+ * Hide the element:
*
* $(element).hide();
*
* Return an [[Enumerable]] of all descendant nodes of the element with the id
- * "article"
+ * "articles":
*
* $('articles').descendants();
**/
@@ -230,7 +234,7 @@
element = $(element);
var result = '<' + element.tagName.toLowerCase();
- var attribute;
+ var attribute, value;
for (var property in INSPECT_ATTRIBUTES) {
attribute = INSPECT_ATTRIBUTES[property];
value = (element[property] || '').toString();
@@ -242,7 +246,7 @@
methods.inspect = inspect;
- // VISIBLITY
+ // VISIBILITY
/**
* Element.visible(@element) -> Boolean
@@ -303,8 +307,8 @@
*
* ##### Examples
*
- * <div id="welcome-message"></div>
- * <div id="error-message" style="display:none;"></div>
+ * <div id="welcome-message">Welcome</div>
+ * <div id="error-message" style="display:none;">Error</div>
*
* $('welcome-message').toggle();
* // -> Element (and hides div#welcome-message)
@@ -312,7 +316,7 @@
* $('error-message').toggle();
* // -> Element (and displays div#error-message)
*
- * $('error-message).toggle(true);
+ * $('error-message').toggle(true);
* // -> Element (and displays div#error-message, no matter what its
* // previous state)
*
@@ -517,7 +521,7 @@
var LINK_ELEMENT_INNERHTML_BUGGY = (function() {
try {
var el = document.createElement('div');
- el.innerHTML = "<link>";
+ el.innerHTML = "<link />";
var isBuggy = (el.childNodes.length === 0);
el = null;
return isBuggy;
@@ -1121,7 +1125,7 @@
}
if (workaround) {
- div.innerHTML = ' ' + t[0] + html + t[1];
+ div.innerHTML = ' ' + t[0] + html + t[1];
div.removeChild(div.firstChild);
for (var i = t[2]; i--; )
div = div.firstChild;
@@ -1162,7 +1166,7 @@
var uid = getUniqueElementID(element);
if (uid) {
Element.stopObserving(element);
- if (HAS_UNIQUE_ID_PROPERTY)
+ if (!HAS_UNIQUE_ID_PROPERTY)
element._prototypeUID = UNDEFINED;
delete Element.Storage[uid];
}
@@ -1175,7 +1179,7 @@
}
function purgeCollection_IE(elements) {
- var i = elements.length, element, eventName, responders, uid, j;
+ var i = elements.length, element, uid;
while (i--) {
element = elements[i];
uid = getUniqueElementID(element);
@@ -1184,7 +1188,7 @@
}
}
- if (!window.addEventListener && window.attachEvent) {
+ if (HAS_UNIQUE_ID_PROPERTY) {
purgeCollection = purgeCollection_IE;
}
@@ -1347,14 +1351,14 @@
* Then:
*
* $('australopithecus').firstDescendant();
- * // -> div#homo-herectus
+ * // -> div#homo-erectus
*
* // the DOM property returns any first node
- * $('homo-herectus').firstChild;
+ * $('homo-erectus').firstChild;
* // -> comment node "Latin is super"
*
* // this is what we want!
- * $('homo-herectus').firstDescendant();
+ * $('homo-erectus').firstDescendant();
* // -> div#homo-neanderthalensis
**/
function firstDescendant(element) {
@@ -1541,6 +1545,30 @@
return selector.match(element);
}
+
+ // Internal method for optimizing traversal. Works like
+ // `recursivelyCollect`, except it stops at the first match and doesn't
+ // extend any elements except for the returned element.
+ function _recursivelyFind(element, property, expression, index) {
+ element = $(element), expression = expression || 0, index = index || 0;
+ if (Object.isNumber(expression)) {
+ index = expression, expression = null;
+ }
+
+ while (element = element[property]) {
+ // Skip any non-element nodes.
+ if (element.nodeType !== 1) continue;
+ // Skip any nodes that don't match the expression, if there is one.
+ if (expression && !Prototype.Selector.match(element, expression))
+ continue;
+ // Skip the first `index` matches we find.
+ if (--index >= 0) continue;
+
+ return Element.extend(element);
+ }
+ }
+
+
/**
* Element.up(@element[, expression[, index = 0]]) -> Element
* Element.up(@element[, index = 0]) -> Element
@@ -1644,14 +1672,11 @@
**/
function up(element, expression, index) {
element = $(element);
-
+
if (arguments.length === 1) return $(element.parentNode);
-
- var ancestors = Element.ancestors(element);
- return Object.isNumber(expression) ? ancestors[expression] :
- Prototype.Selector.find(ancestors, expression, index);
+ return _recursivelyFind(element, 'parentNode', expression, index);
}
-
+
/**
* Element.down(@element[, expression[, index = 0]]) -> Element
* Element.down(@element[, index = 0]) -> Element
@@ -1750,38 +1775,15 @@
* // -> undefined
**/
function down(element, expression, index) {
- element = $(element);
+ element = $(element), expression = expression || 0, index = index || 0;
- if (arguments.length === 1) return firstDescendant(element);
+ if (Object.isNumber(expression))
+ index = expression, expression = '*';
- return Object.isNumber(expression) ? Element.descendants(element)[expression] :
- Element.select(element, expression)[index || 0];
- }
-
-
- function _descendants(element) {
- var nodes = element.getElementsByTagName('*'), results = [];
- for (var i = 0, node; node = nodes[i]; i++)
- if (node.tagName !== "!") // Filter out comment nodes.
- results.push(node);
- return results;
- }
-
- // We optimize Element#down for IE so that it does not call
- // Element#descendants (and therefore extend all nodes).
- function down_IE(element, expression, index) {
- element = $(element);
- if (arguments.length === 1)
- return Element.firstDescendant(element);
-
- var node = Object.isNumber(expression) ? _descendants(element)[expression] :
- Element.select(element, expression)[index || 0];
+ var node = Prototype.Selector.select(expression, element)[index];
return Element.extend(node);
}
-
- if (!Prototype.BrowserFeatures.ElementExtensions)
- down = down_IE;
-
+
/**
* Element.previous(@element[, expression[, index = 0]]) -> Element
* Element.previous(@element[, index = 0]) -> Element
@@ -1882,16 +1884,7 @@
* // -> undefined
**/
function previous(element, expression, index) {
- element = $(element);
- if (Object.isNumber(expression))
- index = expression, expression = false;
- if (!Object.isNumber(index)) index = 0;
-
- if (expression) {
- return Prototype.Selector.find(previousSiblings(element), expression, index);
- } else {
- return recursivelyCollect(element, 'previousSibling', index + 1)[index];
- }
+ return _recursivelyFind(element, 'previousSibling', expression, index);
}
/**
@@ -1994,16 +1987,7 @@
* // -> undefined
**/
function next(element, expression, index) {
- element = $(element);
- if (Object.isNumber(expression))
- index = expression, expression = false;
- if (!Object.isNumber(index)) index = 0;
-
- if (expression) {
- return Prototype.Selector.find(nextSiblings(element), expression, index);
- } else {
- return recursivelyCollect(element, 'nextSibling', index + 1)[index];
- }
+ return _recursivelyFind(element, 'nextSibling', expression, index);
}
/**
@@ -2135,7 +2119,7 @@
* // -> false
**/
function descendantOf_DOM(element, ancestor) {
- element = $(element);
+ element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element === ancestor) return true;
return false;
@@ -2301,8 +2285,7 @@
* // -> 'some info.'
**/
function readAttribute(element, name) {
- element = $(element);
- return element.getAttribute(name);
+ return $(element).getAttribute(name);
}
function readAttribute_IE(element, name) {
@@ -2329,7 +2312,7 @@
function readAttribute_Opera(element, name) {
if (name === 'title') return element.title;
- return element.getAttribute(attribute);
+ return element.getAttribute(name);
}
var PROBLEMATIC_ATTRIBUTE_READING = (function() {
@@ -2405,7 +2388,7 @@
function getRegExpForClassName(className) {
if (regExpCache[className]) return regExpCache[className];
- re = new RegExp("(^|\\s+)" + className + "(\\s+|$)");
+ var re = new RegExp("(^|\\s+)" + className + "(\\s+|$)");
regExpCache[className] = re;
return re;
}
@@ -2488,7 +2471,7 @@
* $('mutsu').removeClassName('food');
* // -> Element
*
- * $('mutsu').classNames;
+ * $('mutsu').className;
* // -> 'apple fruit'
**/
function removeClassName(element, className) {
@@ -2809,8 +2792,12 @@
*
* ##### Notes
*
- * Internet Explorer returns literal values while other browsers return
- * computed values.
+ * Not all CSS shorthand properties are supported. You may only use the CSS
+ * properties described in the
+ * [Document Object Model (DOM) Level 2 Style Specification](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-ElementCSSInlineStyle).
+ *
+ * Old versions of Internet Explorer return _literal_ values; other browsers
+ * return _computed_ values.
*
* Consider the following HTML snippet:
*
@@ -2829,12 +2816,33 @@
* // -> '1em' in Internet Explorer,
* // -> '12px' elsewhere.
*
+ *
* Safari returns `null` for *any* non-inline property if the element is
* hidden (has `display` set to `'none'`).
+ *
+ * ##### Caveats
+ *
+ * Early versions of Prototype attempted to "fix" this behavior for
+ * certain properties. A few examples:
+ *
+ * 1. Reading and writing the CSS `opacity` property works exactly like
+ * calling [[Element.getOpacity]] and [[Element.setOpacity]]
+ * respectively. This lets us pretend that IE didn't have a
+ * proprietary way to set opacity in versions 6-7.
+ * 2. Browsers disagree on how to report certain properties of hidden
+ * elements (i.e., `display: none`). Opera, for instance, says that a
+ * hidden element has a `width` of `0px`. It's an arguable point, but
+ * we return `null` in those cases instead (so as to agree with the
+ * majority behavior). **In short: if an element is hidden,
+ * `getStyle('width')` and `getStyle('height')` will return `null`.**
+ * 3. In older versions of Internet Explorer, Prototype will return a
+ * pixel value for `width` and `height`, even if the literal value is
+ * a different unit. It does this by treating `width` like `offsetWidth`
+ * and `height` like `offsetHeight`. This is often the incorrect
+ * measurement, but it's a mistake we're stuck with for
+ * backward-compatibility. **If you're trying to measure an element's
+ * dimensions, don't use `getStyle`; use [[Element.measure]] instead.**
*
- * Not all CSS shorthand properties are supported. You may only use the CSS
- * properties described in the
- * [Document Object Model (DOM) Level 2 Style Specification](http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-ElementCSSInlineStyle).
**/
function getStyle(element, style) {
element = $(element);
@@ -2883,7 +2891,7 @@
value = element.currentStyle[style];
}
- if (style === 'opacity')
+ if (style === 'opacity' && !STANDARD_CSS_OPACITY_SUPPORTED)
return getOpacity_IE(element);
if (value === 'auto') {
@@ -2907,6 +2915,11 @@
return element;
}
+ // Opacity feature test borrowed from Modernizr.
+ var STANDARD_CSS_OPACITY_SUPPORTED = (function() {
+ DIV.style.cssText = "opacity:.55";
+ return /^0.55/.test(DIV.style.opacity);
+ })();
/**
* Element.setOpacity(@element, opacity) -> [Element...]
@@ -2936,7 +2949,15 @@
return element;
}
+ // The IE versions of `setOpacity` and `getOpacity` are aware of both
+ // the standard approach (an `opacity` property in CSS) and the old-style
+ // IE approach (a proprietary `filter` property). They are written to
+ // prefer the standard approach unless it isn't supported.
function setOpacity_IE(element, value) {
+ // Prefer the standard CSS approach unless it's not supported.
+ if (STANDARD_CSS_OPACITY_SUPPORTED)
+ return setOpacity(element, value);
+
element = hasLayout_IE($(element));
var filter = Element.getStyle(element, 'filter'),
style = element.style;
@@ -2970,6 +2991,10 @@
}
function getOpacity_IE(element) {
+ // Prefer the standard CSS approach unless it's not supported.
+ if (STANDARD_CSS_OPACITY_SUPPORTED)
+ return getOpacity(element);
+
var filter = Element.getStyle(element, 'filter');
if (filter.length === 0) return 1.0;
var match = (filter || '').match(/alpha\(opacity=(.*)\)/);
@@ -2984,7 +3009,7 @@
setOpacity: setOpacity,
getOpacity: getOpacity
});
-
+
if ('styleFloat' in DIV.style) {
methods.getStyle = getStyle_IE;
methods.setOpacity = setOpacity_IE;
@@ -2994,7 +3019,7 @@
// STORAGE
var UID = 0;
- GLOBAL.Element.Storage = { UID: 0 };
+ GLOBAL.Element.Storage = { UID: 1 };
function getUniqueElementID(element) {
if (element === window) return 0;
@@ -3037,8 +3062,11 @@
/**
* Element.store(@element, key, value) -> Element
+ * Element.store(@element, object) -> Element
*
- * Stores a key/value pair of custom metadata on the element.
+ * Stores a key/value pair of custom metadata on the element. If it is
+ * given one argument instead of two, it treats that argument as an object
+ * of key/value pairs, and stores _each_ pair as element metadata.
*
* The metadata can later be retrieved with [[Element.retrieve]].
**/
diff --git a/src/prototype/dom/event.js b/src/prototype/dom/event.js
index b086b8c..2f5f815 100644
--- a/src/prototype/dom/event.js
+++ b/src/prototype/dom/event.js
@@ -220,6 +220,13 @@
* });
**/
function element(event) {
+ // The public version of `Event.element` is a thin wrapper around the
+ // private `_element` method below. We do this so that we can use it
+ // internally as `_element` without having to extend the node.
+ return Element.extend(_element(event));
+ }
+
+ function _element(event) {
event = Event.extend(event);
var node = event.target, type = event.type,
@@ -253,8 +260,7 @@
* its ancestor chain. If `expression` is not given, the element which fired
* the event is returned.
*
- * *If no matching element is found, the document itself (`HTMLDocument` node)
- * is returned.*
+ * *If no matching element is found, `undefined` is returned.*
*
* ##### Example
*
@@ -263,18 +269,16 @@
*
* document.observe('click', function(event) {
* var element = event.findElement('p');
- * if (element != document)
+ * if (element)
* $(element).hide();
* });
**/
function findElement(event, expression) {
- var element = Event.element(event);
-
- if (!expression) return element;
+ var element = _element(event), match = Prototype.Selector.match;
+ if (!expression) return Element.extend(element);
while (element) {
- if (Object.isElement(element) && Prototype.Selector.match(element, expression)) {
+ if (Object.isElement(element) && match(element, expression))
return Element.extend(element);
- }
element = element.parentNode;
}
}
@@ -529,15 +533,19 @@
Event._isCustomEvent = isCustomEvent;
- function getRegistryForElement(element) {
+ // These two functions take an optional UID as a second argument so that we
+ // can skip lookup if we've already got the element's UID.
+ function getRegistryForElement(element, uid) {
var CACHE = GLOBAL.Event.cache;
- var uid = getUniqueElementID(element);
+ if (Object.isUndefined(uid))
+ uid = getUniqueElementID(element);
if (!CACHE[uid]) CACHE[uid] = { element: element };
return CACHE[uid];
}
- function destroyRegistryForElement(element) {
- var uid = getUniqueElementID(element);
+ function destroyRegistryForElement(element, uid) {
+ if (Object.isUndefined(uid))
+ uid = getUniqueElementID(element);
delete GLOBAL.Event.cache[uid];
}
@@ -892,11 +900,17 @@
// Stop observing _all_ listeners on an element.
function stopObservingElement(element) {
- var registry = getRegistryForElement(element);
- destroyRegistryForElement(element);
+ var uid = getUniqueElementID(element),
+ registry = getRegistryForElement(element, uid);
+
+ destroyRegistryForElement(element, uid);
var entries, i;
for (var eventName in registry) {
+ // Explicitly skip elements so we don't accidentally find one with a
+ // `length` property.
+ if (eventName === 'element') continue;
+
entries = registry[eventName];
i = entries.length;
while (i--)
@@ -1132,6 +1146,7 @@
Element.addMethods({
/**
* Element.fire(@element, eventName[, memo[, bubble = true]]) -> Event
+ *
* See [[Event.fire]].
*
* Fires a custom event with the current element as its target.
@@ -1177,18 +1192,21 @@
/**
* Element.observe(@element, eventName, handler) -> Element
+ *
* See [[Event.observe]].
**/
observe: observe,
/**
* Element.stopObserving(@element[, eventName[, handler]]) -> Element
+ *
* See [[Event.stopObserving]].
**/
stopObserving: stopObserving,
/**
* Element.on(@element, eventName[, selector], callback) -> Element
+ *
* See [[Event.on]].
**/
on: on
@@ -1257,7 +1275,7 @@
stopObserving: stopObserving.methodize(),
/**
- * Element.on(@element, eventName[, selector], callback) -> Event.Handler
+ * document.on(@element, eventName[, selector], callback) -> Event.Handler
*
* See [[Event.on]].
**/
@@ -1297,7 +1315,7 @@
&& 'onmouseleave' in docEl;
function isSimulatedMouseEnterLeaveEvent(eventName) {
- return MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED &&
+ return !MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED &&
(eventName === 'mouseenter' || eventName === 'mouseleave');
}
@@ -1312,9 +1330,9 @@
return createMouseEnterLeaveResponder(uid, eventName, handler);
return function(event) {
- var cacheEntry = Event.cache[uid];
- var element = cacheEntry.element;
-
+ if (!Event.cache) return;
+
+ var element = Event.cache[uid].element;
Event.extend(event, element);
handler.call(element, event);
};
@@ -1322,7 +1340,7 @@
function createResponderForCustomEvent(uid, eventName, handler) {
return function(event) {
- var cacheEntry = Event.cache[uid], element = cacheEntry.element;
+ var element = Event.cache[uid].element;
if (Object.isUndefined(event.eventName))
return false;
@@ -1337,8 +1355,8 @@
function createMouseEnterLeaveResponder(uid, eventName, handler) {
return function(event) {
- var cacheEntry = Event.cache[uid], element = cacheEntry.element;
-
+ var element = Event.cache[uid].element;
+
Event.extend(event, element);
var parent = event.relatedTarget;
diff --git a/src/prototype/dom/form.js b/src/prototype/dom/form.js
index 8088e9d..8aa4b6e 100644
--- a/src/prototype/dom/form.js
+++ b/src/prototype/dom/form.js
@@ -120,7 +120,14 @@ var Form = {
} else {
initial = '';
accumulator = function(result, key, value) {
- return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
+ // Normalize newlines as \r\n because the HTML spec says newlines should
+ // be encoded as CRLFs.
+ value = value.gsub(/(\r)?\n/, '\r\n');
+ value = encodeURIComponent(value);
+ // Likewise, according to the spec, spaces should be '+' rather than
+ // '%20'.
+ value = value.gsub(/%20/, '+');
+ return result + (result ? '&' : '') + encodeURIComponent(key) + '=' + value;
}
}
@@ -184,21 +191,16 @@ Form.Methods = {
* OPTION elements are not included in the result; only their parent
* SELECT control is.
**/
+
getElements: function(form) {
- var elements = $(form).getElementsByTagName('*'),
- element,
- arr = [ ],
- serializers = Form.Element.Serializers;
- // `length` is not used to prevent interference with
- // length-named elements shadowing `length` of a nodelist
+ var elements = $(form).getElementsByTagName('*');
+ var element, results = [], serializers = Form.Element.Serializers;
+
for (var i = 0; element = elements[i]; i++) {
- arr.push(element);
+ if (serializers[element.tagName.toLowerCase()])
+ results.push(Element.extend(element));
}
- return arr.inject([], function(elements, child) {
- if (serializers[child.tagName.toLowerCase()])
- elements.push(Element.extend(child));
- return elements;
- })
+ return results;
},
/**
diff --git a/src/prototype/dom/layout.js b/src/prototype/dom/layout.js
index 71027f6..f376c39 100644
--- a/src/prototype/dom/layout.js
+++ b/src/prototype/dom/layout.js
@@ -1,4 +1,3 @@
-
(function() {
// Converts a CSS percentage value to a decimal.
@@ -9,6 +8,58 @@
return (Number(match[1]) / 100);
}
+ // A bare-bones version of Element.getStyle. Needed because getStyle is
+ // public-facing and too user-friendly for our tastes. We need raw,
+ // non-normalized values.
+ //
+ // Camel-cased property names only.
+ function getRawStyle(element, style) {
+ element = $(element);
+
+ // Try inline styles first.
+ var value = element.style[style];
+ if (!value || value === 'auto') {
+ // Reluctantly retrieve the computed style.
+ var css = document.defaultView.getComputedStyle(element, null);
+ value = css ? css[style] : null;
+ }
+
+ if (style === 'opacity') return value ? parseFloat(value) : 1.0;
+ return value === 'auto' ? null : value;
+ }
+
+ function getRawStyle_IE(element, style) {
+ // Try inline styles first.
+ var value = element.style[style];
+ if (!value && element.currentStyle) {
+ // Reluctantly retrieve the current style.
+ value = element.currentStyle[style];
+ }
+ return value;
+ }
+
+ // Quickly figures out the content width of an element. Used instead of
+ // `element.measure('width')` in several places below; we don't want to
+ // call back into layout code recursively if we don't have to.
+ //
+ // But this means it doesn't handle edge cases. Use it when you know the
+ // element in question is visible and will give accurate measurements.
+ function getContentWidth(element, context) {
+ var boxWidth = element.offsetWidth;
+
+ var bl = getPixelValue(element, 'borderLeftWidth', context) || 0;
+ var br = getPixelValue(element, 'borderRightWidth', context) || 0;
+ var pl = getPixelValue(element, 'paddingLeft', context) || 0;
+ var pr = getPixelValue(element, 'paddingRight', context) || 0;
+
+ return boxWidth - bl - br - pl - pr;
+ }
+
+ if ('currentStyle' in document.documentElement) {
+ getRawStyle = getRawStyle_IE;
+ }
+
+
// Can be called like this:
// getPixelValue("11px");
// Or like this:
@@ -17,10 +68,10 @@
var element = null;
if (Object.isElement(value)) {
element = value;
- value = element.getStyle(property);
+ value = getRawStyle(element, property);
}
- if (value === null) {
+ if (value === null || Object.isUndefined(value)) {
return null;
}
@@ -30,8 +81,8 @@
if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) {
return window.parseFloat(value);
}
-
- var isPercentage = value.include('%'), isViewport = (context === document.viewport);
+
+ var isPercentage = value.include('%'), isViewport = (context === document.viewport);
// When IE gives us something other than a pixel value, this technique
// (invented by Dean Edwards) will convert it to pixels.
@@ -48,20 +99,23 @@
return value;
}
-
+
// For other browsers, we have to do a bit of work.
// (At this point, only percentages should be left; all other CSS units
// are converted to pixels by getComputedStyle.)
if (element && isPercentage) {
+ // The `context` argument comes into play for percentage units; it's
+ // the thing that the unit represents a percentage of. When an
+ // absolutely-positioned element has a width of 50%, we know that's
+ // 50% of its offset parent. If it's `position: fixed` instead, we know
+ // it's 50% of the viewport. And so on.
context = context || element.parentNode;
- var decimal = toDecimal(value);
- var whole = null;
- var position = element.getStyle('position');
+ var decimal = toDecimal(value), whole = null;
var isHorizontal = property.include('left') || property.include('right') ||
property.include('width');
- var isVertical = property.include('top') || property.include('bottom') ||
+ var isVertical = property.include('top') || property.include('bottom') ||
property.include('height');
if (context === document.viewport) {
@@ -87,14 +141,13 @@
// Turns plain numbers into pixel measurements.
function toCSSPixels(number) {
- if (Object.isString(number) && number.endsWith('px')) {
+ if (Object.isString(number) && number.endsWith('px'))
return number;
- }
return number + 'px';
}
+ // Shortcut for figuring out if an element is `display: none` or not.
function isDisplayed(element) {
- var originalElement = element;
while (element && element.parentNode) {
var display = element.getStyle('display');
if (display === 'none') {
@@ -105,6 +158,8 @@
return true;
}
+ // In IE6-7, positioned elements often need hasLayout triggered before they
+ // report accurate measurements.
var hasLayout = Prototype.K;
if ('currentStyle' in document.documentElement) {
hasLayout = function(element) {
@@ -156,7 +211,7 @@
*
* The following are the CSS-related properties that can be retrieved.
* Nearly all of them map directly to their property names in CSS. (The
- * only exception is for borders — e.g., `border-width` instead of
+ * only exception is for borders — e.g., `border-left` instead of
* `border-left-width`.)
*
* * `height`
@@ -282,7 +337,7 @@
**/
get: function($super, property) {
// Try to fetch from the cache.
- var value = $super(property);
+ var value = $super(property);
return value === null ? this._compute(property) : value;
},
@@ -291,14 +346,24 @@
// when hidden), elements need a "preparation" phase that ensures
// accuracy of measurements.
_begin: function() {
- if (this._prepared) return;
-
+ if (this._isPrepared()) return;
+
var element = this.element;
if (isDisplayed(element)) {
- this._prepared = true;
+ this._setPrepared(true);
return;
}
+ // If we get this far, it means this element is hidden. To get usable
+ // measurements, we must remove `display: none`, but in a manner that
+ // isn't noticeable to the user. That means we also set
+ // `visibility: hidden` to make it invisible, and `position: absolute`
+ // so that it won't alter the document flow when displayed.
+ //
+ // Once we do this, the element is "prepared," and we can make our
+ // measurements. When we're done, the `_end` method cleans up our
+ // changes.
+
// Remember the original values for some styles we're going to alter.
var originalStyles = {
position: element.style.position || '',
@@ -307,33 +372,36 @@
display: element.style.display || ''
};
- // We store them so that the `_end` function can retrieve them later.
+ // We store them so that the `_end` method can retrieve them later.
element.store('prototype_original_styles', originalStyles);
- var position = element.getStyle('position'),
- width = element.getStyle('width');
-
- if (width === "0px" || width === null) {
- // Opera won't report the true width of the element through
+ var position = getRawStyle(element, 'position'), width = element.offsetWidth;
+
+ if (width === 0 || width === null) {
+ // Opera/IE won't report the true width of the element through
// `getComputedStyle` if it's hidden. If we got a nonsensical value,
// we need to show the element and try again.
element.style.display = 'block';
- width = element.getStyle('width');
+ width = element.offsetWidth;
}
// Preserve the context in case we get a percentage value.
var context = (position === 'fixed') ? document.viewport :
element.parentNode;
- element.setStyle({
- position: 'absolute',
+ var tempStyles = {
visibility: 'hidden',
display: 'block'
- });
+ };
- var positionedWidth = element.getStyle('width');
+ // If the element's `position: fixed`, it's already out of the document
+ // flow, so it's both unnecessary and inaccurate to set
+ // `position: absolute`.
+ if (position !== 'fixed') tempStyles.position = 'absolute';
+
+ element.setStyle(tempStyles);
- var newWidth;
+ var positionedWidth = element.offsetWidth, newWidth;
if (width && (positionedWidth === width)) {
// If the element's width is the same both before and after
// we set absolute positioning, that means:
@@ -341,11 +409,11 @@
// (b) it has an explicitly-set width, instead of width: auto.
// Either way, it means the element is the width it needs to be
// in order to report an accurate height.
- newWidth = getPixelValue(element, 'width', context);
+ newWidth = getContentWidth(element, context);
} else if (position === 'absolute' || position === 'fixed') {
// Absolute- and fixed-position elements' dimensions don't depend
// upon those of their parents.
- newWidth = getPixelValue(element, 'width', context);
+ newWidth = getContentWidth(element, context);
} else {
// Otherwise, the element's width depends upon the width of its
// parent.
@@ -360,18 +428,20 @@
this.get('margin-right');
}
+ // Whatever the case, we've now figured out the correct `width` value
+ // for the element.
element.setStyle({ width: newWidth + 'px' });
// The element is now ready for measuring.
- this._prepared = true;
+ this._setPrepared(true);
},
_end: function() {
var element = this.element;
var originalStyles = element.retrieve('prototype_original_styles');
- element.store('prototype_original_styles', null);
+ element.store('prototype_original_styles', null);
element.setStyle(originalStyles);
- this._prepared = false;
+ this._setPrepared(false);
},
_compute: function(property) {
@@ -383,6 +453,14 @@
return this._set(property, COMPUTATIONS[property].call(this, this.element));
},
+ _isPrepared: function() {
+ return this.element.retrieve('prototype_element_layout_prepared', false);
+ },
+
+ _setPrepared: function(bool) {
+ return this.element.store('prototype_element_layout_prepared', bool);
+ },
+
/**
* Element.Layout#toObject([keys...]) -> Object
* - keys (String): A space-separated list of keys to include.
@@ -459,8 +537,6 @@
if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return;
var value = this.get(key);
- // Unless the value is null, add 'px' to the end and add it to the
- // returned object.
if (value != null) css[cssNameFor(key)] = value + 'px';
}, this);
return css;
@@ -523,9 +599,8 @@
var pLeft = this.get('padding-left'),
pRight = this.get('padding-right');
-
+
if (!this._preComputing) this._end();
-
return bWidth - bLeft - bRight - pLeft - pRight;
},
@@ -766,10 +841,11 @@
* `Element.getLayout` again only when the values in an existing
* `Element.Layout` object have become outdated.
*
- * Remember that instances of `Element.Layout` compute values the first
- * time they're asked for and remember those values for later retrieval.
- * If you want to compute all an element's measurements at once, pass
- *
+ * If the `preCompute` argument is `true`, all properties will be measured
+ * when the layout object is instantiated. If you plan to measure several
+ * properties of an element's dimensions, it's probably worth it to get a
+ * pre-computed hash.
+ *
* ##### Examples
*
* var layout = $('troz').getLayout();
@@ -1066,10 +1142,9 @@
* Returns the X/Y coordinates of element relative to the viewport.
**/
function viewportOffset(forElement) {
- element = $(element);
var valueT = 0, valueL = 0, docBody = document.body;
- var element = forElement;
+ var element = $(forElement);
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
@@ -1285,8 +1360,11 @@
var storage = Element.getStorage(element),
madeClipping = storage.get('prototype_made_clipping');
- if (!madeClipping) {
- var overflow = Element.getStyle(element, 'overflow') || 'auto';
+ // The "prototype_made_clipping" storage key is meant to hold the
+ // original CSS overflow value. A string value or `null` means that we've
+ // called `makeClipping` already. An `undefined` value means we haven't.
+ if (Object.isUndefined(madeClipping)) {
+ var overflow = Element.getStyle(element, 'overflow');
storage.set('prototype_made_clipping', overflow);
if (overflow !== 'hidden')
element.style.overflow = 'hidden';
@@ -1347,12 +1425,12 @@
var storage = Element.getStorage(element),
overflow = storage.get('prototype_made_clipping');
- if (overflow) {
+ if (!Object.isUndefined(overflow)) {
storage.unset('prototype_made_clipping');
- element.style.overflow = (overflow === 'auto') ? '' : overflow;
+ element.style.overflow = overflow || '';
}
- return element;
+ return element;
}
/**
@@ -1425,34 +1503,31 @@
// Find page position of source.
source = $(source);
element = $(element);
- var p = Element.viewportOffset(source), delta = [0, 0], parent = null;
-
- // A delta of 0/0 will work for `positioned: fixed` elements, but
- // for `position: absolute` we need to get the parent's offset.
- if (Element.getStyle(element, 'position') === 'absolute') {
- parent = Element.getOffsetParent(element);
- delta = Element.viewportOffset(parent);
- }
-
- // Adjust by BODY offsets. Fixes some versions of safari.
- if (parent === document.body) {
- delta[0] -= document.body.offsetLeft;
- delta[1] -= document.body.offsetTop;
+ var p, delta, layout, styles = {};
+
+ if (options.setLeft || options.setTop) {
+ p = Element.viewportOffset(source);
+ delta = [0, 0];
+ // A delta of 0/0 will work for `positioned: fixed` elements, but
+ // for `position: absolute` we need to get the parent's offset.
+ if (Element.getStyle(element, 'position') === 'absolute') {
+ var parent = Element.getOffsetParent(element);
+ if (parent !== document.body) delta = Element.viewportOffset(parent);
+ }
}
+ if (options.setWidth || options.setHeight) {
+ layout = Element.getLayout(source);
+ }
- var layout = Element.getLayout(source);
-
// Set position.
- var styles = {};
-
if (options.setLeft)
styles.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
if (options.setTop)
- styles.top = (p[1] - delta[1] + options.offsetTop) + 'px';
+ styles.top = (p[1] - delta[1] + options.offsetTop) + 'px';
if (options.setWidth)
- styles.width = layout.get('border-box-width') + 'px';
+ styles.width = layout.get('border-box-width') + 'px';
if (options.setHeight)
styles.height = layout.get('border-box-height') + 'px';
@@ -1509,8 +1584,9 @@
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
- if (element.offsetParent == document.body)
+ if (element.offsetParent == document.body) {
if (Element.getStyle(element, 'position') == 'absolute') break;
+ }
element = element.offsetParent;
} while (element);
diff --git a/src/prototype/dom/selector.js b/src/prototype/dom/selector.js
index 61e21af..37fdb7c 100644
--- a/src/prototype/dom/selector.js
+++ b/src/prototype/dom/selector.js
@@ -125,7 +125,7 @@ Prototype.Selector = (function() {
* Prototype.Selector.find(elements, expression[, index = 0]) -> Element
* - elements (Enumerable): a collection of DOM elements.
* - expression (String): A CSS selector.
- * - index: Numeric index of the match to return, defaults to 0.
+ * - index (Number): Numeric index of the match to return, defaults to 0.
*
* Filters the given collection of elements with `expression` and returns the
* first matching element (or the `index`th matching element if `index` is
diff --git a/src/prototype/lang.js b/src/prototype/lang.js
index 8a23edf..ff236d1 100644
--- a/src/prototype/lang.js
+++ b/src/prototype/lang.js
@@ -15,6 +15,7 @@
/**
* == Language ==
+ *
* Additions to JavaScript's "standard library" and extensions to
* built-in JavaScript objects.
**/
diff --git a/src/prototype/lang/array.js b/src/prototype/lang/array.js
index 85b6be9..2a5f065 100644
--- a/src/prototype/lang/array.js
+++ b/src/prototype/lang/array.js
@@ -358,7 +358,7 @@ Array.from = $A;
**/
function intersect(array) {
return this.uniq().findAll(function(item) {
- return array.detect(function(value) { return item === value });
+ return array.indexOf(item) !== -1;
});
}
@@ -411,6 +411,12 @@ Array.from = $A;
* or `-1` if `item` doesn't exist in the array. `Array#indexOf` compares
* items using *strict equality* (`===`).
*
+ * `Array#indexOf` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.4.4.14) for more
+ * information.
+ *
* ##### Examples
*
* [3, 5, 6, 1, 20].indexOf(1)
@@ -423,43 +429,312 @@ Array.from = $A;
* // -> -1 (not found, 1 !== '1')
**/
function indexOf(item, i) {
- i || (i = 0);
- var length = this.length;
- if (i < 0) i = length + i;
- for (; i < length; i++)
- if (this[i] === item) return i;
+ if (this == null) throw new TypeError();
+
+ var array = Object(this), length = array.length >>> 0;
+ if (length === 0) return -1;
+
+ // The rules for the `fromIndex` argument are tricky. Let's follow the
+ // spec line-by-line.
+ i = Number(i);
+ if (isNaN(i)) {
+ i = 0;
+ } else if (i !== 0 && isFinite(i)) {
+ // Equivalent to ES5's `ToInteger` operation.
+ i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i));
+ }
+
+ // If the search index is greater than the length of the array,
+ // return -1.
+ if (i > length) return -1;
+
+ // If the search index is negative, take its absolute value, subtract it
+ // from the length, and make that the new search index. If it's still
+ // negative, make it 0.
+ var k = i >= 0 ? i : Math.max(length - Math.abs(i), 0);
+ for (; k < length; k++)
+ if (k in array && array[k] === item) return k;
return -1;
}
+
/** related to: Array#indexOf
* Array#lastIndexOf(item[, offset]) -> Number
* - item (?): A value that may or may not be in the array.
- * - offset (Number): The number of items at the end to skip before beginning
- * the search.
- *
- * Returns the position of the last occurrence of `item` within the array — or
- * `-1` if `item` doesn't exist in the array.
+ * - offset (Number): The number of items at the end to skip before
+ * beginning the search.
+ *
+ * Returns the position of the last occurrence of `item` within the
+ * array — or `-1` if `item` doesn't exist in the array.
+ *
+ * `Array#lastIndexOf` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.4.4.15) for more
+ * information.
**/
function lastIndexOf(item, i) {
- i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
- var n = this.slice(0, i).reverse().indexOf(item);
- return (n < 0) ? n : i - n - 1;
+ if (this == null) throw new TypeError();
+
+ var array = Object(this), length = array.length >>> 0;
+ if (length === 0) return -1;
+
+ // The rules for the `fromIndex` argument are tricky. Let's follow the
+ // spec line-by-line.
+ if (!Object.isUndefined(i)) {
+ i = Number(i);
+ if (isNaN(i)) {
+ i = 0;
+ } else if (i !== 0 && isFinite(i)) {
+ // Equivalent to ES5's `ToInteger` operation.
+ i = (i > 0 ? 1 : -1) * Math.floor(Math.abs(i));
+ }
+ } else {
+ i = length;
+ }
+
+ // If fromIndex is positive, clamp it to the last index in the array;
+ // if it's negative, subtract its absolute value from the array's length.
+ var k = i >= 0 ? Math.min(i, length - 1) :
+ length - Math.abs(i);
+
+ // (If fromIndex is still negative, it'll bypass this loop altogether and
+ // return -1.)
+ for (; k >= 0; k--)
+ if (k in array && array[k] === item) return k;
+ return -1;
}
// Replaces a built-in function. No PDoc needed.
- function concat() {
- var array = slice.call(this, 0), item;
- for (var i = 0, length = arguments.length; i < length; i++) {
- item = arguments[i];
+ //
+ // Used instead of the broken version of Array#concat in some versions of
+ // Opera. Made to be ES5-compliant.
+ function concat(_) {
+ var array = [], items = slice.call(arguments, 0), item, n = 0;
+ items.unshift(this);
+ for (var i = 0, length = items.length; i < length; i++) {
+ item = items[i];
if (Object.isArray(item) && !('callee' in item)) {
- for (var j = 0, arrayLength = item.length; j < arrayLength; j++)
- array.push(item[j]);
+ for (var j = 0, arrayLength = item.length; j < arrayLength; j++) {
+ if (j in item) array[n] = item[j];
+ n++;
+ }
} else {
- array.push(item);
+ array[n++] = item;
}
}
+ array.length = n;
return array;
}
+
+ // Certain ES5 array methods have the same names as Prototype array methods
+ // and perform the same functions.
+ //
+ // Prototype's implementations of these methods differ from the ES5 spec in
+ // the way a missing iterator function is handled. Prototype uses
+ // `Prototype.K` as a default iterator, while ES5 specifies that a
+ // `TypeError` must be thrown. Implementing the ES5 spec completely would
+ // break backward compatibility and would force users to pass `Prototype.K`
+ // manually.
+ //
+ // Instead, if native versions of these methods exist, we wrap the existing
+ // methods with our own behavior. This has very little performance impact.
+ // It violates the spec by suppressing `TypeError`s for certain methods,
+ // but that's an acceptable trade-off.
+
+ function wrapNative(method) {
+ return function() {
+ if (arguments.length === 0) {
+ // No iterator was given. Instead of throwing a `TypeError`, use
+ // `Prototype.K` as the default iterator.
+ return method.call(this, Prototype.K);
+ } else if (arguments[0] === undefined) {
+ // Same as above.
+ var args = slice.call(arguments, 1);
+ args.unshift(Prototype.K);
+ return method.apply(this, args);
+ } else {
+ // Pass straight through to the native method.
+ return method.apply(this, arguments);
+ }
+ };
+ }
+
+ // Note that #map, #filter, #some, and #every take some extra steps for
+ // ES5 compliance: the context in which they're called is coerced to an
+ // object, and that object's `length` property is coerced to a finite
+ // integer. This makes it easier to use the methods as generics.
+ //
+ // This means that they behave a little differently from other methods in
+ // `Enumerable`/`Array` that don't collide with ES5, but that's OK.
+
+ /**
+ * Array#map([iterator = Prototype.K[, context]]) -> Array
+ * - iterator (Function): The iterator function to apply to each element
+ * in the enumeration.
+ * - context (Object): An optional object to use as `this` within
+ * calls to the iterator.
+ *
+ * Returns the result of applying `iterator` to each item in the array. If
+ * no iterator is provided, the elements are simply copied to the returned
+ * array.
+ *
+ * `Array#map` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.4.4.19) for more
+ * information.
+ **/
+ function map(iterator) {
+ if (this == null) throw new TypeError();
+ iterator = iterator || Prototype.K;
+
+ var object = Object(this);
+ var results = [], context = arguments[1], n = 0;
+
+ for (var i = 0, length = object.length >>> 0; i < length; i++) {
+ if (i in object) {
+ results[n] = iterator.call(context, object[i], i, object);
+ }
+ n++;
+ }
+ results.length = n;
+ return results;
+ }
+
+ if (arrayProto.map) {
+ map = wrapNative(Array.prototype.map);
+ }
+
+ /**
+ * Array#filter(iterator[, context]) -> Array
+ * - iterator (Function): An iterator function to use to test the
+ * elements.
+ * - context (Object): An optional object to use as `this` within
+ * calls to the iterator.
+ *
+ * Returns a new array containing all the items in this array for which
+ * `iterator` returned a truthy value.
+ *
+ * `Array#filter` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.4.4.20) for more
+ * information.
+ **/
+ function filter(iterator) {
+ if (this == null || !Object.isFunction(iterator))
+ throw new TypeError();
+
+ var object = Object(this);
+ var results = [], context = arguments[1], value;
+
+ for (var i = 0, length = object.length >>> 0; i < length; i++) {
+ if (i in object) {
+ value = object[i];
+ if (iterator.call(context, value, i, object)) {
+ results.push(value);
+ }
+ }
+ }
+ return results;
+ }
+
+ if (arrayProto.filter) {
+ // `Array#filter` requires an iterator by nature, so we don't need to
+ // wrap it.
+ filter = Array.prototype.filter;
+ }
+
+ /**
+ * Array#some([iterator = Prototype.K[, context]]) -> Boolean
+ * - iterator (Function): An optional function to use to evaluate each
+ * element in the enumeration; the function should return the value to
+ * test. If this is not provided, the element itself is tested.
+ * - context (Object): An optional object to use as `this` within
+ * calls to the iterator.
+ *
+ * Determines whether at least one element is truthy (boolean-equivalent to
+ * `true`), either directly or through computation by the provided iterator.
+ *
+ * `Array#some` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.4.4.17) for more
+ * information.
+ **/
+ function some(iterator) {
+ if (this == null) throw new TypeError();
+ iterator = iterator || Prototype.K;
+ var context = arguments[1];
+
+ var object = Object(this);
+ for (var i = 0, length = object.length >>> 0; i < length; i++) {
+ if (i in object && iterator.call(context, object[i], i, object)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ if (arrayProto.some) {
+ var some = wrapNative(Array.prototype.some);
+ }
+
+
+ /**
+ * Array#every([iterator = Prototype.K[, context]]) -> Boolean
+ * - iterator (Function): An optional function to use to evaluate each
+ * element in the enumeration; the function should return the value to
+ * test. If this is not provided, the element itself is tested.
+ * - context (Object): An optional object to use as `this` within
+ * calls to the iterator.
+ *
+ * Determines whether all elements are truthy (boolean-equivalent to
+ * `true`), either directly or through computation by the provided iterator.
+ *
+ * `Array#every` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.4.4.16) for more
+ * information.
+ *
+ **/
+ function every(iterator) {
+ if (this == null) throw new TypeError();
+ iterator = iterator || Prototype.K;
+ var context = arguments[1];
+
+ var object = Object(this);
+ for (var i = 0, length = object.length >>> 0; i < length; i++) {
+ if (i in object && !iterator.call(context, object[i], i, object)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ if (arrayProto.every) {
+ var every = wrapNative(Array.prototype.every);
+ }
+
+ // Prototype's `Array#inject` behaves similarly to ES5's `Array#reduce`.
+ var _reduce = arrayProto.reduce;
+ function inject(memo, iterator) {
+ iterator = iterator || Prototype.K;
+ var context = arguments[2];
+ // The iterator must be bound, as `Array#reduce` always binds to
+ // `undefined`.
+ return _reduce.call(this, iterator.bind(context), memo);
+ }
+
+ // Piggyback on `Array#reduce` if it exists; otherwise fall back to the
+ // standard `Enumerable.inject`.
+ if (!arrayProto.reduce) {
+ var inject = Enumerable.inject;
+ }
Object.extend(arrayProto, Enumerable);
@@ -468,6 +743,18 @@ Array.from = $A;
Object.extend(arrayProto, {
_each: _each,
+
+ map: map,
+ collect: map,
+ select: filter,
+ filter: filter,
+ findAll: filter,
+ some: some,
+ any: some,
+ every: every,
+ all: every,
+ inject: inject,
+
clear: clear,
first: first,
last: last,
@@ -486,11 +773,11 @@ Array.from = $A;
// fix for opera
var CONCAT_ARGUMENTS_BUGGY = (function() {
return [].concat(arguments)[0][0] !== 1;
- })(1,2)
+ })(1,2);
if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat;
- // use native browser JS 1.6 implementation if available
+ // Use native browser JS 1.6 implementations if available.
if (!arrayProto.indexOf) arrayProto.indexOf = indexOf;
if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf;
})();
diff --git a/src/prototype/lang/class.js b/src/prototype/lang/class.js
index fa46aa7..5e66965 100644
--- a/src/prototype/lang/class.js
+++ b/src/prototype/lang/class.js
@@ -167,9 +167,22 @@ var Class = (function() {
value = (function(m) {
return function() { return ancestor[m].apply(this, arguments); };
})(property).wrap(method);
-
- value.valueOf = method.valueOf.bind(method);
- value.toString = method.toString.bind(method);
+
+ // We used to use `bind` to ensure that `toString` and `valueOf`
+ // methods were called in the proper context, but now that we're
+ // relying on native bind and/or an existing polyfill, we can't rely
+ // on the nuanced behavior of whatever `bind` implementation is on
+ // the page.
+ //
+ // MDC's polyfill, for instance, doesn't like binding functions that
+ // haven't got a `prototype` property defined.
+ value.valueOf = (function(method) {
+ return function() { return method.valueOf.call(method); };
+ })(method);
+
+ value.toString = (function(method) {
+ return function() { return method.toString.call(method); };
+ })(method);
}
this.prototype[property] = value;
}
diff --git a/src/prototype/lang/enumerable.js b/src/prototype/lang/enumerable.js
index 4d17e62..e6515e1 100644
--- a/src/prototype/lang/enumerable.js
+++ b/src/prototype/lang/enumerable.js
@@ -107,11 +107,8 @@ var Enumerable = (function() {
* has a method to do that for you.
**/
function each(iterator, context) {
- var index = 0;
try {
- this._each(function(value) {
- iterator.call(context, value, index++);
- });
+ this._each(iterator, context);
} catch (e) {
if (e != $break) throw e;
}
@@ -186,9 +183,9 @@ var Enumerable = (function() {
iterator = iterator || Prototype.K;
var result = true;
this.each(function(value, index) {
- result = result && !!iterator.call(context, value, index);
+ result = result && !!iterator.call(context, value, index, this);
if (!result) throw $break;
- });
+ }, this);
return result;
}
@@ -218,9 +215,9 @@ var Enumerable = (function() {
iterator = iterator || Prototype.K;
var result = false;
this.each(function(value, index) {
- if (result = !!iterator.call(context, value, index))
+ if (result = !!iterator.call(context, value, index, this))
throw $break;
- });
+ }, this);
return result;
}
@@ -251,8 +248,8 @@ var Enumerable = (function() {
iterator = iterator || Prototype.K;
var results = [];
this.each(function(value, index) {
- results.push(iterator.call(context, value, index));
- });
+ results.push(iterator.call(context, value, index, this));
+ }, this);
return results;
}
@@ -274,11 +271,11 @@ var Enumerable = (function() {
function detect(iterator, context) {
var result;
this.each(function(value, index) {
- if (iterator.call(context, value, index)) {
+ if (iterator.call(context, value, index, this)) {
result = value;
throw $break;
}
- });
+ }, this);
return result;
}
@@ -299,9 +296,9 @@ var Enumerable = (function() {
function findAll(iterator, context) {
var results = [];
this.each(function(value, index) {
- if (iterator.call(context, value, index))
+ if (iterator.call(context, value, index, this))
results.push(value);
- });
+ }, this);
return results;
}
@@ -345,8 +342,8 @@ var Enumerable = (function() {
this.each(function(value, index) {
if (filter.match(value))
- results.push(iterator.call(context, value, index));
- });
+ results.push(iterator.call(context, value, index, this));
+ }, this);
return results;
}
@@ -449,8 +446,8 @@ var Enumerable = (function() {
**/
function inject(memo, iterator, context) {
this.each(function(value, index) {
- memo = iterator.call(context, memo, value, index);
- });
+ memo = iterator.call(context, memo, value, index, this);
+ }, this);
return memo;
}
@@ -514,10 +511,10 @@ var Enumerable = (function() {
iterator = iterator || Prototype.K;
var result;
this.each(function(value, index) {
- value = iterator.call(context, value, index);
+ value = iterator.call(context, value, index, this);
if (result == null || value >= result)
result = value;
- });
+ }, this);
return result;
}
@@ -554,10 +551,10 @@ var Enumerable = (function() {
iterator = iterator || Prototype.K;
var result;
this.each(function(value, index) {
- value = iterator.call(context, value, index);
+ value = iterator.call(context, value, index, this);
if (result == null || value < result)
result = value;
- });
+ }, this);
return result;
}
@@ -592,9 +589,9 @@ var Enumerable = (function() {
iterator = iterator || Prototype.K;
var trues = [], falses = [];
this.each(function(value, index) {
- (iterator.call(context, value, index) ?
+ (iterator.call(context, value, index, this) ?
trues : falses).push(value);
- });
+ }, this);
return [trues, falses];
}
@@ -636,9 +633,9 @@ var Enumerable = (function() {
function reject(iterator, context) {
var results = [];
this.each(function(value, index) {
- if (!iterator.call(context, value, index))
+ if (!iterator.call(context, value, index, this))
results.push(value);
- });
+ }, this);
return results;
}
@@ -668,9 +665,9 @@ var Enumerable = (function() {
return this.map(function(value, index) {
return {
value: value,
- criteria: iterator.call(context, value, index)
+ criteria: iterator.call(context, value, index, this)
};
- }).sort(function(left, right) {
+ }, this).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
diff --git a/src/prototype/lang/function.js b/src/prototype/lang/function.js
index 9850d3b..f65938f 100644
--- a/src/prototype/lang/function.js
+++ b/src/prototype/lang/function.js
@@ -52,6 +52,12 @@ Object.extend(Function.prototype, (function() {
* function is called, it will call the original ensuring that `this` is set
* to `context`. Also optionally curries arguments for the function.
*
+ * `Function#bind` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.3.4.5) for more
+ * information.
+ *
* ##### Examples
*
* A typical use of [[Function#bind]] is to ensure that a callback (event
@@ -105,13 +111,29 @@ Object.extend(Function.prototype, (function() {
*
* (To curry without binding, see [[Function#curry]].)
**/
+
function bind(context) {
- if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
+ if (arguments.length < 2 && Object.isUndefined(arguments[0]))
+ return this;
+
+ if (!Object.isFunction(this))
+ throw new TypeError("The object is not callable.");
+
+ var nop = function() {};
var __method = this, args = slice.call(arguments, 1);
- return function() {
+
+ var bound = function() {
var a = merge(args, arguments);
- return __method.apply(context, a);
- }
+ // Ignore the supplied context when the bound function is called with
+ // the "new" keyword.
+ var c = this instanceof bound ? this : context;
+ return __method.apply(c, a);
+ };
+
+ nop.prototype = this.prototype;
+ bound.prototype = new nop();
+
+ return bound;
}
/** related to: Function#bind
@@ -376,16 +398,20 @@ Object.extend(Function.prototype, (function() {
return __method.apply(null, a);
};
}
-
- return {
+
+ var extensions = {
argumentNames: argumentNames,
- bind: bind,
bindAsEventListener: bindAsEventListener,
curry: curry,
delay: delay,
defer: defer,
wrap: wrap,
methodize: methodize
- }
+ };
+
+ if (!Function.prototype.bind)
+ extensions.bind = bind;
+
+ return extensions;
})());
diff --git a/src/prototype/lang/hash.js b/src/prototype/lang/hash.js
index 57d43f9..d934327 100644
--- a/src/prototype/lang/hash.js
+++ b/src/prototype/lang/hash.js
@@ -93,12 +93,14 @@ var Hash = Class.create(Enumerable, (function() {
**/
// Our _internal_ each
- function _each(iterator) {
+ function _each(iterator, context) {
+ var i = 0;
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
- iterator(pair);
+ iterator.call(context, pair, i);
+ i++;
}
}
@@ -288,7 +290,17 @@ var Hash = Class.create(Enumerable, (function() {
// Private. No PDoc necessary.
function toQueryPair(key, value) {
if (Object.isUndefined(value)) return key;
- return key + '=' + encodeURIComponent(String.interpret(value));
+
+ var value = String.interpret(value);
+
+ // Normalize newlines as \r\n because the HTML spec says newlines should
+ // be encoded as CRLFs.
+ value = value.gsub(/(\r)?\n/, '\r\n');
+ value = encodeURIComponent(value);
+ // Likewise, according to the spec, spaces should be '+' rather than
+ // '%20'.
+ value = value.gsub(/%20/, '+');
+ return key + '=' + value;
}
/** related to: String#toQueryParams
diff --git a/src/prototype/lang/object.js b/src/prototype/lang/object.js
index 32ab541..e59d9eb 100644
--- a/src/prototype/lang/object.js
+++ b/src/prototype/lang/object.js
@@ -22,6 +22,7 @@
(function() {
var _toString = Object.prototype.toString,
+ _hasOwnProperty = Object.prototype.hasOwnProperty,
NULL_TYPE = 'Null',
UNDEFINED_TYPE = 'Undefined',
BOOLEAN_TYPE = 'Boolean',
@@ -39,6 +40,21 @@
JSON.stringify(0) === '0' &&
typeof JSON.stringify(Prototype.K) === 'undefined';
+
+
+ var DONT_ENUMS = ['toString', 'toLocaleString', 'valueOf',
+ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'];
+
+ // Some versions of JScript fail to enumerate over properties, names of which
+ // correspond to non-enumerable properties in the prototype chain
+ var IS_DONTENUM_BUGGY = (function(){
+ for (var p in { toString: 1 }) {
+ // check actual property name, so that it works with augmented Object.prototype
+ if (p === 'toString') return false;
+ }
+ return true;
+ })();
+
function Type(o) {
switch(o) {
case null: return NULL_TYPE;
@@ -52,7 +68,7 @@
}
return OBJECT_TYPE;
}
-
+
/**
* Object.extend(destination, source) -> Object
* - destination (Object): The object to receive the new properties.
@@ -145,9 +161,7 @@
}
function Str(key, holder, stack) {
- var value = holder[key],
- type = typeof value;
-
+ var value = holder[key];
if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
@@ -167,7 +181,7 @@
case false: return 'false';
}
- type = typeof value;
+ var type = typeof value;
switch (type) {
case 'string':
return value.inspect(true);
@@ -176,7 +190,9 @@
case 'object':
for (var i = 0, length = stack.length; i < length; i++) {
- if (stack[i] === value) { throw new TypeError(); }
+ if (stack[i] === value) {
+ throw new TypeError("Cyclic reference to '" + value + "' in object");
+ }
}
stack.push(value);
@@ -297,6 +313,12 @@
* prescribe an enumeration order. Sort the resulting array if you wish to
* normalize the order of the object keys.
*
+ * `Object.keys` acts as an ECMAScript 5 [polyfill](http://remysharp.com/2010/10/08/what-is-a-polyfill/).
+ * It is only defined if not already present in the user's browser, and it
+ * is meant to behave like the native version as much as possible. Consult
+ * the [ES5 specification](http://es5.github.com/#x15.2.3.14) for more
+ * information.
+ *
* ##### Examples
*
* Object.keys();
@@ -309,10 +331,18 @@
if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
var results = [];
for (var property in object) {
- if (object.hasOwnProperty(property)) {
+ if (_hasOwnProperty.call(object, property))
results.push(property);
+ }
+
+ // Account for the DontEnum properties in affected browsers.
+ if (IS_DONTENUM_BUGGY) {
+ for (var i = 0; property = DONT_ENUMS[i]; i++) {
+ if (_hasOwnProperty.call(object, property))
+ results.push(property);
}
}
+
return results;
}
diff --git a/src/prototype/lang/range.js b/src/prototype/lang/range.js
index 208637d..931542f 100644
--- a/src/prototype/lang/range.js
+++ b/src/prototype/lang/range.js
@@ -94,21 +94,23 @@ var ObjectRange = Class.create(Enumerable, (function() {
function initialize(start, end, exclusive) {
/**
* ObjectRange#start -> ?
+ *
* The lower bounding value of the range.
**/
this.start = start;
/**
* ObjectRange#end -> ?
+ *
* The upper bounding value of the range.
**/
this.end = end;
this.exclusive = exclusive;
}
- function _each(iterator) {
- var value = this.start;
- while (this.include(value)) {
- iterator(value);
+ function _each(iterator, context) {
+ var value = this.start, i;
+ for (i = 0; this.include(value); i++) {
+ iterator.call(context, value, i);
value = value.succ();
}
}
diff --git a/src/prototype/lang/string.js b/src/prototype/lang/string.js
index f2ccd0b..558db32 100644
--- a/src/prototype/lang/string.js
+++ b/src/prototype/lang/string.js
@@ -178,7 +178,7 @@ Object.extend(String.prototype, (function() {
* ##### Examples
*
* 'apple, pear & orange'.scan(/\w+/, alert);
- * // -> 'apple pear orange' (and displays 'apple', 'pear' and 'orange' in three successive alert dialogs)
+ * // -> 'apple pear & orange' (and displays 'apple', 'pear' and 'orange' in three successive alert dialogs)
*
* Can be used to populate an array:
*
@@ -383,11 +383,9 @@ Object.extend(String.prototype, (function() {
* }
*
* (You can leave off the `window.` part of that, but it's bad form.)
- * Evaluates the content of any `script` block present in the string. Returns
- * an array containing the value returned by each script.
**/
function evalScripts() {
- return this.extractScripts().map(function(script) { return eval(script) });
+ return this.extractScripts().map(function(script) { return eval(script); });
}
/** related to: String#unescapeHTML
@@ -452,7 +450,7 @@ Object.extend(String.prototype, (function() {
* 'section=blog&id=45'.toQueryParams();
* // -> {section: 'blog', id: '45'}
*
- * 'section=blog;id=45'.toQueryParams();
+ * 'section=blog;id=45'.toQueryParams(';');
* // -> {section: 'blog', id: '45'}
*
* 'http://www.example.com?section=blog&id=45#comments'.toQueryParams();
diff --git a/src/prototype/prototype.js b/src/prototype/prototype.js
index 7ce3270..ef5b046 100644
--- a/src/prototype/prototype.js
+++ b/src/prototype/prototype.js
@@ -139,7 +139,7 @@ var Prototype = {
})()
},
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
+ ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script\\s*>',
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
/**
diff --git a/test/unit/array_test.js b/test/unit/array_test.js
index 9eb3d19..7e553fc 100644
--- a/test/unit/array_test.js
+++ b/test/unit/array_test.js
@@ -96,6 +96,21 @@ new Test.Unit.Runner({
this.assertEqual(0, [1,2,1].indexOf(1));
this.assertEqual(2, [1,2,1].indexOf(1, -1));
this.assertEqual(1, [undefined,null].indexOf(null));
+
+ // ES5 compatibility tests.
+ var undef;
+ var array = [1, 2, 3, 4, 5, undef, 6, 7, 1, 2, 3];
+
+ this.assertEqual(2, array.indexOf(3, -47),
+ "large negative value for fromIndex");
+ this.assertEqual(10, array.indexOf(3, 4));
+ this.assertEqual(10, array.indexOf(3, -5))
+ this.assertEqual(2, array.indexOf(3, {}),
+ "nonsensical value for fromIndex");
+ this.assertEqual(2, array.indexOf(3, ""),
+ "nonsensical value for fromIndex");
+ this.assertEqual(-1, array.indexOf(3, 41),
+ "fromIndex value larger than the length of the array");
},
testLastIndexOf: function(){
@@ -131,6 +146,7 @@ new Test.Unit.Runner({
testIntersect: function(){
this.assertEnumEqual([1,3], [1,1,3,5].intersect([1,2,3]));
+ this.assertEnumEqual([0,1], [0,1,2].intersect([0,1]));
this.assertEnumEqual([1], [1,1].intersect([1,1]));
this.assertEnumEqual([], [1,1,3,5].intersect([4]));
this.assertEnumEqual([], [1].intersect(['1']));
@@ -182,14 +198,159 @@ new Test.Unit.Runner({
this.assertEnumEqual(['a', 'b', 'c', 'd'], $w(' a b\nc\t\nd\n'));
},
- testConcat: function(){
+ testConcat: function() {
+ var x = {};
+
+ this.assertIdentical(1, Array.prototype.concat.length);
+
+ this.assertEnumEqual(
+ [0, 1],
+ [0, 1].concat(),
+ "test 2"
+ );
+ this.assertIdentical(2, [0, 1].concat().length, "test 3");
+
+ this.assertEnumEqual(
+ [0, 1, 2, 3, 4],
+ [].concat([0, 1], [2, 3, 4]),
+ "test 4"
+ );
+ this.assertIdentical(5, [].concat([0, 1], [2, 3, 4]).length, "test 5");
+
+ this.assertEnumEqual([0, x, 1, 2, true, "NaN"], [0].concat(x, [1, 2], true, "NaN"), "test 6");
+ this.assertIdentical(6, [0].concat(x, [1, 2], true, "NaN").length, "test 7");
+
+ // These tests will fail in older IE because of the trailing comma.
+ // Nothing we can do about that, so just skip them and let the user know.
+ if ([,].length === 2) {
+ this.info("NOTE: Old versions of IE don't like trailing commas in " +
+ "arrays. Skipping some tests.");
+ } else {
+ this.assertEnumEqual([undefined, 1, undefined], [,1].concat([], [,]),
+ "concatenation behavior with a trailing comma (1)");
+ this.assertIdentical(3, [,1].concat([], [,]).length,
+ "concatenation behavior with a trailing comma (2)");
+ }
+
+
+ this.assertEnumEqual([1], Object.keys([,1].concat([], [,])), "test 10");
+
+ // Check that Array.prototype.concat can be used in a generic way
+ x.concat = Array.prototype.concat;
+ this.assertEnumEqual([x], x.concat());
+ this.assertIdentical(1, x.concat().length);
+
+ // Checking an edge case
+ var arr = []; arr[2] = true;
+ this.assertEnumEqual([undefined, undefined, true], [].concat(arr));
+ this.assertIdentical(3, [].concat(arr).length);
+ this.assertEnumEqual([2], Object.keys([].concat(arr)));
+
var args = (function() { return [].concat(arguments) })(1, 2);
this.assertIdentical(1, args[0][0]);
},
testEachOnSparseArrays: function() {
+ var counter = 0;
+
var sparseArray = [0, 1];
sparseArray[5] = 5;
- this.assertEqual('[0, 1, 5]', sparseArray.inspect(), "Array#each should skip nonexistent keys in an array");
+ sparseArray.each( function(item) { counter++; });
+
+ this.assertEqual(3, counter, "Array#each should skip nonexistent keys in an array");
+ },
+
+ testMapGeneric: function() {
+ var result = Array.prototype.map.call({0:0, 1:1, length:2});
+ this.assertEnumEqual([0, 1], result);
+ },
+
+ testMap: function() {
+ this.assertEnumEqual([1,2,3], [1,2,3].map());
+ this.assertEnumEqual([2,4,6], [1,2,3].map(function(x) { return x * 2; }));
+
+ var x = [1,2,3,4];
+ delete x[1];
+ delete x[3];
+ this.assertEnumEqual([1, undefined, 3, undefined], x.map());
+ this.assertIdentical(4, x.map().length);
+
+ var traversed = [];
+ x.map(function(val) {
+ traversed.push(val);
+ });
+ this.assertEnumEqual([1, 3], traversed);
+ this.assertIdentical(2, traversed.length);
+ },
+
+ testFindAllGeneric: function() {
+ var result = Array.prototype.findAll.call({0:0, 1:1, length:2}, function(x) {
+ return x === 1;
+ });
+ this.assertEnumEqual([1], result);
+ },
+
+ testFindAll: function() {
+ this.assertEnumEqual([2, 4, 6], [1, 2, 3, 4, 5, 6].findAll(function(x) {
+ return (x % 2) == 0;
+ }));
+
+ var x = [1,2,3], traversed = [];
+ delete x[1];
+ x.findAll(function(val) { traversed.push(val); });
+ this.assertEnumEqual([1, 3], traversed);
+ this.assertIdentical(2, traversed.length);
+ },
+
+ testAnyGeneric: function() {
+ this.assert(Array.prototype.any.call({ 0:false, 1:true, length:2 }));
+ this.assert(!Array.prototype.any.call({ 0:false, 1:false, length:2 }));
+ },
+
+ testAny: function() {
+ this.assert(!([].any()));
+
+ this.assert([true, true, true].any());
+ this.assert([true, false, false].any());
+ this.assert(![false, false, false].any());
+
+ this.assert([1,2,3,4,5].any(function(value) {
+ return value > 2;
+ }));
+ this.assert(![1,2,3,4,5].any(function(value) {
+ return value > 5;
+ }));
+
+ var x = [1,2,3], traversed = [];
+ delete x[1];
+ x.any(function(val) { traversed.push(val); });
+ this.assertEnumEqual([1, 3], traversed);
+ this.assertIdentical(2, traversed.length);
+ },
+
+ testAllGeneric: function() {
+ this.assert(Array.prototype.all.call({ 0:true, 1:true, length:2 }));
+ this.assert(!Array.prototype.all.call({ 0:false, 1:true, length:2 }));
+ },
+
+ testAll: function() {
+ this.assert([].all());
+
+ this.assert([true, true, true].all());
+ this.assert(![true, false, false].all());
+ this.assert(![false, false, false].all());
+
+ this.assert([1,2,3,4,5].all(function(value) {
+ return value > 0;
+ }));
+ this.assert(![1,2,3,4,5].all(function(value) {
+ return value > 1;
+ }));
+
+ var x = [1,2,3], traversed = [];
+ delete x[1];
+ x.all(function(val) { traversed.push(val); return true; });
+ this.assertEnumEqual([1, 3], traversed);
+ this.assertIdentical(2, traversed.length);
}
});
\ No newline at end of file
diff --git a/test/unit/dom_test.js b/test/unit/dom_test.js
index 738c543..425261c 100644
--- a/test/unit/dom_test.js
+++ b/test/unit/dom_test.js
@@ -7,6 +7,8 @@ var createParagraph = function(text) {
return p;
}
+var RESIZE_DISABLED = false;
+
function simulateClick(node) {
var oEvent;
if (document.createEvent) {
@@ -70,7 +72,7 @@ new Test.Unit.Runner({
'getElementById and $ should return the same element');
this.assertEnumEqual([ $('testdiv'), $('container') ], $('testdiv', 'container'));
- this.assertEnumEqual([ $('testdiv'), undefined, $('container') ],
+ this.assertEnumEqual([ $('testdiv'), null, $('container') ],
$('testdiv', 'noWayThisIDExists', 'container'));
var elt = $('testdiv');
this.assertIdentical(elt, $(elt));
@@ -198,34 +200,35 @@ new Test.Unit.Runner({
testElementMethodInsert: function() {
$('element-insertions-main').insert({before:'some text before'});
- this.assert(getInnerHTML('element-insertions-container').startsWith('some text before'));
+ this.assert(getInnerHTML('element-insertions-container').startsWith('some text before'), 'some text before');
$('element-insertions-main').insert({after:'some text after'});
- this.assert(getInnerHTML('element-insertions-container').endsWith('some text after'));
+ this.assert(getInnerHTML('element-insertions-container').endsWith('some text after'), 'some text after');
$('element-insertions-main').insert({top:'some text top'});
- this.assert(getInnerHTML('element-insertions-main').startsWith('some text top'));
+ this.assert(getInnerHTML('element-insertions-main').startsWith('some text top'), 'some text top');
$('element-insertions-main').insert({bottom:'some text bottom'});
- this.assert(getInnerHTML('element-insertions-main').endsWith('some text bottom'));
+ this.assert(getInnerHTML('element-insertions-main').endsWith('some text bottom'), 'some text bottom');
$('element-insertions-main').insert('some more text at the bottom');
- this.assert(getInnerHTML('element-insertions-main').endsWith('some more text at the bottom'));
+ this.assert(getInnerHTML('element-insertions-main').endsWith('some more text at the bottom'),
+ 'some more text at the bottom');
$('element-insertions-main').insert({TOP:'some text uppercase top'});
- this.assert(getInnerHTML('element-insertions-main').startsWith('some text uppercase top'));
+ this.assert(getInnerHTML('element-insertions-main').startsWith('some text uppercase top'), 'some text uppercase top');
$('element-insertions-multiple-main').insert({
top:'1', bottom:2, before: new Element('p').update('3'), after:'4'
});
- this.assert(getInnerHTML('element-insertions-multiple-main').startsWith('1'));
- this.assert(getInnerHTML('element-insertions-multiple-main').endsWith('2'));
- this.assert(getInnerHTML('element-insertions-multiple-container').startsWith('<p>3</p>'));
- this.assert(getInnerHTML('element-insertions-multiple-container').endsWith('4'));
+ this.assert(getInnerHTML('element-insertions-multiple-main').startsWith('1'), '1');
+ this.assert(getInnerHTML('element-insertions-multiple-main').endsWith('2'), '2');
+ this.assert(getInnerHTML('element-insertions-multiple-container').startsWith('<p>3</p>'), '<p>3</p>');
+ this.assert(getInnerHTML('element-insertions-multiple-container').endsWith('4'), '4');
$('element-insertions-main').update('test');
$('element-insertions-main').insert(null);
$('element-insertions-main').insert({bottom:null});
- this.assertEqual('test', getInnerHTML('element-insertions-main'));
+ this.assertEqual('test', getInnerHTML('element-insertions-main'), 'should insert nothing when called with null');
$('element-insertions-main').insert(1337);
- this.assertEqual('test1337', getInnerHTML('element-insertions-main'));
+ this.assertEqual('test1337', getInnerHTML('element-insertions-main'), 'should coerce to string when called with number');
},
testNewElementInsert: function() {
@@ -988,7 +991,18 @@ new Test.Unit.Runner({
$('op3').setStyle({opacity: 0});
this.assertEqual(0, $('op3').getStyle('opacity'), 'get opacity on #op3');
- if(navigator.appVersion.match(/MSIE/)) {
+ // Opacity feature test borrowed from Modernizr.
+ var STANDARD_CSS_OPACITY_SUPPORTED = (function() {
+ var DIV = document.createElement('div');
+ DIV.style.cssText = "opacity:.55";
+ var result = /^0.55/.test(DIV.style.opacity);
+ DIV = null;
+ return result;
+ })();
+
+ if (!STANDARD_CSS_OPACITY_SUPPORTED) {
+ // Run these tests only on older versions of IE. IE9 and 10 dropped
+ // support for filters and therefore fail these tests.
this.assertEqual('alpha(opacity=30)', $('op1').getStyle('filter'));
this.assertEqual('progid:DXImageTransform.Microsoft.Blur(strength=10)alpha(opacity=30)', $('op2').getStyle('filter'));
$('op2').setStyle({opacity:''});
@@ -996,6 +1010,7 @@ new Test.Unit.Runner({
this.assertEqual('alpha(opacity=0)', $('op3').getStyle('filter'));
this.assertEqual(0.3, $('op4-ie').getStyle('opacity'));
}
+
// verify that value is still found when using camelized
// strings (function previously used getPropertyValue()
// which expected non-camelized strings)
@@ -1090,10 +1105,10 @@ new Test.Unit.Runner({
testElementWriteAttributeWithIssues: function() {
var input = $('write_attribute_input').writeAttribute({maxlength: 90, tabindex: 10}),
td = $('write_attribute_td').writeAttribute({valign: 'bottom', colspan: 2, rowspan: 2});
- this.assertEqual(90, input.readAttribute('maxlength'));
- this.assertEqual(10, input.readAttribute('tabindex'));
- this.assertEqual(2, td.readAttribute('colspan'));
- this.assertEqual(2, td.readAttribute('rowspan'));
+ this.assertEqual("90", input.readAttribute('maxlength'));
+ this.assertEqual("10", input.readAttribute('tabindex'));
+ this.assertEqual("2", td.readAttribute('colspan'));
+ this.assertEqual("2", td.readAttribute('rowspan'));
this.assertEqual('bottom', td.readAttribute('valign'));
var p = $('write_attribute_para'), label = $('write_attribute_label');
@@ -1448,15 +1463,41 @@ new Test.Unit.Runner({
},
testViewportDimensions: function() {
- preservingBrowserDimensions(function() {
- window.resizeTo(800, 600);
+ var original = document.viewport.getDimensions();
+
+ window.resizeTo(800, 600);
+
+ this.wait(1000, function() {
var before = document.viewport.getDimensions();
+
+ var delta = { width: 800 - before.width, height: 600 - before.height };
+
window.resizeBy(50, 50);
- var after = document.viewport.getDimensions();
-
- this.assertEqual(before.width + 50, after.width, "NOTE: YOU MUST ALLOW JAVASCRIPT TO RESIZE YOUR WINDOW FOR THIS TEST TO PASS");
- this.assertEqual(before.height + 50, after.height, "NOTE: YOU MUST ALLOW JAVASCRIPT TO RESIZE YOUR WINDOW FOR THIS TEST TO PASS");
- }.bind(this));
+ this.wait(1000, function() {
+ var after = document.viewport.getDimensions();
+
+ // Assume that JavaScript window resizing is disabled if before width
+ // and after width are the same.
+ if (before.width === after.width) {
+ RESIZE_DISABLED = true;
+ this.info("SKIPPING REMAINING TESTS (JavaScript window resizing disabled)");
+ return;
+ }
+
+ this.assertEqual(before.width + 50, after.width,
+ "NOTE: YOU MUST ALLOW JAVASCRIPT TO RESIZE YOUR WINDOW FOR THIS TEST TO PASS");
+ this.assertEqual(before.height + 50, after.height,
+ "NOTE: YOU MUST ALLOW JAVASCRIPT TO RESIZE YOUR WINDOW FOR THIS TEST TO PASS");
+
+ this.wait(1000, function() {
+ // Restore original dimensions.
+ window.resizeTo(
+ original.width + delta.width,
+ original.height + delta.height
+ );
+ });
+ })
+ });
},
testElementToViewportDimensionsDoesNotAffectDocumentProperties: function() {
@@ -1475,19 +1516,37 @@ new Test.Unit.Runner({
},
testViewportScrollOffsets: function() {
- preservingBrowserDimensions(function() {
- window.scrollTo(0, 0);
- this.assertEqual(0, document.viewport.getScrollOffsets().top);
+ var original = document.viewport.getDimensions();
- window.scrollTo(0, 35);
- this.assertEqual(35, document.viewport.getScrollOffsets().top);
+ window.scrollTo(0, 0);
+ this.assertEqual(0, document.viewport.getScrollOffsets().top);
+
+ window.scrollTo(0, 35);
+ this.assertEqual(35, document.viewport.getScrollOffsets().top);
- window.resizeTo(200, 650);
- window.scrollTo(25, 35);
- this.assertEqual(25, document.viewport.getScrollOffsets().left, "NOTE: YOU MUST ALLOW JAVASCRIPT TO RESIZE YOUR WINDOW FOR THESE TESTS TO PASS");
+ if (RESIZE_DISABLED) {
+ this.info("SKIPPING REMAINING TESTS (JavaScript window resizing disabled)");
+ return;
+ }
+
+ window.resizeTo(200, 650);
- window.resizeTo(850, 650);
- }.bind(this));
+ this.wait(1000, function() {
+ var before = document.viewport.getDimensions();
+ var delta = { width: 200 - before.width, height: 650 - before.height };
+
+ window.scrollTo(25, 35);
+ this.assertEqual(25, document.viewport.getScrollOffsets().left,
+ "NOTE: YOU MUST ALLOW JAVASCRIPT TO RESIZE YOUR WINDOW FOR THESE TESTS TO PASS");
+
+ this.wait(1000, function() {
+ // Restore original dimensions.
+ window.resizeTo(
+ original.width + delta.width,
+ original.height + delta.height
+ );
+ });
+ });
},
testNodeConstants: function() {
@@ -1600,10 +1659,14 @@ new Test.Unit.Runner({
},
testElementPurge: function() {
+ function uidForElement(elem) {
+ return elem.uniqueID ? elem.uniqueID : elem._prototypeUID;
+ }
+
var element = new Element('div');
element.store('foo', 'bar');
- var uid = element._prototypeUID;
+ var uid = uidForElement(element);
this.assert(uid in Element.Storage, "newly-created element's uid should exist in `Element.Storage`");
var storageKeysBefore = Object.keys(Element.Storage).length;
@@ -1647,14 +1710,20 @@ new Test.Unit.Runner({
function preservingBrowserDimensions(callback) {
var original = document.viewport.getDimensions();
+
window.resizeTo(640, 480);
+
var resized = document.viewport.getDimensions();
original.width += 640 - resized.width, original.height += 480 - resized.height;
try {
window.resizeTo(original.width, original.height);
callback();
- } finally {
+ } catch(e) {
+ throw e;
+ }finally {
window.resizeTo(original.width, original.height);
}
}
+
+
diff --git a/test/unit/enumerable_test.js b/test/unit/enumerable_test.js
index 3e0d00b..27bd024 100644
--- a/test/unit/enumerable_test.js
+++ b/test/unit/enumerable_test.js
@@ -24,6 +24,16 @@ new Test.Unit.Runner({
this.assertEqual('1, 3', results.join(', '));
},
+ "test #each passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.each(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ }, this);
+ },
+
testEachChaining: function() {
this.assertEqual(Fixtures.Primes, Fixtures.Primes.each(Prototype.emptyFunction));
this.assertEqual(3, Fixtures.Basic.each(Prototype.emptyFunction).length);
@@ -63,6 +73,19 @@ new Test.Unit.Runner({
}));
},
+ "test #any passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.any(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+
+ // Iterate over all values
+ return value > 5;
+ }, this);
+ },
+
testAll: function() {
this.assert([].all());
@@ -78,6 +101,19 @@ new Test.Unit.Runner({
}));
},
+ "test #all passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.all(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+
+ // Iterate over all values
+ return value > 0;
+ }, this);
+ },
+
testCollect: function() {
this.assertEqual(Fixtures.Nicknames.join(', '),
Fixtures.People.collect(function(person) {
@@ -87,6 +123,17 @@ new Test.Unit.Runner({
this.assertEqual(26, Fixtures.Primes.map().length);
},
+ "test #collect passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.collect(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value;
+ }, this);
+ },
+
testDetect: function() {
this.assertEqual('Marcel Molina Jr.',
Fixtures.People.detect(function(person) {
@@ -94,6 +141,19 @@ new Test.Unit.Runner({
}).name);
},
+ "test #detect passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.detect(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+
+ // Iterate over all values
+ return value > 5;
+ }, this);
+ },
+
testEachSlice: function() {
this.assertEnumEqual([], [].eachSlice(2));
this.assertEqual(1, [1].eachSlice(1).length);
@@ -125,6 +185,17 @@ new Test.Unit.Runner({
Fixtures.Z.findAll(prime).join(', '));
},
+ "test #findAll passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.findAll(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value > 5;
+ }, this);
+ },
+
testGrep: function() {
this.assertEqual('noradio, htonl',
Fixtures.Nicknames.grep(/o/).join(", "));
@@ -146,6 +217,17 @@ new Test.Unit.Runner({
this.assertEnumEqual(['|a', 'c|'], ['|a','b','c|'].grep('|'));
},
+ "test #grep passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.grep(/\d/, function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value;
+ }, this);
+ },
+
testInclude: function() {
this.assert(Fixtures.Nicknames.include('sam-'));
this.assert(Fixtures.Nicknames.include('noradio'));
@@ -191,6 +273,18 @@ new Test.Unit.Runner({
}));
},
+ "test #inject passes memo, value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.inject(0, function(memo, value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+
+ return memo + value;
+ }, this);
+ },
+
testInvoke: function() {
var result = [[2, 1, 3], [6, 5, 4]].invoke('sort');
this.assertEqual(2, result.length);
@@ -209,12 +303,34 @@ new Test.Unit.Runner({
this.assertEqual('sam-', Fixtures.Nicknames.max()); // ?s > ?U
},
+ "test #max passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.max(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value;
+ }, this);
+ },
+
testMin: function() {
this.assertEqual(1, Fixtures.Z.min());
this.assertEqual(0, [ 1, 2, 3, 4, 5, 6, 7, 8, 0, 9 ].min());
this.assertEqual('Ulysses', Fixtures.Nicknames.min()); // ?U < ?h
},
+ "test #min passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.min(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value;
+ }, this);
+ },
+
testPartition: function() {
var result = Fixtures.People.partition(function(person) {
return person.name.length < 15;
@@ -225,6 +341,17 @@ new Test.Unit.Runner({
this.assertEqual('noradio, Ulysses', result[1].join(', '));
},
+ "test #partition passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.partition(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value < 2;
+ }, this);
+ },
+
testPluck: function() {
this.assertEqual(Fixtures.Nicknames.join(', '),
Fixtures.People.pluck('nickname').join(', '));
@@ -240,6 +367,17 @@ new Test.Unit.Runner({
}).join(', '));
},
+ "test #reject passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.reject(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value < 2;
+ }, this);
+ },
+
testSortBy: function() {
this.assertEqual('htonl, noradio, sam-, Ulysses',
Fixtures.People.sortBy(function(value) {
@@ -247,6 +385,17 @@ new Test.Unit.Runner({
}).pluck('nickname').join(', '));
},
+ "test #sortBy passes value, index and collection to the iterator": function() {
+ var i = 0;
+ Fixtures.Basic.sortBy(function(value, index, collection) {
+ this.assertIdentical(Fixtures.Basic[i], value);
+ this.assertIdentical(i, index);
+ this.assertIdentical(Fixtures.Basic, collection);
+ i++;
+ return value;
+ }, this);
+ },
+
testToArray: function() {
var result = Fixtures.People.toArray();
this.assert(result != Fixtures.People); // they're different objects...
diff --git a/test/unit/event_test.js b/test/unit/event_test.js
index ba90b9f..de274cb 100644
--- a/test/unit/event_test.js
+++ b/test/unit/event_test.js
@@ -160,19 +160,23 @@ new Test.Unit.Runner({
span.observe("test:somethingHappened", observer);
- var registry = span.getStorage().get('prototype_event_registry');
+ function uidForElement(elem) {
+ return elem.uniqueID ? elem.uniqueID : elem._prototypeUID;
+ }
- this.assert(registry);
- this.assert(Object.isArray(registry.get('test:somethingHappened')));
- this.assertEqual(1, registry.get('test:somethingHappened').length);
+ var registry = Event.cache[uidForElement(span)];
+
+ this.assert(registry, 'registry should exist');
+ this.assert(Object.isArray(registry['test:somethingHappened']));
+ this.assertEqual(1, registry['test:somethingHappened'].length);
span.stopObserving("test:somethingHappened", observer);
- registry = span.getStorage().get('prototype_event_registry');
+ registry = Event.cache[uidForElement(span)];
this.assert(registry);
- this.assert(Object.isArray(registry.get('test:somethingHappened')));
- this.assertEqual(0, registry.get('test:somethingHappened').length);
+ this.assert(Object.isArray(registry['test:somethingHappened']));
+ this.assertEqual(0, registry['test:somethingHappened'].length);
},
testObserveAndStopObservingAreChainable: function() {
diff --git a/test/unit/form_test.js b/test/unit/form_test.js
index f2c7b0a..84e0a10 100644
--- a/test/unit/form_test.js
+++ b/test/unit/form_test.js
@@ -257,10 +257,10 @@ new Test.Unit.Runner({
};
// return params
- this.assertHashEqual(expected, Form.serialize('various', true));
+ this.assertHashEqual(expected, Form.serialize('various', true), "test the whole form (as a hash)");
// return string
this.assertEnumEqual(Object.toQueryString(expected).split('&').sort(),
- Form.serialize('various').split('&').sort());
+ Form.serialize('various').split('&').sort(), "test the whole form (as a string)");
this.assertEqual('string', typeof $('form').serialize({ hash:false }));
// Checks that disabled element is not included in serialized form.
diff --git a/test/unit/function_test.js b/test/unit/function_test.js
index 2a9e8b2..abb1f61 100644
--- a/test/unit/function_test.js
+++ b/test/unit/function_test.js
@@ -30,12 +30,15 @@ new Test.Unit.Runner({
},
testFunctionBind: function() {
- function methodWithoutArguments() { return this.hi };
- function methodWithArguments() { return this.hi + ',' + $A(arguments).join(',') };
+ function methodWithoutArguments() { return this.hi; }
+ function methodWithArguments() { return this.hi + ',' + $A(arguments).join(','); }
+ function methodReturningContext() { return this; }
var func = Prototype.emptyFunction;
+ var u;
+
+ // We used to test that `bind` without a `context` argument simply
+ // returns the original function, but this contradicts the ES5 spec.
- this.assertIdentical(func, func.bind());
- this.assertIdentical(func, func.bind(undefined));
this.assertNotIdentical(func, func.bind(null));
this.assertEqual('without', methodWithoutArguments.bind({ hi: 'without' })());
@@ -44,6 +47,40 @@ new Test.Unit.Runner({
methodWithArguments.bind({ hi: 'withBindArgs' }, 'arg1', 'arg2')());
this.assertEqual('withBindArgsAndArgs,arg1,arg2,arg3,arg4',
methodWithArguments.bind({ hi: 'withBindArgsAndArgs' }, 'arg1', 'arg2')('arg3', 'arg4'));
+
+ this.assertEqual(window, methodReturningContext.bind(null)(), 'null has window as its context');
+ this.assertEqual(window, methodReturningContext.bind(u)(), 'undefined has window as its context');
+ this.assertEqual('', methodReturningContext.bind('')(), 'other falsy values should not have window as their context');
+
+
+ // Ensure that bound functions ignore their `context` when used as
+ // constructors. Taken from example at:
+ // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
+ function Point(x, y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ Point.prototype.toString = function() {
+ return this.x + "," + this.y;
+ };
+
+ var p = new Point(1, 2);
+ p.toString(); // "1,2"
+
+ var emptyObj = {};
+ var YAxisPoint = Point.bind(emptyObj, 0 /* x */);
+
+ var axisPoint = new YAxisPoint(5);
+ axisPoint.toString(); // "0,5"
+
+ this.assertEqual("0,5", axisPoint.toString(),
+ "bound constructor should ignore context and curry properly");
+
+ this.assert(axisPoint instanceof Point,
+ "should be an instance of Point");
+ this.assert(axisPoint instanceof YAxisPoint,
+ "should be an instance of YAxisPoint");
},
testFunctionCurry: function() {
@@ -102,8 +139,35 @@ new Test.Unit.Runner({
deferredFunction2.defer('test');
this.wait(50, function() {
this.assertEqual('test', window.deferredValue);
+
+ window.deferBoundProperly = false;
+
+ var obj = { foo: 'bar' };
+ var func = function() {
+ if ('foo' in this) window.deferBoundProperly = true;
+ };
+
+ func.bind(obj).defer();
+
+ this.wait(50, function() {
+ this.assert(window.deferBoundProperly,
+ "deferred bound functions should preserve original scope");
+
+ window.deferBoundProperlyOnString = false;
+ var str = "<script>window.deferBoundProperlyOnString = true;</script>"
+
+ str.evalScripts.bind(str).defer();
+
+ this.wait(50, function() {
+ this.assert(window.deferBoundProperlyOnString);
+ });
+
+ });
+
});
});
+
+
},
testFunctionMethodize: function() {
diff --git a/test/unit/hash_test.js b/test/unit/hash_test.js
index cf3bcbd..d39f078 100644
--- a/test/unit/hash_test.js
+++ b/test/unit/hash_test.js
@@ -130,6 +130,15 @@ new Test.Unit.Runner({
this.assertEqual("stuff%5B%5D=%24&stuff%5B%5D=a&stuff%5B%5D=%3B", $H(Fixtures.multiple_special).toQueryString());
this.assertHashEqual(Fixtures.multiple_special, $H(Fixtures.multiple_special).toQueryString().toQueryParams());
this.assertIdentical(Object.toQueryString, Hash.toQueryString);
+
+ // Serializing newlines and spaces is weird. See:
+ // http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#h-17.13.4.1
+ var complex = "an arbitrary line\n\'something in single quotes followed by a newline\'\r\n" +
+ "and more text eventually";
+ var queryString = $H({ val: complex }).toQueryString();
+ var expected = "val=an+arbitrary+line%0D%0A'something+in+single+quotes+followed+by+a+" +
+ "newline'%0D%0Aand+more+text+eventually";
+ this.assertEqual(expected, queryString, "newlines and spaces should be properly encoded");
},
testInspect: function() {
@@ -173,6 +182,15 @@ new Test.Unit.Runner({
var foo = new FooMaker('bar');
this.assertEqual("key=bar", new Hash(foo).toQueryString());
this.assertEqual("key=bar", new Hash(new Hash(foo)).toQueryString());
+ },
+
+ testIterationWithEach: function() {
+ var h = $H({a:1, b:2});
+ var result = []
+ h.each(function(kv, i){
+ result.push(i);
+ });
+ this.assertEnumEqual([0,1], result);
}
});
\ No newline at end of file
diff --git a/test/unit/layout_test.js b/test/unit/layout_test.js
index 7315dce..03d61d1 100644
--- a/test/unit/layout_test.js
+++ b/test/unit/layout_test.js
@@ -121,6 +121,8 @@ new Test.Unit.Runner({
var viewportWidth = document.viewport.getWidth();
var layout = $('box9').getLayout();
+ this.info("NOTE: IE6 WILL fail these tests because it doesn't support position: fixed. This is expected.");
+
function assertNear(v1, v2, message) {
var abs = Math.abs(v1 - v2);
this.assert(abs <= 1, message + ' (actual: ' + v1 + ', ' + v2 + ')');
@@ -132,7 +134,8 @@ new Test.Unit.Runner({
assertNear.call(this, vWidth, eWidth, 'width (visible)');
$('box9').hide();
- assertNear.call(this, vWidth, $('box9').measure('width'), 'width (hidden)');
+ assertNear.call(this, vWidth, $('box9').measure('width'), 'width (hidden)');
+ $('box9').show();
},
'test #toCSS, #toObject, #toHash': function() {
diff --git a/test/unit/object_test.js b/test/unit/object_test.js
index 1d213fe..782992e 100644
--- a/test/unit/object_test.js
+++ b/test/unit/object_test.js
@@ -31,6 +31,15 @@ new Test.Unit.Runner({
Foo.prototype.foo = 'foo';
this.assertEnumEqual(['bar'], Object.keys(new Foo()));
this.assertRaise('TypeError', function(){ Object.keys() });
+
+ var obj = {
+ foo: 'bar',
+ baz: 'thud',
+ toString: function() { return '1'; },
+ valueOf: function() { return 1; }
+ };
+
+ this.assertEqual(4, Object.keys(obj).length, 'DontEnum properties should be included in Object.keys');
},
testObjectInspect: function() {
diff --git a/test/unit/range_test.js b/test/unit/range_test.js
index bcf5acb..c4618de 100644
--- a/test/unit/range_test.js
+++ b/test/unit/range_test.js
@@ -27,6 +27,13 @@ new Test.Unit.Runner({
});
this.assertEnumEqual([0, 1, 2, 3], results);
+
+ results = [];
+ $R(2, 4, true).each(function(value, index) {
+ results.push(index);
+ });
+ this.assertEnumEqual([0, 1], results);
+
},
testAny: function() {
diff --git a/test/unit/selector_test.js b/test/unit/selector_test.js
index 56c730c..074bcdf 100644
--- a/test/unit/selector_test.js
+++ b/test/unit/selector_test.js
@@ -285,9 +285,9 @@ new Test.Unit.Runner({
},
testSelectorWithEnabledDisabledChecked: function() {
- this.assertEnumEqual([$('disabled_text_field')], $$('#troubleForm > *:disabled'));
- this.assertEnumEqual($('troubleForm').getInputs().without($('disabled_text_field'), $('hidden')), $$('#troubleForm > *:enabled'));
- this.assertEnumEqual($('checked_box', 'checked_radio'), $$('#troubleForm *:checked'));
+ this.assertEnumEqual([$('disabled_text_field')], $$('#troubleForm > *:disabled'), ':disabled');
+ this.assertEnumEqual($('troubleForm').getInputs().without($('disabled_text_field'), $('hidden')), $$('#troubleForm > *:enabled'), ':enabled');
+ this.assertEnumEqual($('checked_box', 'checked_radio'), $$('#troubleForm *:checked'), ':checked');
},
testSelectorWithEmpty: function() {
diff --git a/test/unit/string_test.js b/test/unit/string_test.js
index bec0eba..5b274b2 100644
--- a/test/unit/string_test.js
+++ b/test/unit/string_test.js
@@ -220,6 +220,9 @@ new Test.Unit.Runner({
this.assertEqual('foo bar', 'foo bar'.stripScripts());
this.assertEqual('foo bar', ('foo <script>boo();<'+'/script>bar').stripScripts());
this.assertEqual('foo bar', ('foo <script type="text/javascript">boo();\nmoo();<'+'/script>bar').stripScripts());
+
+ this.assertEqual('foo bar', ('foo <script>boo();<'+'/script >bar').stripScripts(),
+ 'should properly handle whitespace in closing tag');
},
testExtractScripts: function() {
| 0 | 4 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
1d617df4df4b2ae8dff41038c59ee67928e0f3cd
|
Avoid using arguments.callee in string.js.
|
commit 1d617df4df4b2ae8dff41038c59ee67928e0f3cd
Author: Tobie Langel <[email protected]>
Date: Thu Dec 11 04:28:35 2008 +0100
Avoid using arguments.callee in string.js.
diff --git a/src/lang/string.js b/src/lang/string.js
index f50e570..587c944 100644
--- a/src/lang/string.js
+++ b/src/lang/string.js
@@ -83,9 +83,8 @@ Object.extend(String.prototype, (function() {
}
function escapeHTML() {
- var self = arguments.callee;
- self.text.data = this;
- return self.div.innerHTML;
+ escapeHTML.text.data = this;
+ return escapeHTML.div.innerHTML;
}
function unescapeHTML() {
| 0 | 7 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
9e78eff0245c23b3104a814db0920f9b9740f938
|
Ensure `String#extractScripts` and `String#evalScripts` ignore `SCRIPT` tags with a `type` attribute set to a non-JavaScript MIME-type. (Closes #304)
|
commit 9e78eff0245c23b3104a814db0920f9b9740f938
Author: Andrew Dupont <[email protected]>
Date: Sun Apr 9 17:39:14 2017 -0500
Ensure `String#extractScripts` and `String#evalScripts` ignore `SCRIPT` tags with a `type` attribute set to a non-JavaScript MIME-type. (Closes #304)
diff --git a/src/prototype/lang/string.js b/src/prototype/lang/string.js
index 81950d3..433a1c0 100644
--- a/src/prototype/lang/string.js
+++ b/src/prototype/lang/string.js
@@ -337,9 +337,25 @@ Object.extend(String.prototype, (function() {
function extractScripts() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img'),
matchOne = new RegExp(Prototype.ScriptFragment, 'im');
- return (this.match(matchAll) || []).map(function(scriptTag) {
- return (scriptTag.match(matchOne) || ['', ''])[1];
+ var matchMimeType = new RegExp(Prototype.ExecutableScriptFragment, 'im');
+ var matchTypeAttribute = /type=/i;
+
+ var results = [];
+ (this.match(matchAll) || []).each(function(scriptTag) {
+ var match = scriptTag.match(matchOne);
+ var attributes = match[1];
+ if (attributes !== '') {
+ // If the script has a `type` attribute, make sure it has a
+ // JavaScript MIME-type. If not, ignore it.
+ attributes = attributes.strip();
+ var hasTypeAttribute = (matchTypeAttribute).test(attributes);
+ var hasMimeType = (matchMimeType).test(attributes);
+ if (hasTypeAttribute && !hasMimeType) return;
+ }
+ results.push(match ? match[2] : '');
});
+
+ return results;
}
/**
diff --git a/src/prototype/prototype.js b/src/prototype/prototype.js
index fbc6382..b31e1aa 100644
--- a/src/prototype/prototype.js
+++ b/src/prototype/prototype.js
@@ -120,7 +120,8 @@ var Prototype = {
SpecificElementExtensions: true
},
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script\\s*>',
+ ScriptFragment: '<script([^>]*)>([\\S\\s]*?)<\/script\\s*>',
+ ExecutableScriptFragment: /(?:text|application)\/(?:x-)?(?:java|ecma)script/i,
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
/**
diff --git a/test/unit/tests/string.test.js b/test/unit/tests/string.test.js
index e1d760e..27ef2b6 100644
--- a/test/unit/tests/string.test.js
+++ b/test/unit/tests/string.test.js
@@ -238,6 +238,9 @@ suite('String', function () {
('foo <script>boo();<'+'/script><script type="text/javascript">boo();\nmoo();<'+'/script>bar').extractScripts());
assert.enumEqual(['boo();','boo();\nmoo();'],
('foo <script>boo();<'+'/script>blub\nblub<script type="text/javascript">boo();\nmoo();<'+'/script>bar').extractScripts());
+
+ assert.enumEqual([], ('<' + 'script type="x-something">wat();<' + '/script>').extractScripts());
+ assert.enumEqual(['wat();'], ('<' + 'script type="text/javascript">wat();<' + '/script>').extractScripts());
});
test('#evalScripts', function () {
@@ -250,6 +253,27 @@ suite('String', function () {
(3).times(function(){ stringWithScripts += 'foo <script>evalScriptsCounter++<'+'/script>bar' });
stringWithScripts.evalScripts();
assert.equal(4, evalScriptsCounter);
+
+ // Other executable MIME-types.
+ ('foo <script type="text/javascript">evalScriptsCounter++<'+'/script>bar')
+ .evalScripts();
+ ('foo <script type="application/javascript">evalScriptsCounter++<'+'/script>bar')
+ .evalScripts();
+ ('foo <script type="application/x-javascript">evalScriptsCounter++<'+'/script>bar')
+ .evalScripts();
+ ('foo <script type="text/x-javascript">evalScriptsCounter++<'+'/script>bar')
+ .evalScripts();
+ ('foo <script type="application/ecmascript">evalScriptsCounter++<'+'/script>bar')
+ .evalScripts();
+ ('foo <script type="text/ecmascript">evalScriptsCounter++<'+'/script>bar')
+ .evalScripts();
+
+ assert.equal(10, evalScriptsCounter);
+
+ // a wrong one
+ ('foo <script type="text/x-dot-template">evalScriptsCounter++<'+'/script>bar').evalScripts();
+
+ assert.equal(10, evalScriptsCounter);
});
test('#escapeHTML', function () {
| 0 | 2 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
6a992259424e028616dc83147d18f0160219079d
|
Add a numeric query string to all the assets we serve out of /static just to be safe.
|
commit 6a992259424e028616dc83147d18f0160219079d
Author: Andrew Dupont <[email protected]>
Date: Sun May 18 20:46:06 2014 -0500
Add a numeric query string to all the assets we serve out of /static just to be safe.
diff --git a/test.new/views/layout.erb b/test.new/views/layout.erb
index 4567690..74eebc6 100644
--- a/test.new/views/layout.erb
+++ b/test.new/views/layout.erb
@@ -36,10 +36,10 @@
}
</style>
- <script src="/prototype.js" type="text/javascript"></script>
- <script src="/js/mocha.js" type="text/javascript"></script>
- <script src="/js/proclaim.js" type="text/javascript"></script>
- <script src="/js/test_helpers.js" type="text/javascript"></script>
+ <script src="/prototype.js?<%= @unique_asset_string %>" type="text/javascript"></script>
+ <script src="/js/mocha.js?<%= @unique_asset_string %>" type="text/javascript"></script>
+ <script src="/js/proclaim.js?<%= @unique_asset_string %>" type="text/javascript"></script>
+ <script src="/js/test_helpers.js?<%= @unique_asset_string %>" type="text/javascript"></script>
<script type="text/javascript">
var eventResults = {};
@@ -52,7 +52,7 @@
</script>
<% @suites.each do |suite| %>
- <script src="/js/tests/<%= suite %>.test.js" type="text/javascript"></script>
+ <script src="/js/tests/<%= suite %>.test.js?<%= @unique_asset_string %>" type="text/javascript"></script>
<% end %>
</head>
| 0 | 3 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
f64393e13b33ef61c435f9e03ad610e75e59df0d
|
Fix a URIError encountered in Chrome when interpreting an `X-JSON` header with extended characters.
|
commit f64393e13b33ef61c435f9e03ad610e75e59df0d
Author: Andrew Dupont <[email protected]>
Date: Tue Jun 5 01:21:35 2012 -0500
Fix a URIError encountered in Chrome when interpreting an `X-JSON` header with extended characters.
diff --git a/src/prototype/ajax/response.js b/src/prototype/ajax/response.js
index 5054909..7b70092 100644
--- a/src/prototype/ajax/response.js
+++ b/src/prototype/ajax/response.js
@@ -151,7 +151,23 @@ Ajax.Response = Class.create({
_getHeaderJSON: function() {
var json = this.getHeader('X-JSON');
if (!json) return null;
- json = decodeURIComponent(escape(json));
+
+ try {
+ // Browsers expect HTTP headers to be ASCII and nothing else. Running
+ // them through `decodeURIComponent` processes them with the page's
+ // specified encoding.
+ json = decodeURIComponent(escape(json));
+ } catch(e) {
+ // Except Chrome doesn't seem to need this, and calling
+ // `decodeURIComponent` on text that's already in the proper encoding
+ // will throw a `URIError`. The ugly solution is to assume that a
+ // `URIError` raised here signifies that the text is, in fact, already
+ // in the correct encoding, and treat the failure as a good sign.
+ //
+ // This is ugly, but so too is sending extended characters in an HTTP
+ // header with no spec to back you up.
+ }
+
try {
return json.evalJSON(this.request.options.sanitizeJSON ||
!this.request.isSameOrigin());
| 0 | 5 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
5e5cfff7c2c253eaf415c279f9083b4650cd4506
|
Sprockets 2 compatibility
|
commit 5e5cfff7c2c253eaf415c279f9083b4650cd4506
Author: Joshua Peek <[email protected]>
Date: Wed Dec 1 14:16:11 2010 -0600
Sprockets 2 compatibility
diff --git a/Rakefile b/Rakefile
index f3dc99e..c2b744c 100755
--- a/Rakefile
+++ b/Rakefile
@@ -76,7 +76,7 @@ module PrototypeHelper
</h1>
EOF
PDoc.run({
- :source_files => Dir[File.join('src', '**', '*.js')],
+ :source_files => Dir[File.join('src', 'prototype', '**', '*.js')],
:destination => DOC_DIR,
:index_page => 'README.markdown',
:syntax_highlighter => syntax_highlighter,
diff --git a/src/prototype.js b/src/prototype.js
index 3be3775..f493a74 100644
--- a/src/prototype.js
+++ b/src/prototype.js
@@ -1,188 +1,6 @@
-/* Prototype JavaScript framework, version <%= PROTOTYPE_VERSION %>
- * (c) 2005-2010 Sam Stephenson
- *
- * Prototype is freely distributable under the terms of an MIT-style license.
- * For details, see the Prototype web site: http://www.prototypejs.org/
- *
- *--------------------------------------------------------------------------*/
-
-/**
- * Prototype
- *
- * The [[Prototype]] namespace provides fundamental information about the
- * Prototype library you're using, as well as a central repository for default
- * iterators or functions.
- *
- * We say "namespace," because the [[Prototype]] object is not intended for
- * instantiation, nor for mixing in other objects. It's really just... a
- * namespace.
- *
- * ##### Your version of Prototype
- *
- * Your scripts can check against a particular version of Prototype by
- * examining [[Prototype.Version]], which is a version [[String]] (e.g.
- * "<%= PROTOTYPE_VERSION %>"). The famous
- * [script.aculo.us](http://script.aculo.us) library does this at load time to
- * ensure it's being used with a reasonably recent version of Prototype, for
- * instance.
- *
- * ##### Browser features
- *
- * Prototype also provides a (nascent) repository of
- * [[Prototype.BrowserFeatures browser feature information]], which it then
- * uses here and there in its source code. The idea is, first, to make
- * Prototype's source code more readable; and second, to centralize whatever
- * scripting trickery might be necessary to detect the browser feature, in
- * order to ease maintenance.
- *
- * ##### Default iterators and functions
- *
- * Numerous methods in Prototype objects (most notably the [[Enumerable]]
- * module) let the user pass in a custom iterator, but make it optional by
- * defaulting to an "identity function" (an iterator that just returns its
- * argument, untouched). This is the [[Prototype.K]] function, which you'll
- * see referred to in many places.
- *
- * Many methods also take it easy by protecting themselves against missing
- * methods here and there, reverting to empty functions when a supposedly
- * available method is missing. Such a function simply ignores its potential
- * arguments, and does nothing whatsoever (which is, oddly enough,
- * blazing fast). The quintessential empty function sits, unsurprisingly,
- * at [[Prototype.emptyFunction]] (note the lowercase first letter).
-**/
-var Prototype = {
-
- /**
- * Prototype.Version -> String
- *
- * The version of the Prototype library you are using (e.g.
- * "<%= PROTOTYPE_VERSION %>").
- **/
- Version: '<%= PROTOTYPE_VERSION %>',
-
- /**
- * Prototype.Browser
- *
- * A collection of [[Boolean]] values indicating the browser which is
- * currently in use. Available properties are `IE`, `Opera`, `WebKit`,
- * `MobileSafari` and `Gecko`.
- *
- * Example
- *
- * Prototype.Browser.WebKit;
- * //-> true, when executed in any WebKit-based browser.
- **/
- Browser: (function(){
- var ua = navigator.userAgent;
- // Opera (at least) 8.x+ has "Opera" as a [[Class]] of `window.opera`
- // This is a safer inference than plain boolean type conversion of `window.opera`
- var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
- return {
- IE: !!window.attachEvent && !isOpera,
- Opera: isOpera,
- WebKit: ua.indexOf('AppleWebKit/') > -1,
- Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
- MobileSafari: /Apple.*Mobile/.test(ua)
- }
- })(),
-
- /**
- * Prototype.BrowserFeatures
- *
- * A collection of [[Boolean]] values indicating the presence of specific
- * browser features.
- **/
- BrowserFeatures: {
- /**
- * Prototype.BrowserFeatures.XPath -> Boolean
- *
- * Used internally to detect if the browser supports
- * [DOM Level 3 XPath](http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html).
- **/
- XPath: !!document.evaluate,
-
- /**
- * Prototype.BrowserFeatures.SelectorsAPI -> Boolean
- *
- * Used internally to detect if the browser supports the
- * [NodeSelector API](http://www.w3.org/TR/selectors-api/#nodeselector).
- **/
- SelectorsAPI: !!document.querySelector,
-
- /**
- * Prototype.BrowserFeatures.ElementExtensions -> Boolean
- *
- * Used internally to detect if the browser supports extending html element
- * prototypes.
- **/
- ElementExtensions: (function() {
- var constructor = window.Element || window.HTMLElement;
- return !!(constructor && constructor.prototype);
- })(),
- SpecificElementExtensions: (function() {
- // First, try the named class
- if (typeof window.HTMLDivElement !== 'undefined')
- return true;
-
- var div = document.createElement('div'),
- form = document.createElement('form'),
- isSupported = false;
-
- if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) {
- isSupported = true;
- }
-
- div = form = null;
-
- return isSupported;
- })()
- },
-
- ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
- JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
-
- /**
- * Prototype.emptyFunction([argument...]) -> undefined
- * - argument (Object): Optional arguments
- *
- * The [[Prototype.emptyFunction]] does nothing... and returns nothing!
- *
- * It is used thoughout the framework to provide a fallback function in order
- * to cut down on conditionals. Typically you'll find it as a default value
- * for optional callback functions.
- **/
- emptyFunction: function() { },
-
- /**
- * Prototype.K(argument) -> argument
- * - argument (Object): Optional argument...
- *
- * [[Prototype.K]] is Prototype's very own
- * [identity function](http://en.wikipedia.org/wiki/Identity_function), i.e.
- * it returns its `argument` untouched.
- *
- * This is used throughout the framework, most notably in the [[Enumerable]]
- * module as a default value for iterators.
- *
- * ##### Examples
- *
- * Prototype.K('hello world!');
- * // -> 'hello world!'
- *
- * Prototype.K(200);
- * // -> 200
- *
- * Prototype.K(Prototype.K);
- * // -> Prototype.K
- **/
- K: function(x) { return x }
-};
-
-if (Prototype.Browser.MobileSafari)
- Prototype.BrowserFeatures.SpecificElementExtensions = false;
-
-//= require "lang"
-//= require "ajax"
-//= require "dom"
-
-//= require "deprecated"
+//= compat
+//= require "./prototype/prototype"
+//= require "./prototype/lang"
+//= require "./prototype/ajax"
+//= require "./prototype/dom"
+//= require "./prototype/deprecated"
diff --git a/src/ajax.js b/src/prototype/ajax.js
similarity index 99%
rename from src/ajax.js
rename to src/prototype/ajax.js
index b246aa8..137be07 100644
--- a/src/ajax.js
+++ b/src/prototype/ajax.js
@@ -1,3 +1,12 @@
+//= compat
+//= require "ajax/ajax"
+//= require "ajax/responders"
+//= require "ajax/base"
+//= require "ajax/request"
+//= require "ajax/response"
+//= require "ajax/updater"
+//= require "ajax/periodical_updater"
+
/**
* == Ajax ==
*
@@ -31,7 +40,7 @@
*
* * `asynchronous` ([[Boolean]]; default `true`): Determines whether
* `XMLHttpRequest` is used asynchronously or not. Synchronous usage is
- * **strongly discouraged** — it halts all script execution for the
+ * **strongly discouraged** — it halts all script execution for the
* duration of the request _and_ blocks the browser UI.
* * `contentType` ([[String]]; default `application/x-www-form-urlencoded`):
* The `Content-type` header for your request. Change this header if you
@@ -106,11 +115,3 @@
* happened during the request.
*
**/
-
-//= require "ajax/ajax"
-//= require "ajax/responders"
-//= require "ajax/base"
-//= require "ajax/request"
-//= require "ajax/response"
-//= require "ajax/updater"
-//= require "ajax/periodical_updater"
diff --git a/src/ajax/ajax.js b/src/prototype/ajax/ajax.js
similarity index 100%
rename from src/ajax/ajax.js
rename to src/prototype/ajax/ajax.js
diff --git a/src/ajax/base.js b/src/prototype/ajax/base.js
similarity index 100%
rename from src/ajax/base.js
rename to src/prototype/ajax/base.js
diff --git a/src/ajax/periodical_updater.js b/src/prototype/ajax/periodical_updater.js
similarity index 100%
rename from src/ajax/periodical_updater.js
rename to src/prototype/ajax/periodical_updater.js
diff --git a/src/ajax/request.js b/src/prototype/ajax/request.js
similarity index 100%
rename from src/ajax/request.js
rename to src/prototype/ajax/request.js
diff --git a/src/ajax/responders.js b/src/prototype/ajax/responders.js
similarity index 100%
rename from src/ajax/responders.js
rename to src/prototype/ajax/responders.js
diff --git a/src/ajax/response.js b/src/prototype/ajax/response.js
similarity index 100%
rename from src/ajax/response.js
rename to src/prototype/ajax/response.js
diff --git a/src/ajax/updater.js b/src/prototype/ajax/updater.js
similarity index 100%
rename from src/ajax/updater.js
rename to src/prototype/ajax/updater.js
diff --git a/src/deprecated.js b/src/prototype/deprecated.js
similarity index 100%
rename from src/deprecated.js
rename to src/prototype/deprecated.js
diff --git a/src/dom.js b/src/prototype/dom.js
similarity index 98%
rename from src/dom.js
rename to src/prototype/dom.js
index 79d6924..6003cd0 100644
--- a/src/dom.js
+++ b/src/prototype/dom.js
@@ -1,3 +1,11 @@
+//= compat
+//= require "dom/dom"
+//= require "dom/layout"
+//= require "dom/selector"
+//= require <selector_engine>
+//= require "dom/form"
+//= require "dom/event"
+
/**
* == DOM ==
* Extensions to DOM elements, plus other utilities for DOM traversal
@@ -19,11 +27,4 @@
*
**/
-//= require "dom/dom"
-//= require "dom/layout"
-//= require "dom/selector"
-//= require <selector_engine>
-//= require "dom/form"
-//= require "dom/event"
-
Element.addMethods();
diff --git a/src/dom/dom.js b/src/prototype/dom/dom.js
similarity index 100%
rename from src/dom/dom.js
rename to src/prototype/dom/dom.js
diff --git a/src/dom/event.js b/src/prototype/dom/event.js
similarity index 100%
rename from src/dom/event.js
rename to src/prototype/dom/event.js
diff --git a/src/dom/form.js b/src/prototype/dom/form.js
similarity index 100%
rename from src/dom/form.js
rename to src/prototype/dom/form.js
diff --git a/src/dom/layout.js b/src/prototype/dom/layout.js
similarity index 100%
rename from src/dom/layout.js
rename to src/prototype/dom/layout.js
diff --git a/src/dom/selector.js b/src/prototype/dom/selector.js
similarity index 100%
rename from src/dom/selector.js
rename to src/prototype/dom/selector.js
diff --git a/src/lang.js b/src/prototype/lang.js
similarity index 95%
rename from src/lang.js
rename to src/prototype/lang.js
index fea6479..8a23edf 100644
--- a/src/lang.js
+++ b/src/prototype/lang.js
@@ -1,3 +1,18 @@
+//= compat
+//= require "lang/class"
+//= require "lang/object"
+//= require "lang/function"
+//= require "lang/date"
+//= require "lang/regexp"
+//= require "lang/periodical_executer"
+//= require "lang/string"
+//= require "lang/template"
+//= require "lang/enumerable"
+//= require "lang/array"
+//= require "lang/hash"
+//= require "lang/number"
+//= require "lang/range"
+
/**
* == Language ==
* Additions to JavaScript's "standard library" and extensions to
@@ -16,23 +31,23 @@ var Abstract = { };
*
* Accepts an arbitrary number of functions and returns the result of the
* first one that doesn't throw an error.
- *
+ *
* **This method is deprecated.**
*
* <h5>More information</h5>
*
- * [[Try.these]] provides a simple idiom for trying out blocks of code in
- * sequence. Such a sequence of attempts usually represents a downgrading
+ * [[Try.these]] provides a simple idiom for trying out blocks of code in
+ * sequence. Such a sequence of attempts usually represents a downgrading
* approach to obtaining a given feature.
*
- * In this example from Prototype's [[Ajax section]] internals, we want to get an
- * `XMLHttpRequest` object. Internet Explorer 6 and earlier, however, does not
- * provide it as a vanilla JavaScript object, and will throw an error if we
- * attempt a simple instantiation. Also, over time, its proprietary way
+ * In this example from Prototype's [[Ajax section]] internals, we want to get an
+ * `XMLHttpRequest` object. Internet Explorer 6 and earlier, however, does not
+ * provide it as a vanilla JavaScript object, and will throw an error if we
+ * attempt a simple instantiation. Also, over time, its proprietary way
* evolved, changing COM interface names.
*
- * [[Try.these]] will try several ways in sequence, from the best (and,
- * theoretically, most widespread) one to the oldest and rarest way, returning
+ * [[Try.these]] will try several ways in sequence, from the best (and,
+ * theoretically, most widespread) one to the oldest and rarest way, returning
* the result of the first successful function.
*
* If none of the blocks succeeded, [[Try.these]] will return `undefined`, which
@@ -64,17 +79,3 @@ var Try = {
return returnValue;
}
};
-
-//= require "lang/class"
-//= require "lang/object"
-//= require "lang/function"
-//= require "lang/date"
-//= require "lang/regexp"
-//= require "lang/periodical_executer"
-//= require "lang/string"
-//= require "lang/template"
-//= require "lang/enumerable"
-//= require "lang/array"
-//= require "lang/hash"
-//= require "lang/number"
-//= require "lang/range"
diff --git a/src/lang/array.js b/src/prototype/lang/array.js
similarity index 100%
rename from src/lang/array.js
rename to src/prototype/lang/array.js
diff --git a/src/lang/class.js b/src/prototype/lang/class.js
similarity index 100%
rename from src/lang/class.js
rename to src/prototype/lang/class.js
diff --git a/src/lang/date.js b/src/prototype/lang/date.js
similarity index 100%
rename from src/lang/date.js
rename to src/prototype/lang/date.js
diff --git a/src/lang/enumerable.js b/src/prototype/lang/enumerable.js
similarity index 100%
rename from src/lang/enumerable.js
rename to src/prototype/lang/enumerable.js
diff --git a/src/lang/function.js b/src/prototype/lang/function.js
similarity index 100%
rename from src/lang/function.js
rename to src/prototype/lang/function.js
diff --git a/src/lang/hash.js b/src/prototype/lang/hash.js
similarity index 100%
rename from src/lang/hash.js
rename to src/prototype/lang/hash.js
diff --git a/src/lang/number.js b/src/prototype/lang/number.js
similarity index 100%
rename from src/lang/number.js
rename to src/prototype/lang/number.js
diff --git a/src/lang/object.js b/src/prototype/lang/object.js
similarity index 100%
rename from src/lang/object.js
rename to src/prototype/lang/object.js
diff --git a/src/lang/periodical_executer.js b/src/prototype/lang/periodical_executer.js
similarity index 100%
rename from src/lang/periodical_executer.js
rename to src/prototype/lang/periodical_executer.js
diff --git a/src/lang/range.js b/src/prototype/lang/range.js
similarity index 100%
rename from src/lang/range.js
rename to src/prototype/lang/range.js
diff --git a/src/lang/regexp.js b/src/prototype/lang/regexp.js
similarity index 100%
rename from src/lang/regexp.js
rename to src/prototype/lang/regexp.js
diff --git a/src/lang/string.js b/src/prototype/lang/string.js
similarity index 100%
rename from src/lang/string.js
rename to src/prototype/lang/string.js
diff --git a/src/lang/template.js b/src/prototype/lang/template.js
similarity index 100%
rename from src/lang/template.js
rename to src/prototype/lang/template.js
diff --git a/src/prototype/prototype.js b/src/prototype/prototype.js
new file mode 100644
index 0000000..7ce3270
--- /dev/null
+++ b/src/prototype/prototype.js
@@ -0,0 +1,183 @@
+//= compat
+/* Prototype JavaScript framework, version <%= PROTOTYPE_VERSION %>
+ * (c) 2005-2010 Sam Stephenson
+ *
+ * Prototype is freely distributable under the terms of an MIT-style license.
+ * For details, see the Prototype web site: http://www.prototypejs.org/
+ *
+ *--------------------------------------------------------------------------*/
+
+/**
+ * Prototype
+ *
+ * The [[Prototype]] namespace provides fundamental information about the
+ * Prototype library you're using, as well as a central repository for default
+ * iterators or functions.
+ *
+ * We say "namespace," because the [[Prototype]] object is not intended for
+ * instantiation, nor for mixing in other objects. It's really just... a
+ * namespace.
+ *
+ * ##### Your version of Prototype
+ *
+ * Your scripts can check against a particular version of Prototype by
+ * examining [[Prototype.Version]], which is a version [[String]] (e.g.
+ * "<%= PROTOTYPE_VERSION %>"). The famous
+ * [script.aculo.us](http://script.aculo.us) library does this at load time to
+ * ensure it's being used with a reasonably recent version of Prototype, for
+ * instance.
+ *
+ * ##### Browser features
+ *
+ * Prototype also provides a (nascent) repository of
+ * [[Prototype.BrowserFeatures browser feature information]], which it then
+ * uses here and there in its source code. The idea is, first, to make
+ * Prototype's source code more readable; and second, to centralize whatever
+ * scripting trickery might be necessary to detect the browser feature, in
+ * order to ease maintenance.
+ *
+ * ##### Default iterators and functions
+ *
+ * Numerous methods in Prototype objects (most notably the [[Enumerable]]
+ * module) let the user pass in a custom iterator, but make it optional by
+ * defaulting to an "identity function" (an iterator that just returns its
+ * argument, untouched). This is the [[Prototype.K]] function, which you'll
+ * see referred to in many places.
+ *
+ * Many methods also take it easy by protecting themselves against missing
+ * methods here and there, reverting to empty functions when a supposedly
+ * available method is missing. Such a function simply ignores its potential
+ * arguments, and does nothing whatsoever (which is, oddly enough,
+ * blazing fast). The quintessential empty function sits, unsurprisingly,
+ * at [[Prototype.emptyFunction]] (note the lowercase first letter).
+**/
+var Prototype = {
+
+ /**
+ * Prototype.Version -> String
+ *
+ * The version of the Prototype library you are using (e.g.
+ * "<%= PROTOTYPE_VERSION %>").
+ **/
+ Version: '<%= PROTOTYPE_VERSION %>',
+
+ /**
+ * Prototype.Browser
+ *
+ * A collection of [[Boolean]] values indicating the browser which is
+ * currently in use. Available properties are `IE`, `Opera`, `WebKit`,
+ * `MobileSafari` and `Gecko`.
+ *
+ * Example
+ *
+ * Prototype.Browser.WebKit;
+ * //-> true, when executed in any WebKit-based browser.
+ **/
+ Browser: (function(){
+ var ua = navigator.userAgent;
+ // Opera (at least) 8.x+ has "Opera" as a [[Class]] of `window.opera`
+ // This is a safer inference than plain boolean type conversion of `window.opera`
+ var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
+ return {
+ IE: !!window.attachEvent && !isOpera,
+ Opera: isOpera,
+ WebKit: ua.indexOf('AppleWebKit/') > -1,
+ Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
+ MobileSafari: /Apple.*Mobile/.test(ua)
+ }
+ })(),
+
+ /**
+ * Prototype.BrowserFeatures
+ *
+ * A collection of [[Boolean]] values indicating the presence of specific
+ * browser features.
+ **/
+ BrowserFeatures: {
+ /**
+ * Prototype.BrowserFeatures.XPath -> Boolean
+ *
+ * Used internally to detect if the browser supports
+ * [DOM Level 3 XPath](http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html).
+ **/
+ XPath: !!document.evaluate,
+
+ /**
+ * Prototype.BrowserFeatures.SelectorsAPI -> Boolean
+ *
+ * Used internally to detect if the browser supports the
+ * [NodeSelector API](http://www.w3.org/TR/selectors-api/#nodeselector).
+ **/
+ SelectorsAPI: !!document.querySelector,
+
+ /**
+ * Prototype.BrowserFeatures.ElementExtensions -> Boolean
+ *
+ * Used internally to detect if the browser supports extending html element
+ * prototypes.
+ **/
+ ElementExtensions: (function() {
+ var constructor = window.Element || window.HTMLElement;
+ return !!(constructor && constructor.prototype);
+ })(),
+ SpecificElementExtensions: (function() {
+ // First, try the named class
+ if (typeof window.HTMLDivElement !== 'undefined')
+ return true;
+
+ var div = document.createElement('div'),
+ form = document.createElement('form'),
+ isSupported = false;
+
+ if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) {
+ isSupported = true;
+ }
+
+ div = form = null;
+
+ return isSupported;
+ })()
+ },
+
+ ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
+ JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
+
+ /**
+ * Prototype.emptyFunction([argument...]) -> undefined
+ * - argument (Object): Optional arguments
+ *
+ * The [[Prototype.emptyFunction]] does nothing... and returns nothing!
+ *
+ * It is used thoughout the framework to provide a fallback function in order
+ * to cut down on conditionals. Typically you'll find it as a default value
+ * for optional callback functions.
+ **/
+ emptyFunction: function() { },
+
+ /**
+ * Prototype.K(argument) -> argument
+ * - argument (Object): Optional argument...
+ *
+ * [[Prototype.K]] is Prototype's very own
+ * [identity function](http://en.wikipedia.org/wiki/Identity_function), i.e.
+ * it returns its `argument` untouched.
+ *
+ * This is used throughout the framework, most notably in the [[Enumerable]]
+ * module as a default value for iterators.
+ *
+ * ##### Examples
+ *
+ * Prototype.K('hello world!');
+ * // -> 'hello world!'
+ *
+ * Prototype.K(200);
+ * // -> 200
+ *
+ * Prototype.K(Prototype.K);
+ * // -> Prototype.K
+ **/
+ K: function(x) { return x }
+};
+
+if (Prototype.Browser.MobileSafari)
+ Prototype.BrowserFeatures.SpecificElementExtensions = false;
diff --git a/src/selector_engine.js b/src/selector_engine.js
index 46e296f..b8deea8 100644
--- a/src/selector_engine.js
+++ b/src/selector_engine.js
@@ -1,9 +1,11 @@
-Prototype._original_property = window.Sizzle;
+//= compat
//= require "sizzle"
+Prototype._original_property = window.Sizzle;
+
;(function(engine) {
var extendElements = Prototype.Selector.extendElements;
-
+
function select(selector, scope) {
return extendElements(engine(selector, scope || document));
}
@@ -11,7 +13,7 @@ Prototype._original_property = window.Sizzle;
function match(element, selector) {
return engine.matches(selector, [element]).length == 1;
}
-
+
Prototype.Selector.engine = engine;
Prototype.Selector.select = select;
Prototype.Selector.match = match;
| 0 | 6 |
CVE-2007-2383
|
The Prototype (prototypejs) framework before 1.5.1 RC3 exchanges data using JavaScript Object Notation (JSON) without an associated protection scheme, which allows remote attackers to obtain the data via a web page that retrieves the data through a URL in the SRC attribute of a SCRIPT element and captures the data using other JavaScript code, aka "JavaScript Hijacking."
|
sstephenson/prototype
|
fea6bc1a21011c82290f6b5eeb3c3a34e9cdc62b
|
prototype: Automatically strip security delimiter comments from JSON strings before evaling them. The default delimiter is '/*-secure- ... */' or you can specify your own with the Prototype.JSONFilter regular expression. If you wrap your JSON response bodies in this delimiter on the server side, rogue external sites can't hijack potentially sensitive data via <script> tags. Closes #7910.
|
commit fea6bc1a21011c82290f6b5eeb3c3a34e9cdc62b
Author: Sam Stephenson <[email protected]>
Date: Tue Apr 24 03:31:14 2007 +0000
prototype: Automatically strip security delimiter comments from JSON strings before evaling them. The default delimiter is '/*-secure- ... */' or you can specify your own with the Prototype.JSONFilter regular expression. If you wrap your JSON response bodies in this delimiter on the server side, rogue external sites can't hijack potentially sensitive data via <script> tags. Closes #7910.
diff --git a/CHANGELOG b/CHANGELOG
index 68201a1..69dfe48 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,8 @@
*SVN*
+* Automatically strip security delimiter comments from JSON strings before evaling them. The default delimiter is '/*-secure- ... */' or you can specify your own with the Prototype.JSONFilter regular expression. If you wrap your JSON response bodies in this delimiter on the server side, rogue external sites can't hijack potentially sensitive data via <script> tags. Closes #7910. [Tobie Langel]
+ For more details on potential security problems, see: http://www.fortifysoftware.com/servlet/downloads/public/JavaScript_Hijacking.pdf
+
* Add extra spacing so Array#toJSON and Hash#toJSON generate YAML-loadable JSON. Closes #7883. [Andrew Dupont]
* Fix Form.request for forms containing an input element with name="action". Closes #8063. [Thomas Fuchs, Mislav Marohnić]
diff --git a/src/ajax.js b/src/ajax.js
index ca40b3e..7bcf479 100644
--- a/src/ajax.js
+++ b/src/ajax.js
@@ -212,13 +212,13 @@ Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
evalJSON: function() {
try {
var json = this.getHeader('X-JSON');
- return json ? eval('(' + json + ')') : null;
+ return json ? json.evalJSON() : null;
} catch (e) { return null }
},
evalResponse: function() {
try {
- return eval(this.transport.responseText);
+ return eval((this.transport.responseText || '').unfilterJSON());
} catch (e) {
this.dispatchException(e);
}
diff --git a/src/prototype.js b/src/prototype.js
index c42c185..41d7418 100644
--- a/src/prototype.js
+++ b/src/prototype.js
@@ -9,6 +9,7 @@ var Prototype = {
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
},
+
BrowserFeatures: {
XPath: !!document.evaluate,
ElementExtensions: !!window.HTMLElement,
@@ -16,9 +17,11 @@ var Prototype = {
(document.createElement('div').__proto__ !==
document.createElement('form').__proto__)
},
-
+
ScriptFragment: '<script[^>]*>([\u0001-\uFFFF]*?)</script>',
- emptyFunction: function() {},
+ JSONFilter: /^\/\*-secure-\s*(.*)\s*\*\/\s*$/,
+
+ emptyFunction: function() { },
K: function(x) { return x }
}
diff --git a/src/string.js b/src/string.js
index 96fc361..9f0d1bf 100644
--- a/src/string.js
+++ b/src/string.js
@@ -163,12 +163,17 @@ Object.extend(String.prototype, {
return this.inspect(true);
},
+ unfilterJSON: function(filter) {
+ return this.sub(filter || Prototype.JSONFilter, '#{1}');
+ },
+
evalJSON: function(sanitize) {
+ var json = this.unfilterJSON();
try {
- if (!sanitize || (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)))
- return eval('(' + this + ')');
- } catch (e) {}
- throw new SyntaxError('Badly formated JSON string: ' + this.inspect());
+ if (!sanitize || (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(json)))
+ return eval('(' + json + ')');
+ } catch (e) { }
+ throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
},
include: function(pattern) {
diff --git a/test/unit/string.html b/test/unit/string.html
index 6e09746..d46eec9 100644
--- a/test/unit/string.html
+++ b/test/unit/string.html
@@ -430,7 +430,13 @@
attackTarget = "Not scared!";
assertRaise('SyntaxError', function(){dangerous.evalJSON(true)});
assertEqual("Not scared!", attackTarget);
- }}
+
+ assertEqual('hello world!', ('/*-secure-\n' + valid + '\n*/').evalJSON().test);
+ var temp = Prototype.JSONFilter;
+ Prototype.JSONFilter = /^\/\*(.*)\*\/$/; // test custom delimiters.
+ assertEqual('hello world!', ('/*' + valid + '*/').evalJSON().test);
+ Prototype.JSONFilter = temp;
+ }}
}, 'testlog');
// ]]>
</script>
| 1 | 1 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
baaccba1411afab6b3794d405d5143b4cf9d75c0
|
Fixed Signup Limits bug where an invalid check was being done on the role
limit, causing queuing when over limit not to occur.
The software was checking $count['Tank'] instead of $count['role1'] (which
is what is returned by the count function) and thus the equality check
always failed (meaning $queue was never set).
|
commit baaccba1411afab6b3794d405d5143b4cf9d75c0
Author: Douglas Wagner <[email protected]>
Date: Wed Jul 15 16:18:41 2009 -0500
Fixed Signup Limits bug where an invalid check was being done on the role
limit, causing queuing when over limit not to occur.
The software was checking $count['Tank'] instead of $count['role1'] (which
is what is returned by the count function) and thus the equality check
always failed (meaning $queue was never set).
diff --git a/view.php b/view.php
index 358e42e..2733767 100644
--- a/view.php
+++ b/view.php
@@ -1106,7 +1106,7 @@ elseif($mode == 'signup')
if($phpraid_config['enforce_role_limits'])
{
- $sql = sprintf("SELECT role_name
+ $sql = sprintf("SELECT role_name, c.role_id
FROM " . $phpraid_config['db_prefix'] . "chars AS a,
" . $phpraid_config['db_prefix'] . "class_role AS b,
" . $phpraid_config['db_prefix'] . "roles AS c
@@ -1118,7 +1118,7 @@ elseif($mode == 'signup')
$role_name = $role_name_data['role_name'];
foreach ($wrm_global_roles as $global_role)
if ($global_role['role_name'] != '' && $role_name == $global_role['role_name'])
- if ($count[$global_role['role_name']] >= $raid_role_array[$global_role['role_name']])
+ if ($count[$global_role['role_id']] >= $raid_role_array[$global_role['role_name']])
$queue = 1;
}
@@ -1330,19 +1330,22 @@ elseif($mode == 'draft')
if($phpraid_config['enforce_role_limits'])
{
- $sql = sprintf("SELECT role_name
- FROM " . $phpraid_config['db_prefix'] . "chars AS a,
- " . $phpraid_config['db_prefix'] . "class_role AS b,
- " . $phpraid_config['db_prefix'] . "roles AS c
- WHERE a.pri_spec = b.subclass
+ // User is in Queue, Therefor should have a signup record already.
+ $sql = sprintf("SELECT c.role_name, c.role_id
+ FROM " . $phpraid_config['db_prefix'] . "signups AS a,
+ " . $phpraid_config['db_prefix'] . "class_role AS b,
+ " . $phpraid_config['db_prefix'] . "roles AS c
+ WHERE a.selected_spec = b.subclass
AND b.role_id = c.role_id
- AND a.char_id=%s", quote_smart($char_id));
+ AND a.raid_id=%s
+ AND a.char_id=%s", quote_smart($raid_id), quote_smart($char_id));
+
$result_role_name = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
$role_name_data = $db_raid->sql_fetchrow($result_role_name, true);
$role_name = $role_name_data['role_name'];
foreach ($wrm_global_roles as $global_role)
if ($global_role['role_name'] != '' && $role_name == $global_role['role_name'])
- if ($count[$global_role['role_name']] >= $raid_role_array[$global_role['role_name']])
+ if ($count[$global_role['role_id']] >= $raid_role_array[$global_role['role_name']])
$queue = 1;
}
| 0 | 3 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
7e018942065a006e82c0789230824783a4f171c5
|
Bug fix for getCookiePath() to support users below PHP v5.1.2
The second parameter (PHP_URL_PATH) added to parse_url is not supported
until php 5.1.2, this was causing people to get parse_url errors and
session start errors thrown at them.
This should now be fixed.
|
commit 7e018942065a006e82c0789230824783a4f171c5
Author: Douglas Wagner <[email protected]>
Date: Fri Jan 2 18:25:50 2009 -0600
Bug fix for getCookiePath() to support users below PHP v5.1.2
The second parameter (PHP_URL_PATH) added to parse_url is not supported
until php 5.1.2, this was causing people to get parse_url errors and
session start errors thrown at them.
This should now be fixed.
diff --git a/includes/functions_auth.php b/includes/functions_auth.php
index ef86ef9..20d0e8f 100644
--- a/includes/functions_auth.php
+++ b/includes/functions_auth.php
@@ -45,7 +45,10 @@ function curPageURL() {
// Creates the cookie storage path.
function getCookiePath()
{
- $cookie_path = parse_url(curPageURL(), PHP_URL_PATH);
+ $URL_Array = array();
+ $URL_Array = parse_url(curPageURL());
+ $cookie_path = $URL_Array['path'];
+
$pos = strrpos($cookie_path, "/");
if ($pos === false)
{
| 0 | 6 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
8e73576c53b13b4583e1bf796492ca9e49db184a
|
clean up Auth Code
Signed-off-by: neme <[email protected]>
|
commit 8e73576c53b13b4583e1bf796492ca9e49db184a
Author: neme <[email protected]>
Date: Tue Aug 24 00:57:56 2010 +0200
clean up Auth Code
Signed-off-by: neme <[email protected]>
diff --git a/auth/auth_e107.php b/auth/auth_e107.php
index 51098bc..b835582 100644
--- a/auth/auth_e107.php
+++ b/auth/auth_e107.php
@@ -1,12 +1,8 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_e107.php
* -------------------
- * begin : July 22, 2008
- * Dev : Carsten Hölbing
- * email : [email protected]
*
- * based on : auth_e107.php @ Douglas Wagner
* copyright : (C) 2007-2008 Douglas Wagner
* email : [email protected]
*
@@ -40,6 +36,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = TRUE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -255,6 +252,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -328,36 +326,4 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_iums.php b/auth/auth_iums.php
index 18f7acd..06c4ff8 100644
--- a/auth/auth_iums.php
+++ b/auth/auth_iums.php
@@ -37,6 +37,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
die("Hacking attempt detected!");
$BridgeSupportPWDChange = TRUE;
+$Bridge2ColumGroup = FALSE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -54,6 +55,8 @@ $db_table_user_name = "profile";
$table_prefix = $phpraid_config['db_prefix'];
+$auth_user_class = "";
+$auth_alt_user_class = "";
//change password in WRM DB
function db_password_change($profile_id, $dbusernewpassword)
@@ -157,6 +160,7 @@ function phpraid_login() {
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -228,36 +232,5 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_joomla.php b/auth/auth_joomla.php
index 5472f7a..092ce09 100644
--- a/auth/auth_joomla.php
+++ b/auth/auth_joomla.php
@@ -1,6 +1,6 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_joomla.php
* -------------------
* begin : July 22, 2008
* Dev : Carsten Hölbing
@@ -40,6 +40,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = FALSE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -274,6 +275,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -348,36 +350,5 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_phpbb.php b/auth/auth_phpbb.php
index d0c7de4..67fcd47 100644
--- a/auth/auth_phpbb.php
+++ b/auth/auth_phpbb.php
@@ -1,6 +1,6 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_phpbb.php
* -------------------
* begin : July 22, 2008
* Dev : Carsten Hölbing
@@ -40,6 +40,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = FALSE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -246,6 +247,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -320,36 +322,4 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_phpbb3.php b/auth/auth_phpbb3.php
index 74803b5..328b3d2 100644
--- a/auth/auth_phpbb3.php
+++ b/auth/auth_phpbb3.php
@@ -40,6 +40,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
//This is NOT SAFE to turn on.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = FALSE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -239,6 +240,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -318,37 +320,4 @@ require ($phpraid_dir . "includes/functions_pwdhash.php");
// setup Password Hasher Routine
$pwd_hasher = new PasswordHash(8, FALSE);
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-
?>
diff --git a/auth/auth_smf.php b/auth/auth_smf.php
index ba9a73c..c1dcf13 100644
--- a/auth/auth_smf.php
+++ b/auth/auth_smf.php
@@ -1,6 +1,6 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_smf.php
* -------------------
* begin : July 22, 2008
* Dev : Carsten Hölbing
@@ -40,6 +40,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = TRUE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -285,6 +286,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -359,36 +361,4 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_smf2.php b/auth/auth_smf2.php
index 21fc6b2..58defdd 100644
--- a/auth/auth_smf2.php
+++ b/auth/auth_smf2.php
@@ -1,6 +1,6 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_smf2.php
* -------------------
* begin : July 22, 2008
* Dev : Carsten Hölbing
@@ -40,6 +40,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = TRUE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -285,6 +286,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -359,36 +361,4 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_wbb.php b/auth/auth_wbb.php
index 4caa07c..d793620 100644
--- a/auth/auth_wbb.php
+++ b/auth/auth_wbb.php
@@ -1,6 +1,6 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_wbb.php
* -------------------
* begin : July 22, 2008
* Dev : Carsten Hölbing
@@ -75,6 +75,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = FALSE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -348,6 +349,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -425,36 +427,4 @@ function phpraid_logout()
// Read In the Include File.
include('options.inc.php');
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/auth/auth_xoops.php b/auth/auth_xoops.php
index 8e26872..a4647bc 100644
--- a/auth/auth_xoops.php
+++ b/auth/auth_xoops.php
@@ -1,6 +1,6 @@
<?php
/***************************************************************************
- * auth_phpbb3.php
+ * auth_xoops.php
* -------------------
* begin : July 22, 2008
* Dev : Carsten Hölbing
@@ -40,6 +40,7 @@ if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
// THIS IS SAFE TO TURN ON.
$BridgeSupportPWDChange = FALSE;
+$Bridge2ColumGroup = FALSE;
/***********************************************
* Table and Column Names - change per CMS.
@@ -248,6 +249,7 @@ function phpraid_login()
// they want automatic logins so set the cookie
// set to expire in one month
setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
setcookie('password', $cmspass, time() + 2629743);
}
@@ -322,37 +324,4 @@ function phpraid_logout()
setcookie('password', '', time() - 2629743);
}
-// good ole authentication
-$lifetime = get_cfg_var("session.gc_maxlifetime");
-$temp = session_name("WRM-" . $phpraid_config['auth_type']);
-$temp = session_set_cookie_params($lifetime, getCookiePath());
-session_start();
-$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
-
-
-// set session defaults
-if (!isset($_SESSION['initiated']))
-{
- if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
- {
- $testval = phpraid_login();
- if (!$testval)
- {
- phpraid_logout();
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
- }
- else
- {
- session_regenerate_id();
- $_SESSION['initiated'] = true;
- $_SESSION['username'] = 'Anonymous';
- $_SESSION['session_logged_in'] = 0;
- $_SESSION['profile_id'] = -1;
- }
-}
-?>
\ No newline at end of file
+?>
diff --git a/common.php b/common.php
index ce8f6ae..0e791a0 100644
--- a/common.php
+++ b/common.php
@@ -198,6 +198,40 @@ else
***************************************************/
// get auth type
require_once($phpraid_dir.'auth/auth_' . $phpraid_config['auth_type'] . '.php');
+
+// good ole authentication
+$lifetime = get_cfg_var("session.gc_maxlifetime");
+$temp = session_name("WRM-" . $phpraid_config['auth_type']);
+$temp = session_set_cookie_params($lifetime, getCookiePath());
+session_start();
+$_SESSION['name'] = "WRM-" . $phpraid_config['auth_type'];
+
+// set session defaults
+if (!isset($_SESSION['initiated']))
+{
+ if(isset($_COOKIE['profile_id']) && isset($_COOKIE['password']))
+ {
+ $testval = wrm_login();
+ if (!$testval)
+ {
+ wrm_logout();
+ session_regenerate_id();
+ $_SESSION['initiated'] = true;
+ $_SESSION['username'] = 'Anonymous';
+ $_SESSION['session_logged_in'] = 0;
+ $_SESSION['profile_id'] = -1;
+ }
+ }
+ else
+ {
+ session_regenerate_id();
+ $_SESSION['initiated'] = true;
+ $_SESSION['username'] = 'Anonymous';
+ $_SESSION['session_logged_in'] = 0;
+ $_SESSION['profile_id'] = -1;
+ }
+}
+
get_permissions();
/***************************************************
diff --git a/includes/class_loginbox.php b/includes/class_loginbox.php
index 44c1e8a..616a4fe 100644
--- a/includes/class_loginbox.php
+++ b/includes/class_loginbox.php
@@ -33,7 +33,7 @@
*/
class wrm_loginbox
{
- //gerneral stuff
+ //general stuff
var $db_raid;
var $phpraid_config;
var $phprlang;
@@ -41,6 +41,7 @@ class wrm_loginbox
var $loginbox_show_status;
var $BridgeSupportPWDChange_status;
+
//
// Constructor
//
@@ -57,12 +58,28 @@ class wrm_loginbox
function wrm_show_loginbox_gethtmlstring()
{
+ $wrm_db_user_name = "username";
+ $wrm_table_prefix = $this->phpraid_config['db_prefix'];
+ $wrm__db_table_user_name = "profile";
+
$phpraid_dir = "./";
$phprlang = $this->phprlang;
$login_form = "";
$priv_config = scrub_input($_SESSION['priv_configuration']);
$logged_in = scrub_input($_SESSION['session_logged_in']);
+ $profile_id = scrub_input($_SESSION['profile_id']);
+
+ //database
+ $sql = sprintf( "SELECT ". $wrm_db_user_name .
+ " FROM " . $wrm_table_prefix . $wrm__db_table_user_name.
+ " WHERE profile_id = %s", quote_smart($profile_id)
+ );
+ $result = $this->db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $this->db_raid->sql_fetchrow($result, true);
+ $login_username_name = $data[$wrm_db_user_name];
+
+ //$login_username_name = scrub_input($_SESSION['username']);
/**************************************************************
* Show Login Box / Field
@@ -74,7 +91,7 @@ class wrm_loginbox
$login_username = '<input name="username" type="text" value="username" size="15" maxlength="45" onFocus="if(this.value==\'username\')this.value=\'\';" class="post">';
$login_password = '<input name="password" type="password" value="password" size="15" onFocus="if(this.value==\'password\')this.value=\'\';" class="post">';
$login_button = '<input type="submit" name="login" value="'.$phprlang['login'].'" style="font-size:10px" class="mainoption">';
- $login_remember = '<input type="checkbox" checked="checked" name="autologin">';
+ //$login_remember = '<input type="checkbox" checked="checked" name="autologin">';
$login_remember_hidden = '<input type="hidden" value="1" name="autologin">';
//$BridgeSupportPWDChange came from the bridge
@@ -88,10 +105,10 @@ class wrm_loginbox
else
{
$login_form_open = '<form action="login.php?logout=true" method="POST">';
- $login_username = scrub_input($_SESSION['username']);
+ $login_username = $login_username_name;
$login_password = '';
$login_button = '<input type="submit" name="login" value="'.$phprlang['logout'].'" style="font-size:10px" class="mainoption">';
- $login_remember = '';
+ //$login_remember = '';
$login_remember_hidden = '';
//$BridgeSupportPWDChange came from the bridge
diff --git a/includes/functions_auth.php b/includes/functions_auth.php
index 1cda9e4..8bc3e9e 100755
--- a/includes/functions_auth.php
+++ b/includes/functions_auth.php
@@ -82,12 +82,12 @@ function get_permissions()
$profile_id = scrub_input($_SESSION['profile_id']);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($profile_id));
- $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(),1);
+ $result = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(),1);
$data = $db_raid->sql_fetchrow($result, true);
// check all permissions
$sql_priv = "SELECT * FROM " . $phpraid_config['db_prefix'] . "permissions WHERE permission_id='{$data['priv']}'";
- $result_priv = $db_raid->sql_query($sql_priv) or print_error($sql_priv, mysql_error(),1);
+ $result_priv = $db_raid->sql_query($sql_priv) or print_error($sql_priv, $db_raid->sql_error(),1);
$data_priv = $db_raid->sql_fetchrow($result_priv, true);
@@ -108,7 +108,7 @@ function check_permission($perm_type, $profile_id) {
".$phpraid_config['db_prefix']."profile.priv = ".$phpraid_config['db_prefix']."permissions.permission_id
WHERE ".$phpraid_config['db_prefix']."profile.profile_id = ".$profile_id;
- $perm_data = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $perm_data = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
$permission_val = $db_raid->sql_fetchrow($perm_data, true);
if ($permission_val['perm_val'] == "1")
@@ -123,10 +123,10 @@ function delete_permissions() {
$id = scrub_input($_GET['perm_id']);
$sql = sprintf("DELETE FROM " . $phpraid_config['db_prefix'] . "permissions WHERE permission_id=%s", quote_smart($id));
- $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
$sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET priv='0' WHERE priv=%s", quote_smart($id));
- $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
}
function remove_user() {
@@ -136,12 +136,12 @@ function remove_user() {
$perm_id = scrub_input($_GET['perm_id']);
$sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET priv='0' WHERE profile_id=%s", quote_smart($user_id));
- $sql = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $sql = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
header("Location: permissions.php?mode=details&perm_id=". $perm_id);
}
//group permission
-//are all classes that could be found (in (cms) bridge) back/return
+//get are all classes that could be found (in (cms) bridge)
function get_group_array()
{
global $db_raid, $table_prefix, $db_raid;
@@ -152,7 +152,7 @@ function get_group_array()
" FROM " . $table_prefix . $db_table_allgroups .
" ORDER BY ". $db_group_id;
- $result_group = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $result_group = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
while ($data_wrm = $db_raid->sql_fetchrow($result_group,true))
{
array_push($group,
@@ -166,12 +166,227 @@ function get_group_array()
return $group;
}
-//WRM Logout
+/**************************************************************
+ * WRM Login
+ **************************************************************/
+function wrm_login()
+{
+ global $db_user_id, $db_group_id, $db_user_name, $db_user_email, $db_user_password, $db_table_user_name;
+ global $db_table_group_name, $auth_user_class, $auth_alt_user_class, $table_prefix, $db_raid, $phpraid_config;
+ global $Bridge2ColumGroup;
+
+ $username = $password = "";
+ $username_id = "";
+
+ //first login
+ if(isset($_POST['username'])){
+ // User is logging in, set encryption flag to 0 to identify login with plain text password.
+ $pwdencrypt = FALSE;
+ //$username = strtolower_wrap(scrub_input($_POST['username']), "UTF-8");
+ $password = $_POST['password'];
+ $wrmpass = md5($_POST['password']);
+ //database
+ $sql = sprintf( "SELECT profile_id " .
+ " FROM " . $table_prefix . "profile".
+ " WHERE username = %s", quote_smart($_POST['username'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
+ if ($db_raid->sql_numrows($result) > 0 )
+ {
+ $data = $db_raid->sql_fetchrow($result, true);
+ $username_id = $data['profile_id'];
+ }
+ else
+ {
+ wrm_logout();
+ return -1;
+ }
+
+ }// get infos from the COOKIE
+ elseif(isset($_COOKIE['profile_id']) && isset($_COOKIE['password'])) {
+ // User is not logging in but processing cooking, set encryption flag to 1 to identify login with encrypted password.
+ $pwdencrypt = TRUE;
+ //$username = strtolower_wrap(scrub_input($_COOKIE['username']), "UTF-8");
+ $password = $_COOKIE['password'];
+ $username_id = $_COOKIE['profile_id'];
+ $wrmpass = '';
+ } else {
+ wrm_logout();
+ }
+
+ //database
+ $sql = sprintf( "SELECT ". $db_user_id . "," . $db_user_name . "," . $db_user_email . "," . $db_user_password.
+ " FROM " . $table_prefix . $db_table_user_name .
+ " WHERE ". $db_user_id . " = %s", quote_smart($username_id)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+
+ if( ($username_id == $data[$db_user_id]) && ($cmspass = password_check($password, $data[$db_user_id], $pwdencrypt)) )
+ {
+ // The user has a matching username and proper password in the BRIDGE database.
+ // We need to validate the users group. If it does not contain the user group that has been set as
+ // authorized to use WRM, we need to fail the login with a proper message.
+ if ($auth_user_class != "")
+ {
+ $FoundUserInGroup = FALSE;
+
+ $sql = sprintf( "SELECT " . $db_group_id. "," .$db_add_group_ids ." FROM " . $table_prefix . $db_table_group_name.
+ " WHERE ".$db_user_id." = %s", quote_smart($data[$db_user_id])
+ );
+ $resultgroup = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
+ $datagroup = $db_raid->sql_fetchrow($resultgroup, true);
+
+ /*e107, smf*/
+ if ($Bridge2ColumGroup == TRUE)
+ {
+ if (($datagroup[$db_group_id] == $auth_user_class) or
+ ($datagroup[$db_group_id] == $auth_alt_user_class))
+ {
+ $FoundUserInGroup = TRUE;
+ }
+
+ if (($datagroup[$db_add_group_ids] == $auth_user_class) or
+ ($datagroup[$db_add_group_ids] == $auth_alt_user_class))
+ {
+ $FoundUserInGroup = TRUE;
+ }
+
+ /* old
+ $user_class = $datagroup[$db_group_id];
+ $user_class = $datagroup[$db_group_id] . "," . $datagroup[$db_add_group_ids];
+
+ $pos = strpos($user_class, $auth_user_class);
+ $pos2 = strpos($user_class, $auth_alt_user_class);
+ if ($pos === false && $auth_user_class != 0)
+ {
+ if ($pos2 === false)
+ $FoundUserInGroup = FALSE;
+ else
+ $FoundUserInGroup = TRUE;
+ }
+ else
+ $FoundUserInGroup = TRUE;
+ */
+ }
+ /* phpbb,...*/
+ else
+ {
+ if( ($datagroup[$db_group_id] == $auth_user_class) or
+ ($datagroup[$db_group_id] == $auth_alt_user_class)
+ )
+ {
+ $FoundUserInGroup = TRUE;
+ }
+ }
+ if ($FoundUserInGroup == FALSE)
+ {
+ wrm_logout();
+ return -1;
+ }
+ }
+
+
+ // User is properly logged in and is allowed to use WRM, go ahead and process his login.
+ $autologin = scrub_input($_POST['autologin']);
+ if(isset($autologin)) {
+ // they want automatic logins so set the cookie
+ // set to expire in one month
+ setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('profile_id', $data[$db_user_id], time() + 2629743);
+ setcookie('password', $cmspass, time() + 2629743);
+ }
+ /**************************************************************
+ * set user profile variables in SESSION
+ **************************************************************/
+ $_SESSION['username'] = strtolower_wrap($data[$db_user_name], "UTF-8");
+ $_SESSION['session_logged_in'] = 1;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
+ if ($auth_user_class != "")
+ {
+
+ if($phpraid_config['default_group'] != 'nil')
+ $user_priv = $phpraid_config['default_group'];
+ else
+ $user_priv = '0';
+
+ // User is all logged in and setup, the session is initialized properly. Now we need to create the users
+ // profile in the WRM database if it does not already exist.
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
+
+ if ($data = $db_raid->sql_fetchrow($result))
+ {
+ wrm_profile_update_last_login_time($_SESSION['profile_id']);
+ }
+ else
+ {
+ wrm_profile_add($data[$db_user_id],$data[$db_user_email],$wrmpass,$user_priv,strtolower_wrap($_SESSION['username'], "UTF-8"));
+ }
+ }
+ else
+ {
+ wrm_profile_update_last_login_time($_SESSION['profile_id']);
+ }
+
+ get_permissions();
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($cmspass);
+ unset($wrmpass);
+
+ return 1;
+ }
+
+ return 0;
+
+}// end wrm_login()
+
+/**************************************************************
+ * add new Profile to WRM
+ **************************************************************/
+function wrm_profile_add($profile_id,$email,$wrmpass,$user_priv,$username)
+{
+ global $db_raid, $phpraid_config;
+
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($profile_id), quote_smart($email), quote_smart($wrmpass),
+ quote_smart($user_priv), quote_smart($username), quote_smart(time())
+ );
+ $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
+}
+
+/**************************************************************
+ * WRM Profile update last_login_time
+ **************************************************************/
+function wrm_profile_update_last_login_time($profile_id)
+{
+ global $db_raid, $phpraid_config;
+
+ $sql = sprintf( "UPDATE " . $phpraid_config['db_prefix'] .
+ "profile SET last_login_time = %s WHERE profile_id = %s",
+ quote_smart(time()),quote_smart($profile_id)
+ );
+ $db_raid->sql_query($sql) or print_error($sql, $db_raid->sql_error(), 1);
+}
+
+/**************************************************************
+ * WRM Logout
+ **************************************************************/
function wrm_logout()
{
// unset the session and remove all cookies
clear_session();
setcookie('username', '', time() - 2629743);
+ setcookie('profile_id', '', time() - 2629743);
setcookie('password', '', time() - 2629743);
}
-?>
\ No newline at end of file
+?>
diff --git a/login.php b/login.php
index 6afbbf4..6c5133a 100644
--- a/login.php
+++ b/login.php
@@ -44,7 +44,8 @@ if(!isset($_GET['mode']))
// is the user already logged in? if so, there's no need for them to login again
if($_SESSION['session_logged_in'] == 0) {
if(isset($_POST['login'])) {
- $logged_in = phpraid_login();
+ //$logged_in = phpraid_login();
+ $logged_in = wrm_login();
if($logged_in == 0)
{
$ShowLoginForm = FALSE;
@@ -56,10 +57,6 @@ if(!isset($_GET['mode']))
{
$forgot_password_line='<a href="login.php?mode=new_pwd">'.$phprlang['login_forgot_password'].'</a>';
}
-
- //$page->set_file(array(
- // 'output' => $phpraid_config['template'] . '/error_login.htm')
- //);
$wrmsmarty->assign('login_frm',
array(
@@ -95,7 +92,7 @@ if(!isset($_GET['mode']))
// or they shouldn't be accessing this page
if(isset($_GET['logout'])) {
// it would appear they're trying to logout
- phpraid_logout();
+ wrm_logout();
header("Location: index.php");
} else {
@@ -140,8 +137,8 @@ if ($_GET['mode'] == "new_pwd"){
//check: is user in WRM DB
$sql = sprintf("SELECT profile_id, email, username FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s and email= %s", quote_smart($username),quote_smart($email));
- $profilresult = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
- if (mysql_num_rows($profilresult) != 1)
+ $profilresult = $db_raid->sql_query($sql) or print_error($sql,$db_raid->sql_error(),1);
+ if ($db_raid->sql_numrows($profilresult) != 1)
{
$errorTitle = $phprlang['login_pwdreset_fail_title'];
$errorMsg = $phprlang['login_username_email_incorrect'];
@@ -211,8 +208,8 @@ if ($_GET['mode'] == "ch_pwd"){
//check: is user in WRM DB
$sql = sprintf("SELECT profile_id, password, username FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s and password = %s", quote_smart($username),quote_smart(md5($curr_pass)));
- $profilresult = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
- if (mysql_num_rows($profilresult) != 1)
+ $profilresult = $db_raid->sql_query($sql) or print_error($sql,$db_raid->sql_error(),1);
+ if ($db_raid->sql_numrows($profilresult) != 1)
{
$errorTitle = $phprlang['login_pwdreset_fail_title'];
$errorMsg = $phprlang['login_password_incorrect'];
| 0 | 5 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
8d04162c448ba0b179058a4a77f301cec8f8fc7a
|
Bridge Updates: Bug 0000047 and 0000048
Fix to the "Update" statement bugs and a bug in PHPBB3 that removed the
ability to display pages anonymously...as well as allowed raid creation to
users that weren't supposed to be able to creat raids.
|
commit 8d04162c448ba0b179058a4a77f301cec8f8fc7a
Author: Douglas Wagner <[email protected]>
Date: Mon Aug 11 13:30:03 2008 -0500
Bridge Updates: Bug 0000047 and 0000048
Fix to the "Update" statement bugs and a bug in PHPBB3 that removed the
ability to display pages anonymously...as well as allowed raid creation to
users that weren't supposed to be able to creat raids.
diff --git a/auth/auth_phpbb.php b/auth/auth_phpbb.php
index b76c3f6..aac5fc3 100644
--- a/auth/auth_phpbb.php
+++ b/auth/auth_phpbb.php
@@ -50,7 +50,7 @@ function check_profile($userdata)
//Update email incase it doesn't match phpBB
if($userdata['user_email'] != $result['email'])
{
- $sql = sprintf("UPDATE" . $phpraid_config['db_prefix'] . "profile SET email=%s, last_login_time=%s WHERE profile_id=%s", quote_smart($email), quote_smart(time()), quote_smart($user_id));
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s, last_login_time=%s WHERE profile_id=%s", quote_smart($email), quote_smart(time()), quote_smart($user_id));
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
diff --git a/auth/auth_phpbb3.php b/auth/auth_phpbb3.php
index 28a583f..531ac1d 100644
--- a/auth/auth_phpbb3.php
+++ b/auth/auth_phpbb3.php
@@ -44,7 +44,7 @@ function check_profile($user)
//Update email incase it doesn't match phpBB
if($user->data['user_email'] != $result['email'])
{
- $sql = sprintf("UPDATE" . $phpraid_config['db_prefix'] . "profile SET email=%s, last_login_time=%s WHERE profile_id=%s", quote_smart($email), quote_smart(time()), quote_smart($user_id));
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s, last_login_time=%s WHERE profile_id=%s", quote_smart($email), quote_smart(time()), quote_smart($user_id));
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
@@ -154,8 +154,9 @@ unset($template);
//0 = not log in
//1 = log in
+
if ($user->data['username'] != 'Anonymous' ) {
-
+
if ($user->data['user_id'] != '1') {
// check profile in db
@@ -172,10 +173,12 @@ if ($user->data['username'] != 'Anonymous' ) {
$_SESSION['session_logged_in'] = 0;
}
}else{
+
//if user login -> Anonymous
- $_SESSION['priv_configuration'] = 0;
+ $_SESSION['session_logged_in'] = 0;
+// $_SESSION['priv_configuration'] = 0;
$_SESSION['priv_profile'] = -1;
- define("PAGE_LVL","profile");
+// define("PAGE_LVL","profile");
}
?>
\ No newline at end of file
| 0 | 9 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
17ead31e9541467a897ccd23bdb480383c1808db
|
Bridge Update: Brings all bridges into alignment.
This update to the bridge files by Neme brings all bridge files into
aligment code wise. They should now all be doing the same thing. At this
point a massive re-write needs to be done on all bridges to get them to
work properly.
|
commit 17ead31e9541467a897ccd23bdb480383c1808db
Author: Douglas Wagner <[email protected]>
Date: Thu Sep 11 11:26:53 2008 -0500
Bridge Update: Brings all bridges into alignment.
This update to the bridge files by Neme brings all bridge files into
aligment code wise. They should now all be doing the same thing. At this
point a massive re-write needs to be done on all bridges to get them to
work properly.
diff --git a/auth/auth_e107.php b/auth/auth_e107.php
index d07d1dc..a9e7381 100644
--- a/auth/auth_e107.php
+++ b/auth/auth_e107.php
@@ -30,11 +30,106 @@
*
****************************************************************************/
+$BridgeSupportPWDChange = FALSE;
+
+/******************************
+ * NOTE: Bridges SHOULD NOT be changing passwords in upstream systems. Enable the above at your own risk.
+ ******************************/
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //table and column name
+ $db_user_id = "user_id";
+ $db_user_password = "user_password";
+ $db_table_user_name = "user";
+ $table_prefix = $phpraid_config['e107_table_prefix'];
+
+ //convert pwd
+ $dbusernewpassword = md5($dbusernewpassword);
+
+ //check: is user_id in WRM DB
+ $sql = sprintf( "SELECT ".$db_user_id." FROM " . $table_prefix . $db_table_user_name .
+ " WHERE ".$db_user_id." = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf( "UPDATE " . $table_prefix . $db_table_user_name .
+ " SET ".$db_user_password." = %s WHERE " . $db_user_id . " = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+
+ $table_prefix = $phpraid_config['e107_table_prefix'];
+ $db_user_id = "user_id";
+ $db_user_name = "user_loginname";
+ $db_user_password = "user_password";
+ $db_table_user_name = "user";
+
+ $sql = sprintf("SELECT username FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ $sql = sprintf( "SELECT " . $db_user_password .
+ " FROM " . $table_prefix . $db_table_user_name .
+ " WHERE %s = %s",
+ quote_smart($db_user_name), quote_smart($data['username'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( md5($oldpassword) == $data[$db_user_password])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
function phpraid_login() {
global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set e107 Configuration Options
+ $table_prefix = $phpraid_config['e107_table_prefix'];
+ $auth_user_class = $phpraid_config['e107_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['alt_auth_user_class'];
+
+ //table and column name
+ $db_user_id = "user_id";
+ $db_user_name = "user_loginname";
+ $db_user_password = "user_password";
+ $db_user_email = "user_email";
+ $db_group_id = "user_class";
+ $db_table_user_name = "user";
if(isset($_POST['username'])) {
- $username = scrub_input(strtolower($_POST['username']));
+ $username = scrub_input(strtolower(utf8_decode($_POST['username'])));
$password = md5($_POST['password']);
} elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$username = scrub_input(strtolower($_COOKIE['username']));
@@ -43,25 +138,28 @@ function phpraid_login() {
phpraid_logout();
}
- // Set e107 Configuration Options
- $e107_table_prefix = $phpraid_config['e107_table_prefix'];
- $e107_auth_user_class = $phpraid_config['e107_auth_user_class'];
- $alt_auth_user_class = $phpraid_config['alt_auth_user_class'];
-
// Get the user_loginname and password and the various user classes that the user belongs to.
- $sql = "SELECT user_id, user_loginname, user_password, user_email, user_class FROM " . $e107_table_prefix . "user";
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ //e107 database
+ $sql = sprintf( "SELECT ".$db_user_id." , ". $db_user_name ." , ". $db_user_email . " , ".$db_group_id. " , ".$db_user_password.
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
while($data = $db_raid->sql_fetchrow($result, true)) {
- //echo "<br>Processing: " . $data['user_loginname'] . " : " . $data['user_password'];
- if($username == strtolower($data['user_loginname']) && $password == $data['user_password']) {
+ //echo "<br>Processing: " . $data[$db_user_name] . " : " . $data[$db_user_password];
+ if($username == strtolower($data[$db_user_name]) && $password == $data[$db_user_password]) {
+
+ $wrmuserpassword = $data[$db_user_password];
+
// The user has a matching username and proper password in the e107 database.
// We need to validate the users class. If it does not contain the user class that has been set as
- // authorized to use phpRaid, we need to fail the login with a proper message.
- $user_class = $data['user_class'];
- $pos = strpos($user_class, $e107_auth_user_class);
- $pos2 = strpos($user_class, $alt_auth_user_class);
- if ($pos === false && $e107_auth_user_class != 0)
+ // authorized to use WRM, we need to fail the login with a proper message.
+ $user_class = $data[$db_group_id];
+ $pos = strpos($user_class, $auth_user_class);
+ $pos2 = strpos($user_class, $auth_alt_user_class);
+ if ($pos === false && $auth_user_class != 0)
{
if ($pos2 === false)
{
@@ -70,40 +168,56 @@ function phpraid_login() {
}
}
- // User is properly logged in and is allowed to use phpRaid, go ahead and process his login.
- $autologin=scrub_input($_POST['autologin']);
+ // User is properly logged in and is allowed to use WRM, go ahead and process his login.
+ $autologin = scrub_input($_POST['autologin']);
if(isset($autologin)) {
// they want automatic logins so set the cookie
// set to expire in one month
- setcookie('username', $data['user_loginname'], time() + 2629743);
- setcookie('password', $data['user_password'], time() + 2629743);
+ setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('password', $wrmuserpassword, time() + 2629743);
}
// set user profile variables
- $_SESSION['username'] = strtolower($data['user_loginname']);
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
$_SESSION['session_logged_in'] = 1;
- $_SESSION['profile_id'] = $data['user_id'];
- $_SESSION['email'] = $data['user_email'];
- $user_password = $data['user_password'];
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
if($phpraid_config['default_group'] != 'nil')
$user_priv = $phpraid_config['default_group'];
else
$user_priv = '0';
// User is all logged in and setup, the session is initialized properly. Now we need to create the users
- // profile in the phpRaid database if it does not already exist.
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($_SESSION['profile_id']));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ // profile in the WRM database if it does not already exist.
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data = $db_raid->sql_fetchrow($result))
- { //We found the profile in the database, update.
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s,password=%s,last_login_time=%s WHERE profile_id=%s",quote_smart($_SESSION['email']),quote_smart($user_password),quote_smart(time()),quote_smart($_SESSION['profile_id']));
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf( "UPDATE " . $phpraid_config['db_prefix'] .
+ "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
else
- { //Profile not found in the database or DB Error, insert.
- $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)", quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($user_password), quote_smart($user_priv), quote_smart($_SESSION['username']),quote_smart(time()));
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
@@ -121,7 +235,7 @@ function phpraid_logout()
// good ole authentication
session_start();
-$_SESSION['name'] = "WRM";
+$_SESSION['name'] = "WRM-e107";
// set session defaults
if (!isset($_SESSION['initiated'])) {
diff --git a/auth/auth_iums.php b/auth/auth_iums.php
index 5b43f96..7a4cbc9 100644
--- a/auth/auth_iums.php
+++ b/auth/auth_iums.php
@@ -30,10 +30,76 @@
*
****************************************************************************/
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //convert pwd
+ //$dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+ $dbusernewpassword = md5($dbusernewpassword);
+
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(),1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( md5($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
function phpraid_login() {
-
global $groups, $db_raid, $phpraid_config;
-
+ $wrmuserpassword = $username = $password = "";
+
+ $table_prefix = $phpraid_config['db_prefix'];
+
+ //table and column name
+ $db_user_id = "profile_id";
+ $db_user_name = "username";
+ $db_user_password = "password";
+ $db_user_email = "email";
+ $db_table_user_name = "profile";
+
if(isset($_POST['username'])) {
$username = strtolower(scrub_input($_POST['username']));
$password = md5($_POST['password']);
@@ -44,32 +110,84 @@ function phpraid_login() {
phpraid_logout();
}
+
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "profile";
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+
+ $sql = sprintf( "SELECT ".$db_user_id." , ". $db_user_name ." , ". $db_user_email . " , " . $db_user_password .
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
while($data = $db_raid->sql_fetchrow($result, true)) {
- if($username == strtolower($data['username']) && $password == $data['password']) {
- if(isset($_POST['autologin'])) {
+ if($username == strtolower($data[$db_user_name]) && $password == $data[$db_user_password]) {
+
+ $wrmuserpassword = $data[$db_user_password];
+
+ // User is properly logged in and is allowed to use WRM, go ahead and process his login.
+ $autologin = scrub_input($_POST['autologin']);
+ if(isset($autologin)) {
// they want automatic logins so set the cookie
// set to expire in one month
- setcookie('username', $data['username'], time() + 2629743);
- setcookie('password', $data['password'], time() + 2629743);
+ setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('password', $wrmuserpassword, time() + 2629743);
}
-
- // set user variables
- $_SESSION['username'] = $data['username'];
+
+ // set user profile variables
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
$_SESSION['session_logged_in'] = 1;
- $_SESSION['profile_id'] = $data['profile_id'];
- $_SESSION['email'] = $data['email'];
-
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
// get user permissions
get_permissions();
-
+
+ // ********************
+ // * NOTE * IUMS Auth does not do profile checking like external bridges do.
+ // ********************
+
+ /* if($phpraid_config['default_group'] != 'nil')
+ $user_priv = $phpraid_config['default_group'];
+ else
+ $user_priv = '0'; */
+
+ // User is all logged in and setup, the session is initialized properly. Now we need to create the users
+ // profile in the WRM database if it does not already exist.
+ /* $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if ($data = $db_raid->sql_fetchrow($result))
+ {*/
+ //We found the profile in the database, update.
+ /* $sql = sprintf( "UPDATE " . $phpraid_config['db_prefix'] . "profile ".
+ " SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ }
+ else
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ }*/
+
$sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET last_login_time=%s WHERE profile_id=%s",
quote_smart(time()),quote_smart($_SESSION['profile_id']));
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
-
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
+
return 1;
}
}
@@ -83,10 +201,10 @@ function phpraid_logout()
setcookie('username', '', time() - 2629743);
setcookie('password', '', time() - 2629743);
}
-
+
// good ole authentication
session_start();
-$_SESSION['name'] = "phpRaid";
+$_SESSION['name'] = "WRM-iums";
// set session defaults
if (!isset($_SESSION['initiated'])) {
@@ -100,4 +218,5 @@ if (!isset($_SESSION['initiated'])) {
$_SESSION['profile_id'] = -1;
}
}
+
?>
\ No newline at end of file
diff --git a/auth/auth_joomla.php b/auth/auth_joomla.php
new file mode 100644
index 0000000..21c782a
--- /dev/null
+++ b/auth/auth_joomla.php
@@ -0,0 +1,252 @@
+<?php
+/***************************************************************************
+ * auth_jommla.php
+ * -------------------
+ * begin : July 23, 2008
+ * Dev : Carsten Hölbing
+ * email : [email protected]
+ *
+ * based on : auth_e107.php @ Douglas Wagner
+ * copyright : (C) 2007-2008 Douglas Wagner
+ * email : [email protected]
+ *
+ ***************************************************************************/
+
+/***************************************************************************
+*
+* WoW Raid Manager - Raid Management Software for World of Warcraft
+* Copyright (C) 2007-2008 Douglas Wagner
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* 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 for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*
+****************************************************************************/
+
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //convert pwd
+ $dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+ //$dbusernewpassword = md5($dbusernewpassword);
+
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( $pwd_hasher->HashPassword($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
+function phpraid_login() {
+ global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set joomla Configuration Options
+ $table_prefix = $phpraid_config['joomla_table_prefix'];
+ $auth_user_class = $phpraid_config['joomla_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['joomla_auth_alt_user_class'];
+
+ //table and column name
+ $db_user_id = "id";
+ $db_user_name = "username";
+ //$db_user_password = "";
+ $db_user_email = "email";
+ $db_group_id = "gid";
+ $db_table_user_name = "jos_users";
+
+
+ # Try to use stronger but system-specific hashes, with a possible fallback to
+ # the weaker portable hashes.
+ $pwd_hasher = new PasswordHash(8, FALSE);
+
+ if(isset($_POST['username'])){
+ $username = scrub_input(strtolower($_POST['username']));
+ //pwd hash
+ $password = $pwd_hasher->HashPassword($_POST['password']);
+
+ } elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
+ $username = scrub_input(strtolower($_COOKIE['username']));
+ $password = scrub_input($_COOKIE['password']);
+ } else {
+ phpraid_logout();
+ }
+
+ //Joomla database
+ $sql = sprintf( "SELECT ".$db_user_id." , ". $db_user_name ." , ". $db_user_email . " , ".$db_group_id.
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+
+ //WRM database
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if ($data2 = $db_raid->sql_fetchrow($result2))
+ {
+ $wrmuserpassword = $data2['password'];
+ }
+
+ while($data = $db_raid->sql_fetchrow($result, true)) {
+
+ if( ($username == strtolower($data[$db_user_name])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+
+ // if( ($username == strtolower($data[$db_user_name])) && (($password == $wrmuserpassword) or ($data2['password'] == "" ) ) ) {
+
+ //first use: password insert in WRM DB
+ if ($wrmuserpassword == ""){
+ $wrmuserpassword = $password;
+ }
+
+ // We need to validate the users group. If it does not contain the user group that has been set as
+ // authorized to use WRM, we need to fail the login with a proper message.
+ $user_class = $data[$db_group_id];
+ $pos = strpos($user_class, $auth_user_class);
+ $pos2 = strpos($user_class, $auth_alt_user_class);
+ if ($pos === false && $smf_auth_user_class != 0)
+ {
+ if ($pos2 === false)
+ {
+ phpraid_logout();
+ return -1;
+ }
+ }
+
+
+ // User is properly logged in and is allowed to use WRM, go ahead and process his login.
+ $autologin = scrub_input($_POST['autologin']);
+ if(isset($autologin)) {
+ // they want automatic logins so set the cookie
+ // set to expire in one month
+ setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('password', $wrmuserpassword, time() + 2629743);
+ }
+
+ // set user profile variables
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
+ $_SESSION['session_logged_in'] = 1;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
+ if($phpraid_config['default_group'] != 'nil')
+ $user_priv = $phpraid_config['default_group'];
+ else
+ $user_priv = '0';
+
+ // User is all logged in and setup, the session is initialized properly. Now we need to create the users
+ // profile in the WRM database if it does not already exist.
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if ($data = $db_raid->sql_fetchrow($result))
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ }
+ else
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ }
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
+
+ return 1;
+ }
+ }
+ return 0;
+}
+
+function phpraid_logout()
+{
+ // unset the session and remove all cookies
+ clear_session();
+ setcookie('username', '', time() - 2629743);
+ setcookie('password', '', time() - 2629743);
+}
+
+require ("includes/functions_pwdhash.php");
+
+// good ole authentication
+session_start();
+$_SESSION['name'] = "WRM-joomla";
+
+// set session defaults
+if (!isset($_SESSION['initiated'])) {
+ if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
+ phpraid_login();
+ } else {
+ session_regenerate_id();
+ $_SESSION['initiated'] = true;
+ $_SESSION['username'] = 'Anonymous';
+ $_SESSION['session_logged_in'] = 0;
+ $_SESSION['profile_id'] = -1;
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/auth/auth_phpbb.php b/auth/auth_phpbb.php
index aac5fc3..ac665b9 100644
--- a/auth/auth_phpbb.php
+++ b/auth/auth_phpbb.php
@@ -1,12 +1,14 @@
<?php
/***************************************************************************
- * auth_phpbb.php
+ * auth_phpbb3.php
* -------------------
- * begin : Saturday, Jan 16, 2005
- * copyright : (C) 2007-2008 Douglas Wagner
- * email : [email protected]
+ * begin : Sep 09, 2008
+ * Dev : Carsten Hölbing
+ * email : [email protected]
*
- * $Id: auth_phpbb.php,v 2.00 2007/11/18 17:35:00 psotfx Exp $
+ * based on : auth_e107.php @ Douglas Wagner
+ * copyright : (C) 2007-2008 Douglas Wagner
+ * email : [email protected]
*
***************************************************************************/
@@ -27,124 +29,236 @@
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
-*
+*
****************************************************************************/
-// define our auth type
-if( isset( $_GET["phpbb_root_path"] ) || isset( $_POST["phpbb_root_path"]) )
- log_hack();
-
-// check profile
-// Specific to phpBB authentication only. Checks to see if a profile exists
-// for phpBB user and if not, creates one.
-function check_profile($userdata)
+
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
{
global $db_raid, $phpraid_config;
-
- $user_id = $userdata['user_id'];
- $email = $userdata['user_email'];
-
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($user_id));
- $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
-
- //Update email incase it doesn't match phpBB
- if($userdata['user_email'] != $result['email'])
+
+ //convert pwd
+ //$dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+ $dbusernewpassword = md5($dbusernewpassword);
+
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(),1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
{
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s, last_login_time=%s WHERE profile_id=%s", quote_smart($email), quote_smart(time()), quote_smart($user_id));
- $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ //pwd change
+ return 1;
}
-
- // if nothing returns we need to create profile
- // otherwise they have a profile so let's set their ID
- // we'll just use the phpBB user id as the profile ID to simplify things
- if($db_raid->sql_numrows($result) == 0 && $userdata['username'] != 'Anonymous')
+ else
{
- $user_id = $userdata['user_id'];
- $username = $userdata['username'];
-
- if($phpraid_config['default_group'] != 'nil')
- $default = $phpraid_config['default_group'];
- else
- $default = '0';
-
- // nothing returned, create profile
- $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile (`profile_id`,`email`,`password`,`priv`,`username`,`last_login_time`)" .
- "VALUES (%s, %s, '', %s, %s, %s)", quote_smart($user_id), quote_smart($email), quote_smart($default), quote_smart($username), quote_smart(time()));
- $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( md5($oldpassword) == $data['password'])
+ {
+ return 0;
}
-
- return $userdata['user_id'];
+ else
+ return 1;
}
-// login function for phpBB
-function phpraid_login()
-{
- global $db, $user_ip;
-
- $username = isset($_POST['username']) ? phpbb_clean_username($_POST['username']) : '';
- $password = isset($_POST['password']) ? $_POST['password'] : '';
- $sql = "SELECT user_id, username, user_password, user_active, user_level
- FROM " . USERS_TABLE . "
- WHERE username = '" . str_replace("\\'", "''", $username) . "'";
-
- if ( !($result = $db->sql_query($sql)) )
- message_die(GENERAL_ERROR, 'Error in obtaining userdata', '', __LINE__, __FILE__, $sql);
-
- if( $row = $db->sql_fetchrow($result, true) )
+function phpraid_login() {
+ global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set phpbb Configuration Options
+ $table_prefix = $phpraid_config['phpbb_prefix'];
+ $auth_user_class = $phpraid_config['phpBB_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['phpBB_alt_auth_user_class'];
+
+ //table and column name
+ $db_user_id = "user_id";
+ $db_user_name = "username";
+ //$db_user_password = "";
+ $db_user_email = "user_email";
+ $db_group_id = "group_id";
+ $db_table_user_name = "users";
+ $db_table_group_name = "user_group";
+
+
+ # Try to use stronger but system-specific hashes, with a possible fallback to
+ # the weaker portable hashes.
+ //$pwd_hasher = new PasswordHash(8, FALSE);
+
+ if(isset($_POST['username'])){
+ $username = scrub_input(strtolower($_POST['username']));
+ //pwd hash
+ //$password = $pwd_hasher->HashPassword($_POST['password']);
+ $password = md5($_POST['password']);
+
+ } elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
+ $username = scrub_input(strtolower($_COOKIE['username']));
+ $password = scrub_input($_COOKIE['password']);
+ } else {
+ phpraid_logout();
+ }
+
+ //phpbb database
+ $sql = sprintf( "SELECT ".$db_user_id.",". $db_user_name .",".$db_user_email .
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+
+ //WRM database
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if ($data2 = $db_raid->sql_fetchrow($result2))
{
- if( md5($password) == $row['user_password'] && $row['user_active'] )
- {
- // success
- $autologin = ( isset($_POST['autologin']) ) ? TRUE : 0;
- $admin = (isset($_POST['admin'])) ? 1 : 0;
- $session_id = session_begin($row['user_id'], $user_ip, PAGE_INDEX, FALSE, $autologin, $admin);
+ $wrmuserpassword = $data2['password'];
+ }
+
+ while($data = $db_raid->sql_fetchrow($result, true)) {
+
+ // if( ($username == strtolower($data['username_clean'])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+
+ if( ($username == strtolower($data[$db_user_name])) && (($password == $wrmuserpassword) or ($data2['password'] == "" ) ) ) {
+
+ //first use: password insert in WRM DB
+ if ($wrmuserpassword == ""){
+ $wrmuserpassword = $password;
+ }
+
+ // The user has a matching username and proper password in the phpbb database.
+ // We need to validate the users group. If it does not contain the user group that has been set as
+ // authorized to use WRM, we need to fail the login with a proper message.
+ if ($auth_user_class != 0)
+ {
+ $FoundUserInGroup = FALSE;
+
+ $sql = sprintf( "SELECT " . $db_user_id. "," .$db_group_id ." FROM " . $table_prefix . $db_table_group_name.
+ " WHERE ".$db_user_id." = %s", quote_smart($data[$db_user_id])
+ );
+ $resultgroup = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ while($datagroup = $db_raid->sql_fetchrow($resultgroup, TRUE)) {
+ if( ($datagroup[$db_group_id] == $auth_user_class) or ($datagroup[$db_group_id] == $auth_alt_user_class) )
+ {
+ $FoundUserInGroup = TRUE;
+ }
+ }
+
+ if ($FoundUserInGroup == FALSE){
+ return -1;
+ }
+ }
+
+
+ // User is properly logged in and is allowed to use WRM, go ahead and process his login.
+ $autologin = scrub_input($_POST['autologin']);
+ if(isset($autologin)) {
+ // they want automatic logins so set the cookie
+ // set to expire in one month
+ setcookie('username', $data[$db_user_name], time() + 2629743);
+ setcookie('password', $wrmuserpassword, time() + 2629743);
+ }
+
+ // set user profile variables
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
+ $_SESSION['session_logged_in'] = 1;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
+ if($phpraid_config['default_group'] != 'nil')
+ $user_priv = $phpraid_config['default_group'];
+ else
+ $user_priv = '0';
+
+ // User is all logged in and setup, the session is initialized properly. Now we need to create the users
+ // profile in the WRM database if it does not already exist.
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if ($data = $db_raid->sql_fetchrow($result))
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ }
+ else
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ }
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET last_login_time=%s WHERE profile_id=%s",
- quote_smart(time()),quote_smart($_SESSION['profile_id']));
- $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
- else
- {
- // login failure
- return 0;
- }
}
+ return 0;
}
-// logout function for phpBB
function phpraid_logout()
{
- global $userdata;
-
- session_end($userdata['session_id'], $userdata['user_id']);
+ // unset the session and remove all cookies
clear_session();
+ setcookie('username', '', time() - 2629743);
+ setcookie('password', '', time() - 2629743);
}
-// database connection
-$phpbb_prefix = $phpraid_config['phpbb_prefix'];
-
-global $user_group_table;
-$user_group_table = $phpbb_prefix . "user_group";
+//require ("includes/functions_pwdhash.php");
-// setup phpBB user integration
-define('IN_PHPBB', true);
+// good ole authentication
+session_start();
+$_SESSION['name'] = "WRM-phpbb";
-$phpbb_root_path = $phpraid_config['phpbb_root_path'];
-
-// set this as the path to your phpBB installation
-include($phpbb_root_path . 'extension.inc');
-include($phpbb_root_path . 'common.'.$phpEx);
-
-$userdata = session_pagestart($user_ip, PAGE_INDEX);
-init_userprefs($userdata);
-
-// set user variables
-$_SESSION['username'] = $userdata['username'];
-$_SESSION['session_logged_in'] = $userdata['session_logged_in'];
+// set session defaults
+if (!isset($_SESSION['initiated'])) {
+ if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
+ phpraid_login();
+ } else {
+ session_regenerate_id();
+ $_SESSION['initiated'] = true;
+ $_SESSION['username'] = 'Anonymous';
+ $_SESSION['session_logged_in'] = 0;
+ $_SESSION['profile_id'] = -1;
+ }
+}
-// check if they have a phpRaid profile yet
-// if not, create one if so set profile_id to correct
-$_SESSION['profile_id'] = check_profile($userdata);
?>
\ No newline at end of file
diff --git a/auth/auth_phpbb3.php b/auth/auth_phpbb3.php
index e0396ba..78b95d8 100644
--- a/auth/auth_phpbb3.php
+++ b/auth/auth_phpbb3.php
@@ -32,20 +32,23 @@
*
****************************************************************************/
-
$BridgeSupportPWDChange = TRUE;
//change password in WRM DB
-function db_password_change($profile_id,$dbusernewpassword)
+function db_password_change($profile_id, $dbusernewpassword)
{
+ global $db_raid, $phpraid_config;
+
//convert pwd
//$dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
$dbusernewpassword = md5($dbusernewpassword);
//check: is profile_id in WRM DB
- $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s", quote_smart($profile_id));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if (mysql_num_rows($result) != 1) {
//user not found in WRM DB
return 2;
@@ -66,9 +69,26 @@ function db_password_change($profile_id,$dbusernewpassword)
return 0;
}
}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( md5($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
function phpraid_login() {
-
global $groups, $db_raid, $phpraid_config;
$wrmuserpassword = $username = $password = "";
@@ -77,6 +97,7 @@ function phpraid_login() {
$auth_user_class = $phpraid_config['phpBB_auth_user_class'];
$auth_alt_user_class = $phpraid_config['phpBB_alt_auth_user_class'];
+ //table and column name
$db_user_id = "user_id";
$db_user_name = "username_clean";
//$db_user_password = "";
@@ -91,7 +112,7 @@ function phpraid_login() {
//$pwd_hasher = new PasswordHash(8, FALSE);
if(isset($_POST['username'])){
- $username = scrub_input(strtolower(utf8_decode($_POST['username'])));
+ $username = scrub_input(strtolower($_POST['username']));
//pwd hash
//$password = $pwd_hasher->HashPassword($_POST['password']);
$password = md5($_POST['password']);
@@ -111,15 +132,18 @@ function phpraid_login() {
}
//phpbb database
- $sql = sprintf( "SELECT ".$db_user_id.",". $db_user_name .",".$db_user_email ." FROM " . $table_prefix . $db_table_user_name.
+ $sql = sprintf( "SELECT ".$db_user_id.",". $db_user_name .",".$db_user_email .
+ " FROM " . $table_prefix . $db_table_user_name.
" WHERE ".$db_user_name." = %s", quote_smart($username)
);
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
//WRM database
- $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s", quote_smart($username));
- $result2 = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data2 = $db_raid->sql_fetchrow($result2))
{
$wrmuserpassword = $data2['password'];
@@ -127,9 +151,9 @@ function phpraid_login() {
while($data = $db_raid->sql_fetchrow($result, true)) {
- // if( ($username == strtolower($data['username_clean'])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+ // if( ($username == strtolower($data[$db_user_name])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
- if( ($username == strtolower($data['username_clean'])) && (($password == $wrmuserpassword) or ($data2['password'] == "" ) ) ) {
+ if( ($username == strtolower($data[$db_user_name])) && (($password == $wrmuserpassword) or ($data2['password'] == "" ) ) ) {
//first use: password insert in WRM DB
if ($wrmuserpassword == ""){
@@ -147,7 +171,7 @@ function phpraid_login() {
$sql = sprintf( "SELECT " . $db_user_id. "," .$db_group_id ." FROM " . $table_prefix . $db_table_group_name.
" WHERE ".$db_user_id." = %s", quote_smart($data[$db_user_id])
);
- $resultgroup = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $resultgroup = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
while($datagroup = $db_raid->sql_fetchrow($resultgroup, true)) {
if( ($datagroup[$db_group_id] == $auth_user_class) or ($datagroup[$db_group_id] == $auth_alt_user_class) )
{
@@ -183,13 +207,16 @@ function phpraid_login() {
// User is all logged in and setup, the session is initialized properly. Now we need to create the users
// profile in the WRM database if it does not already exist.
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s", quote_smart($_SESSION['profile_id']));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data = $db_raid->sql_fetchrow($result))
{
//We found the profile in the database, update.
$sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
- quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
);
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
@@ -202,6 +229,11 @@ function phpraid_login() {
);
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
@@ -221,7 +253,7 @@ require ("includes/functions_pwdhash.php");
// good ole authentication
session_start();
-$_SESSION['name'] = "WRM";
+$_SESSION['name'] = "WRM-phpbb3";
// set session defaults
if (!isset($_SESSION['initiated'])) {
diff --git a/auth/auth_smf.php b/auth/auth_smf.php
index e1977bf..ba781ea 100644
--- a/auth/auth_smf.php
+++ b/auth/auth_smf.php
@@ -32,18 +32,85 @@
*
****************************************************************************/
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //convert pwd
+ $dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( $pwd_hasher->HashPassword($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
function phpraid_login() {
global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set smf Configuration Options
+ $table_prefix = $phpraid_config['smf_table_prefix'];
+ $auth_user_class = $phpraid_config['smf_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['smf_alt_auth_user_class'];
+
+ //table and column name
+ $db_user_id = "ID_MEMBER";
+ $db_user_name = "memberName";
+ //$db_user_password = "";
+ $db_user_email = "emailAddress";
+ $db_group_id = "ID_GROUP";
+ $db_table_user_name = "members";
# Try to use stronger but system-specific hashes, with a possible fallback to
# the weaker portable hashes.
$pwd_hasher = new PasswordHash(8, FALSE);
-
- if(isset($_POST['username'])) {
+
+ if(isset($_POST['username'])){
$username = scrub_input(strtolower($_POST['username']));
//pwd hash
$password = $pwd_hasher->HashPassword($_POST['password']);
-
} elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$username = scrub_input(strtolower($_COOKIE['username']));
$password = scrub_input($_COOKIE['password']);
@@ -51,32 +118,37 @@ function phpraid_login() {
phpraid_logout();
}
- // Set smf Configuration Options
- $smf_table_prefix = $phpraid_config['smf_table_prefix'];
- $smf_auth_user_class = $phpraid_config['smf_auth_user_class'];
- $smf_alt_auth_user_class = $phpraid_config['smf_alt_auth_user_class'];
-
-
- // Get the user_loginname and password and the various user classes that the user belongs to.
- $sql = "SELECT ID_MEMBER, memberName, emailAddress, ID_GROUP FROM " . $smf_table_prefix . "members WHERE memberName = '".$username."'";
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
-
- $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username=%s", quote_smart($username));
- $result2 = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ //SMF database
+ $sql = sprintf( "SELECT ".$db_user_id." , ". $db_user_name ." , ". $db_user_email . " , ".$db_group_id.
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+
+ //WRM database
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data2 = $db_raid->sql_fetchrow($result2))
- {
- $wrmuserpassword = $data2['password'];
- }
-
+ {
+ $wrmuserpassword = $data2['password'];
+ }
+
while($data = $db_raid->sql_fetchrow($result, true)) {
- //echo "<br>Processing: " . $data['member_name'] . " : " . $data['passwd'].'<br>pwd:'.$password;
- if($username == strtolower($data['memberName']) && $pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) {
- // The user has a matching username and proper password in the smf database.
+ if( ($username == strtolower($data[$db_user_name])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+
+ //first use: password insert in WRM DB
+ if ($wrmuserpassword == ""){
+ $wrmuserpassword = $password;
+ }
+
// We need to validate the users class. If it does not contain the user class that has been set as
- // authorized to use smf, we need to fail the login with a proper message.
- $user_class = $data['ID_GROUP'];
- $pos = strpos($user_class, $smf_auth_user_class);
- $pos2 = strpos($user_class, $smf_alt_auth_user_class);
+ // authorized to use WRM, we need to fail the login with a proper message.
+ $user_class = $data[$db_group_id];
+ $pos = strpos($user_class, $auth_user_class);
+ $pos2 = strpos($user_class, $auth_alt_user_class);
if ($pos === false && $smf_auth_user_class != 0)
{
if ($pos2 === false)
@@ -87,20 +159,20 @@ function phpraid_login() {
}
// User is properly logged in and is allowed to use WRM, go ahead and process his login.
- $autologin=scrub_input($_POST['autologin']);
+ $autologin = scrub_input($_POST['autologin']);
if(isset($autologin)) {
// they want automatic logins so set the cookie
// set to expire in one month
- setcookie('username', $data['memberName'], time() + 2629743);
+ setcookie('username', $data[$db_user_name], time() + 2629743);
setcookie('password', $wrmuserpassword, time() + 2629743);
}
// set user profile variables
- $_SESSION['username'] = strtolower($data['memberName']);
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
$_SESSION['session_logged_in'] = 1;
- $_SESSION['profile_id'] = $data['ID_MEMBER'];
- $_SESSION['email'] = $data['emailAddress'];
- $user_password = $wrmuserpassword;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
if($phpraid_config['default_group'] != 'nil')
$user_priv = $phpraid_config['default_group'];
else
@@ -108,18 +180,33 @@ function phpraid_login() {
// User is all logged in and setup, the session is initialized properly. Now we need to create the users
// profile in the WRM database if it does not already exist.
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($_SESSION['profile_id']));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data = $db_raid->sql_fetchrow($result))
- { //We found the profile in the database, update.
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s,password=%s,last_login_time=%s WHERE profile_id=%s",quote_smart($_SESSION['email']),quote_smart($user_password),quote_smart(time()),quote_smart($_SESSION['profile_id']));
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
else
- { //Profile not found in the database or DB Error, insert.
- $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)", quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($user_password), quote_smart($user_priv), quote_smart($_SESSION['username']), quote_smart(time()));
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
@@ -139,7 +226,7 @@ require ("includes/functions_pwdhash.php");
// good ole authentication
session_start();
-$_SESSION['name'] = "WRM";
+$_SESSION['name'] = "WRM-SMF";
// set session defaults
if (!isset($_SESSION['initiated'])) {
diff --git a/auth/auth_smf2.php b/auth/auth_smf2.php
index dec53ce..862725b 100644
--- a/auth/auth_smf2.php
+++ b/auth/auth_smf2.php
@@ -32,18 +32,85 @@
*
****************************************************************************/
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //convert pwd
+ $dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( $pwd_hasher->HashPassword($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
function phpraid_login() {
global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set smf Configuration Options
+ $table_prefix = $phpraid_config['smf_table_prefix'];
+ $auth_user_class = $phpraid_config['smf_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['smf_alt_auth_user_class'];
+
+ //table and column name
+ $db_user_id = "id_member";
+ $db_user_name = "member_name";
+ //$db_user_password = "";
+ $db_user_email = "email_address";
+ $db_group_id = "id_group";
+ $db_table_user_name = "members";
# Try to use stronger but system-specific hashes, with a possible fallback to
# the weaker portable hashes.
$pwd_hasher = new PasswordHash(8, FALSE);
-
- if(isset($_POST['username'])) {
+
+ if(isset($_POST['username'])){
$username = scrub_input(strtolower($_POST['username']));
//pwd hash
$password = $pwd_hasher->HashPassword($_POST['password']);
-
} elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$username = scrub_input(strtolower($_COOKIE['username']));
$password = scrub_input($_COOKIE['password']);
@@ -51,32 +118,37 @@ function phpraid_login() {
phpraid_logout();
}
- // Set smf Configuration Options
- $smf_table_prefix = $phpraid_config['smf_table_prefix'];
- $smf_auth_user_class = $phpraid_config['smf_auth_user_class'];
- $smf_alt_auth_user_class = $phpraid_config['smf_alt_auth_user_class'];
-
-
- // Get the user_loginname and password and the various user classes that the user belongs to.
- $sql = "SELECT id_member, member_name, email_address, id_group FROM " . $smf_table_prefix . "members WHERE member_name = '".$username."'";
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
-
- $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username=%s", quote_smart($username));
- $result2 = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ //SMF database
+ $sql = sprintf( "SELECT ".$db_user_id." , ". $db_user_name ." , ". $db_user_email . " , ".$db_group_id.
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+
+ //WRM database
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data2 = $db_raid->sql_fetchrow($result2))
- {
- $wrmuserpassword = $data2['password'];
- }
-
+ {
+ $wrmuserpassword = $data2['password'];
+ }
+
while($data = $db_raid->sql_fetchrow($result, true)) {
- //echo "<br>Processing: " . $data['member_name'] . " : " . $data['passwd'].'<br>pwd:'.$password;
- if($username == strtolower($data['member_name']) && $pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) {
- // The user has a matching username and proper password in the smf database.
+ if( ($username == strtolower($data[$db_user_name])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+
+ //first use: password insert in WRM DB
+ if ($wrmuserpassword == ""){
+ $wrmuserpassword = $password;
+ }
+
// We need to validate the users class. If it does not contain the user class that has been set as
- // authorized to use smf, we need to fail the login with a proper message.
- $user_class = $data['id_group'];
- $pos = strpos($user_class, $smf_auth_user_class);
- $pos2 = strpos($user_class, $smf_alt_auth_user_class);
+ // authorized to use WRM, we need to fail the login with a proper message.
+ $user_class = $data[$db_group_id];
+ $pos = strpos($user_class, $auth_user_class);
+ $pos2 = strpos($user_class, $auth_alt_user_class);
if ($pos === false && $smf_auth_user_class != 0)
{
if ($pos2 === false)
@@ -87,20 +159,20 @@ function phpraid_login() {
}
// User is properly logged in and is allowed to use WRM, go ahead and process his login.
- $autologin=scrub_input($_POST['autologin']);
+ $autologin = scrub_input($_POST['autologin']);
if(isset($autologin)) {
// they want automatic logins so set the cookie
// set to expire in one month
- setcookie('username', $data['member_name'], time() + 2629743);
+ setcookie('username', $data[$db_user_name], time() + 2629743);
setcookie('password', $wrmuserpassword, time() + 2629743);
}
// set user profile variables
- $_SESSION['username'] = strtolower($data['member_name']);
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
$_SESSION['session_logged_in'] = 1;
- $_SESSION['profile_id'] = $data['id_member'];
- $_SESSION['email'] = $data['email_address'];
- $user_password = $wrmuserpassword;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
if($phpraid_config['default_group'] != 'nil')
$user_priv = $phpraid_config['default_group'];
else
@@ -108,18 +180,33 @@ function phpraid_login() {
// User is all logged in and setup, the session is initialized properly. Now we need to create the users
// profile in the WRM database if it does not already exist.
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($_SESSION['profile_id']));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data = $db_raid->sql_fetchrow($result))
- { //We found the profile in the database, update.
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s,password=%s,last_login_time=%s WHERE profile_id=%s",quote_smart($_SESSION['email']),quote_smart($user_password),quote_smart(time()),quote_smart($_SESSION['profile_id']));
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
else
- { //Profile not found in the database or DB Error, insert.
- $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)", quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($user_password), quote_smart($user_priv), quote_smart($_SESSION['username']),quote_smart(time()));
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
@@ -139,7 +226,7 @@ require ("includes/functions_pwdhash.php");
// good ole authentication
session_start();
-$_SESSION['name'] = "WRM";
+$_SESSION['name'] = "WRM-SMF2";
// set session defaults
if (!isset($_SESSION['initiated'])) {
diff --git a/auth/auth_wbb.php b/auth/auth_wbb.php
index d39023b..3d03bfc 100644
--- a/auth/auth_wbb.php
+++ b/auth/auth_wbb.php
@@ -32,18 +32,85 @@
*
****************************************************************************/
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //convert pwd
+ $dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( $pwd_hasher->HashPassword($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
function phpraid_login() {
global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set wbb Configuration Options
+ $table_prefix = $phpraid_config['wbb_table_prefix'];
+ $auth_user_class = $phpraid_config['wbb_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['wbb_alt_auth_user_class'];
+
+ //table and column name
+ $db_user_id = "userid";
+ $db_user_name = "username";
+ //$db_user_password = "";
+ $db_user_email = "email";
+ $db_group_id = "groupid";
+ $db_table_user_name = "users";
# Try to use stronger but system-specific hashes, with a possible fallback to
# the weaker portable hashes.
$pwd_hasher = new PasswordHash(8, FALSE);
-
- if(isset($_POST['username'])) {
+
+ if(isset($_POST['username'])){
$username = scrub_input(strtolower($_POST['username']));
//pwd hash
$password = $pwd_hasher->HashPassword($_POST['password']);
-
} elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$username = scrub_input(strtolower($_COOKIE['username']));
$password = scrub_input($_COOKIE['password']);
@@ -51,33 +118,38 @@ function phpraid_login() {
phpraid_logout();
}
- // Set wbb Configuration Options
- $wbb_table_prefix = $phpraid_config['wbb_table_prefix'];
- $wbb_auth_user_class = $phpraid_config['wbb_auth_user_class'];
- $wbb_alt_auth_user_class = $phpraid_config['wbb_alt_auth_user_class'];
-
-
- // Get the user_loginname and password and the various user classes that the user belongs to.
- $sql = "SELECT userid, username, email, groupid FROM " . $wbb_table_prefix . "users WHERE username = '".$username."'";
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
-
- $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username=%s", quote_smart($username));
- $result2 = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ //wbb database
+ $sql = sprintf( "SELECT ".$db_user_id." , ". $db_user_name ." , ". $db_user_email . " , ".$db_group_id.
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
+
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+
+ //WRM database
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data2 = $db_raid->sql_fetchrow($result2))
- {
- $wrmuserpassword = $data2['password'];
- }
-
+ {
+ $wrmuserpassword = $data2['password'];
+ }
+
while($data = $db_raid->sql_fetchrow($result, true)) {
- //echo "<br>Processing: " . $data['member_name'] . " : " . $data['passwd'].'<br>pwd:'.$password;
- if($username == strtolower($data['username']) && $pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) {
- // The user has a matching username and proper password in the wbb database.
+ if( ($username == strtolower($data[$db_user_name])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+
+ //first use: password insert in WRM DB
+ if ($wrmuserpassword == ""){
+ $wrmuserpassword = $password;
+ }
+
// We need to validate the users class. If it does not contain the user class that has been set as
- // authorized to use wbb, we need to fail the login with a proper message.
- $user_class = $data['groupid'];
- $pos = strpos($user_class, $wbb_auth_user_class);
- $pos2 = strpos($user_class, $wbb_alt_auth_user_class);
- if ($pos === false && $wbb_auth_user_class != 0)
+ // authorized to use WRM, we need to fail the login with a proper message.
+ $user_class = $data[$db_group_id];
+ $pos = strpos($user_class, $auth_user_class);
+ $pos2 = strpos($user_class, $auth_alt_user_class);
+ if ($pos === false && $smf_auth_user_class != 0)
{
if ($pos2 === false)
{
@@ -87,20 +159,20 @@ function phpraid_login() {
}
// User is properly logged in and is allowed to use WRM, go ahead and process his login.
- $autologin=scrub_input($_POST['autologin']);
+ $autologin = scrub_input($_POST['autologin']);
if(isset($autologin)) {
// they want automatic logins so set the cookie
// set to expire in one month
- setcookie('username', $data['username'], time() + 2629743);
+ setcookie('username', $data[$db_user_name], time() + 2629743);
setcookie('password', $wrmuserpassword, time() + 2629743);
}
// set user profile variables
- $_SESSION['username'] = strtolower($data['username']);
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
$_SESSION['session_logged_in'] = 1;
- $_SESSION['profile_id'] = $data['userid'];
- $_SESSION['email'] = $data['email'];
- $user_password = $wrmuserpassword;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
if($phpraid_config['default_group'] != 'nil')
$user_priv = $phpraid_config['default_group'];
else
@@ -108,18 +180,33 @@ function phpraid_login() {
// User is all logged in and setup, the session is initialized properly. Now we need to create the users
// profile in the WRM database if it does not already exist.
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($_SESSION['profile_id']));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data = $db_raid->sql_fetchrow($result))
- { //We found the profile in the database, update.
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s,password=%s,last_login_time=%s WHERE profile_id=%s",quote_smart($_SESSION['email']),quote_smart($user_password),quote_smart(time()),quote_smart($_SESSION['profile_id']));
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
else
- { //Profile not found in the database or DB Error, insert.
- $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)", quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($user_password), quote_smart($user_priv), quote_smart($_SESSION['username']),quote_smart(time()));
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
@@ -139,7 +226,7 @@ require ("includes/functions_pwdhash.php");
// good ole authentication
session_start();
-$_SESSION['name'] = "WRM";
+$_SESSION['name'] = "WRM-wbb";
// set session defaults
if (!isset($_SESSION['initiated'])) {
diff --git a/auth/auth_xoops.php b/auth/auth_xoops.php
index 1ec40d2..bc4b503 100644
--- a/auth/auth_xoops.php
+++ b/auth/auth_xoops.php
@@ -32,8 +32,77 @@
*
****************************************************************************/
+$BridgeSupportPWDChange = TRUE;
+
+//change password in WRM DB
+function db_password_change($profile_id, $dbusernewpassword)
+{
+ global $db_raid, $phpraid_config;
+
+ //convert pwd
+ $dbusernewpassword = $pwd_hasher->HashPassword(dbusernewpassword);
+
+ //check: is profile_id in WRM DB
+ $sql = sprintf("SELECT profile_id FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ if (mysql_num_rows($result) != 1) {
+ //user not found in WRM DB
+ return 2;
+ }
+
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET password = %s WHERE profile_id = %s",
+ quote_smart($dbusernewpassword), quote_smart($profile_id)
+ );
+
+ if (($db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)) == true)
+ {
+ //pwd change
+ return 1;
+ }
+ else
+ {
+ //pwd NOT change
+ return 0;
+ }
+}
+//compare password
+//return value -> 0 equal ;1 Not equal
+function password_check($oldpassword, $profile_id)
+{
+ global $db_raid, $phpraid_config;
+ $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($profile_id)
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $data = $db_raid->sql_fetchrow($result, true);
+
+ if ( $pwd_hasher->HashPassword($oldpassword) == $data['password'])
+ {
+ return 0;
+ }
+ else
+ return 1;
+}
+
function phpraid_login() {
global $groups, $db_raid, $phpraid_config;
+ $wrmuserpassword = $username = $password = "";
+
+ // Set xoops Configuration Options
+ $table_prefix = $phpraid_config['xoops_table_prefix'];
+ $auth_user_class = $phpraid_config['xoops_auth_user_class'];
+ $auth_alt_user_class = $phpraid_config['xoops_alt_auth_user_class'];
+
+ //table and column name
+ $db_user_id = "uid";
+ $db_user_name = "loginname";
+ //$db_user_password = "";
+ $db_user_email = "email";
+ $db_group_id = "groupid";
+ $db_table_user_name = "users";
+ $db_table_group_name = "groups_users_link";
# Try to use stronger but system-specific hashes, with a possible fallback to
# the weaker portable hashes.
@@ -51,62 +120,70 @@ function phpraid_login() {
phpraid_logout();
}
- // Set xoops Configuration Options
- $xoops_table_prefix = $phpraid_config['xoops_table_prefix'];
- $xoops_auth_user_class = $phpraid_config['xoops_auth_user_class'];
- $xoops_alt_auth_user_class = $phpraid_config['xoops_alt_auth_user_class'];
+ //xoops database
+ $sql = sprintf( "SELECT ".$db_user_id.",". $db_user_name .",".$db_user_email .
+ " FROM " . $table_prefix . $db_table_user_name.
+ " WHERE ".$db_user_name." = %s", quote_smart($username)
+ );
-
- // Get the user_loginname and password and the various user classes that the user belongs to.
- //$sql = "SELECT * FROM " . $phpraid_config['db_dkp_prefix'] . "members, " . $phpraid_config['db_dkp_prefix'] . "classes WHERE " . $phpraid_config['db_dkp_prefix'] . "classes.class_id = " . $phpraid_config['db_dkp_prefix'] . "members.member_class_id";
-
- $sql = sprintf("SELECT password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username=%s", quote_smart($username));
- $result2 = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+
+ //WRM database
+ $sql = sprintf("SELECT username, password FROM " . $phpraid_config['db_prefix'] . "profile WHERE username = %s",
+ quote_smart($username)
+ );
+ $result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data2 = $db_raid->sql_fetchrow($result2))
- {
- $wrmuserpassword = $data2['password'];
- }
- $xoops_table_prefix_user = $xoops_table_prefix . "users";
- $xoops_table_prefix_gul = $xoops_table_prefix . "groups_users_link";
-
- //cross table
- $sql = "SELECT ".$xoops_table_prefix_user.".uid, ".$xoops_table_prefix_user.".loginname, ".$xoops_table_prefix_user.".email, ".$xoops_table_prefix_user.".groupid FROM " . $xoops_table_prefix_user.", " . $xoops_table_prefix_gul." WHERE " . $xoops_table_prefix_user.".uid = ".$xoops_table_prefix_gul.".uid AND ".$xoops_table_prefix_user."loginname = ".$username;
-
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ {
+ $wrmuserpassword = $data2['password'];
+ }
while($data = $db_raid->sql_fetchrow($result, true)) {
- //echo "<br>Processing: " . $data['member_name'] . " : " . $data['passwd'].'<br>pwd:'.
- if($username == strtolower($data['loginname']) && $pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) {
- // The user has a matching username and proper password in the smf database.
+
+ if( ($username == strtolower($data[$db_user_name])) && (($pwd_hasher->CheckPassword($password, $wrmuserpassword)==0) or ($data2['password'] == "" ) ) ) {
+
+ //first use: password insert in WRM DB
+ if ($wrmuserpassword == ""){
+ $wrmuserpassword = $password;
+ }
+
// We need to validate the users class. If it does not contain the user class that has been set as
- // authorized to use smf, we need to fail the login with a proper message.
- $user_class = $data['groupid'];
- $pos = strpos($user_class, $xoops_auth_user_class);
- $pos2 = strpos($user_class, $xoops_alt_auth_user_class);
- if ($pos === false && $xoops_auth_user_class != 0)
+ // authorized to use WRM, we need to fail the login with a proper message.
+ if ($auth_user_class != 0)
{
- if ($pos2 === false)
- {
- phpraid_logout();
+ $FoundUserInGroup = FALSE;
+
+ $sql = sprintf( "SELECT " . $db_user_id. "," .$db_group_id ." FROM " . $table_prefix . $db_table_group_name.
+ " WHERE ".$db_user_id." = %s", quote_smart($data[$db_user_id])
+ );
+ $resultgroup = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ while($datagroup = $db_raid->sql_fetchrow($resultgroup, true)) {
+ if( ($datagroup[$db_group_id] == $auth_user_class) or ($datagroup[$db_group_id] == $auth_alt_user_class) )
+ {
+ $FoundUserInGroup = TRUE;
+ }
+ }
+
+ if ($FoundUserInGroup == FALSE){
return -1;
}
}
// User is properly logged in and is allowed to use WRM, go ahead and process his login.
- $autologin=scrub_input($_POST['autologin']);
+ $autologin = scrub_input($_POST['autologin']);
if(isset($autologin)) {
// they want automatic logins so set the cookie
// set to expire in one month
- setcookie('username', $data['loginname'], time() + 2629743);
+ setcookie('username', $data[$db_user_name], time() + 2629743);
setcookie('password', $wrmuserpassword, time() + 2629743);
}
// set user profile variables
- $_SESSION['username'] = strtolower($data['loginname']);
+ $_SESSION['username'] = strtolower($data[$db_user_name]);
$_SESSION['session_logged_in'] = 1;
- $_SESSION['profile_id'] = $data['uid'];
- $_SESSION['email'] = $data['email'];
- $user_password = $wrmuserpassword;
+ $_SESSION['profile_id'] = $data[$db_user_id];
+ $_SESSION['email'] = $data[$db_user_email];
+
if($phpraid_config['default_group'] != 'nil')
$user_priv = $phpraid_config['default_group'];
else
@@ -114,18 +191,33 @@ function phpraid_login() {
// User is all logged in and setup, the session is initialized properly. Now we need to create the users
// profile in the WRM database if it does not already exist.
- $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($_SESSION['profile_id']));
- $result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
+ $sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id = %s",
+ quote_smart($_SESSION['profile_id'])
+ );
+ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
if ($data = $db_raid->sql_fetchrow($result))
- { //We found the profile in the database, update.
- $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email=%s,password=%s,last_login_time=%s WHERE profile_id=%s",quote_smart($_SESSION['email']),quote_smart($user_password),quote_smart(time()),quote_smart($_SESSION['profile_id']));
+ {
+ //We found the profile in the database, update.
+ $sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "profile SET email = %s, password = %s, last_login_time = %s WHERE profile_id = %s",
+ quote_smart($_SESSION['email']),quote_smart($wrmuserpassword),
+ quote_smart(time()),quote_smart($_SESSION['profile_id'])
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
else
- { //Profile not found in the database or DB Error, insert.
- $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)", quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($user_password), quote_smart($user_priv), quote_smart($_SESSION['username']),quote_smart(time()));
+ {
+ //Profile not found in the database or DB Error, insert.
+ $sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s, %s)",
+ quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($wrmuserpassword),
+ quote_smart($user_priv), quote_smart(strtolower($_SESSION['username'])), quote_smart(time())
+ );
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
+
+ //security fix
+ unset($username);
+ unset($password);
+ unset($wrmuserpassword);
return 1;
}
@@ -145,7 +237,7 @@ require ("includes/functions_pwdhash.php");
// good ole authentication
session_start();
-$_SESSION['name'] = "WRM";
+$_SESSION['name'] = "WRM-Xoops";
// set session defaults
if (!isset($_SESSION['initiated'])) {
| 0 | 10 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
f85e6f5d9d29110be9564e008d8f40cb4dd2bab6
|
Bug 0000039: HTMLSPECIALCHARS_DECODE Fails on PHP4.
The htmlspecialchars_decode function is PHP5 (5.1.0) only and doesn't work
for php4.
There is a new function definition at the top of the file to define the
function for php4 folks.
|
commit f85e6f5d9d29110be9564e008d8f40cb4dd2bab6
Author: Douglas Wagner <[email protected]>
Date: Tue Aug 5 13:33:30 2008 -0500
Bug 0000039: HTMLSPECIALCHARS_DECODE Fails on PHP4.
The htmlspecialchars_decode function is PHP5 (5.1.0) only and doesn't work
for php4.
There is a new function definition at the top of the file to define the
function for php4 folks.
diff --git a/includes/functions.php b/includes/functions.php
index 6c4a36d..8935ab0 100644
--- a/includes/functions.php
+++ b/includes/functions.php
@@ -29,6 +29,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************************/
+if (!function_exists("htmlspecialchars_decode")) {
+ function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) {
+ return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
+ }
+}
+
function email($to, $subject, $message) {
global $phpraid_config;
| 0 | 7 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
64ad34abd7c038572b2cceee4f9efd9c3399ccdb
|
Quick fix for log deletes that doesn't leave a vulnerability.
Code submitted by LuL0r of wowraidmanager.net. This quick
change fixes the problems of deleting logs without the
"hole" introduced in the last patch. The table name is now
generated passed through quote smart before being used in the
truncate SQL.
|
commit 64ad34abd7c038572b2cceee4f9efd9c3399ccdb
Author: Douglas Wagner (Illydth) <[email protected]>
Date: Sun Apr 27 17:04:24 2008 -0500
Quick fix for log deletes that doesn't leave a vulnerability.
Code submitted by LuL0r of wowraidmanager.net. This quick
change fixes the problems of deleting logs without the
"hole" introduced in the last patch. The table name is now
generated passed through quote smart before being used in the
truncate SQL.
diff --git a/logs.php b/logs.php
index 576f81f..2ddf77a 100644
--- a/logs.php
+++ b/logs.php
@@ -78,6 +78,7 @@ if($_GET['mode'] == 'delete')
}
else
{
+ $table = $phpraid_config['db_prefix'] . substr(quote_smart($logtype), 1, strlen(quote_smart($logtype)) - 2);
$sql = printf("TRUNCATE TABLE " . $phpraid_config['db_prefix'] . $logtype);
$db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
header("Location: logs.php");
| 0 | 8 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
8b65411c17f2b9a2729976e2719f0c2f4e2d310d
|
Cookie/Login fix:
Problem identified with cookies and being logged out of the software
tracked back to an issue with capitalization. The incoming cookie username
was NOT being passed through strtolower, and thus did not match the
username being passed in or compared against (which WAS being strtolowered).
Thanks go dn on the WRM boards for this.
Signed-off-by: Douglas Wagner <[email protected]>
|
commit 8b65411c17f2b9a2729976e2719f0c2f4e2d310d
Author: Douglas Wagner <[email protected]>
Date: Wed Feb 16 01:37:01 2011 -0600
Cookie/Login fix:
Problem identified with cookies and being logged out of the software
tracked back to an issue with capitalization. The incoming cookie username
was NOT being passed through strtolower, and thus did not match the
username being passed in or compared against (which WAS being strtolowered).
Thanks go dn on the WRM boards for this.
Signed-off-by: Douglas Wagner <[email protected]>
diff --git a/includes/functions_auth.php b/includes/functions_auth.php
index 15be2a9..ef410c1 100644
--- a/includes/functions_auth.php
+++ b/includes/functions_auth.php
@@ -259,7 +259,7 @@ function DEFINE_wrm_login()
{
// User is not logging in but processing cookie, set encryption flag to 1 to identify login with encrypted password.
$pwdencrypt = TRUE;
- $username = $_COOKIE['username'];
+ $username = strtolower_wrap(scrub_input($_COOKIE['username']), "UTF-8");
$password = $_COOKIE['password'];
$profile_id = $_COOKIE['profile_id'];
$wrmpass = '';
@@ -463,6 +463,7 @@ function DEFINE_wrm_login()
get_permissions($profile_id);
//security fix
+ unset($username);
unset($password);
unset($cmspass);
unset($wrmpass);
| 0 | 4 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
26e2f2ddffb886bdd7bd877c09da3049e47ff7e9
|
v3.2.1 De-Sanitization Error Fix
While 3.2.0 Sanitized all database inputs, the code failed to
de-sanitize data as it came back out of the database. Generally this
showed up as escaped quotes (\') and other display issues such as this.
|
commit 26e2f2ddffb886bdd7bd877c09da3049e47ff7e9
Author: root <[email protected]>
Date: Sun Apr 13 23:57:14 2008 -0500
v3.2.1 De-Sanitization Error Fix
While 3.2.0 Sanitized all database inputs, the code failed to
de-sanitize data as it came back out of the database. Generally this
showed up as escaped quotes (\') and other display issues such as this.
diff --git a/announcements.php b/announcements.php
old mode 100644
new mode 100755
index b7fa796..f3b65b4
--- a/announcements.php
+++ b/announcements.php
@@ -43,7 +43,7 @@ if($_GET['mode'] == 'view')
$announcements = array();
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "announcements";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$id = $data['announcements_id'];
$title = $data['title'];
@@ -189,7 +189,7 @@ if($_GET['mode'] != 'delete')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "announcements WHERE announcements_id=%s",quote_smart($id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$form_action = 'announcements.php?mode=edit&id=' . $id;
$title = '<input type="text" size="69" name="title" class="post" value="' . $data['title'] . '">';
diff --git a/auth/auth_e107.php b/auth/auth_e107.php
old mode 100644
new mode 100755
index d4d316e..2697407
--- a/auth/auth_e107.php
+++ b/auth/auth_e107.php
@@ -52,7 +52,7 @@ function phpraid_login() {
$sql = "SELECT user_id, user_loginname, user_password, user_email, user_class FROM " . $e107_table_prefix . "user";
$result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
//echo "<br>Processing: " . $data['user_loginname'] . " : " . $data['user_password'];
if($username == strtolower($data['user_loginname']) && $password == $data['user_password']) {
// The user has a matching username and proper password in the e107 database.
@@ -99,7 +99,7 @@ function phpraid_login() {
else
{ //Profile not found in the database or DB Error, insert.
$sql = sprintf("INSERT INTO " . $phpraid_config['db_prefix'] . "profile VALUES (%s, %s, %s, %s, %s)", quote_smart($_SESSION['profile_id']), quote_smart($_SESSION['email']), quote_smart($user_password), quote_smart($user_priv), quote_smart($_SESSION['username']));
- $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+ $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
return 1;
diff --git a/auth/auth_phpbb.php b/auth/auth_phpbb.php
old mode 100644
new mode 100755
index 06303c0..70ade25
--- a/auth/auth_phpbb.php
+++ b/auth/auth_phpbb.php
@@ -90,7 +90,7 @@ function phpraid_login()
if ( !($result = $db->sql_query($sql)) )
message_die(GENERAL_ERROR, 'Error in obtaining userdata', '', __LINE__, __FILE__, $sql);
- if( $row = $db->sql_fetchrow($result) )
+ if( $row = $db->sql_fetchrow($result, true) )
{
if( md5($password) == $row['user_password'] && $row['user_active'] )
{
diff --git a/auth/auth_phpraid.php b/auth/auth_phpraid.php
old mode 100644
new mode 100755
index 225a99d..e13329a
--- a/auth/auth_phpraid.php
+++ b/auth/auth_phpraid.php
@@ -46,7 +46,7 @@ function phpraid_login() {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "profile";
$result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
if($username == strtolower($data['username']) && $password == $data['password']) {
if(isset($_POST['autologin'])) {
// they want automatic logins so set the cookie
diff --git a/calendar.php b/calendar.php
old mode 100644
new mode 100755
index f616a27..dc5ccca
--- a/calendar.php
+++ b/calendar.php
@@ -60,7 +60,7 @@ if($db_raid->sql_numrows($result) > 0)
while($i >= 0)
{
$db_raid->sql_rowseek($i, $result);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$time = new_date($phpraid_config['time_format'], $data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$date = new_date($phpraid_config['date_format'], $data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -144,7 +144,7 @@ $daylast = mktime(23, 59, 59, date("m",$start ) , date("d",$start ) +$i-1 , date
$result = $db_raid->sql_query("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE start_time > '" . $dayfirst . "' AND start_time <= '" . $daylast . "' ORDER BY start_time");
$bob = "a";
-while($data = $db_raid->sql_fetchrow($result)) {
+while($data = $db_raid->sql_fetchrow($result, true)) {
$invitetime = new_date($phpraid_config['time_format'], $data['invite_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$starttime = new_date($phpraid_config['time_format'], $data['start_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -160,7 +160,7 @@ while($data = $db_raid->sql_fetchrow($result)) {
$resultz = $db_raid->sql_query("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id='" . $data['raid_id']. "' AND profile_id='{$_SESSION['profile_id']}'");
if($db_raid->sql_numrows($resultz) > 0)
{
- $data2 = $db_raid->sql_fetchrow($resultz);
+ $data2 = $db_raid->sql_fetchrow($resultz, true);
if (($data2['queue'] == '0') and ($data2['cancel'] == '0')) {
$issignedup = "*";
} else {
diff --git a/common.php b/common.php
old mode 100644
new mode 100755
index 59683cb..2e08831
--- a/common.php
+++ b/common.php
@@ -1,111 +1,115 @@
-<?php
-/***************************************************************************
-* common.php
-* -------------------
-* begin : Saturday, Jan 16, 2005
-* copyright : (C) 2007-2008 Douglas Wagner
-* email : [email protected]
-*
-* $Id: common.php,v 2.00 2007/11/23 14:45:33 psotfx Exp $
-*
-***************************************************************************/
-
-/***************************************************************************
-*
-* WoW Raid Manager - Raid Management Software for World of Warcraft
-* Copyright (C) 2007-2008 Douglas Wagner
-*
-* This program is free software: you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation, either version 3 of the License, or
-* (at your option) any later version.
-*
-* 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 for more details.
-*
-* You should have received a copy of the GNU General Public License
-*
-****************************************************************************/
-
-if ( !defined('IN_PHPRAID'))
- print_error("Hacking Attempt", "Invalid access detected", 1);
-
-if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
- die("Hacking attempt detected!");
-
-// force reporting
-error_reporting(E_ALL ^ E_NOTICE);
-
-// feel free to set this to absolute if necessary
-$phpraid_dir = './';
-
-require_once($phpraid_dir.'version.php');
-
-// Class require_onces
-require_once($phpraid_dir.'config.php');
-require_once($phpraid_dir.'db/mysql.php');
-require_once($phpraid_dir.'includes/functions.php');
-require_once($phpraid_dir.'includes/functions_auth.php');
-require_once($phpraid_dir.'includes/functions_date.php');
-require_once($phpraid_dir.'includes/functions_logging.php');
-require_once($phpraid_dir.'includes/functions_users.php');
-require_once($phpraid_dir.'includes/report.php');
-require_once($phpraid_dir.'includes/template.php');
-require_once($phpraid_dir.'includes/ubb.php');
-
-// redirect to setup if it exists
-if(file_exists($phpraid_dir.'install/')) {
- header("Location: install/install.php");
-}
-
-// reports for all data listing
-global $report;
-$report = &new ReportList;
-
-// database connection
-global $db_raid, $errorTitle, $errorMsg, $errorDie;
-$db_raid = &new sql_db($phpraid_config['db_host'],$phpraid_config['db_user'],$phpraid_config['db_pass'],$phpraid_config['db_name']);
-
-if(!$db_raid->db_connect_id)
-{
- die('<div align="center"><strong>There appears to be a problem with the database server.<br>We should be back up shortly.</strong></div>');
-}
-
-// unset database password for security reasons
-// we won't use it after this point
-unset($phpraid_config['db_pass']);
-
-$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "config";
-$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
-while($data = $db_raid->sql_fetchrow($result))
-{
- $phpraid_config["{$data['0']}"] = $data['1'];
-}
-
-// templates
-$page = &new wrmTemplate();
-$page->set_root($phpraid_dir.'templates');
-
-if(!is_file($phpraid_dir."language/lang_{$phpraid_config['language']}/lang_main.php"))
-{
- die("The language file <i>" . $phpraid_config['language'] . "</i> could not be found!");
- $db_raid->sql_close();
-}
-else
-{
- require_once($phpraid_dir."language/lang_{$phpraid_config['language']}/lang_main.php");
-}
-
-// get auth type
-require_once($phpraid_dir.'auth/auth_' . $phpraid_config['auth_type'] . '.php');
-get_permissions();
-
-if($phpraid_config['disable'] == 1 && $_SESSION['priv_configuration'] == 0)
-{
- $errorTitle = $phprlang['disable_header'];
- $errorMsg = $phprlang['disable_message'];
- $errorDie = 1;
-}
+<?php
+/***************************************************************************
+* common.php
+* -------------------
+* begin : Saturday, Jan 16, 2005
+* copyright : (C) 2007-2008 Douglas Wagner
+* email : [email protected]
+*
+* $Id: common.php,v 2.00 2007/11/23 14:45:33 psotfx Exp $
+*
+***************************************************************************/
+
+/***************************************************************************
+*
+* WoW Raid Manager - Raid Management Software for World of Warcraft
+* Copyright (C) 2007-2008 Douglas Wagner
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* 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 for more details.
+*
+* You should have received a copy of the GNU General Public License
+*
+****************************************************************************/
+
+if ( !defined('IN_PHPRAID'))
+ print_error("Hacking Attempt", "Invalid access detected", 1);
+
+if(isset($_GET['phpraid_dir']) || isset($_POST['phpraid_dir']))
+ die("Hacking attempt detected!");
+
+// force reporting
+error_reporting(E_ALL ^ E_NOTICE);
+
+// feel free to set this to absolute if necessary
+$phpraid_dir = './';
+
+require_once($phpraid_dir.'version.php');
+
+// Class require_onces
+require_once($phpraid_dir.'config.php');
+require_once($phpraid_dir.'db/mysql.php');
+require_once($phpraid_dir.'includes/functions.php');
+require_once($phpraid_dir.'includes/functions_auth.php');
+require_once($phpraid_dir.'includes/functions_date.php');
+require_once($phpraid_dir.'includes/functions_logging.php');
+require_once($phpraid_dir.'includes/functions_users.php');
+require_once($phpraid_dir.'includes/report.php');
+require_once($phpraid_dir.'includes/template.php');
+require_once($phpraid_dir.'includes/ubb.php');
+
+// redirect to setup if it exists
+if(file_exists($phpraid_dir.'install/')) {
+ header("Location: install/install.php");
+}
+
+// reports for all data listing
+global $report;
+$report = &new ReportList;
+
+// database connection
+global $db_raid, $errorTitle, $errorMsg, $errorDie;
+$db_raid = &new sql_db($phpraid_config['db_host'],$phpraid_config['db_user'],$phpraid_config['db_pass'],$phpraid_config['db_name']);
+
+if(!$db_raid->db_connect_id)
+{
+ die('<div align="center"><strong>There appears to be a problem with the database server.<br>We should be back up shortly.</strong></div>');
+}
+
+// unset database password for security reasons
+// we won't use it after this point
+unset($phpraid_config['db_pass']);
+
+
+//
+// Populate the $phpraid_config array
+//
+$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "config";
+$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
+while($data = $db_raid->sql_fetchrow($result, true))
+{
+ $phpraid_config["{$data['0']}"] = $data['1'];
+}
+
+// templates
+$page = &new wrmTemplate();
+$page->set_root($phpraid_dir.'templates');
+
+if(!is_file($phpraid_dir."language/lang_{$phpraid_config['language']}/lang_main.php"))
+{
+ die("The language file <i>" . $phpraid_config['language'] . "</i> could not be found!");
+ $db_raid->sql_close();
+}
+else
+{
+ require_once($phpraid_dir."language/lang_{$phpraid_config['language']}/lang_main.php");
+}
+
+// get auth type
+require_once($phpraid_dir.'auth/auth_' . $phpraid_config['auth_type'] . '.php');
+get_permissions();
+
+if($phpraid_config['disable'] == 1 && $_SESSION['priv_configuration'] == 0)
+{
+ $errorTitle = $phprlang['disable_header'];
+ $errorMsg = $phprlang['disable_message'];
+ $errorDie = 1;
+}
?>
\ No newline at end of file
diff --git a/configuration.php b/configuration.php
old mode 100644
new mode 100755
index 4579e60..13c6986
--- a/configuration.php
+++ b/configuration.php
@@ -257,7 +257,7 @@ $result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
$default = '<select name="default" class="post"><option value="nil">'.$phprlang['none'].'</option>';
-while($data = $db_raid->sql_fetchrow($result))
+while($data = $db_raid->sql_fetchrow($result, true))
{
if($phpraid_config['default_group'] == $data['permission_id'])
$default .= '<option value="'.$data['permission_id'].'" selected>'.$data['name'].'</option>';
diff --git a/db/mysql.php b/db/mysql.php
old mode 100644
new mode 100755
index 8bca222..56d5e5b
--- a/db/mysql.php
+++ b/db/mysql.php
@@ -28,6 +28,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************************/
+require_once($phpraid_dir.'includes/functions.php');
+
if(!defined("SQL_LAYER"))
{
@@ -206,7 +208,7 @@ class sql_db
return false;
}
}
- function sql_fetchrow($sql_id = 0)
+ function sql_fetchrow($sql_id = 0, $desanitize = false)
{
if(!$sql_id)
{
@@ -215,7 +217,10 @@ class sql_db
if($sql_id)
{
$this->row[$sql_id] = @mysql_fetch_array($sql_id);
- return $this->row[$sql_id];
+ if ($desanitize)
+ return desanitize($this->row[$sql_id]);
+ else
+ return $this->row[$sql_id];
}
else
{
diff --git a/gpl-3.0.txt b/gpl-3.0.txt
deleted file mode 100644
index 94a9ed0..0000000
--- a/gpl-3.0.txt
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- 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 for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/guilds.php b/guilds.php
old mode 100644
new mode 100755
index 6441dde..b3a7119
--- a/guilds.php
+++ b/guilds.php
@@ -44,7 +44,7 @@ if($_GET['mode'] == 'view') {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "guilds";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(),1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
$edit = '<a href="guilds.php?mode=update&id='.$data['guild_id'].'"><img src="templates/' . $phpraid_config['template'] .
@@ -170,7 +170,7 @@ if($_GET['mode'] != 'delete') {
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "guilds WHERE guild_id=%s",quote_smart($id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
// it's an edit... joy
$form_action = "guilds.php?mode=edit&id=$id";
diff --git a/includes/functions.php b/includes/functions.php
old mode 100644
new mode 100755
index d55925c..97dceae
--- a/includes/functions.php
+++ b/includes/functions.php
@@ -130,4 +130,68 @@ function setup_output() {
$report->setRowAttributes('class="row1"', 'class="row2"', 'rowHover');
$report->setFieldHeadingAttributes('class="listHeader"');
}
+
+function linebreak_to_br($str) {
+ $str = preg_replace("/(\r\n?)|(\n\r?)/s", "<br />", $str);
+
+ return $str;
+}
+
+function strip_linebreaks($str) {
+ $str = preg_replace("/(\r\n?)+|(\n\r?)+/s", " ", $str);
+
+ return $str;
+}
+
+// Sanitizes data for entry into the database. Escapes special
+// characters and encodes html entities.
+function sanitize(&$array) {
+ escape_db_data($array);
+
+ return $array;
+}
+
+// Reverses database sanitization by removing escape backslashes
+// and decoding html entities.
+function desanitize(&$array) {
+ unescape_db_data($array);
+
+ return $array;
+}
+
+function escape_db_data(&$array) {
+ foreach($array as &$value) {
+ if (is_string($value)) {
+ escape_data($value);
+ }
+ }
+ unset($value);
+}
+
+function escape_data(&$data) {
+ $data = addslashes($data);
+ $data = htmlspecialchars($data);
+}
+
+function unescape_db_data(&$array) {
+ foreach($array as &$value) {
+ if (is_string($value)) {
+ unescape_data($value);
+ }
+ }
+ unset($value);
+}
+
+function unescape_data(&$data) {
+ $data = stripslashes($data);
+ $data = htmlspecialchars_decode($data);
+}
+
+function magic_quotes_on() {
+ if ((get_magic_quotes_gpc() == '0') OR (strtolower(get_magic_quotes_gpc()) == 'off')) {
+ return false;
+ }
+
+ return true;
+}
?>
\ No newline at end of file
diff --git a/includes/functions_auth.php b/includes/functions_auth.php
old mode 100644
new mode 100755
index a98c597..aaf9b2f
--- a/includes/functions_auth.php
+++ b/includes/functions_auth.php
@@ -54,13 +54,13 @@ function get_permissions()
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE profile_id=%s", quote_smart($profile_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(),1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
// check all permissions
$sql_priv = "SELECT * FROM " . $phpraid_config['db_prefix'] . "permissions WHERE permission_id='{$data['priv']}'";
$result_priv = $db_raid->sql_query($sql_priv) or print_error($sql_priv, mysql_error(),1);
- $data_priv = $db_raid->sql_fetchrow($result_priv);
+ $data_priv = $db_raid->sql_fetchrow($result_priv, true);
$data_priv['announcements'] ? $_SESSION['priv_announcements'] = 1 : $_SESSION['priv_announcements'] = 0;
$data_priv['configuration'] ? $_SESSION['priv_configuration'] = 1 : $_SESSION['priv_configuration'] = 0;
@@ -96,7 +96,7 @@ function permissions($report) {
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "profile WHERE priv=%s", quote_smart($id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
// set delete permissions
if($_SESSION['priv_permissions'] == 1) {
if($id == 1 && $data['profile_id'] == 1) {
@@ -165,7 +165,7 @@ function permissions($report) {
$users = array();
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
$actions = '<input type="checkbox" name="addtolist' . $data['profile_id'] . '" value="' . $data['profile_id'] . '">';
array_push($users, array('id'=>$data['profile_id'],'username'=>ucwords(strtolower($data['username'])), 'email'=>$data['email'], 'actions'=>$actions));
}
diff --git a/includes/functions_users.php b/includes/functions_users.php
old mode 100644
new mode 100755
index b6a7c1d..53ac44e
--- a/includes/functions_users.php
+++ b/includes/functions_users.php
@@ -35,7 +35,7 @@ function check_frozen($raid_id) {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "raids where raid_id='$raid_id'";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$raid_date_month = new_date("m",$data['start_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$raid_date_day = new_date("d",$data['start_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -104,10 +104,10 @@ function get_char_count($id, $type) {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id='$id' AND queue='0' AND cancel='0'";
$result_signups = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
- while($signups = $db_raid->sql_fetchrow($result_signups)) {
+ while($signups = $db_raid->sql_fetchrow($result_signups, true)) {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id='{$signups['char_id']}'";
$result_char = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $char = $db_raid->sql_fetchrow($result_char);
+ $char = $db_raid->sql_fetchrow($result_char, true);
switch($char['class']) {
case $phprlang['druid']:
@@ -149,7 +149,7 @@ function get_priv_name($id)
$sql = "SELECT `name` FROM " . $phpraid_config['db_prefix'] . "permissions WHERE permission_id='$id'";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
return($data['name']);
}
@@ -161,7 +161,7 @@ function get_queued($raid_id) {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "queues";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
if($raid_id == $data['raid_id']) {
// match, push onto array
array_push($queued, array('pos'=>$data['pos'],'char_id'=>$data['char_id']));
@@ -181,7 +181,7 @@ function get_signups($raid_id) {
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "signups";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
if($raid_id == $data['raid_id']) {
// match, push onto array
array_push($signups, array('pos'=>$data['pos'],'char_id'=>$data['char_id']));
diff --git a/includes/page_header.php b/includes/page_header.php
old mode 100644
new mode 100755
index 4bf4a03..2407543
--- a/includes/page_header.php
+++ b/includes/page_header.php
@@ -3,22 +3,34 @@
* page_header.php
* -------------------
* begin : Saturday, Jan 16, 2005
- * copyright : (C) 2005 Kyle Spraggs
- * email : <a rel='external' href='javascript:window.location="mai"+"lto:"+"spiffyjr"+"@"+"gmail.com";self.close();' onmouseover='window.status="mai"+"lto:"+"spiffyjr"+"@"+"gmail.com"; return true;' onmouseout='window.status="";return true;'>- Send E-Mail -</a>
+ * copyright : (C) 2007-2008 Douglas Wagner
+ * email : [email protected]
*
- * $Id: mysql.php,v 1.16 2002/03/19 01:07:36 psotfx Exp $
+ * $Id: page_header.php,v 2.00 2008/03/04 14:26:10 psotfx Exp $
*
***************************************************************************/
/***************************************************************************
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- ***************************************************************************/
-//
+*
+* WoW Raid Manager - Raid Management Software for World of Warcraft
+* Copyright (C) 2007-2008 Douglas Wagner
+*
+* This program is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* 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 for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program. If not, see <http://www.gnu.org/licenses/>.
+*
+****************************************************************************/
+
+/
// Parse and show the overall header.
//
$page->set_file('headerFile',$phpraid_config['template'] . '/header.htm');
@@ -26,9 +38,9 @@ $page->set_file('headerFile',$phpraid_config['template'] . '/header.htm');
// This looks like dead code due to BC making shaman and paladins all on both sides.
// setup header variables
//if($phpraid_config['faction'] == 'alliance')
-// $page->set_var('other_name',$phprlang['paladin']);
+// $page->set_var('other_name',$phprlang['paladin']);
//else
-// $page->set_var('other_name',$phprlang['shaman']);
+// $page->set_var('other_name',$phprlang['shaman']);
$priv_announcement=scrub_input($_SESSION['priv_announcements']);
$priv_config=scrub_input($_SESSION['priv_configuration']);
$priv_guilds=scrub_input($_SESSION['priv_guilds']);
@@ -48,54 +60,54 @@ $guild_date = new_date($phpraid_config['date_format'],time(),$phpraid_config['ti
// now for the links
if($logged_in != 1)
{
- $login_form_open = '<form action="login.php" method="POST">';
- $login_username = '<input name="username" type="text" value="username" size="15" maxlength="45" onFocus="if(this.value==\'username\')this.value=\'\';" class="post">';
- $login_password = '<input name="password" type="password" value="password" size="15" onFocus="if(this.value==\'password\')this.value=\'\';" class="post">';
- $login_button = '<input type="submit" name="login" value="Log in" style="font-size:10px" class="mainoption"></form>';
- $login_remember = '<input type="checkbox" checked="checked" name="autologin">';
- $login_remember_hidden = '<input type="hidden" value="1" name="autologin">';
- $login_form_close = '</form>';
+ $login_form_open = '<form action="login.php" method="POST">';
+ $login_username = '<input name="username" type="text" value="username" size="15" maxlength="45" onFocus="if(this.value==\'username\')this.value=\'\';" class="post">';
+ $login_password = '<input name="password" type="password" value="password" size="15" onFocus="if(this.value==\'password\')this.value=\'\';" class="post">';
+ $login_button = '<input type="submit" name="login" value="Log in" style="font-size:10px" class="mainoption"></form>';
+ $login_remember = '<input type="checkbox" checked="checked" name="autologin">';
+ $login_remember_hidden = '<input type="hidden" value="1" name="autologin">';
+ $login_form_close = '</form>';
}
else
{
- $login_form_open = '<form action="login.php?logout=true" method="POST">';
- $login_username = scrub_input($_SESSION['username']);
- $login_password = '';
- $login_button = '<input type="submit" name="login" value="Log out" style="font-size:10px" class="mainoption"></form>';
- $login_remember = '';
- $login_remember_hidden = '';
- $login_form_close = '</form>';
+ $login_form_open = '<form action="login.php?logout=true" method="POST">';
+ $login_username = scrub_input($_SESSION['username']);
+ $login_password = '';
+ $login_button = '<input type="submit" name="login" value="Log out" style="font-size:10px" class="mainoption"></form>';
+ $login_remember = '';
+ $login_remember_hidden = '';
+ $login_form_close = '</form>';
}
if(($phpraid_config['disable'] == '1') AND ($priv_config == 1))
{
- $site_disabled_warning = "
- <br>
- <div align=\"center\">
- <div class=\"errorHeader\">Site disabled notice</div>
- <div class=\"errorBody\">Please note, your site is disabled. Visitors can't use the system right now!<br>
- Go to <u>Configuration</u> and then uncheck <u>Disable phpRaid</u></div>
- </div>
- ";
+ $site_disabled_warning = "
+ <br>
+ <div align=\"center\">
+ <div class=\"errorHeader\">Site disabled notice</div>
+ <div class=\"errorBody\">Please note, your site is disabled. Visitors can't use the system right now!<br>
+ Go to <u>Configuration</u> and then uncheck <u>Disable phpRaid</u></div>
+ </div>
+ ";
}
$page->set_var(
- array(
- 'header_link' => $phpraid_config['header_link'],
- 'title_guild_name'=>$phpraid_config['guild_name'],
- 'title_guild_server'=>$phpraid_config['guild_server'],
- 'title_guild_description'=>$phpraid_config['guild_description'],
- 'header_logo' => $phpraid_config['header_logo'],
- 'guild_time' => $guild_time,
- 'guild_date' => $guild_date,
- 'login_form_open' => $login_form_open,
- 'login_form_close' => $login_form_close,
- 'login_username' => $login_username,
- 'login_password' => $login_password,
- 'login_remember' => $login_remember,
- 'login_remember_hidden' => $login_remember_hidden,
- 'login_button' => $login_button,
- 'site_disabled_warning' => $site_disabled_warning
- )
+ array(
+ 'header_link' => $phpraid_config['header_link'],
+ 'title_guild_name'=>$phpraid_config['guild_name'],
+ 'title_guild_server'=>$phpraid_config['guild_server'],
+ 'title_guild_description'=>$phpraid_config['guild_description'],
+ 'header_logo' => $phpraid_config['header_logo'],
+ 'guild_time' => $guild_time,
+ 'guild_date' => $guild_date,
+ 'login_form_open' => $login_form_open,
+ 'login_form_close' => $login_form_close,
+ 'login_username' => $login_username,
+ 'login_password' => $login_password,
+ 'login_remember' => $login_remember,
+ 'login_remember_hidden' => $login_remember_hidden,
+ 'login_button' => $login_button,
+ 'site_disabled_warning' => $site_disabled_warning
+ )
);
// setup link permissions
@@ -111,7 +123,7 @@ $roster_link = '<a href="roster.php">' . $theme_roster_link . '</a>';
$priv_announcement ? $announce_link = '<a href="announcements.php?mode=view">' . $theme_announcement_link . '</a>' : $announce_link = '';
$priv_config ? $phpraid_configure_link = '<a href="configuration.php">' . $theme_configure_link . '</a>' : $phpraid_configure_link = '';
$priv_permissions ? $permissions_link = '<a href="permissions.php?mode=view">' . $theme_permissions_link . '</a>' : $permissions_link = '';
-$priv_guilds ? $guild_link = '<a href="guilds.php?mode=view">' . $theme_guild_link . '</a>' : $guild_link = '';
+$priv_guilds ? $guild_link = '<a href="guilds.php?mode=view">' . $theme_guild_link . '</a>' : $guild_link = '';
$priv_locations ? $locations_link = '<a href="locations.php?mode=view">' . $theme_locations_link . '</a>' : $locations_link = '';
$priv_logs ? $logs_link = '<a href="logs.php?mode=view">' . $theme_logs_link . '</a>' : $logs_link = '';
$priv_profile ? $profile_link = '<a href="profile.php?mode=view">' . $theme_profile_link . '</a>' : $profile_link = '';
@@ -119,13 +131,13 @@ $priv_users ? $users_link = '<a href="users.php?mode=view">' . $theme_users_link
$logged_in != '1' ? $register_link = '<a href="' . $phpraid_config['register_url'] . '">' . $theme_register_link . '</a>' : $register_link = '';
if ( $priv_raids OR ($phpraid_config['enable_five_man'] AND $priv_profile) )
{
- $raids_link = '<a href="raids.php?mode=view">' . $theme_raids_link . '</a>';
- $lua_output_link = '<a href="lua_output.php">' . $theme_lua_output_link . '</a>';
+ $raids_link = '<a href="raids.php?mode=view">' . $theme_raids_link . '</a>';
+ $lua_output_link = '<a href="lua_output.php">' . $theme_lua_output_link . '</a>';
}
else
{
- $raids_link = '';
- $lua_output_link = '';
+ $raids_link = '';
+ $lua_output_link = '';
}
// setup menu
@@ -233,8 +245,8 @@ if($priv_users == 1)
}
if($logged_in == 0) {
- $menu .= '<li>' . $register_link . '</li>';
- $page->set_var('register_link',$register_link);
+ $menu .= '<li>' . $register_link . '</li>';
+ $page->set_var('register_link',$register_link);
}
if (preg_match("/(.*)roster\.php(.*)/", $_SERVER['PHP_SELF'])) {
@@ -251,27 +263,27 @@ $page->parse('header','headerFile');
// display any errors if they exist
if(isset($errorMsg))
{
- if(isset($errorSpace) && $errorSpace == 1) {
- $errorMsg .= '</div><br>';
- } else {
- $errorMsg .= '</div>';
- }
+ if(isset($errorSpace) && $errorSpace == 1) {
+ $errorMsg .= '</div><br>';
+ } else {
+ $errorMsg .= '</div>';
+ }
- $page->set_file('errorFile',$phpraid_config['template'] . '/error.htm');
- $page->set_var(array(
- 'error_msg' => $errorMsg,
- 'error_title' => $errorTitle)
- );
+ $page->set_file('errorFile',$phpraid_config['template'] . '/error.htm');
+ $page->set_var(array(
+ 'error_msg' => $errorMsg,
+ 'error_title' => $errorTitle)
+ );
- $page->parse('header','errorFile',true);
+ $page->parse('header','errorFile',true);
- // is the error fatal?
- if($errorDie)
- {
- $page->p('header');
- require_once('page_footer.php');
- exit;
- }
+ // is the error fatal?
+ if($errorDie)
+ {
+ $page->p('header');
+ require_once('page_footer.php');
+ exit;
+ }
}
$page->p('header');
?>
\ No newline at end of file
diff --git a/includes/ubb.php b/includes/ubb.php
old mode 100644
new mode 100755
index e7fcb1b..0dfea14
--- a/includes/ubb.php
+++ b/includes/ubb.php
@@ -2,33 +2,26 @@
function UBB($post)
{
- if ((get_magic_quotes_gpc() == '0') OR (strtolower(get_magic_quotes_gpc()) == 'off'))
- {
- $post = str_replace("\'","'",$post);
- }
-
- $post = str_replace("\n","<br>",$post);
- $post = str_replace("\r","",$post);
+ if (!magic_quotes_on())
+ $post = stripslashes($post);
+
+ $post = linebreak_to_br($post);
return $post;
}
function UBB2($post)
{
- if ((get_magic_quotes_gpc() == '0') OR (strtolower(get_magic_quotes_gpc()) == 'off'))
- {
- $post = str_replace("\'","'",$post);
- }
+ if (!magic_quotes_on())
+ $post = stripslashes($post);
return $post;
}
function DEUBB($post)
{
- if ((get_magic_quotes_gpc() == '0') OR (strtolower(get_magic_quotes_gpc()) == 'off'))
- {
- $post = str_replace("'","\'",$post);
- }
+ if (!magic_quotes_on())
+ $post = addslashes($post);
return $post;
}
@@ -36,9 +29,8 @@ function DEUBB($post)
//For comments
function DEUBB2($post)
{
- $post = str_replace("'","\'",$post);
- $post = str_replace("\n","<br>",$post);
- $post = str_replace("\r","",$post);
+ $post = addslashes($post);
+ $post = linebreak_to_br($post);
return $post;
}
diff --git a/index.php b/index.php
old mode 100644
new mode 100755
index 3413889..2d51047
--- a/index.php
+++ b/index.php
@@ -50,7 +50,7 @@ $raids_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1)
$count = array();
-while($raids = $db_raid->sql_fetchrow($raids_result)) {
+while($raids = $db_raid->sql_fetchrow($raids_result, true)) {
$date = new_date($phpraid_config['date_format'],$raids['start_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$invite = new_date($phpraid_config['time_format'], $raids['invite_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$start = new_date($phpraid_config['time_format'], $raids['start_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -226,7 +226,7 @@ if($db_raid->sql_numrows($result) > 0)
while($i >= 0)
{
$db_raid->sql_rowseek($i, $result);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$time = new_date($phpraid_config['time_format'], $data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$date = new_date($phpraid_config['date_format'], $data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
diff --git a/install/auth/install_e107.php b/install/auth/install_e107.php
old mode 100644
new mode 100755
diff --git a/license.txt b/license.txt
deleted file mode 100644
index 98a412d..0000000
--- a/license.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-A note about the license surrounding phpRaid.
-
-It has come to my attention, through conversations with a few of my users,
-that the phpRaid software, versions 3.1.0, 3.1.1 and 3.1.2 are NOT properly
-released under the terms of the GNU GPL.
-
-Specifically,
-
-* the Copyright Notices have not been updated throughout the code.
-* The proper header on all files has not been made on all files.
-* No copy of the GNU GPL has been distributed with the software.
-
-There may be other, smaller issues with the GNU License, but the above have
-been identified as existing issues.
-
-To clarify:
-
-THIS SOFTWARE HAS, IS, AND WILL BE RELEASED ACCORDING TO THE GNU GENERAL PUBLIC
-LICENSE unless otherwise noted to the community at large. The failure of the
-current and any past versions of the software to properly meet the requirements
-of the license DOES NOT invalidate the license as a whole.
-
-While I realize that this may not be legaly binding and is certainly not a "good
-enough", it will have to do till I get the time to properly bring the code up
-to the reqirements of the GNU GPL.
-
-This said, I am officially announcing the release of phpRaid fully under the
-GNU GPL v2 or any later version of the GNU GPL license (it always has been, i'm
-just doing my best to make this as legal as possible).
-
-As of this statement, I am hereby stating all copyright notices in the code and
-software at large should read: Copyright (C) 2007 Douglas Wagner
-
-All code headers should read:
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- 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 for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Lastly in the 3.1.2 release I have included a file gpl-3.0.txt that contains
-the GNU GPL v3 License.
-
-Please note this license file has been written with the intent to SUPERCEED any
-other liceses and/or copyrights distributed in the code itself. As the original
-software was produced under the GNU GPL I have been given rights by the GPL to
-do this.
-
-If there are any questions about the above or other license questions, please
-direct them to douglasw at wagnerweb dot org.
-
-Douglas Wagner
-Illydth - phpRaid Maintainer.
\ No newline at end of file
diff --git a/locations.php b/locations.php
old mode 100644
new mode 100755
index e170cfd..472dea0
--- a/locations.php
+++ b/locations.php
@@ -44,7 +44,7 @@ if($_GET['mode'] == 'view')
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "locations";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$edit = '<a href="locations.php?mode=update&id='.$data['location_id'].'"><img src="templates/' . $phpraid_config['template'] .
'/images/icons/icon_edit.gif" border="0" onMouseover="ddrivetip(\'' . $phprlang['edit'] . '\')"; onMouseout="hideddrivetip()"></a>';
@@ -244,7 +244,7 @@ if($_GET['mode'] != 'delete')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "locations WHERE location_id=%s",quote_smart($id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
// it's an edit... joy
$form_action = "locations.php?mode=edit&id=$id";
diff --git a/logs.php b/logs.php
old mode 100644
new mode 100755
index ce3a54e..d473d22
--- a/logs.php
+++ b/logs.php
@@ -183,7 +183,7 @@ else
$create = array();
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$date = new_date($phpraid_config['date_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$time = new_date($phpraid_config['time_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -197,7 +197,7 @@ else
$delete = array();
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$date = new_date($phpraid_config['date_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$time = new_date($phpraid_config['time_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -222,7 +222,7 @@ else
$hack = array();
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$date = new_date($phpraid_config['date_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$time = new_date($phpraid_config['time_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -236,7 +236,7 @@ else
$raid = array();
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$date = new_date($phpraid_config['date_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$time = new_date($phpraid_config['time_format'],$data['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']);
diff --git a/lua_output_data.php b/lua_output_data.php
old mode 100644
new mode 100755
index 79e23f5..07e224c
--- a/lua_output_data.php
+++ b/lua_output_data.php
@@ -216,11 +216,11 @@ class Output_Data
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='0' AND cancel='0'",quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s",quote_smart($data['char_id']));
$result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data2 = $db_raid->sql_fetchrow($result2);
+ $data2 = $db_raid->sql_fetchrow($result2, true);
$data2['name'] = ucfirst(strtolower($data2['name']));
$text .= "/i {$data2['name']}\n";
}
@@ -230,11 +230,11 @@ class Output_Data
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='1' AND cancel='0'",quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id='" . $data['char_id'] . "'";
$result2 = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data2 = $db_raid->sql_fetchrow($result2);
+ $data2 = $db_raid->sql_fetchrow($result2, true);
$data2['name'] = ucfirst(strtolower($data2['name']));
$text .= "/i {$data2['name']}\n";
}
@@ -286,7 +286,7 @@ class Output_Data
// parse result
$count = 0;
- while($raid_data = $db_raid->sql_fetchrow($raids_result))
+ while($raid_data = $db_raid->sql_fetchrow($raids_result, true))
{
$lua_output .= "\t\t[{$count}] = {\n";
$lua_output .= "\t\t\t[\"location\"] = \"{$raid_data['location']}\",\n";
@@ -335,7 +335,7 @@ class Output_Data
$order_by = 'ORDER BY '.$phpraid_config['db_prefix'].'signups.timestamp ASC';
$sql1 = $sql."0 ".$order_by.";";
$signup_result = $db_raid->sql_query($sql1) or print_error($sql1, mysql_error(), 1);
- while($signup = $db_raid->sql_fetchrow($signup_result))
+ while($signup = $db_raid->sql_fetchrow($signup_result, true))
{
if ($format=="1")
{
@@ -343,7 +343,7 @@ class Output_Data
"FROM ".$phpraid_config['db_prefix']."teams " .
"WHERE raid_id=".$raid_data['raid_id']." and char_id=".$signup['ID'];
$team_result = $db_raid->sql_query($sql2) or print_error($sql2, mysql_error(), 1);
- $team = $db_raid->sql_fetchrow($team_result);
+ $team = $db_raid->sql_fetchrow($team_result, true);
array_push($signups, array(
'name' => ucfirst(strtolower($signup['name'])),
@@ -351,7 +351,7 @@ class Output_Data
'race' => $signup['race'],
'class' => $signup['class'],
'team_name' => $team['team_name'],
- 'comment' => preg_replace("/\r|\n/s", " ", str_replace('"', '\"', $signup['comment'])),
+ 'comment' => strip_linebreaks($signup['comment']),
'timestamp' => new_date($phpraid_config['date_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']) . ' - ' . new_date($phpraid_config['time_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']),
));
}
@@ -362,7 +362,7 @@ class Output_Data
'level' => $signup['lvl'],
'race' => $signup['race'],
'class' => $signup['class'],
- 'comment' => preg_replace("/\r|\n/s", " ", str_replace('"', '\"', $signup['comment'])),
+ 'comment' => strip_linebreaks($signup['comment']),
'timestamp' => new_date($phpraid_config['date_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']) . ' - ' . new_date($phpraid_config['time_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']),
));
}
@@ -379,7 +379,7 @@ class Output_Data
$order_by = 'ORDER BY '.$phpraid_config['db_prefix'].'chars.class ASC';
$sql1 = $sql."1 ".$order_by.";";
$signup_result = $db_raid->sql_query($sql1) or print_error($sql1, mysql_error(), 1);
- while($signup = $db_raid->sql_fetchrow($signup_result))
+ while($signup = $db_raid->sql_fetchrow($signup_result, true))
{
if ($format=="1")
{
@@ -387,7 +387,7 @@ class Output_Data
"FROM ".$phpraid_config['db_prefix']."teams " .
"WHERE raid_id=".$raid_data['raid_id']." and char_id=".$signup['ID'];
$team_result = $db_raid->sql_query($sql2) or print_error($sql2, mysql_error(), 1);
- $team = $db_raid->sql_fetchrow($team_result);
+ $team = $db_raid->sql_fetchrow($team_result, true);
array_push($queue, array(
'name' => ucfirst(strtolower($signup['name'])),
@@ -395,7 +395,7 @@ class Output_Data
'race' => $signup['race'],
'class' => $signup['class'],
'team_name' => $team['team_name'],
- 'comment' => preg_replace("/\r|\n/s", " ", str_replace('"', '\"', $signup['comment'])),
+ 'comment' => strip_linebreaks($signup['comment']),
'timestamp' => new_date($phpraid_config['date_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']) . ' - ' . new_date($phpraid_config['time_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']),
));
}
@@ -406,7 +406,7 @@ class Output_Data
'level' => $signup['lvl'],
'race' => $signup['race'],
'class' => $signup['class'],
- 'comment' => preg_replace("/\r|\n/s", " ", str_replace('"', '\"', $signup['comment'])),
+ 'comment' => strip_linebreaks($signup['comment']),
'timestamp' => new_date($phpraid_config['date_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']) . ' - ' . new_date($phpraid_config['time_format'],$signup['timestamp'],$phpraid_config['timezone'] + $phpraid_config['dst']),
));
}
diff --git a/permissions.php b/permissions.php
old mode 100644
new mode 100755
index 6be4e58..e4c393a
--- a/permissions.php
+++ b/permissions.php
@@ -50,7 +50,7 @@ if($_GET['mode'] == 'view')
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "permissions";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
$edit = '<a href="permissions.php?mode=edit&id='.$data['permission_id'].'"><img src="templates/' . $phpraid_config['template'] .
'/images/icons/icon_edit.gif" border="0" onMouseover="ddrivetip(\'' . $phprlang['edit'] . '\')"; onMouseout="hideddrivetip()"></a>';
@@ -301,7 +301,7 @@ if($_GET['mode'] != 'delete' && $_GET['mode'] != 'details')
// grab from DB
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "permissions WHERE permission_id=%s",quote_smart($id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$announcements = '<select name="announcements" class="post">';
if($data['announcements'] == 1) {
diff --git a/profile.php b/profile.php
old mode 100644
new mode 100755
index a44f10b..6dd7bc0
--- a/profile.php
+++ b/profile.php
@@ -44,7 +44,7 @@ if($_GET['mode'] == 'view') {
$profile_id = scrub_input($_SESSION['profile_id']);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE profile_id=%s",quote_smart($profile_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
array_push($chars,
array(
@@ -105,14 +105,14 @@ if($_GET['mode'] == 'view') {
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE profile_id=%s", quote_smart($profile_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($signups = $db_raid->sql_fetchrow($result))
+ while($signups = $db_raid->sql_fetchrow($result, true))
{
// setup the count array
$count = array('dr'=>'0','hu'=>'0','ma'=>'0','pr'=>'0','pa'=>'0','ro'=>'0','sh'=>'0','wk'=>'0','wa'=>'0');
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($signups['raid_id']));
$result_raid = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result_raid);
+ $data = $db_raid->sql_fetchrow($result_raid, true);
$desc = strip_tags($data['description']);
$desc = UBB($desc);
@@ -279,7 +279,7 @@ if($_GET['mode'] == 'view') {
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s",quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$guild = $data['guild'];
$race = $data['race'];
@@ -649,7 +649,7 @@ if($db_raid->sql_numrows($result) == 0) {
// get guild list
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "guilds";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
If($guild == $data['guild_tag'])
{
diff --git a/raids.php b/raids.php
old mode 100644
new mode 100755
index 354a1ec..8cb82fd
--- a/raids.php
+++ b/raids.php
@@ -57,7 +57,7 @@ if($_GET['mode'] == 'view')
// Get information for current raids
// And push into current array so that we can output it with our report class
- while($data = $db_raid->sql_fetchrow($result)) {
+ while($data = $db_raid->sql_fetchrow($result, true)) {
if ($priv_raids or $username == $data['officer'])
{
$edit = '<a href="raids.php?mode=edit&id='.$data['raid_id'].'"><img src="templates/' . $phpraid_config['template'] .
@@ -269,13 +269,13 @@ elseif($_GET['mode'] == 'new' || $_GET['mode'] == 'edit')
{
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "locations WHERE name=%s", quote_smart($location));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
}
else
{
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "locations WHERE name=%s and locked='0'", quote_smart($location));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
}
$max = $data['max'];
@@ -317,13 +317,13 @@ elseif($_GET['mode'] == 'new' || $_GET['mode'] == 'edit')
{
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "locations WHERE name=%s", quote_smart($location));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
}
else
{
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "locations WHERE name=%s and locked='0'", quote_smart($location));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
}
$max = $data['max'];
@@ -343,7 +343,7 @@ elseif($_GET['mode'] == 'new' || $_GET['mode'] == 'edit')
$id = scrub_input($_GET['id']);
$sql2 = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($id));
$result2 = $db_raid->sql_query($sql2) or print_error($sql2, mysql_error(), 1);
- $data2 = $db_raid->sql_fetchrow($result2);
+ $data2 = $db_raid->sql_fetchrow($result2, true);
$date_value = new_date("m/d/Y",$data2['start_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
$i_time_hour_value = new_date("h",$data2['invite_time'],$phpraid_config['timezone'] + $phpraid_config['dst']);
@@ -360,7 +360,7 @@ elseif($_GET['mode'] == 'new' || $_GET['mode'] == 'edit')
$id = scrub_input($_GET['id']);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$max = $data['max'];
$dr = $data['dr_lmt'];
@@ -555,7 +555,7 @@ elseif($_GET['mode'] == 'new' || $_GET['mode'] == 'edit')
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "locations WHERE locked='0' ORDER BY name";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
}
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
if (isset($_GET['location'])) {
$raid_location = scrub_input($_GET['location']);
@@ -792,7 +792,7 @@ elseif($_GET['mode'] == 'mark')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
if($data['old'] == 1)
{
diff --git a/register.php b/register.php
old mode 100644
new mode 100755
index a9eb79f..f75f142
--- a/register.php
+++ b/register.php
@@ -78,7 +78,7 @@ if(isset($_POST['submit']))
// check if username or email already exists
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "profile";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
if($user == $data['username'])
{
diff --git a/roster.php b/roster.php
old mode 100644
new mode 100755
index ef8d644..964d131
--- a/roster.php
+++ b/roster.php
@@ -43,7 +43,7 @@ $chars = array();
// get all the chars and throw them in that nice array for
// output by the report class
-while($data = $db_raid->sql_fetchrow($result)) {
+while($data = $db_raid->sql_fetchrow($result, true)) {
array_push($chars,
array(
'id'=>$data['char_id'],
diff --git a/rss.php b/rss.php
old mode 100644
new mode 100755
index a9ed45a..52c8200
--- a/rss.php
+++ b/rss.php
@@ -44,7 +44,7 @@
<language>en-us</language>
';
- while(($data = $db_raid->sql_fetchrow($result)) && ($i < $feeds))
+ while(($data = $db_raid->sql_fetchrow($result, true)) && ($i < $feeds))
{
$raid_id = $data['raid_id'];
diff --git a/teams.php b/teams.php
old mode 100644
new mode 100755
index a82b6e2..667c2f6
--- a/teams.php
+++ b/teams.php
@@ -78,7 +78,7 @@ if($mode == 'view')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "teams WHERE (raid_id=%s and char_id='-1') or char_id='-2'",quote_smart($raid_id));
$teams_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($team = $db_raid->sql_fetchrow($teams_result))
+ while($team = $db_raid->sql_fetchrow($teams_result, true))
{
if ($team['char_id']=="-2")
$team_cur_teams .= "<b>" . $team['team_name'] . "</b> ";
@@ -110,7 +110,7 @@ if($mode == 'view')
"where " . $phpraid_config['db_prefix'] . "teams.char_id = " . $phpraid_config['db_prefix'] . "chars.char_id " .
"and " . $phpraid_config['db_prefix'] . "teams.raid_id = %s", quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($team = $db_raid->sql_fetchrow($result))
+ while($team = $db_raid->sql_fetchrow($result, true))
{
// set delete permissions
if($_SESSION['priv_raids'] == 1) {
@@ -176,7 +176,7 @@ if($mode == 'view')
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
$X=0;
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$signups[$X]['char_id'] = $data['char_id'];
$X++;
@@ -188,7 +188,7 @@ if($mode == 'view')
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
$X=0;
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$teamed_users[$X]['char_id']=$data['char_id'];
$X++;
@@ -224,7 +224,7 @@ if($mode == 'view')
// get character data from the characters table.
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s",quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$action='<input type="checkbox" name="addtolist' . $data['char_id'] . '" value="' . $data['char_id'] . '">';
@@ -248,7 +248,7 @@ if($mode == 'view')
// get character data from the teams table.
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "teams WHERE (raid_id=%s and char_id='-1') or char_id='-2'",quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while ($data = $db_raid->sql_fetchrow($result))
+ while ($data = $db_raid->sql_fetchrow($result, true))
$team_add_body .= '<option value="' . $data['team_id']. '">' . $data['team_name'] . '</option>';
$team_add_body .= '</select></center><br>';
@@ -318,7 +318,7 @@ elseif($mode == 'add')
//get team_name from team_id: Only one team name can be passed at any given time, so only retrieve team once.
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "teams WHERE team_id=%s",quote_smart($team_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$team_name = $data['team_name'];
//For each char id on input, we need to add a record to the teams table noteing that that char is now on a team.
diff --git a/users.php b/users.php
old mode 100644
new mode 100755
index 2131c2e..38f874b
--- a/users.php
+++ b/users.php
@@ -50,7 +50,7 @@ if($mode == 'view')
$sql = "SELECT * FROM " . $phpraid_config['db_prefix'] . "profile";
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$usersname = '<a href="users.php?mode=details&user_id='.$data['profile_id'].'">'.$data['username'].'</a>';
@@ -126,7 +126,7 @@ else if($mode == 'details')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE profile_id=%s",quote_smart($user_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
array_push($chars,
array(
diff --git a/view.php b/view.php
old mode 100644
new mode 100755
index b2bac88..a0ea21e
--- a/view.php
+++ b/view.php
@@ -67,7 +67,7 @@ require_once('./signup_flow.php');
// a default permission that will be checked within the signup flow.
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
-$data = $db_raid->sql_fetchrow($result);
+$data = $db_raid->sql_fetchrow($result, true);
$priv_raids = scrub_input($_SESSION['priv_raids']);
$username = scrub_input($_SESSION['username']);
@@ -84,9 +84,11 @@ else
if($mode == 'view')
{
+ //
+ // Obtain data for the raid
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$raid_location = UBB2($data['location']);
$raid_officer = $data['officer'];
@@ -166,7 +168,7 @@ if($mode == 'view')
// parse the signup array and seperate to classes
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='0' AND cancel='0'", quote_smart($raid_id));
$signups_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($signups = $db_raid->sql_fetchrow($signups_result))
+ while($signups = $db_raid->sql_fetchrow($signups_result, true))
{
$race = '';
$name = '';
@@ -176,11 +178,11 @@ if($mode == 'view')
// get all the character information from the database
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s",quote_smart($signups['char_id']));
$data_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($data_result);
+ $data = $db_raid->sql_fetchrow($data_result, true);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "teams WHERE char_id=%s and raid_id=%s",quote_smart($signups['char_id']),quote_smart($raid_id));
$teams_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $teamrow = $db_raid->sql_fetchrow($teams_result);
+ $teamrow = $db_raid->sql_fetchrow($teams_result, true);
if ($db_raid->sql_numrows($teams_result) > 0)
{
@@ -195,7 +197,7 @@ if($mode == 'view')
// "and " .$phpraid_config['db_prefix'] . "chars.char_id=" .$phpraid_config['db_prefix'] . "teams.char_id " .
// "and " .$phpraid_config['db_prefix'] . "teams.raid_id=%s",quote_smart($signups['char_id']),quote_smart($raid_id));
//$data_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- //$data = $db_raid->sql_fetchrow($data_result);
+ //$data = $db_raid->sql_fetchrow($data_result, true);
//$team_name=$data['team_name'];
@@ -370,13 +372,13 @@ if($mode == 'view')
// parse the queue array and seperate to classes
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='1' AND cancel='0'",quote_smart($raid_id));
$signups_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($signups = $db_raid->sql_fetchrow($signups_result))
+ while($signups = $db_raid->sql_fetchrow($signups_result, true))
{
// okay, push the value into the array after we
// get all the character information from the database
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s",quote_smart($signups['char_id']));
$data_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($data_result);
+ $data = $db_raid->sql_fetchrow($data_result, true);
$comments = DEUBB2(scrub_input($signups['comments']));
@@ -510,13 +512,13 @@ if($mode == 'view')
// parse the cancel array and seperate to classes
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='0' AND cancel='1'",quote_smart($raid_id));
$signups_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($signups = $db_raid->sql_fetchrow($signups_result))
+ while($signups = $db_raid->sql_fetchrow($signups_result, true))
{
// okay, push the value into the array after we
// get all the character information from the database
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s",quote_smart($signups['char_id']));
$data_result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($data_result);
+ $data = $db_raid->sql_fetchrow($data_result, true);
$comments = DEUBB2(scrub_input($signups['comments']));
@@ -741,7 +743,7 @@ if($mode == 'view')
// last but not least, tooltips for class breakdown
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s",quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$druid_count = $druid_count . ' of ' . $data['dr_lmt'];
$hunter_count = $hunter_count . ' of ' . $data['hu_lmt'];
@@ -929,12 +931,12 @@ elseif($mode == 'signup')
$count = array('dr'=>'0','hu'=>'0','ma'=>'0','pa'=>'0','pr'=>'0','ro'=>'0','sh'=>'0','wk'=>'0','wa'=>'0');
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='0' AND cancel='0'",quote_smart($raid_id));
$result_char = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($char = $db_raid->sql_fetchrow($result_char))
+ while($char = $db_raid->sql_fetchrow($result_char, true))
{
$signup_char_id = scrub_input($char['char_id']);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s", quote_smart($signup_char_id));
$result_count = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $tmp = $db_raid->sql_fetchrow($result_count);
+ $tmp = $db_raid->sql_fetchrow($result_count, true);
switch($tmp['class'])
{
@@ -969,11 +971,11 @@ elseif($mode == 'signup')
}
$sql = sprintf("SELECT dr_lmt,hu_lmt,ma_lmt,pa_lmt,pr_lmt,ro_lmt,sh_lmt,wk_lmt,wa_lmt FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($raid_id));
$result_raid = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $total = $db_raid->sql_fetchrow($result_raid);
+ $total = $db_raid->sql_fetchrow($result_raid, true);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s", quote_smart($char_id));
$result_class = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $class = $db_raid->sql_fetchrow($result_class);
+ $class = $db_raid->sql_fetchrow($result_class, true);
$queue = scrub_input($_POST['queue']);
switch($class['class'])
@@ -1176,7 +1178,7 @@ elseif($mode == 'queue')
// Get Profile ID with Char ID to verify user.
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND char_id=%s", quote_smart($raid_id), quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
$profile_id = $data['profile_id'];
@@ -1189,7 +1191,7 @@ elseif($mode == 'queue')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND char_id=%s", quote_smart($raid_id), quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
//Check for a hacking attempt sending in a URL without clicking a button.
$hackattempt=1;
@@ -1229,7 +1231,7 @@ elseif($mode == 'draft')
// Get Profile ID with Char ID to verify user.
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND char_id=%s", quote_smart($raid_id), quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
// verify user is editing own data
if($user_perm_group['admin'] != 1 && $user_perm_group['RL'] != 1 &&
@@ -1241,11 +1243,11 @@ elseif($mode == 'draft')
$count = array('dr'=>'0','hu'=>'0','ma'=>'0','pa'=>'0','pr'=>'0','ro'=>'0','sh'=>'0','wk'=>'0','wa'=>'0');
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND queue='0' AND cancel='0'",quote_smart($raid_id));
$result_char = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($char = $db_raid->sql_fetchrow($result_char))
+ while($char = $db_raid->sql_fetchrow($result_char, true))
{
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s", quote_smart($char['char_id']));
$result_count = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $tmp = $db_raid->sql_fetchrow($result_count);
+ $tmp = $db_raid->sql_fetchrow($result_count, true);
switch($tmp['class'])
{
@@ -1280,11 +1282,11 @@ elseif($mode == 'draft')
}
$sql = sprintf("SELECT dr_lmt,hu_lmt,ma_lmt,pa_lmt,pr_lmt,ro_lmt,sh_lmt,wk_lmt,wa_lmt FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($raid_id));
$result_raid = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $total = $db_raid->sql_fetchrow($result_raid);
+ $total = $db_raid->sql_fetchrow($result_raid, true);
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s", quote_smart($char_id));
$result_class = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $class = $db_raid->sql_fetchrow($result_class);
+ $class = $db_raid->sql_fetchrow($result_class, true);
$queue=0;
switch($class['class'])
@@ -1329,7 +1331,7 @@ elseif($mode == 'draft')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND char_id=%s", quote_smart($raid_id), quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
//Debug Section
//echo "<br>user_perm_group_admin: " . $user_perm_group['admin'];
@@ -1404,7 +1406,8 @@ elseif($mode == 'cancel')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE raid_id=%s AND char_id=%s", quote_smart($raid_id), quote_smart($char_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
+
if($S_profile_id == $data['profile_id'] || $priv_raids == 1) {
if($data['cancel'] == 0) {
$sql = sprintf("UPDATE " . $phpraid_config['db_prefix'] . "signups set cancel='1',queue='0' WHERE raid_id=%s AND char_id=%s", quote_smart($raid_id), quote_smart($char_id));
@@ -1434,7 +1437,7 @@ else if($mode == 'edit_comment')
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "signups WHERE signup_id=%s", quote_smart($signup_id));
$result = $db_raid->sql_query($sql) or print_error($sql,mysql_error(),1);
- $data = $db_raid->sql_fetchrow($result);
+ $data = $db_raid->sql_fetchrow($result, true);
// verify user
if($S_profile_id != $data['profile_id'] AND
@@ -1490,7 +1493,7 @@ if($show_signup == 1 && $priv_profile == 1)
// setup min/max levels
$sql = sprintf("SELECT min_lvl,max_lvl FROM " . $phpraid_config['db_prefix'] . "raids WHERE raid_id=%s", quote_smart($raid_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $limit = $db_raid->sql_fetchrow($result);
+ $limit = $db_raid->sql_fetchrow($result, true);
$signup_action = 'view.php?mode=signup&raid_id=' . $raid_id;
@@ -1501,11 +1504,11 @@ if($show_signup == 1 && $priv_profile == 1)
$character = '<select name="character" class="post">';
$sql = sprintf("SELECT * FROM " . $phpraid_config['db_prefix'] . "chars WHERE profile_id=%s", quote_smart($profile_id));
$result = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- while($data = $db_raid->sql_fetchrow($result))
+ while($data = $db_raid->sql_fetchrow($result, true))
{
$sql = sprintf("SELECT lvl FROM " . $phpraid_config['db_prefix'] . "chars WHERE char_id=%s", quote_smart($data['char_id']));
$result_lvl = $db_raid->sql_query($sql) or print_error($sql, mysql_error(), 1);
- $lvl = $db_raid->sql_fetchrow($result_lvl);
+ $lvl = $db_raid->sql_fetchrow($result_lvl, true);
if($lvl['lvl'] >= $limit['min_lvl'] && $lvl['lvl'] <= $limit['max_lvl'])
$character .= '<option value="' . $data['char_id'] . '">' . $data['name'] . '</option>';
| 0 | 1 |
CVE-2008-7050
|
The password_check function in auth/auth_phpbb3.php in WoW Raid Manager 3.5.1 before Patch 1, when using PHPBB3 authentication, (1) does not invoke the CheckPassword function with the required arguments, which always triggers an authentication failure, and (2) returns true instead of false when an authentication failure occurs, which allows remote attackers to bypass authentication and gain privileges with an arbitrary password.
|
Illydth/wowraidmanager
|
48e6e105c87618f8de5f5123b98f3ef6adf2c11e
|
Bug 0000055: Fix for UTF8 in Username failing phpbb3 auth.
Added utf8_decode() (Thanks Muffin) to the input value from the login page.
This forces the login information into UTF8 format and allows the
information to be properly used to pull info from the database.
|
commit 48e6e105c87618f8de5f5123b98f3ef6adf2c11e
Author: Douglas Wagner <[email protected]>
Date: Mon Sep 8 15:47:43 2008 -0500
Bug 0000055: Fix for UTF8 in Username failing phpbb3 auth.
Added utf8_decode() (Thanks Muffin) to the input value from the login page.
This forces the login information into UTF8 format and allows the
information to be properly used to pull info from the database.
diff --git a/auth/auth_phpbb3.php b/auth/auth_phpbb3.php
index 3ff5d4a..e0396ba 100644
--- a/auth/auth_phpbb3.php
+++ b/auth/auth_phpbb3.php
@@ -91,7 +91,7 @@ function phpraid_login() {
//$pwd_hasher = new PasswordHash(8, FALSE);
if(isset($_POST['username'])){
- $username = scrub_input(strtolower($_POST['username']));
+ $username = scrub_input(strtolower(utf8_decode($_POST['username'])));
//pwd hash
//$password = $pwd_hasher->HashPassword($_POST['password']);
$password = md5($_POST['password']);
diff --git a/configuration.php b/configuration.php
old mode 100755
new mode 100644
| 0 | 2 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
cb729625ae2d5eff54a162e9a9c2c4f78ef83dd2
|
Use native `String.prototype.trim` in `String.prototype.trim` when available. (kangax)
|
commit cb729625ae2d5eff54a162e9a9c2c4f78ef83dd2
Author: Juriy Zaytsev <[email protected]>
Date: Thu May 7 15:33:13 2009 -0400
Use native `String.prototype.trim` in `String.prototype.trim` when available. (kangax)
diff --git a/src/lang/string.js b/src/lang/string.js
index 6d715c1..2798bcc 100644
--- a/src/lang/string.js
+++ b/src/lang/string.js
@@ -407,7 +407,9 @@ Object.extend(String.prototype, (function() {
sub: sub,
scan: scan,
truncate: truncate,
- strip: strip,
+ // Firefox 3.5+ supports String.prototype.trim
+ // (`trim` is ~ 5x faster than `strip` in FF3.5)
+ strip: String.prototype.trim ? String.prototype.trim : strip,
stripTags: stripTags,
stripScripts: stripScripts,
extractScripts: extractScripts,
| 0 | 5 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
86407790d238f74cb4e6858998f467e39d20e846
|
Fix issue where certain versions of Safari treat class names
case-insensitively in Selector/7390 queries. [#390 state:resolved]
|
commit 86407790d238f74cb4e6858998f467e39d20e846
Author: Tobie Langel <[email protected]>
Date: Thu Dec 11 12:07:23 2008 +0100
Fix issue where certain versions of Safari treat class names
case-insensitively in Selector/7390 queries. [#390 state:resolved]
diff --git a/CHANGELOG b/CHANGELOG
index adb377e..fa101e6 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,5 @@
+* Fix issue where certain versions of Safari treat class names case-insensitively in Selector/$$ queries. (Andrew Dupont, kangax, Brice)
+
* Fix issue where Function#argumentNames returned incorrect results in IE when comments were intermixed with argument names. (Christophe Porteneuve, T.J. Crowder)
* Selector.patterns should be represented as an ordered structure. (ADO, kangax)
diff --git a/src/dom/selector.js b/src/dom/selector.js
index 1561b39..11486c7 100644
--- a/src/dom/selector.js
+++ b/src/dom/selector.js
@@ -38,6 +38,8 @@ var Selector = Class.create({
shouldUseSelectorsAPI: function() {
if (!Prototype.BrowserFeatures.SelectorsAPI) return false;
+
+ if (Selector.CASE_INSENSITIVE_CLASS_NAMES) return false;
if (!Selector._div) Selector._div = new Element('div');
@@ -180,6 +182,24 @@ var Selector = Class.create({
}
});
+if (Prototype.BrowserFeatures.SelectorsAPI &&
+ document.compatMode === 'BackCompat') {
+ // Versions of Safari 3 before 3.1.2 treat class names case-insensitively in
+ // quirks mode. If we detect this behavior, we should use a different
+ // approach.
+ Selector.CASE_INSENSITIVE_CLASS_NAMES = (function(){
+ var div = document.createElement('div'),
+ span = document.createElement('span');
+
+ div.id = "prototype_test_id";
+ span.className = 'Test';
+ div.appendChild(span);
+ var isIgnored = (div.querySelector('#prototype_test_id .test') !== null);
+ div = span = null;
+ return isIgnored;
+ })();
+}
+
Object.extend(Selector, {
_cache: { },
| 0 | 6 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
29cd62ebeb41b2ca528f1b6eae83e3ad5144010e
|
prototype: Temporary workaround for Prototype.BrowserFeatures.SpecificElementExtensions incorrectly evaluating to true on iPhone.
|
commit 29cd62ebeb41b2ca528f1b6eae83e3ad5144010e
Author: Sam Stephenson <[email protected]>
Date: Sat Jun 30 16:38:18 2007 +0000
prototype: Temporary workaround for Prototype.BrowserFeatures.SpecificElementExtensions incorrectly evaluating to true on iPhone.
diff --git a/CHANGELOG b/CHANGELOG
index 972d389..1f0d6ff 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Temporary workaround for Prototype.BrowserFeatures.SpecificElementExtensions incorrectly evaluating to true on iPhone. (needs further investigation) [sam]
+
* The action for Form#request defaults to the current URL if the "action" attribute is empty. (This is what most of the major browsers do.) Fixes #8483. [Tomas, Mislav Marohnić]
* In form serialization, change the way submit buttons are handled. Previously all submit buttons were serialized; now Prototype serializes only the first one. Change Form#serialize and Form.serializeElements to accept a params hash. With the "hash: false" option, a serialized string is returned instead of the hash data object. With the "submit: 'foo'" option, only the submit button with the name "foo" is serialized. References #5031. [Mislav Marohnić]
diff --git a/src/prototype.js b/src/prototype.js
index 6e86083..9ff3816 100644
--- a/src/prototype.js
+++ b/src/prototype.js
@@ -14,6 +14,7 @@ var Prototype = {
XPath: !!document.evaluate,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
+ navigator.userAgent.indexOf('iPhone') == -1 &&
(document.createElement('div').__proto__ !==
document.createElement('form').__proto__)
},
| 0 | 7 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
769ae42fcc7f32b6e4726b26a1ae5f2fd2b560a5
|
prototype: Ensure that an Ajax.Request's parameters option can be a Hash. Closes #10172.
|
commit 769ae42fcc7f32b6e4726b26a1ae5f2fd2b560a5
Author: Sam Stephenson <[email protected]>
Date: Thu Nov 29 00:24:54 2007 +0000
prototype: Ensure that an Ajax.Request's parameters option can be a Hash. Closes #10172.
diff --git a/CHANGELOG b/CHANGELOG
index cb7fe5e..a88b262 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,7 @@
+*SVN*
+
+* Ensure that an Ajax.Request's parameters option can be a Hash. Closes #10172. [kangax, sam]
+
* Ensure no comment nodes are returned in Selector queries (IE improperly returns comment nodes on getElementsByTagName("*")). Change Element#descendants to use Element#getElementsBySelector in order to avoid this issue. Closes #10220. [Jeff Gobel, Andrew Dupont]
* Re-enable the XPath approach in Selector for Safari 3. Falls back to the non-XPath version when it sees a problematic token. [Andrew Dupont]
diff --git a/src/ajax.js b/src/ajax.js
index 0ecec59..dc1aa99 100644
--- a/src/ajax.js
+++ b/src/ajax.js
@@ -58,8 +58,11 @@ Ajax.Base = Class.create({
Object.extend(this.options, options || { });
this.options.method = this.options.method.toLowerCase();
+
if (Object.isString(this.options.parameters))
this.options.parameters = this.options.parameters.toQueryParams();
+ else if (Object.isHash(this.options.parameters))
+ this.options.parameters = this.options.parameters.toObject();
}
});
diff --git a/test/unit/ajax.html b/test/unit/ajax.html
index 0de88a0..7cf836f 100644
--- a/test/unit/ajax.html
+++ b/test/unit/ajax.html
@@ -389,7 +389,22 @@
parameters: { 'X-TEST': 'some value' },
onComplete: function(transport) {
assertEqual('some value', transport.getHeader('X-Test'));
- assertNull(null, transport.getHeader('X-Inexistant'));
+ assertNull(transport.getHeader('X-Inexistant'));
+ }
+ }));
+ } else {
+ info(message);
+ }
+ }},
+
+ testParametersCanBeHash: function() {with(this) {
+ if (isRunningFromRake) {
+ new Ajax.Request("/response", extendDefault({
+ parameters: $H({ "one": "two", "three": "four" }),
+ onComplete: function(transport) {
+ assertEqual("two", transport.getHeader("one"));
+ assertEqual("four", transport.getHeader("three"));
+ assertNull(transport.getHeader("toObject"));
}
}));
} else {
| 0 | 8 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
4174060d5bd3721089ea9b949da9f2ea667c67a7
|
prototype: Don't call evalResponse() when an Ajax response has no Content-type header. Closes #7827.
|
commit 4174060d5bd3721089ea9b949da9f2ea667c67a7
Author: Sam Stephenson <[email protected]>
Date: Tue Apr 24 03:34:30 2007 +0000
prototype: Don't call evalResponse() when an Ajax response has no Content-type header. Closes #7827.
diff --git a/CHANGELOG b/CHANGELOG
index 69dfe48..0c3a831 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Don't call evalResponse() when an Ajax response has no Content-type header. Closes #7827. [Tobie Langel]
+
* Automatically strip security delimiter comments from JSON strings before evaling them. The default delimiter is '/*-secure- ... */' or you can specify your own with the Prototype.JSONFilter regular expression. If you wrap your JSON response bodies in this delimiter on the server side, rogue external sites can't hijack potentially sensitive data via <script> tags. Closes #7910. [Tobie Langel]
For more details on potential security problems, see: http://www.fortifysoftware.com/servlet/downloads/public/JavaScript_Hijacking.pdf
diff --git a/src/ajax.js b/src/ajax.js
index 7bcf479..5d4cfe4 100644
--- a/src/ajax.js
+++ b/src/ajax.js
@@ -185,7 +185,8 @@ Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
this.dispatchException(e);
}
- if ((this.getHeader('Content-type') || 'text/javascript').strip().
+ var contentType = this.getHeader('Content-type');
+ if (contentType && contentType.strip().
match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
this.evalResponse();
}
| 0 | 4 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
29c0de6937d84593c89aa6f77d23dd69480fe909
|
prototype: Make submitting forms work in Opera < 9.1.
|
commit 29c0de6937d84593c89aa6f77d23dd69480fe909
Author: Tobie Langel <[email protected]>
Date: Thu Oct 18 15:46:30 2007 +0000
prototype: Make submitting forms work in Opera < 9.1.
diff --git a/CHANGELOG b/CHANGELOG
index 59b8f25..5867df3 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Make submitting forms work in Opera < 9.1. Closes #9917, #9463, #8260. [kangax]
+
* Fix template evaluation with empty replacements. Closes #9692. [Ryan McGeary]
* Hash#toTemplateReplacements is an alias for Hash#toObject so you can once again pass hashes to Template#evaluate and String#interpolate. [sam]
diff --git a/src/prototype.js b/src/prototype.js
index 6ba0413..e4bb823 100644
--- a/src/prototype.js
+++ b/src/prototype.js
@@ -15,6 +15,7 @@ var Prototype = {
XPath: !!document.evaluate,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
+ document.createElement('div').__proto__ &&
document.createElement('div').__proto__ !==
document.createElement('form').__proto__
},
| 0 | 3 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
704aa4033010059402336437f7fe6498ce780be0
|
Stop appending `&_=` to the parameters for non-GET Ajax requests in Safari. We no longer support any version of Safari for which this is necessary. [#327 state:resolved] (John-David Dalton, Andrew Dupont)
|
commit 704aa4033010059402336437f7fe6498ce780be0
Author: Andrew Dupont <[email protected]>
Date: Mon Oct 18 20:55:06 2010 -0500
Stop appending `&_=` to the parameters for non-GET Ajax requests in Safari. We no longer support any version of Safari for which this is necessary. [#327 state:resolved] (John-David Dalton, Andrew Dupont)
diff --git a/CHANGELOG b/CHANGELOG
index df8c4f5..314b86d 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,5 @@
+* Stop appending `&_=` to the parameters for non-GET Ajax requests in Safari. We no longer support any version of Safari for which this is necessary. [#327 state:resolved] (John-David Dalton, Andrew Dupont)
+
* Ensure `Form.focusFirstElement` doesn't raise an exception on forms with no fields. [#341 state:resolved] (achernin, Andrew Dupont)
* Define a `relatedTarget` property on extended mouseenter/mouseleave events in IE's legacy event system. [#708 state:resolved] (Walter Smith, Tobie Langel, Andrew Dupont)
diff --git a/src/ajax/request.js b/src/ajax/request.js
index a1c5f7a..82d504f 100644
--- a/src/ajax/request.js
+++ b/src/ajax/request.js
@@ -189,12 +189,9 @@ Ajax.Request = Class.create(Ajax.Base, {
this.method = 'post';
}
- if (params) {
+ if (params && this.method === 'get') {
// when GET, append parameters to URL
- if (this.method == 'get')
- this.url += (this.url.include('?') ? '&' : '?') + params;
- else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
- params += '&_=';
+ this.url += (this.url.include('?') ? '&' : '?') + params;
}
this.parameters = params.toQueryParams();
| 0 | 9 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
23823048d13e1d70bee26908760381e943f7e483
|
prototype: Prevent memory leaks in Ajax.PeriodicalUpdater. Closes #10049
|
commit 23823048d13e1d70bee26908760381e943f7e483
Author: Tobie Langel <[email protected]>
Date: Thu Nov 15 23:14:36 2007 +0000
prototype: Prevent memory leaks in Ajax.PeriodicalUpdater. Closes #10049
diff --git a/CHANGELOG b/CHANGELOG
index c3fd9ee..bac2d0c 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,5 @@
+* Make Ajax.Updater clone its options hash before modifying it. Prevents memory leaks in Ajax.PeriodicalUpdater. Closes #10049 [Mislav Marohnić, Tobie Langel].
+
* Remove useless variable in Selector.handlers.child. Closes #10006 [kuriyama]
* Don't redeclare previously declared variables. Closes #10007 [kuriyama]
diff --git a/src/ajax.js b/src/ajax.js
index d7790b0..0ecec59 100644
--- a/src/ajax.js
+++ b/src/ajax.js
@@ -306,11 +306,11 @@ Ajax.Updater = Class.create(Ajax.Request, {
failure: (container.failure || (container.success ? null : container))
};
- options = options || { };
+ options = Object.clone(options);
var onComplete = options.onComplete;
- options.onComplete = (function(response, param) {
+ options.onComplete = (function(response, json) {
this.updateContent(response.responseText);
- if (Object.isFunction(onComplete)) onComplete(response, param);
+ if (Object.isFunction(onComplete)) onComplete(response, json);
}).bind(this);
$super(url, options);
@@ -332,10 +332,6 @@ Ajax.Updater = Class.create(Ajax.Request, {
}
else receiver.update(responseText);
}
-
- if (this.success()) {
- if (this.onComplete) this.onComplete.bind(this).defer();
- }
}
});
diff --git a/test/unit/ajax.html b/test/unit/ajax.html
index 7e7e98e..0de88a0 100644
--- a/test/unit/ajax.html
+++ b/test/unit/ajax.html
@@ -161,7 +161,19 @@
});
});
}},
-
+
+ testUpdaterOptions: function() {with(this) {
+ var options = {
+ method: 'get',
+ asynchronous: false,
+ evalJS: 'force',
+ onComplete: Prototype.emptyFunction
+ }
+ var request = new Ajax.Updater("content", "fixtures/hello.js", options);
+ request.options.onComplete = function() {};
+ assertIdentical(Prototype.emptyFunction, options.onComplete);
+ }},
+
testResponders: function(){with(this) {
// check for internal responder
assertEqual(1, Ajax.Responders.responders.length);
| 0 | 2 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
484287d1de3b66933a5e159bcfd6dff0be9e4d6f
|
Ensure Ajax.activeRequestCount decrements even if an exception is thrown in an `onComplete` callback. (close #324)
|
commit 484287d1de3b66933a5e159bcfd6dff0be9e4d6f
Author: Andrew Dupont <[email protected]>
Date: Sat Apr 8 16:48:06 2017 -0500
Ensure Ajax.activeRequestCount decrements even if an exception is thrown in an `onComplete` callback. (close #324)
diff --git a/src/prototype/ajax/request.js b/src/prototype/ajax/request.js
index 9bcd689..da2f387 100644
--- a/src/prototype/ajax/request.js
+++ b/src/prototype/ajax/request.js
@@ -10,7 +10,7 @@
* In the optional `options` hash, you usually provide an `onComplete` and/or
* `onSuccess` callback, unless you're in the edge case where you're getting a
* JavaScript-typed response, that will automatically be `eval`'d.
- *
+ *
* For a full list of common options and callbacks, see "Ajax options" heading
* of the [[Ajax section]].
*
@@ -23,20 +23,20 @@
* });
*
* ##### Request life-cycle
- *
+ *
* Underneath our nice requester objects lies, of course, `XMLHttpRequest`. The
* defined life-cycle is as follows:
- *
+ *
* 1. Created
* 2. Initialized
* 3. Request sent
* 4. Response being received (can occur many times, as packets come in)
* 5. Response received, request complete
- *
+ *
* As you can see under the "Ajax options" heading of the [[Ajax section]],
* Prototype's AJAX objects define a whole slew of callbacks, which are
* triggered in the following order:
- *
+ *
* 1. `onCreate` (this is actually a callback reserved to [[Ajax.Responders]])
* 2. `onUninitialized` (maps on Created)
* 3. `onLoading` (maps on Initialized)
@@ -44,28 +44,28 @@
* 5. `onInteractive` (maps on Response being received)
* 6. `on`*XYZ* (numerical response status code), onSuccess or onFailure (see below)
* 7. `onComplete`
- *
+ *
* The two last steps both map on *Response received*, in that order. If a
* status-specific callback is defined, it gets invoked. Otherwise, if
* `onSuccess` is defined and the response is deemed a success (see below), it
* is invoked. Otherwise, if `onFailure` is defined and the response is *not*
* deemed a success, it is invoked. Only after that potential first callback is
* `onComplete` called.
- *
+ *
* ##### A note on portability
- *
+ *
* Depending on how your browser implements `XMLHttpRequest`, one or more
* callbacks may never be invoked. In particular, `onLoaded` and
* `onInteractive` are not a 100% safe bet so far. However, the global
* `onCreate`, `onUninitialized` and the two final steps are very much
* guaranteed.
- *
+ *
* ##### `onSuccess` and `onFailure`, the under-used callbacks
- *
+ *
* Way too many people use [[Ajax.Request]] in a similar manner to raw XHR,
* defining only an `onComplete` callback even when they're only interested in
* "successful" responses, thereby testing it by hand:
- *
+ *
* // This is too bad, there's better!
* new Ajax.Request('/your/url', {
* onComplete: function(response) {
@@ -73,21 +73,21 @@
* // yada yada yada
* }
* });
- *
+ *
* First, as described below, you could use better "success" detection: success
* is generally defined, HTTP-wise, as either no response status or a "2xy"
* response status (e.g., 201 is a success, too). See the example below.
- *
+ *
* Second, you could dispense with status testing altogether! Prototype adds
* callbacks specific to success and failure, which we listed above. Here's
* what you could do if you're only interested in success, for instance:
- *
+ *
* new Ajax.Request('/your/url', {
* onSuccess: function(response) {
* // yada yada yada
* }
* });
- *
+ *
* ##### Automatic JavaScript response evaluation
*
* If an Ajax request follows the _same-origin policy_ **and** its response
@@ -305,9 +305,10 @@ Ajax.Request = Class.create(Ajax.Base, {
try {
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
- Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
+ } finally {
+ Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
}
if (state == 'Complete') {
diff --git a/test/unit/tests/ajax.test.js b/test/unit/tests/ajax.test.js
index caca3ee..bacf9e6 100644
--- a/test/unit/tests/ajax.test.js
+++ b/test/unit/tests/ajax.test.js
@@ -104,6 +104,23 @@ suite("Ajax", function () {
}, 1000);
});
+ test("activeRequestCount decrements when an exception occurs in a handler", function (done) {
+
+ new Ajax.Request('/fixtures/hello.js', {
+ method: 'GET',
+ onComplete: function () {
+ assert.equal(1, Ajax.activeRequestCount);
+ throw new Error('test');
+ }
+ });
+
+ setTimeout(function () {
+ assert.equal(0, Ajax.activeRequestCount);
+ done();
+ }, 1000);
+
+ });
+
suite('Updater', function () {
setup(function () {
| 0 | 10 |
CVE-2008-7220
|
Unspecified vulnerability in Prototype JavaScript framework (prototypejs) before 1.6.0.2 allows attackers to make "cross-site ajax requests" via unknown vectors.
|
sstephenson/prototype
|
02cc9992e915c024650ddc77a91064f7a4252914
|
prototype: Prevent a potential security issue for cross-site ajax requests.
|
commit 02cc9992e915c024650ddc77a91064f7a4252914
Author: Tobie Langel <[email protected]>
Date: Wed Jan 23 00:51:25 2008 +0000
prototype: Prevent a potential security issue for cross-site ajax requests.
diff --git a/CHANGELOG b/CHANGELOG
index 37ac38e..cd5bdb2 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Prevent a potential security issue for cross-site ajax requests. [Alexey Feldgendler, sam, Tobie Langel]
+
* Test for attribute existence before applying more complex CSS3 selectors. Closes #10870. [arty, Tobie Langel]
* Fix "function $A" declaration inside of a conditional (confuses IE). Closes #10882. [Jacco, Andrew Dupont]
diff --git a/src/ajax.js b/src/ajax.js
index e576a1e..a1abed6 100644
--- a/src/ajax.js
+++ b/src/ajax.js
@@ -189,7 +189,7 @@ Ajax.Request = Class.create(Ajax.Base, {
var contentType = response.getHeader('Content-type');
if (this.options.evalJS == 'force'
- || (this.options.evalJS && contentType
+ || (this.options.evalJS && this.isSameOrigin() && contentType
&& contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
this.evalResponse();
}
@@ -207,6 +207,15 @@ Ajax.Request = Class.create(Ajax.Base, {
}
},
+ isSameOrigin: function() {
+ var m = this.url.match(/^\s*https?:\/\/[^/]*/);
+ return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
+ protocol: location.protocol,
+ domain: document.domain,
+ port: location.port ? ':' + location.port : ''
+ }));
+ },
+
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name) || null;
@@ -282,7 +291,8 @@ Ajax.Response = Class.create({
if (!json) return null;
json = decodeURIComponent(escape(json));
try {
- return json.evalJSON(this.request.options.sanitizeJSON);
+ return json.evalJSON(this.request.options.sanitizeJSON ||
+ !this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
@@ -295,7 +305,8 @@ Ajax.Response = Class.create({
this.responseText.blank())
return null;
try {
- return this.responseText.evalJSON(options.sanitizeJSON);
+ return this.responseText.evalJSON(options.sanitizeJSON ||
+ !this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
diff --git a/test/unit/ajax.html b/test/unit/ajax.html
index 1d533ad..3744d34 100644
--- a/test/unit/ajax.html
+++ b/test/unit/ajax.html
@@ -410,6 +410,45 @@
} else {
info(message);
}
+ }},
+
+ testIsSameOriginMethod: function() {with(this) {
+ var isSameOrigin = Ajax.Request.prototype.isSameOrigin;
+ assert(isSameOrigin.call({ url: '/foo/bar.html' }), '/foo/bar.html');
+ assert(isSameOrigin.call({ url: window.location.toString() }), window.location);
+ assert(!isSameOrigin.call({ url: 'http://example.com' }), 'http://example.com');
+
+ if (isRunningFromRake) {
+ Ajax.Request.prototype.isSameOrigin = function() {
+ return false
+ };
+
+ $("content").update('same origin policy');
+ new Ajax.Request("/response", extendDefault({
+ parameters: Fixtures.js,
+ onComplete: function(transport) {
+ assertEqual("same origin policy", $("content").innerHTML);
+ }
+ }));
+
+ new Ajax.Request("/response", extendDefault({
+ parameters: Fixtures.invalidJson,
+ onException: function(request, error) {
+ assert(error.message.include('Badly formed JSON string'));
+ }
+ }));
+
+ new Ajax.Request("/response", extendDefault({
+ parameters: { 'X-JSON': '{});window.attacked = true;({}' },
+ onException: function(request, error) {
+ assert(error.message.include('Badly formed JSON string'));
+ }
+ }));
+
+ Ajax.Request.prototype.isSameOrigin = isSameOrigin;
+ } else {
+ info(message);
+ }
}}
});
// ]]>
| 1 | 1 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
7e0e0a79d54e6bcd80ef3794eaf10de8bf579c56
|
=== Released 1.15.1 ===
2006-12-04 Behdad Esfahbod <[email protected]>
* === Released 1.15.1 ===
* configure.in: Version 1.15.1
* NEWS: Updated.
|
commit 7e0e0a79d54e6bcd80ef3794eaf10de8bf579c56
Author: Behdad Esfahbod <[email protected]>
Date: Tue Dec 5 00:23:25 2006 +0000
=== Released 1.15.1 ===
2006-12-04 Behdad Esfahbod <[email protected]>
* === Released 1.15.1 ===
* configure.in: Version 1.15.1
* NEWS: Updated.
diff --git a/ChangeLog b/ChangeLog
index 993a7ead..6023c25f 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,11 @@
+2006-12-04 Behdad Esfahbod <[email protected]>
+
+ * === Released 1.15.1 ===
+
+ * configure.in: Version 1.15.1
+
+ * NEWS: Updated.
+
2006-12-04 Behdad Esfahbod <[email protected]>
Bug 135683 – Cache glyphstring extents
diff --git a/NEWS b/NEWS
index 522abd40..59a1c867 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,57 @@
+Overview of changes between 1.15.0 and 1.15.1
+==============================================
+* Add Thai langauage engine. (currently makes tests/testboundary fail.)
+* Add Lao and improved Thai sample text.
+* Improved Indic module.
+* Output correct path for hexboxes in pango_cairo_layout_path().
+* Implement get_resolution method for the FT2 fontmap. Shouldn't make
+ any difference whatsoever. Open a bug if it does.
+* Misc small fixes.
+
+* Optimizations:
+ - Rework PangoLayout algorithms to avoid calling a recursive call to
+ pango_layout_get_extents(). Avoids one pango_font_get_glyph_extents()
+ call per glyph per layout rendering. We now make 2 such calls.
+ - Don't cache run_logical_rect in PangoLayoutIter.
+ Avoids one pango_font_get_glyph_extents() call per glyph per layout
+ rendering. We are down to 1 now.
+ - Cache line extents. This avoids the final pango_font_get_glyph_extents()
+ call per glyph per layout rendering. Now we don't make any
+ pango_font_get_glyph_extents() calls when rendering a layout (some
+ conditions apply)!
+ - Replace PANGO_IS_RENDERER with PANGO_IS_RENDERER_FAST for most
+ internal uses, that is, just a NULL-check.
+ - Use simple, fast, casts instead of PANGO_CAIRO_*() macros where the
+ object cannot have reached us if it wasn't of the right type.
+
+* Bugs fixed in this release:
+ Bug 135683 – Cache glyphstring extents
+ Red Hat Bug 211964: [ta] Rendering issue with Tamil
+ Patch from LingNing Zhang
+ Red Hat Bug 213632: ZWJ (200d) and ZWNJ (200c) showing same output
+ Patch from LingNing Zhang
+ Bug 371388 – Add Thai langauage engine
+ Patch from Theppitak Karoonboonyanan
+ Bug 377975 – bug in _pango_glyph_item_iter_next_cluster
+ Bug 369670 – Checked g_free calls
+
+Changes that also appeared between 1.14.7 and 1.14.8
+=====================================================
+* Improved thread-safety. Pango is still NOT thread-safe, but this fixes
+ lots of crashes using pangocairo from multiple threads.
+* Fix out-of-bounds array access.
+* Improved Indic shaper.
+* Improved Arabic language engine.
+* Choose shaper/font for unassigned Unicode codepoints.
+* Build fixes.
+* Bugs fixed in this release:
+ Bug 356666 – pango is not thread-safe, nautilus does not honour that
+ Bug 352795 – configure.in: Bug in "checking Whether to write
+ dependencies into .pc files"
+ Bug 350132 – backspacing doesn't work properly for Arabic
+ Bug 330407 – Multiple dependant vowel signs (indic) displayed as one
+ Patch from LingNing Zhang
+
Overview of changes between 1.14.7 and 1.15.0
==============================================
* Add basic support for vertical text. (PangoGravity and related API)
diff --git a/configure.in b/configure.in
index 114c0191..cf27638f 100644
--- a/configure.in
+++ b/configure.in
@@ -22,13 +22,13 @@ dnl
dnl The triplet
m4_define([pango_major_version], [1])
m4_define([pango_minor_version], [15])
-m4_define([pango_micro_version], [0])
+m4_define([pango_micro_version], [1])
m4_define([pango_version],
[pango_major_version.pango_minor_version.pango_micro_version])
dnl The X.Y in -lpango-X.Y line. This is expected to stay 1.0 until Pango 2.
m4_define([pango_api_version], [1.0])
dnl Number of releases since we've added interfaces
-m4_define([pango_interface_age], [0])
+m4_define([pango_interface_age], [1])
dnl Number of releases since we've broken binary compatibility.
m4_define([pango_binary_age],
[m4_eval(100 * pango_minor_version + pango_micro_version)])
| 0 | 6 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
58359bf5d1fcfb54a160992df44dd897854f5bdd
|
Find shaper/font for Private Use and space characters too. Finding shaper
2006-08-22 Behdad Esfahbod <[email protected]>
* pango/pango-context.c (itemize_state_process_run): Find shaper/font
for Private Use and space characters too. Finding shaper for Private
Use is needed for any practical use of those areas. Ideally, spaces
should be synthesized if they are not available in the font, but
falling back to other fonts is far easier, and should give pretty good
results with the current set of common fonts. These fixes allow
Firefox+Pango to render MathML like Firefox+Xft does.
|
commit 58359bf5d1fcfb54a160992df44dd897854f5bdd
Author: Behdad Esfahbod <[email protected]>
Date: Tue Aug 22 23:12:28 2006 +0000
Find shaper/font for Private Use and space characters too. Finding shaper
2006-08-22 Behdad Esfahbod <[email protected]>
* pango/pango-context.c (itemize_state_process_run): Find shaper/font
for Private Use and space characters too. Finding shaper for Private
Use is needed for any practical use of those areas. Ideally, spaces
should be synthesized if they are not available in the font, but
falling back to other fonts is far easier, and should give pretty good
results with the current set of common fonts. These fixes allow
Firefox+Pango to render MathML like Firefox+Xft does.
diff --git a/ChangeLog b/ChangeLog
index eb71b5f6..f905f2c3 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,13 @@
+2006-08-22 Behdad Esfahbod <[email protected]>
+
+ * pango/pango-context.c (itemize_state_process_run): Find shaper/font
+ for Private Use and space characters too. Finding shaper for Private
+ Use is needed for any practical use of those areas. Ideally, spaces
+ should be synthesized if they are not available in the font, but
+ falling back to other fonts is far easier, and should give pretty good
+ results with the current set of common fonts. These fixes allow
+ Firefox+Pango to render MathML like Firefox+Xft does.
+
2006-08-22 Behdad Esfahbod <[email protected]>
* pango/fonts.c (gravity_map): Rename "Upright" to "Not-Rotated".
diff --git a/pango/pango-context.c b/pango/pango-context.c
index 6044dafc..0d8c3def 100644
--- a/pango/pango-context.c
+++ b/pango/pango-context.c
@@ -1257,17 +1257,19 @@ itemize_state_process_run (ItemizeState *state)
/* We don't want space characters to affect font selection; in general,
* it's always wrong to select a font just to render a space.
- * To make this really work well, we'd need to emulate missing
- * space characters, which we don't yet do, so we sometimes
- * will get hex boxes.
*
* The exception of U+3000 (IDEOGRAPHIC SPACE) here is because we
* want to choose an ideographic space that matches ideographic text
* in cell width. Even if we were emulating missing spaces, an
* emulated ideographic space for the primary font wouldn't be the
* right size.
+ *
+ * The exception of PrivateUse characters is indeed necessary to be
+ * able to render any of them.
*/
- if (!g_unichar_isgraph (wc) && wc != 0x3000)
+ if (G_UNLIKELY (!g_unichar_isgraph (wc) &&
+ !g_unichar_isspace (wc) /*wc != 0x3000*/ &&
+ g_unichar_type (wc) != G_UNICODE_PRIVATE_USE))
{
shape_engine = NULL;
font = NULL;
| 0 | 9 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
55bdaf842fb6cf02eae9bbbb1a6e48bfbed021cf
|
Fix the "menu accels are two chars wide" bug that was introduced by the
2007-01-22 Behdad Esfahbod <[email protected]>
* pango/pango-glyph-item.c (_pango_glyph_item_iter_next_cluster):
Fix the "menu accels are two chars wide" bug that was introduced
by the recent changes in this function, in 1.15.4. Apparently
glyph_index means separate things in next_cluster and prev_cluster.
svn path=/trunk/; revision=2179
|
commit 55bdaf842fb6cf02eae9bbbb1a6e48bfbed021cf
Author: Behdad Esfahbod <[email protected]>
Date: Tue Jan 23 00:15:32 2007 +0000
Fix the "menu accels are two chars wide" bug that was introduced by the
2007-01-22 Behdad Esfahbod <[email protected]>
* pango/pango-glyph-item.c (_pango_glyph_item_iter_next_cluster):
Fix the "menu accels are two chars wide" bug that was introduced
by the recent changes in this function, in 1.15.4. Apparently
glyph_index means separate things in next_cluster and prev_cluster.
svn path=/trunk/; revision=2179
diff --git a/ChangeLog b/ChangeLog
index 7a83833c..0557eaa1 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,10 @@
+2007-01-22 Behdad Esfahbod <[email protected]>
+
+ * pango/pango-glyph-item.c (_pango_glyph_item_iter_next_cluster):
+ Fix the "menu accels are two chars wide" bug that was introduced
+ by the recent changes in this function, in 1.15.4. Apparently
+ glyph_index means separate things in next_cluster and prev_cluster.
+
2007-01-22 Behdad Esfahbod <[email protected]>
* pango/fonts.c (pango_font_get_metrics): Populate metrics for
diff --git a/pango/pango-glyph-item.c b/pango/pango-glyph-item.c
index 94f07881..6d5c5d98 100644
--- a/pango/pango-glyph-item.c
+++ b/pango/pango-glyph-item.c
@@ -182,7 +182,7 @@ _pango_glyph_item_iter_next_cluster (PangoGlyphItemIter *iter)
if (LTR (iter->glyph_item))
{
- cluster = glyphs->log_clusters[glyph_index + 1];
+ cluster = glyphs->log_clusters[glyph_index];
while (TRUE)
{
glyph_index++;
@@ -205,7 +205,7 @@ _pango_glyph_item_iter_next_cluster (PangoGlyphItemIter *iter)
}
else /* RTL */
{
- cluster = glyphs->log_clusters[glyph_index - 1];
+ cluster = glyphs->log_clusters[glyph_index];
while (TRUE)
{
glyph_index--;
| 0 | 7 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
25878a0341a8076296ab4ae88ee972641e6f963c
|
Use complete PANGO_VERSION in zip file names.
2002-05-26 Tor Lillqvist <[email protected]>
* pango-zip.sh.in: Use complete PANGO_VERSION in zip file
names.
* pango/Makefile.am: (Win32) Compile resource files and link with
them.
* pango/pango.rc.in
* pango/pangoft2.rc.in
* pango/pangowin32.rc.in: Include also the micro version number.
* pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
of lfHeight.
* pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
Instead of HORZSIZE which is Windows idea of physical monitor
width (but which can be *very* wrong), use LOGPIXELSY (the
"logical" dpi). This can be set by the user by choosing "small
fonts", "large fonts", or a custom dpi in the Display Settings.
Thanks to Joaquin Cuenca Abela.
(pango_win32_make_matching_logfont): Set lfHeight to the negative
of the requested size. Positive lfHeight indicates "cell height",
negative "character height" (?), which is closer to what we want,
says Joaquin Cuenca Abela.
|
commit 25878a0341a8076296ab4ae88ee972641e6f963c
Author: Tor Lillqvist <[email protected]>
Date: Sun May 26 00:19:10 2002 +0000
Use complete PANGO_VERSION in zip file names.
2002-05-26 Tor Lillqvist <[email protected]>
* pango-zip.sh.in: Use complete PANGO_VERSION in zip file
names.
* pango/Makefile.am: (Win32) Compile resource files and link with
them.
* pango/pango.rc.in
* pango/pangoft2.rc.in
* pango/pangowin32.rc.in: Include also the micro version number.
* pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
of lfHeight.
* pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
Instead of HORZSIZE which is Windows idea of physical monitor
width (but which can be *very* wrong), use LOGPIXELSY (the
"logical" dpi). This can be set by the user by choosing "small
fonts", "large fonts", or a custom dpi in the Display Settings.
Thanks to Joaquin Cuenca Abela.
(pango_win32_make_matching_logfont): Set lfHeight to the negative
of the requested size. Positive lfHeight indicates "cell height",
negative "character height" (?), which is closer to what we want,
says Joaquin Cuenca Abela.
diff --git a/ChangeLog b/ChangeLog
index f0faf305..730bb624 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,30 @@
+2002-05-26 Tor Lillqvist <[email protected]>
+
+ * pango-zip.sh.in: Use complete PANGO_VERSION in zip file
+ names.
+
+ * pango/Makefile.am: (Win32) Compile resource files and link with
+ them.
+
+ * pango/pango.rc.in
+ * pango/pangoft2.rc.in
+ * pango/pangowin32.rc.in: Include also the micro version number.
+
+ * pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
+ of lfHeight.
+
+ * pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
+ Instead of HORZSIZE which is Windows idea of physical monitor
+ width (but which can be *very* wrong), use LOGPIXELSY (the
+ "logical" dpi). This can be set by the user by choosing "small
+ fonts", "large fonts", or a custom dpi in the Display Settings.
+ Thanks to Joaquin Cuenca Abela.
+
+ (pango_win32_make_matching_logfont): Set lfHeight to the negative
+ of the requested size. Positive lfHeight indicates "cell height",
+ negative "character height" (?), which is closer to what we want,
+ says Joaquin Cuenca Abela.
+
Tue May 21 15:27:41 2002 Owen Taylor <[email protected]>
* modules/basic/tables-big.i: Fix C++ comment.
diff --git a/ChangeLog.pre-1-10 b/ChangeLog.pre-1-10
index f0faf305..730bb624 100644
--- a/ChangeLog.pre-1-10
+++ b/ChangeLog.pre-1-10
@@ -1,3 +1,30 @@
+2002-05-26 Tor Lillqvist <[email protected]>
+
+ * pango-zip.sh.in: Use complete PANGO_VERSION in zip file
+ names.
+
+ * pango/Makefile.am: (Win32) Compile resource files and link with
+ them.
+
+ * pango/pango.rc.in
+ * pango/pangoft2.rc.in
+ * pango/pangowin32.rc.in: Include also the micro version number.
+
+ * pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
+ of lfHeight.
+
+ * pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
+ Instead of HORZSIZE which is Windows idea of physical monitor
+ width (but which can be *very* wrong), use LOGPIXELSY (the
+ "logical" dpi). This can be set by the user by choosing "small
+ fonts", "large fonts", or a custom dpi in the Display Settings.
+ Thanks to Joaquin Cuenca Abela.
+
+ (pango_win32_make_matching_logfont): Set lfHeight to the negative
+ of the requested size. Positive lfHeight indicates "cell height",
+ negative "character height" (?), which is closer to what we want,
+ says Joaquin Cuenca Abela.
+
Tue May 21 15:27:41 2002 Owen Taylor <[email protected]>
* modules/basic/tables-big.i: Fix C++ comment.
diff --git a/ChangeLog.pre-1-2 b/ChangeLog.pre-1-2
index f0faf305..730bb624 100644
--- a/ChangeLog.pre-1-2
+++ b/ChangeLog.pre-1-2
@@ -1,3 +1,30 @@
+2002-05-26 Tor Lillqvist <[email protected]>
+
+ * pango-zip.sh.in: Use complete PANGO_VERSION in zip file
+ names.
+
+ * pango/Makefile.am: (Win32) Compile resource files and link with
+ them.
+
+ * pango/pango.rc.in
+ * pango/pangoft2.rc.in
+ * pango/pangowin32.rc.in: Include also the micro version number.
+
+ * pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
+ of lfHeight.
+
+ * pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
+ Instead of HORZSIZE which is Windows idea of physical monitor
+ width (but which can be *very* wrong), use LOGPIXELSY (the
+ "logical" dpi). This can be set by the user by choosing "small
+ fonts", "large fonts", or a custom dpi in the Display Settings.
+ Thanks to Joaquin Cuenca Abela.
+
+ (pango_win32_make_matching_logfont): Set lfHeight to the negative
+ of the requested size. Positive lfHeight indicates "cell height",
+ negative "character height" (?), which is closer to what we want,
+ says Joaquin Cuenca Abela.
+
Tue May 21 15:27:41 2002 Owen Taylor <[email protected]>
* modules/basic/tables-big.i: Fix C++ comment.
diff --git a/ChangeLog.pre-1-4 b/ChangeLog.pre-1-4
index f0faf305..730bb624 100644
--- a/ChangeLog.pre-1-4
+++ b/ChangeLog.pre-1-4
@@ -1,3 +1,30 @@
+2002-05-26 Tor Lillqvist <[email protected]>
+
+ * pango-zip.sh.in: Use complete PANGO_VERSION in zip file
+ names.
+
+ * pango/Makefile.am: (Win32) Compile resource files and link with
+ them.
+
+ * pango/pango.rc.in
+ * pango/pangoft2.rc.in
+ * pango/pangowin32.rc.in: Include also the micro version number.
+
+ * pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
+ of lfHeight.
+
+ * pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
+ Instead of HORZSIZE which is Windows idea of physical monitor
+ width (but which can be *very* wrong), use LOGPIXELSY (the
+ "logical" dpi). This can be set by the user by choosing "small
+ fonts", "large fonts", or a custom dpi in the Display Settings.
+ Thanks to Joaquin Cuenca Abela.
+
+ (pango_win32_make_matching_logfont): Set lfHeight to the negative
+ of the requested size. Positive lfHeight indicates "cell height",
+ negative "character height" (?), which is closer to what we want,
+ says Joaquin Cuenca Abela.
+
Tue May 21 15:27:41 2002 Owen Taylor <[email protected]>
* modules/basic/tables-big.i: Fix C++ comment.
diff --git a/ChangeLog.pre-1-6 b/ChangeLog.pre-1-6
index f0faf305..730bb624 100644
--- a/ChangeLog.pre-1-6
+++ b/ChangeLog.pre-1-6
@@ -1,3 +1,30 @@
+2002-05-26 Tor Lillqvist <[email protected]>
+
+ * pango-zip.sh.in: Use complete PANGO_VERSION in zip file
+ names.
+
+ * pango/Makefile.am: (Win32) Compile resource files and link with
+ them.
+
+ * pango/pango.rc.in
+ * pango/pangoft2.rc.in
+ * pango/pangowin32.rc.in: Include also the micro version number.
+
+ * pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
+ of lfHeight.
+
+ * pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
+ Instead of HORZSIZE which is Windows idea of physical monitor
+ width (but which can be *very* wrong), use LOGPIXELSY (the
+ "logical" dpi). This can be set by the user by choosing "small
+ fonts", "large fonts", or a custom dpi in the Display Settings.
+ Thanks to Joaquin Cuenca Abela.
+
+ (pango_win32_make_matching_logfont): Set lfHeight to the negative
+ of the requested size. Positive lfHeight indicates "cell height",
+ negative "character height" (?), which is closer to what we want,
+ says Joaquin Cuenca Abela.
+
Tue May 21 15:27:41 2002 Owen Taylor <[email protected]>
* modules/basic/tables-big.i: Fix C++ comment.
diff --git a/ChangeLog.pre-1-8 b/ChangeLog.pre-1-8
index f0faf305..730bb624 100644
--- a/ChangeLog.pre-1-8
+++ b/ChangeLog.pre-1-8
@@ -1,3 +1,30 @@
+2002-05-26 Tor Lillqvist <[email protected]>
+
+ * pango-zip.sh.in: Use complete PANGO_VERSION in zip file
+ names.
+
+ * pango/Makefile.am: (Win32) Compile resource files and link with
+ them.
+
+ * pango/pango.rc.in
+ * pango/pangoft2.rc.in
+ * pango/pangowin32.rc.in: Include also the micro version number.
+
+ * pango/pangowin32-fontcache.c (logfont_hash): Use absolute value
+ of lfHeight.
+
+ * pango/pangowin32-fontmap.c (pango_win32_font_map_for_display):
+ Instead of HORZSIZE which is Windows idea of physical monitor
+ width (but which can be *very* wrong), use LOGPIXELSY (the
+ "logical" dpi). This can be set by the user by choosing "small
+ fonts", "large fonts", or a custom dpi in the Display Settings.
+ Thanks to Joaquin Cuenca Abela.
+
+ (pango_win32_make_matching_logfont): Set lfHeight to the negative
+ of the requested size. Positive lfHeight indicates "cell height",
+ negative "character height" (?), which is closer to what we want,
+ says Joaquin Cuenca Abela.
+
Tue May 21 15:27:41 2002 Owen Taylor <[email protected]>
* modules/basic/tables-big.i: Fix C++ comment.
diff --git a/pango-zip.sh.in b/pango-zip.sh.in
index 2b2ecde3..3a6883ae 100755
--- a/pango-zip.sh.in
+++ b/pango-zip.sh.in
@@ -2,8 +2,8 @@
# Build zipfiles for Pango on Win32: separate runtime and developer packages
-ZIP=/tmp/pango-@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@-`date +%Y%m%d`.zip
-DEVZIP=/tmp/pango-dev-@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@-`date +%Y%m%d`.zip
+ZIP=/tmp/pango-@PANGO_VERSION@-`date +%Y%m%d`.zip
+DEVZIP=/tmp/pango-dev-@PANGO_VERSION@-`date +%Y%m%d`.zip
cd @prefix@
rm $ZIP
diff --git a/pango/Makefile.am b/pango/Makefile.am
index 1de42abb..08093ee8 100644
--- a/pango/Makefile.am
+++ b/pango/Makefile.am
@@ -72,6 +72,10 @@ pango_export_symbols = -export-symbols pango.def
pangowin32_export_symbols = -export-symbols pangowin32.def
pangoft2_export_symbols = -export-symbols pangoft2.def
+pango_win32res = pango-win32res.lo
+pangowin32_win32res = pangowin32-win32res.lo
+pangoft2_win32res = pangoft2-win32res.lo
+
install-libtool-import-lib:
$(INSTALL) .libs/libpango-$(PANGO_API_VERSION).dll.a $(DESTDIR)$(libdir)
if HAVE_FREETYPE
@@ -154,14 +158,19 @@ libpango_1_0_la_LDFLAGS = \
$(no_undefined) $(pango_export_symbols)
if HAVE_FRIBIDI
+libpango_1_0_la_LIBADD = $(pango_win32res)
else
-libpango_1_0_la_LIBADD = mini-fribidi/libmini-fribidi.la
+libpango_1_0_la_LIBADD = mini-fribidi/libmini-fribidi.la $(pango_win32res)
endif
+libpango_1_0_la_DEPENDENCIES = $(pango_win32res)
libpangox_1_0_la_LDFLAGS = -version-info $(LT_VERSION_INFO)
libpangox_1_0_la_LIBADD = libpango-$(PANGO_API_VERSION).la $(INCLUDED_X_MODULES) $(X_LIBS) $(X_EXTRA_LIBS)
libpangox_1_0_la_DEPENDENCIES = $(INCLUDED_X_MODULES) libpango-$(PANGO_API_VERSION).la
+pango-win32res.lo : pango.rc
+ $(top_srcdir)/../glib/build/win32/lt-compile-resource pango.rc pango-win32res.lo
+
libpangowin32_1_0_la_SOURCES = \
pangowin32.h \
pangowin32.c \
@@ -173,9 +182,11 @@ libpangowin32_1_0_la_SOURCES = \
libpangowin32_1_0_la_LDFLAGS = -version-info $(LT_VERSION_INFO) \
$(GLIB_LIBS) \
$(no_undefined) $(pangowin32_export_symbols)
-libpangowin32_1_0_la_LIBADD = libpango-$(PANGO_API_VERSION).la $(INCLUDED_WIN32_MODULES) $(WIN32_LIBS)
-libpangowin32_1_0_la_DEPENDENCIES = libpango-$(PANGO_API_VERSION).la
+libpangowin32_1_0_la_LIBADD = libpango-$(PANGO_API_VERSION).la $(INCLUDED_WIN32_MODULES) $(WIN32_LIBS) $(pangowin32_win32res)
+libpangowin32_1_0_la_DEPENDENCIES = libpango-$(PANGO_API_VERSION).la $(pangowin32_win32res)
+pangowin32-win32res.lo : pangowin32.rc
+ $(top_srcdir)/../glib/build/win32/lt-compile-resource pangowin32.rc pangowin32-win32res.lo
libpangoxft_1_0_la_SOURCES = \
pangoxft-font.c \
@@ -197,8 +208,11 @@ libpangoft2_1_0_la_SOURCES = \
libpangoft2_1_0_la_LDFLAGS = -version-info $(LT_VERSION_INFO) \
$(GLIB_LIBS) \
$(no_undefined) $(pangoft2_export_symbols)
-libpangoft2_1_0_la_LIBADD = mini-xft/libmini-xft.la opentype/libpango-ot.la libpango-$(PANGO_API_VERSION).la $(INCLUDED_FT2_MODULES) $(FREETYPE_LIBS)
-libpangoft2_1_0_la_DEPENDENCIES = $(INCLUDED_FT2_MODULES) libpango-$(PANGO_API_VERSION).la
+libpangoft2_1_0_la_LIBADD = mini-xft/libmini-xft.la opentype/libpango-ot.la libpango-$(PANGO_API_VERSION).la $(INCLUDED_FT2_MODULES) $(FREETYPE_LIBS) $(pangoft2_win32res)
+libpangoft2_1_0_la_DEPENDENCIES = $(INCLUDED_FT2_MODULES) libpango-$(PANGO_API_VERSION).la $(pangoft2_win32res)
+
+pangoft2-win32res.lo : pangoft2.rc
+ $(top_srcdir)/../glib/build/win32/lt-compile-resource pangoft2.rc pangoft2-win32res.lo
pangoincludedir=$(includedir)/pango-1.0/pango
diff --git a/pango/pango.rc.in b/pango/pango.rc.in
index de051b0a..814e9a42 100644
--- a/pango/pango.rc.in
+++ b/pango/pango.rc.in
@@ -1,8 +1,8 @@
#include <winver.h>
VS_VERSION_INFO VERSIONINFO
- FILEVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,0,BUILDNUMBER
- PRODUCTVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,0,0
+ FILEVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,@PANGO_MICRO_VERSION@,BUILDNUMBER
+ PRODUCTVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,@PANGO_MICRO_VERSION@,0
FILEFLAGSMASK 0
FILEFLAGS 0
FILEOS VOS__WINDOWS32
@@ -15,12 +15,12 @@ VS_VERSION_INFO VERSIONINFO
BEGIN
VALUE "CompanyName", "Red Hat Software"
VALUE "FileDescription", "Pango"
- VALUE "FileVersion", "@PANGO_MAJOR_VERSION@.@[email protected]"
+ VALUE "FileVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@.@[email protected]"
VALUE "InternalName", "pango-@PANGO_API_VERSION@-@LT_CURRENT_MINUS_AGE@"
VALUE "LegalCopyright", "Copyright ? 1999 Red Hat Software."
VALUE "OriginalFilename", "pango-@PANGO_API_VERSION@-@[email protected]"
VALUE "ProductName", "Pango"
- VALUE "ProductVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@"
+ VALUE "ProductVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@.@PANGO_MICRO_VERSION@"
END
END
BLOCK "VarFileInfo"
diff --git a/pango/pangoft2.rc.in b/pango/pangoft2.rc.in
index 733a8390..c6438004 100644
--- a/pango/pangoft2.rc.in
+++ b/pango/pangoft2.rc.in
@@ -1,8 +1,8 @@
#include <winver.h>
VS_VERSION_INFO VERSIONINFO
- FILEVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,0,BUILDNUMBER
- PRODUCTVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,0,0
+ FILEVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,@PANGO_MICRO_VERSION@,BUILDNUMBER
+ PRODUCTVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,@PANGO_MICRO_VERSION@,0
FILEFLAGSMASK 0
FILEFLAGS 0
FILEOS VOS__WINDOWS32
@@ -15,12 +15,12 @@ VS_VERSION_INFO VERSIONINFO
BEGIN
VALUE "CompanyName", "Red Hat Software"
VALUE "FileDescription", "PangoFT2"
- VALUE "FileVersion", "@PANGO_MAJOR_VERSION@.@[email protected]"
+ VALUE "FileVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@.@[email protected]"
VALUE "InternalName", "pangoft2-@PANGO_API_VERSION@-@LT_CURRENT_MINUS_AGE@"
VALUE "LegalCopyright", "Copyright ? 1999 Red Hat Software. Copyright ? 2000 Tor Lillqvist"
VALUE "OriginalFilename", "pangoft2-@PANGO_API_VERSION@-@[email protected]"
VALUE "ProductName", "PangoFT2"
- VALUE "ProductVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@"
+ VALUE "ProductVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@.@PANGO_MICRO_VERSION@"
END
END
BLOCK "VarFileInfo"
diff --git a/pango/pangowin32-fontcache.c b/pango/pangowin32-fontcache.c
index 6dd87c5b..9d8db725 100644
--- a/pango/pangowin32-fontcache.c
+++ b/pango/pangowin32-fontcache.c
@@ -91,7 +91,7 @@ logfont_hash (gconstpointer v)
lfp->lfItalic +
lfp->lfWeight/10 +
lfp->lfOrientation +
- lfp->lfHeight * 10;
+ abs (lfp->lfHeight) * 10;
}
static gint
diff --git a/pango/pangowin32-fontmap.c b/pango/pangowin32-fontmap.c
index 31a945d6..01227d04 100644
--- a/pango/pangowin32-fontmap.c
+++ b/pango/pangowin32-fontmap.c
@@ -244,7 +244,6 @@ PangoFontMap *
pango_win32_font_map_for_display (void)
{
LOGFONT logfont;
- RECT rect;
/* Make sure that the type system is initialized */
g_type_init ();
@@ -265,10 +264,7 @@ pango_win32_font_map_for_display (void)
pango_win32_font_map_read_aliases (fontmap);
#endif
- SystemParametersInfo(SPI_GETWORKAREA, 0, &rect, 0);
- fontmap->resolution =
- (PANGO_SCALE * 72.27 / 25.4) * ((double) GetDeviceCaps (pango_win32_hdc, HORZSIZE) /
- (rect.right - rect.left));
+ fontmap->resolution = PANGO_SCALE / GetDeviceCaps (pango_win32_hdc, LOGPIXELSY) * 72.0;
return PANGO_FONT_MAP (fontmap);
}
@@ -888,7 +884,7 @@ pango_win32_make_matching_logfont (PangoFontMap *fontmap,
while (tmp_list)
{
LOGFONT *tmp_logfont = tmp_list->data;
- int font_size = tmp_logfont->lfHeight;
+ int font_size = abs (tmp_logfont->lfHeight);
if (size != -1)
{
@@ -911,7 +907,7 @@ pango_win32_make_matching_logfont (PangoFontMap *fontmap,
/* OK, we have a match; let's modify it to fit this size */
*out = *closest_match;
- out->lfHeight = (int)((double)size / win32fontmap->resolution + 0.5);
+ out->lfHeight = -(int)((double)size / win32fontmap->resolution + 0.5);
out->lfWidth = 0;
}
else
diff --git a/pango/pangowin32.rc.in b/pango/pangowin32.rc.in
index 4ca3aced..b7e87fd9 100644
--- a/pango/pangowin32.rc.in
+++ b/pango/pangowin32.rc.in
@@ -1,8 +1,8 @@
#include <winver.h>
VS_VERSION_INFO VERSIONINFO
- FILEVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,0,BUILDNUMBER
- PRODUCTVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,0,0
+ FILEVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,@PANGO_MICRO_VERSION@,BUILDNUMBER
+ PRODUCTVERSION @PANGO_MAJOR_VERSION@,@PANGO_MINOR_VERSION@,@PANGO_MICRO_VERSION@,0
FILEFLAGSMASK 0
FILEFLAGS 0
FILEOS VOS__WINDOWS32
@@ -15,12 +15,12 @@ VS_VERSION_INFO VERSIONINFO
BEGIN
VALUE "CompanyName", "Red Hat Software"
VALUE "FileDescription", "PangoWin32"
- VALUE "FileVersion", "@PANGO_MAJOR_VERSION@.@[email protected]"
+ VALUE "FileVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@.@[email protected]"
VALUE "InternalName", "pangowin32-@PANGO_API_VERSION@-@LT_CURRENT_MINUS_AGE@"
VALUE "LegalCopyright", "Copyright ? 1999 Red Hat Software. Copyright ? 2000 Tor Lillqvist"
VALUE "OriginalFilename", "pangowin32-@PANGO_API_VERSION@-@[email protected]"
VALUE "ProductName", "PangoWin32"
- VALUE "ProductVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@"
+ VALUE "ProductVersion", "@PANGO_MAJOR_VERSION@.@PANGO_MINOR_VERSION@.@PANGO_MICRO_VERSION@"
END
END
BLOCK "VarFileInfo"
| 0 | 10 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
b9f7b88e3d100b87a856e077b5f2fdbf49c73ebb
|
Fix silly error in implementation of pango_glyph_string_get_width(), and
2006-07-08 Behdad Esfahbod <[email protected]>
* pango/glyphstring.c (pango_glyph_string_get_width):
* pango/pango-glyph.h:
* pango/pango-layout.c (pango_layout_line_index_to_x),
(pango_layout_line_x_to_index), (pango_layout_line_get_x_ranges):
* pango/pango-renderer.c (pango_renderer_draw_layout_line): Fix silly
error in implementation of pango_glyph_string_get_width(), and also
remove unused font parameter from its signature.
|
commit b9f7b88e3d100b87a856e077b5f2fdbf49c73ebb
Author: Behdad Esfahbod <[email protected]>
Date: Sat Jul 8 22:15:32 2006 +0000
Fix silly error in implementation of pango_glyph_string_get_width(), and
2006-07-08 Behdad Esfahbod <[email protected]>
* pango/glyphstring.c (pango_glyph_string_get_width):
* pango/pango-glyph.h:
* pango/pango-layout.c (pango_layout_line_index_to_x),
(pango_layout_line_x_to_index), (pango_layout_line_get_x_ranges):
* pango/pango-renderer.c (pango_renderer_draw_layout_line): Fix silly
error in implementation of pango_glyph_string_get_width(), and also
remove unused font parameter from its signature.
diff --git a/ChangeLog b/ChangeLog
index d57cb2aa..35ae23d9 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,13 @@
+2006-07-08 Behdad Esfahbod <[email protected]>
+
+ * pango/glyphstring.c (pango_glyph_string_get_width):
+ * pango/pango-glyph.h:
+ * pango/pango-layout.c (pango_layout_line_index_to_x),
+ (pango_layout_line_x_to_index), (pango_layout_line_get_x_ranges):
+ * pango/pango-renderer.c (pango_renderer_draw_layout_line): Fix silly
+ error in implementation of pango_glyph_string_get_width(), and also
+ remove unused font parameter from its signature.
+
2006-07-08 Behdad Esfahbod <[email protected]>
* configure.in: Remove obsolete checks for varargs that were
diff --git a/docs/tmpl/glyphs.sgml b/docs/tmpl/glyphs.sgml
index 8292c688..54daf25e 100644
--- a/docs/tmpl/glyphs.sgml
+++ b/docs/tmpl/glyphs.sgml
@@ -388,7 +388,6 @@ The #GObject type for #PangoGlyphString.
</para>
@glyphs:
-@font:
@Returns:
diff --git a/pango/glyphstring.c b/pango/glyphstring.c
index 82770349..353fa2a4 100644
--- a/pango/glyphstring.c
+++ b/pango/glyphstring.c
@@ -266,7 +266,6 @@ pango_glyph_string_extents (PangoGlyphString *glyphs,
/**
* pango_glyph_string_get_width:
* @glyphs: a #PangoGlyphString
- * @font: a #PangoFont
*
* Computes the logical width of the glyph string as can also be computed
* using pango_glyph_string_extents(). However, since this only computes the
@@ -278,14 +277,13 @@ pango_glyph_string_extents (PangoGlyphString *glyphs,
* Since: 1.14
*/
int
-pango_glyph_string_get_width (PangoGlyphString *glyphs,
- PangoFont *font)
+pango_glyph_string_get_width (PangoGlyphString *glyphs)
{
int i;
int width = 0;
for (i = 0; i < glyphs->num_glyphs; i++)
- width += &glyphs->glyphs[i].geometry.width;
+ width += glyphs->glyphs[i].geometry.width;
return width;
}
diff --git a/pango/pango-glyph.h b/pango/pango-glyph.h
index 71b6911e..92a8e6f8 100644
--- a/pango/pango-glyph.h
+++ b/pango/pango-glyph.h
@@ -91,8 +91,7 @@ void pango_glyph_string_extents (PangoGlyphString *glyphs,
PangoFont *font,
PangoRectangle *ink_rect,
PangoRectangle *logical_rect);
-int pango_glyph_string_get_width(PangoGlyphString *glyphs,
- PangoFont *font);
+int pango_glyph_string_get_width(PangoGlyphString *glyphs);
void pango_glyph_string_extents_range (PangoGlyphString *glyphs,
int start,
diff --git a/pango/pango-layout.c b/pango/pango-layout.c
index 69e6b95d..bd76a265 100644
--- a/pango/pango-layout.c
+++ b/pango/pango-layout.c
@@ -1168,7 +1168,7 @@ pango_layout_line_index_to_x (PangoLayoutLine *line,
}
if (!properties.shape_set)
- width += pango_glyph_string_get_width (run->glyphs, run->item->analysis.font);
+ width += pango_glyph_string_get_width (run->glyphs);
else
width += properties.shape_logical_rect->width;
@@ -3577,7 +3577,7 @@ pango_layout_line_x_to_index (PangoLayoutLine *line,
if (properties.shape_set)
logical_width = properties.shape_logical_rect->width;
else
- logical_width = pango_glyph_string_get_width (run->glyphs, run->item->analysis.font);
+ logical_width = pango_glyph_string_get_width (run->glyphs);
if (x_pos >= start_pos && x_pos < start_pos + logical_width)
{
@@ -3782,7 +3782,7 @@ pango_layout_line_get_x_ranges (PangoLayoutLine *line,
}
if (tmp_list->next)
- accumulated_width += pango_glyph_string_get_width (run->glyphs, run->item->analysis.font);
+ accumulated_width += pango_glyph_string_get_width (run->glyphs);
tmp_list = tmp_list->next;
}
diff --git a/pango/pango-renderer.c b/pango/pango-renderer.c
index 4c96972a..c53f645d 100644
--- a/pango/pango-renderer.c
+++ b/pango/pango-renderer.c
@@ -496,7 +496,7 @@ pango_renderer_draw_layout_line (PangoRenderer *renderer,
renderer->strikethrough)
pango_glyph_string_extents (run->glyphs, run->item->analysis.font,
&ink_rect, NULL);
- glyph_string_width = pango_glyph_string_get_width (run->glyphs, run->item->analysis.font);
+ glyph_string_width = pango_glyph_string_get_width (run->glyphs);
}
state.logical_rect_end = x + x_off + glyph_string_width;
| 0 | 8 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
b178da14dabd63937c3867f6d5cbb29f7a31d69f
|
Bug 471577 – GBoxed GType for PangoGlyphItem
2007-10-24 Behdad Esfahbod <[email protected]>
Bug 471577 – GBoxed GType for PangoGlyphItem
* pango/pango-glyph-item.h:
* pango/pango-glyph-item.c:
New public API:
PANGO_TYPE_GLYPH_ITEM
pango_glyph_item_copy()
pango_glyph_item_get_type()
* pango/pango-layout.c:
New public API:
pango_layout_iter_copy()
* pango/fonts.c (pango_font_description_copy),
(pango_font_description_copy_static),
(pango_font_description_free), (pango_font_descriptions_free),
(pango_font_metrics_ref), (pango_font_metrics_unref):
* pango/glyphstring.c (pango_glyph_string_copy),
(pango_glyph_string_free):
* pango/pango-attributes.c (pango_attr_list_ref),
(pango_attr_list_unref), (pango_attr_list_copy):
* pango/pango-color.c (pango_color_copy), (pango_color_free):
* pango/pango-item.c (pango_item_copy), (pango_item_free):
* pango/pango-layout.c (pango_layout_line_ref),
(pango_layout_line_unref), (pango_layout_iter_copy),
(pango_layout_iter_free):
* pango/pango-layout.h:
* pango/pango-matrix.c (pango_matrix_copy), (pango_matrix_free):
Update all copy/free functions to accept NULL as legitimate input.
Previously all were g_return_[val_]if_fail()ing it.
* pango/pango.def:
* docs/pango-sections.txt:
* docs/tmpl/glyphs.sgml:
* docs/tmpl/layout.sgml:
Update.
svn path=/trunk/; revision=2457
|
commit b178da14dabd63937c3867f6d5cbb29f7a31d69f
Author: Behdad Esfahbod <[email protected]>
Date: Wed Oct 24 04:50:09 2007 +0000
Bug 471577 – GBoxed GType for PangoGlyphItem
2007-10-24 Behdad Esfahbod <[email protected]>
Bug 471577 – GBoxed GType for PangoGlyphItem
* pango/pango-glyph-item.h:
* pango/pango-glyph-item.c:
New public API:
PANGO_TYPE_GLYPH_ITEM
pango_glyph_item_copy()
pango_glyph_item_get_type()
* pango/pango-layout.c:
New public API:
pango_layout_iter_copy()
* pango/fonts.c (pango_font_description_copy),
(pango_font_description_copy_static),
(pango_font_description_free), (pango_font_descriptions_free),
(pango_font_metrics_ref), (pango_font_metrics_unref):
* pango/glyphstring.c (pango_glyph_string_copy),
(pango_glyph_string_free):
* pango/pango-attributes.c (pango_attr_list_ref),
(pango_attr_list_unref), (pango_attr_list_copy):
* pango/pango-color.c (pango_color_copy), (pango_color_free):
* pango/pango-item.c (pango_item_copy), (pango_item_free):
* pango/pango-layout.c (pango_layout_line_ref),
(pango_layout_line_unref), (pango_layout_iter_copy),
(pango_layout_iter_free):
* pango/pango-layout.h:
* pango/pango-matrix.c (pango_matrix_copy), (pango_matrix_free):
Update all copy/free functions to accept NULL as legitimate input.
Previously all were g_return_[val_]if_fail()ing it.
* pango/pango.def:
* docs/pango-sections.txt:
* docs/tmpl/glyphs.sgml:
* docs/tmpl/layout.sgml:
Update.
svn path=/trunk/; revision=2457
diff --git a/ChangeLog b/ChangeLog
index 567ca5b3..c4f058db 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,44 @@
+2007-10-24 Behdad Esfahbod <[email protected]>
+
+ Bug 471577 – GBoxed GType for PangoGlyphItem
+
+ * pango/pango-glyph-item.h:
+ * pango/pango-glyph-item.c:
+ New public API:
+
+ PANGO_TYPE_GLYPH_ITEM
+ pango_glyph_item_copy()
+ pango_glyph_item_get_type()
+
+ * pango/pango-layout.c:
+ New public API:
+
+ pango_layout_iter_copy()
+
+ * pango/fonts.c (pango_font_description_copy),
+ (pango_font_description_copy_static),
+ (pango_font_description_free), (pango_font_descriptions_free),
+ (pango_font_metrics_ref), (pango_font_metrics_unref):
+ * pango/glyphstring.c (pango_glyph_string_copy),
+ (pango_glyph_string_free):
+ * pango/pango-attributes.c (pango_attr_list_ref),
+ (pango_attr_list_unref), (pango_attr_list_copy):
+ * pango/pango-color.c (pango_color_copy), (pango_color_free):
+ * pango/pango-item.c (pango_item_copy), (pango_item_free):
+ * pango/pango-layout.c (pango_layout_line_ref),
+ (pango_layout_line_unref), (pango_layout_iter_copy),
+ (pango_layout_iter_free):
+ * pango/pango-layout.h:
+ * pango/pango-matrix.c (pango_matrix_copy), (pango_matrix_free):
+ Update all copy/free functions to accept NULL as legitimate input.
+ Previously all were g_return_[val_]if_fail()ing it.
+
+ * pango/pango.def:
+ * docs/pango-sections.txt:
+ * docs/tmpl/glyphs.sgml:
+ * docs/tmpl/layout.sgml:
+ Update.
+
2007-10-22 Behdad Esfahbod <[email protected]>
Bug 471571 – Add pango_layout_iter_get_layout()
diff --git a/docs/pango-sections.txt b/docs/pango-sections.txt
index 13395ff5..4ff5160a 100644
--- a/docs/pango-sections.txt
+++ b/docs/pango-sections.txt
@@ -117,13 +117,16 @@ pango_glyph_string_get_width
pango_glyph_string_index_to_x
pango_glyph_string_x_to_index
pango_glyph_string_get_logical_widths
+PANGO_TYPE_GLYPH_ITEM
pango_glyph_item_split
pango_glyph_item_apply_attrs
pango_glyph_item_letter_space
+pango_glyph_item_copy
pango_glyph_item_free
<SUBSECTION Private>
pango_glyph_string_get_type
+pango_glyph_item_get_type
pango_matrix_get_type
</SECTION>
@@ -491,6 +494,7 @@ pango_layout_get_lines
pango_layout_get_lines_readonly
pango_layout_get_iter
+pango_layout_iter_copy
pango_layout_iter_free
pango_layout_iter_next_run
pango_layout_iter_next_char
diff --git a/docs/tmpl/glyphs.sgml b/docs/tmpl/glyphs.sgml
index 44dff0db..edf06acb 100644
--- a/docs/tmpl/glyphs.sgml
+++ b/docs/tmpl/glyphs.sgml
@@ -512,6 +512,13 @@ The #GObject type for #PangoGlyphString.
@logical_widths:
+<!-- ##### MACRO PANGO_TYPE_GLYPH_ITEM ##### -->
+<para>
+The #GObject type for #PangoGlyphItem.
+</para>
+
+
+
<!-- ##### FUNCTION pango_glyph_item_split ##### -->
<para>
@@ -545,6 +552,15 @@ The #GObject type for #PangoGlyphString.
@letter_spacing:
+<!-- ##### FUNCTION pango_glyph_item_copy ##### -->
+<para>
+
+</para>
+
+@orig:
+@Returns:
+
+
<!-- ##### FUNCTION pango_glyph_item_free ##### -->
<para>
diff --git a/docs/tmpl/layout.sgml b/docs/tmpl/layout.sgml
index 6bb944fd..64cb2c5a 100644
--- a/docs/tmpl/layout.sgml
+++ b/docs/tmpl/layout.sgml
@@ -599,6 +599,15 @@ The #GObject type for #PangoAlignment.
@Returns:
+<!-- ##### FUNCTION pango_layout_iter_copy ##### -->
+<para>
+
+</para>
+
+@iter:
+@Returns:
+
+
<!-- ##### FUNCTION pango_layout_iter_free ##### -->
<para>
diff --git a/pango/fonts.c b/pango/fonts.c
index 0979ba1a..88627636 100644
--- a/pango/fonts.c
+++ b/pango/fonts.c
@@ -657,19 +657,21 @@ pango_font_description_better_match (const PangoFontDescription *desc,
/**
* pango_font_description_copy:
- * @desc: a #PangoFontDescription
+ * @desc: a #PangoFontDescription, may be %NULL
*
* Make a copy of a #PangoFontDescription.
*
* Return value: the newly allocated #PangoFontDescription, which should
- * be freed with pango_font_description_free().
+ * be freed with pango_font_description_free(), or %NULL
+ * if @desc was %NULL.
**/
PangoFontDescription *
pango_font_description_copy (const PangoFontDescription *desc)
{
PangoFontDescription *result;
- g_return_val_if_fail (desc != NULL, NULL);
+ if (desc == NULL)
+ return NULL;
result = g_slice_new (PangoFontDescription);
@@ -686,7 +688,7 @@ pango_font_description_copy (const PangoFontDescription *desc)
/**
* pango_font_description_copy_static:
- * @desc: a #PangoFontDescription
+ * @desc: a #PangoFontDescription, may be %NULL
*
* Like pango_font_description_copy(), but only a shallow copy is made
* of the family name and other allocated fields. The result can only
@@ -694,14 +696,16 @@ pango_font_description_copy (const PangoFontDescription *desc)
* when the copy is only needed temporarily.
*
* Return value: the newly allocated #PangoFontDescription, which should
- * be freed with pango_font_description_free().
+ * be freed with pango_font_description_free(), or %NULL
+ * if @desc was %NULL.
**/
PangoFontDescription *
pango_font_description_copy_static (const PangoFontDescription *desc)
{
PangoFontDescription *result;
- g_return_val_if_fail (desc != NULL, NULL);
+ if (desc == NULL)
+ return NULL;
result = g_slice_new (PangoFontDescription);
@@ -794,25 +798,25 @@ pango_font_description_hash (const PangoFontDescription *desc)
/**
* pango_font_description_free:
- * @desc: a #PangoFontDescription, or %NULL
+ * @desc: a #PangoFontDescription, may be %NULL
*
* Frees a font description.
**/
void
pango_font_description_free (PangoFontDescription *desc)
{
- if (desc)
- {
- if (desc->family_name && !desc->static_family)
- g_free (desc->family_name);
+ if (desc == NULL)
+ return;
- g_slice_free (PangoFontDescription, desc);
- }
+ if (desc->family_name && !desc->static_family)
+ g_free (desc->family_name);
+
+ g_slice_free (PangoFontDescription, desc);
}
/**
* pango_font_descriptions_free:
- * @descs: a pointer to an array of #PangoFontDescription, or %NULL
+ * @descs: a pointer to an array of #PangoFontDescription, may be %NULL
* @n_descs: number of font descriptions in @descs
*
* Frees a list of font descriptions from pango_font_map_list_fonts()
@@ -823,12 +827,12 @@ pango_font_descriptions_free (PangoFontDescription **descs,
{
int i;
- if (descs)
- {
- for (i = 0; i<n_descs; i++)
- pango_font_description_free (descs[i]);
- g_free (descs);
- }
+ if (descs == NULL)
+ return;
+
+ for (i = 0; i<n_descs; i++)
+ pango_font_description_free (descs[i]);
+ g_free (descs);
}
typedef struct
@@ -1455,7 +1459,7 @@ pango_font_metrics_new (void)
/**
* pango_font_metrics_ref:
- * @metrics: a #PangoFontMetrics structure
+ * @metrics: a #PangoFontMetrics structure, may be %NULL
*
* Increase the reference count of a font metrics structure by one.
*
@@ -1464,7 +1468,7 @@ pango_font_metrics_new (void)
PangoFontMetrics *
pango_font_metrics_ref (PangoFontMetrics *metrics)
{
- if (!metrics)
+ if (metrics == NULL)
return NULL;
metrics->ref_count++;
@@ -1474,7 +1478,7 @@ pango_font_metrics_ref (PangoFontMetrics *metrics)
/**
* pango_font_metrics_unref:
- * @metrics: a #PangoFontMetrics structure
+ * @metrics: a #PangoFontMetrics structure, may be %NULL
*
* Decrease the reference count of a font metrics structure by one. If
* the result is zero, frees the structure and any associated
@@ -1483,8 +1487,9 @@ pango_font_metrics_ref (PangoFontMetrics *metrics)
void
pango_font_metrics_unref (PangoFontMetrics *metrics)
{
- if (!metrics)
+ if (metrics == NULL)
return;
+
g_return_if_fail (metrics->ref_count > 0 );
metrics->ref_count--;
diff --git a/pango/glyphstring.c b/pango/glyphstring.c
index d8e4dd31..6aeba2b7 100644
--- a/pango/glyphstring.c
+++ b/pango/glyphstring.c
@@ -92,17 +92,23 @@ pango_glyph_string_get_type (void)
/**
* pango_glyph_string_copy:
- * @string: a #PangoGlyphString.
+ * @string: a #PangoGlyphString, may be %NULL
*
- * Copy a glyph string and associated storage.
+ * Copy a glyph string and associated storage.
*
* Return value: the newly allocated #PangoGlyphString, which
- * should be freed with pango_glyph_string_free().
+ * should be freed with pango_glyph_string_free(),
+ * or %NULL if @string was %NULL.
*/
PangoGlyphString *
pango_glyph_string_copy (PangoGlyphString *string)
{
- PangoGlyphString *new_string = g_slice_new (PangoGlyphString);
+ PangoGlyphString *new_string;
+
+ if (new_string == NULL)
+ return NULL;
+
+ new_string = g_slice_new (PangoGlyphString);
*new_string = *string;
@@ -116,13 +122,15 @@ pango_glyph_string_copy (PangoGlyphString *string)
/**
* pango_glyph_string_free:
- * @string: a #PangoGlyphString.
+ * @string: a #PangoGlyphString, may be %NULL
*
* Free a glyph string and associated storage.
*/
void
pango_glyph_string_free (PangoGlyphString *string)
{
+ if (string == NULL)
+ return;
g_free (string->glyphs);
g_free (string->log_clusters);
g_slice_free (PangoGlyphString, string);
diff --git a/pango/pango-attributes.c b/pango/pango-attributes.c
index a9a4c26a..1b864678 100644
--- a/pango/pango-attributes.c
+++ b/pango/pango-attributes.c
@@ -1060,7 +1060,7 @@ pango_attr_list_new (void)
/**
* pango_attr_list_ref:
- * @list: a #PangoAttrList
+ * @list: a #PangoAttrList, may be %NULL
*
* Increase the reference count of the given attribute list by one.
*
@@ -1071,7 +1071,8 @@ pango_attr_list_new (void)
PangoAttrList *
pango_attr_list_ref (PangoAttrList *list)
{
- g_return_val_if_fail (list != NULL, NULL);
+ if (list == NULL)
+ return NULL;
list->ref_count++;
@@ -1080,7 +1081,7 @@ pango_attr_list_ref (PangoAttrList *list)
/**
* pango_attr_list_unref:
- * @list: a #PangoAttrList
+ * @list: a #PangoAttrList, may be %NULL
*
* Decrease the reference count of the given attribute list by one.
* If the result is zero, free the attribute list and the attributes
@@ -1091,7 +1092,9 @@ pango_attr_list_unref (PangoAttrList *list)
{
GSList *tmp_list;
- g_return_if_fail (list != NULL);
+ if (list == NULL)
+ return;
+
g_return_if_fail (list->ref_count > 0);
list->ref_count--;
@@ -1114,13 +1117,14 @@ pango_attr_list_unref (PangoAttrList *list)
/**
* pango_attr_list_copy:
- * @list: a #PangoAttrList
+ * @list: a #PangoAttrList, may be %NULL
*
* Copy @list and return an identical new list.
*
* Return value: the newly allocated #PangoAttrList, with a
* reference count of one, which should
* be freed with pango_attr_list_unref().
+ * Returns %NULL if @list was %NULL.
**/
PangoAttrList *
pango_attr_list_copy (PangoAttrList *list)
@@ -1129,7 +1133,8 @@ pango_attr_list_copy (PangoAttrList *list)
GSList *iter;
GSList *new_attrs;
- g_return_val_if_fail (list != NULL, NULL);
+ if (list == NULL)
+ return NULL;
new = pango_attr_list_new ();
diff --git a/pango/pango-color.c b/pango/pango-color.c
index beae87fa..eec81ae4 100644
--- a/pango/pango-color.c
+++ b/pango/pango-color.c
@@ -42,7 +42,7 @@ pango_color_get_type (void)
/**
* pango_color_copy:
- * @src: color to copy
+ * @src: color to copy, may be %NULL
*
* Creates a copy of @src, which should be freed with
* pango_color_free(). Primarily used by language bindings,
@@ -50,14 +50,16 @@ pango_color_get_type (void)
* by assignment in C).
*
* Return value: the newly allocated #PangoColor, which should
- * be freed with pango_color_free().
+ * be freed with pango_color_free(), or %NULL
+ * if @src was %NULL.
**/
PangoColor*
pango_color_copy (const PangoColor *src)
{
PangoColor *ret;
- g_return_val_if_fail (src != NULL, NULL);
+ if (src == NULL)
+ return NULL;
ret = g_slice_new (PangoColor);
@@ -68,14 +70,15 @@ pango_color_copy (const PangoColor *src)
/**
* pango_color_free:
- * @color: an allocated #PangoColor
+ * @color: an allocated #PangoColor, may be %NULL
*
* Frees a color allocated by pango_color_copy().
**/
void
pango_color_free (PangoColor *color)
{
- g_return_if_fail (color != NULL);
+ if (color == NULL)
+ return;
g_slice_free (PangoColor, color);
}
diff --git a/pango/pango-glyph-item.c b/pango/pango-glyph-item.c
index 07b844bc..1da934a4 100644
--- a/pango/pango-glyph-item.c
+++ b/pango/pango-glyph-item.c
@@ -24,6 +24,7 @@
#include "pango-glyph-item.h"
#include "pango-glyph-item-private.h"
+#include "pango-impl-utils.h"
#define LTR(glyph_item) (((glyph_item)->item->analysis.level % 2) == 0)
@@ -129,9 +130,37 @@ pango_glyph_item_split (PangoGlyphItem *orig,
return new;
}
+/**
+ * pango_glyph_item_copy:
+ * @orig: a #PangoGlyphItem, may be %NULL
+ *
+ * Make a deep copy an existing #PangoGlyphItem structure.
+ *
+ * Return value: the newly allocated #PangoGlyphItem, which should
+ * be freed with pango_glyph_item_free(), or %NULL
+ * if @orig was %NULL.
+ *
+ * Since: 1.20
+ **/
+PangoGlyphItem *
+pango_glyph_item_copy (PangoGlyphItem *orig)
+{
+ PangoGlyphItem *result;
+
+ if (orig == NULL)
+ return NULL;
+
+ result = g_slice_new (PangoGlyphItem);
+
+ result->item = pango_item_copy (orig->item);
+ result->glyphs = pango_glyph_string_copy (orig->glyphs);
+
+ return result;
+}
+
/**
* pango_glyph_item_free:
- * @glyph_item: a #PangoGlyphItem
+ * @glyph_item: a #PangoGlyphItem, may be %NULL
*
* Frees a #PangoGlyphItem and memory to which it points.
*
@@ -140,6 +169,9 @@ pango_glyph_item_split (PangoGlyphItem *orig,
void
pango_glyph_item_free (PangoGlyphItem *glyph_item)
{
+ if (glyph_item == NULL)
+ return;
+
if (glyph_item->item)
pango_item_free (glyph_item->item);
if (glyph_item->glyphs)
@@ -148,6 +180,18 @@ pango_glyph_item_free (PangoGlyphItem *glyph_item)
g_slice_free (PangoGlyphItem, glyph_item);
}
+GType
+pango_glyph_item_get_type (void)
+{
+ static GType our_type = 0;
+
+ if (G_UNLIKELY (our_type == 0))
+ our_type = g_boxed_type_register_static (I_("PangoGlyphItem"),
+ (GBoxedCopyFunc) pango_glyph_item_copy,
+ (GBoxedFreeFunc) pango_glyph_item_free);
+ return our_type;
+}
+
/**
* _pango_glyph_item_iter_next_cluster:
* @iter: a #PangoGlyphItemIter
diff --git a/pango/pango-glyph-item.h b/pango/pango-glyph-item.h
index fec086a4..4bad2651 100644
--- a/pango/pango-glyph-item.h
+++ b/pango/pango-glyph-item.h
@@ -37,9 +37,14 @@ struct _PangoGlyphItem
PangoGlyphString *glyphs;
};
+#define PANGO_TYPE_GLYPH_ITEM (pango_glyph_item_get_type ())
+
+GType pango_glyph_item_get_type (void) G_GNUC_CONST;
+
PangoGlyphItem *pango_glyph_item_split (PangoGlyphItem *orig,
const char *text,
int split_index);
+PangoGlyphItem *pango_glyph_item_copy (PangoGlyphItem *orig);
void pango_glyph_item_free (PangoGlyphItem *glyph_item);
GSList * pango_glyph_item_apply_attrs (PangoGlyphItem *glyph_item,
const char *text,
diff --git a/pango/pango-item.c b/pango/pango-item.c
index d5650827..3c7ff57c 100644
--- a/pango/pango-item.c
+++ b/pango/pango-item.c
@@ -42,18 +42,24 @@ pango_item_new (void)
/**
* pango_item_copy:
- * @item: a #PangoItem
+ * @item: a #PangoItem, may be %NULL
*
* Copy an existing #PangoItem structure.
*
* Return value: the newly allocated #PangoItem, which should
- * be freed with pango_item_free().
+ * be freed with pango_item_free(), or %NULL if
+ * @item was NULL.
**/
PangoItem *
pango_item_copy (PangoItem *item)
{
GSList *extra_attrs, *tmp_list;
- PangoItem *result = g_slice_new (PangoItem);
+ PangoItem *result;
+
+ if (item == NULL)
+ return NULL;
+
+ result = g_slice_new (PangoItem);
result->offset = item->offset;
result->length = item->length;
@@ -78,13 +84,16 @@ pango_item_copy (PangoItem *item)
/**
* pango_item_free:
- * @item: a #PangoItem
+ * @item: a #PangoItem, may be %NULL
*
* Free a #PangoItem and all associated memory.
**/
void
pango_item_free (PangoItem *item)
{
+ if (item == NULL)
+ return;
+
if (item->analysis.extra_attrs)
{
g_slist_foreach (item->analysis.extra_attrs, (GFunc)pango_attribute_destroy, NULL);
diff --git a/pango/pango-layout.c b/pango/pango-layout.c
index 0c6c7717..4ddb4b7c 100644
--- a/pango/pango-layout.c
+++ b/pango/pango-layout.c
@@ -3675,7 +3675,7 @@ pango_layout_check_lines (PangoLayout *layout)
/**
* pango_layout_line_ref:
- * @line: a #PangoLayoutLine
+ * @line: a #PangoLayoutLine, may be %NULL
*
* Increase the reference count of a #PangoLayoutLine by one.
*
@@ -3688,7 +3688,8 @@ pango_layout_line_ref (PangoLayoutLine *line)
{
PangoLayoutLinePrivate *private = (PangoLayoutLinePrivate *)line;
- g_return_val_if_fail (line != NULL, NULL);
+ if (line == NULL)
+ return NULL;
private->ref_count++;
@@ -3708,7 +3709,9 @@ pango_layout_line_unref (PangoLayoutLine *line)
{
PangoLayoutLinePrivate *private = (PangoLayoutLinePrivate *)line;
- g_return_if_fail (line != NULL);
+ if (line == NULL)
+ return;
+
g_return_if_fail (private->ref_count > 0);
private->ref_count--;
@@ -5153,12 +5156,27 @@ update_run (PangoLayoutIter *iter,
}
}
-static PangoLayoutIter *
+/**
+ * pango_layout_iter_copy:
+ * @iter: a #PangoLayoutIter, may be %NULL
+ *
+ * Copies a #PangLayoutIter.
+ *
+ * Return value: the newly allocated #PangoLayoutIter, which should
+ * be freed with pango_layout_iter_free(), or %NULL if
+ * @iter was %NULL.
+ *
+ * Since: 1.20
+ **/
+PangoLayoutIter *
pango_layout_iter_copy (PangoLayoutIter *iter)
{
PangoLayoutIter *new;
GSList *l;
+ if (iter == NULL)
+ return NULL;
+
new = g_slice_new (PangoLayoutIter);
new->layout = g_object_ref (iter->layout);
@@ -5269,14 +5287,15 @@ pango_layout_get_iter (PangoLayout *layout)
/**
* pango_layout_iter_free:
- * @iter: a #PangoLayoutIter
+ * @iter: a #PangoLayoutIter, may be %NULL
*
* Frees an iterator that's no longer in use.
**/
void
pango_layout_iter_free (PangoLayoutIter *iter)
{
- g_return_if_fail (iter != NULL);
+ if (iter == NULL)
+ return;
g_slist_foreach (iter->line_extents, (GFunc)extents_free, NULL);
g_slist_free (iter->line_extents);
diff --git a/pango/pango-layout.h b/pango/pango-layout.h
index 4e582b45..2deeedcf 100644
--- a/pango/pango-layout.h
+++ b/pango/pango-layout.h
@@ -243,6 +243,7 @@ typedef struct _PangoLayoutIter PangoLayoutIter;
GType pango_layout_iter_get_type (void) G_GNUC_CONST;
PangoLayoutIter *pango_layout_get_iter (PangoLayout *layout);
+PangoLayoutIter *pango_layout_iter_copy (PangoLayoutIter *iter);
void pango_layout_iter_free (PangoLayoutIter *iter);
int pango_layout_iter_get_index (PangoLayoutIter *iter);
diff --git a/pango/pango-matrix.c b/pango/pango-matrix.c
index 828d4f90..a8df59e3 100644
--- a/pango/pango-matrix.c
+++ b/pango/pango-matrix.c
@@ -41,7 +41,7 @@ pango_matrix_get_type (void)
/**
* pango_matrix_copy:
- * @matrix: a #PangoMatrix, can be %NULL
+ * @matrix: a #PangoMatrix, may be %NULL
*
* Copies a #PangoMatrix.
*
@@ -56,31 +56,31 @@ pango_matrix_copy (const PangoMatrix *matrix)
{
PangoMatrix *new_matrix;
- if (matrix)
- {
- new_matrix = g_slice_new (PangoMatrix);
- *new_matrix = *matrix;
- }
- else
- new_matrix = NULL;
+ if (matrix == NULL)
+ return NULL;
+
+ new_matrix = g_slice_new (PangoMatrix);
+
+ *new_matrix = *matrix;
return new_matrix;
}
/**
* pango_matrix_free:
- * @matrix: a #PangoMatrix, or %NULL
+ * @matrix: a #PangoMatrix, may be %NULL
*
* Free a #PangoMatrix created with pango_matrix_copy().
- * Does nothing if @matrix is %NULL.
*
* Since: 1.6
**/
void
pango_matrix_free (PangoMatrix *matrix)
{
- if (matrix)
- g_slice_free (PangoMatrix, matrix);
+ if (matrix == NULL)
+ return;
+
+ g_slice_free (PangoMatrix, matrix);
}
/**
diff --git a/pango/pango.def b/pango/pango.def
index 5dc464dc..3f822f6c 100644
--- a/pango/pango.def
+++ b/pango/pango.def
@@ -175,7 +175,9 @@ EXPORTS
pango_get_mirror_char
pango_get_sysconf_subdirectory
pango_glyph_item_apply_attrs
+ pango_glyph_item_copy
pango_glyph_item_free
+ pango_glyph_item_get_type
pango_glyph_item_letter_space
pango_glyph_item_split
pango_glyph_string_copy
@@ -243,6 +245,7 @@ EXPORTS
pango_layout_is_ellipsized
pango_layout_is_wrapped
pango_layout_iter_at_last_line
+ pango_layout_iter_copy
pango_layout_iter_free
pango_layout_iter_get_baseline
pango_layout_iter_get_char_extents
| 0 | 4 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
f4fad0c741636d017aefd76d58e271466696cc6f
|
Bug 478914 – Use something invalid instead of '?' when validating input
2007-12-10 Behdad Esfahbod <[email protected]>
Bug 478914 – Use something invalid instead of '?' when validating
input text
* pango/pango-layout.c (pango_layout_set_text): Set invalid input
bytes to -1, which gives a unichar value of -1, and eventually a
glyph value of -1, aka PANGO_GLYPH_INVALID_INPUT.
* pango/fonts.c (pango_font_get_glyph_extents),
(pango_font_get_metrics), (pango_font_get_font_map):
* pango/modules.c (build_map):
* pango/pango-context.c (get_script), (get_shaper_and_font),
(string_from_script), (itemize_state_process_run):
* pango/pango-coverage.c (pango_coverage_get):
* pango/pango-impl-utils.h:
* pango/pango-utils.c:
* pango/pangocairo-font.c (pango_cairo_font_get_scaled_font),
(_pango_cairo_font_private_get_hex_box_info),
(_pango_cairo_font_private_get_glyph_extents_missing):
* pango/pangocairo-private.h:
* pango/pangocairo-render.c (_pango_cairo_renderer_draw_frame),
(_pango_cairo_renderer_draw_box_glyph),
(_pango_cairo_renderer_draw_unknown_glyph):
* pango/pangofc-fontmap.c (pango_fc_font_map_get_patterns):
* pango/pangoft2-private.h:
* pango/pangoft2-render.c (pango_ft2_font_render_box_glyph),
(pango_ft2_font_render_glyph), (pango_ft2_renderer_draw_glyph):
* pango/pangoft2.c (pango_ft2_font_get_face),
(pango_ft2_font_get_glyph_extents):
* pango/pangox.c (pango_x_find_subfont), (pango_x_render):
* pango/pangoxft-font.c (_pango_xft_font_get_mini_font),
(get_glyph_extents_missing), (pango_xft_font_get_font):
* pango/pangoxft-private.h:
* pango/pangoxft-render.c (get_total_matrix), (draw_box),
(_pango_xft_renderer_draw_box_glyph),
(_pango_xft_renderer_draw_unknown_glyph),
(pango_xft_renderer_draw_glyphs):
* pango/shape.c (pango_shape):
Render PANGO_GLYPH_INVALID_INPUT to a single-width box with a cross
inside. Also cleanup spewed warnings and warn at the source, where
we fail to find a shaper, instead of at every location that we see
a NULL font.
* pango/pango-font.h:
* docs/pango-sections.txt:
* docs/tmpl/glyphs.sgml:
New public macro:
PANGO_GLYPH_INVALID_INPUT
svn path=/trunk/; revision=2519
|
commit f4fad0c741636d017aefd76d58e271466696cc6f
Author: Behdad Esfahbod <[email protected]>
Date: Mon Dec 10 08:31:33 2007 +0000
Bug 478914 – Use something invalid instead of '?' when validating input
2007-12-10 Behdad Esfahbod <[email protected]>
Bug 478914 – Use something invalid instead of '?' when validating
input text
* pango/pango-layout.c (pango_layout_set_text): Set invalid input
bytes to -1, which gives a unichar value of -1, and eventually a
glyph value of -1, aka PANGO_GLYPH_INVALID_INPUT.
* pango/fonts.c (pango_font_get_glyph_extents),
(pango_font_get_metrics), (pango_font_get_font_map):
* pango/modules.c (build_map):
* pango/pango-context.c (get_script), (get_shaper_and_font),
(string_from_script), (itemize_state_process_run):
* pango/pango-coverage.c (pango_coverage_get):
* pango/pango-impl-utils.h:
* pango/pango-utils.c:
* pango/pangocairo-font.c (pango_cairo_font_get_scaled_font),
(_pango_cairo_font_private_get_hex_box_info),
(_pango_cairo_font_private_get_glyph_extents_missing):
* pango/pangocairo-private.h:
* pango/pangocairo-render.c (_pango_cairo_renderer_draw_frame),
(_pango_cairo_renderer_draw_box_glyph),
(_pango_cairo_renderer_draw_unknown_glyph):
* pango/pangofc-fontmap.c (pango_fc_font_map_get_patterns):
* pango/pangoft2-private.h:
* pango/pangoft2-render.c (pango_ft2_font_render_box_glyph),
(pango_ft2_font_render_glyph), (pango_ft2_renderer_draw_glyph):
* pango/pangoft2.c (pango_ft2_font_get_face),
(pango_ft2_font_get_glyph_extents):
* pango/pangox.c (pango_x_find_subfont), (pango_x_render):
* pango/pangoxft-font.c (_pango_xft_font_get_mini_font),
(get_glyph_extents_missing), (pango_xft_font_get_font):
* pango/pangoxft-private.h:
* pango/pangoxft-render.c (get_total_matrix), (draw_box),
(_pango_xft_renderer_draw_box_glyph),
(_pango_xft_renderer_draw_unknown_glyph),
(pango_xft_renderer_draw_glyphs):
* pango/shape.c (pango_shape):
Render PANGO_GLYPH_INVALID_INPUT to a single-width box with a cross
inside. Also cleanup spewed warnings and warn at the source, where
we fail to find a shaper, instead of at every location that we see
a NULL font.
* pango/pango-font.h:
* docs/pango-sections.txt:
* docs/tmpl/glyphs.sgml:
New public macro:
PANGO_GLYPH_INVALID_INPUT
svn path=/trunk/; revision=2519
diff --git a/ChangeLog b/ChangeLog
index 40e3b3fe..d17108ba 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,54 @@
+2007-12-10 Behdad Esfahbod <[email protected]>
+
+ Bug 478914 – Use something invalid instead of '?' when validating
+ input text
+
+ * pango/pango-layout.c (pango_layout_set_text): Set invalid input
+ bytes to -1, which gives a unichar value of -1, and eventually a
+ glyph value of -1, aka PANGO_GLYPH_INVALID_INPUT.
+
+ * pango/fonts.c (pango_font_get_glyph_extents),
+ (pango_font_get_metrics), (pango_font_get_font_map):
+ * pango/modules.c (build_map):
+ * pango/pango-context.c (get_script), (get_shaper_and_font),
+ (string_from_script), (itemize_state_process_run):
+ * pango/pango-coverage.c (pango_coverage_get):
+ * pango/pango-impl-utils.h:
+ * pango/pango-utils.c:
+ * pango/pangocairo-font.c (pango_cairo_font_get_scaled_font),
+ (_pango_cairo_font_private_get_hex_box_info),
+ (_pango_cairo_font_private_get_glyph_extents_missing):
+ * pango/pangocairo-private.h:
+ * pango/pangocairo-render.c (_pango_cairo_renderer_draw_frame),
+ (_pango_cairo_renderer_draw_box_glyph),
+ (_pango_cairo_renderer_draw_unknown_glyph):
+ * pango/pangofc-fontmap.c (pango_fc_font_map_get_patterns):
+ * pango/pangoft2-private.h:
+ * pango/pangoft2-render.c (pango_ft2_font_render_box_glyph),
+ (pango_ft2_font_render_glyph), (pango_ft2_renderer_draw_glyph):
+ * pango/pangoft2.c (pango_ft2_font_get_face),
+ (pango_ft2_font_get_glyph_extents):
+ * pango/pangox.c (pango_x_find_subfont), (pango_x_render):
+ * pango/pangoxft-font.c (_pango_xft_font_get_mini_font),
+ (get_glyph_extents_missing), (pango_xft_font_get_font):
+ * pango/pangoxft-private.h:
+ * pango/pangoxft-render.c (get_total_matrix), (draw_box),
+ (_pango_xft_renderer_draw_box_glyph),
+ (_pango_xft_renderer_draw_unknown_glyph),
+ (pango_xft_renderer_draw_glyphs):
+ * pango/shape.c (pango_shape):
+ Render PANGO_GLYPH_INVALID_INPUT to a single-width box with a cross
+ inside. Also cleanup spewed warnings and warn at the source, where
+ we fail to find a shaper, instead of at every location that we see
+ a NULL font.
+
+ * pango/pango-font.h:
+ * docs/pango-sections.txt:
+ * docs/tmpl/glyphs.sgml:
+ New public macro:
+
+ PANGO_GLYPH_INVALID_INPUT
+
2007-12-05 Behdad Esfahbod <[email protected]>
* examples/cairotwisted.c (point_on_path): Optimize double math.
diff --git a/docs/pango-sections.txt b/docs/pango-sections.txt
index 7571eea1..af8ce234 100644
--- a/docs/pango-sections.txt
+++ b/docs/pango-sections.txt
@@ -97,6 +97,7 @@ pango_matrix_transform_pixel_rectangle
pango_matrix_get_font_scale_factor
PangoGlyph
PANGO_GLYPH_EMPTY
+PANGO_GLYPH_INVALID_INPUT
PANGO_GLYPH_UNKNOWN_FLAG
PANGO_GET_UNKNOWN_GLYPH
PangoGlyphInfo
diff --git a/docs/tmpl/glyphs.sgml b/docs/tmpl/glyphs.sgml
index 46a2b2f0..5f019c1c 100644
--- a/docs/tmpl/glyphs.sgml
+++ b/docs/tmpl/glyphs.sgml
@@ -304,6 +304,20 @@ Unicode characters (those passing pango_is_zero_width()).
+<!-- ##### MACRO PANGO_GLYPH_INVALID_INPUT ##### -->
+<para>
+The %PANGO_GLYPH_EMPTY macro represents a #PangoGlyph value that has a
+special meaning of invalid input. #PangoLayout produces one such glyph
+per invalid input UTF-8 byte and such a glyph is rendered as a crossed
+box.
+
+Note that this value is defined such that it has the %PANGO_GLYPH_UNKNOWN_FLAG
+on.
+</para>
+
+@Since: 1.20
+
+
<!-- ##### MACRO PANGO_GLYPH_UNKNOWN_FLAG ##### -->
<para>
The %PANGO_GLYPH_UNKNOWN_FLAG macro is a flag value that can be added to
diff --git a/pango/fonts.c b/pango/fonts.c
index c60c602d..56dc4177 100644
--- a/pango/fonts.c
+++ b/pango/fonts.c
@@ -29,8 +29,6 @@
#include "pango-fontmap.h"
#include "pango-impl-utils.h"
-static const char bad_font_warning[] = "%s called with null font argument, expect ugly output";
-
struct _PangoFontDescription
{
char *family_name;
@@ -1314,6 +1312,9 @@ pango_font_find_shaper (PangoFont *font,
* PANGO_DESCENT(), PANGO_LBEARING(), and PANGO_RBEARING() can be used to convert
* from the extents rectangle to more traditional font metrics. The units
* of the rectangles are in 1/PANGO_SCALE of a device unit.
+ *
+ * If @font is %NULL, this function gracefully sets some sane values in the
+ * output variables and returns.
**/
void
pango_font_get_glyph_extents (PangoFont *font,
@@ -1323,12 +1324,6 @@ pango_font_get_glyph_extents (PangoFont *font,
{
if (G_UNLIKELY (!font))
{
-
- if (!_pango_warning_history.get_glyph_extents)
- {
- _pango_warning_history.get_glyph_extents = TRUE;
- g_warning (bad_font_warning, "pango_font_get_glyph_extents");
- }
if (ink_rect)
{
ink_rect->x = PANGO_SCALE;
@@ -1361,6 +1356,9 @@ pango_font_get_glyph_extents (PangoFont *font,
* be provided to indicate that the metrics should be retrieved that
* correspond to the script(s) used by that language.
*
+ * If @font is %NULL, this function gracefully sets some sane values in the
+ * output variables and returns.
+ *
* Return value: a #PangoFontMetrics object. The caller must call pango_font_metrics_unref()
* when finished using the object.
**/
@@ -1370,14 +1368,7 @@ pango_font_get_metrics (PangoFont *font,
{
if (G_UNLIKELY (!font))
{
- PangoFontMetrics *metrics;
-
- if (!_pango_warning_history.get_metrics)
- {
- _pango_warning_history.get_metrics = TRUE;
- g_warning (bad_font_warning, "pango_font_get_metrics");
- }
- metrics = pango_font_metrics_new ();
+ PangoFontMetrics *metrics = pango_font_metrics_new ();
metrics->ascent = PANGO_SCALE * PANGO_UNKNOWN_GLYPH_HEIGHT;
metrics->descent = 0;
@@ -1400,7 +1391,7 @@ pango_font_get_metrics (PangoFont *font,
*
* Gets the font map for which the font was created.
*
- * Return value: the #PangoFontMap for the font
+ * Return value: the #PangoFontMap for the font, or %NULL if @font is %NULL.
*
* Since: 1.10
**/
@@ -1408,15 +1399,7 @@ PangoFontMap *
pango_font_get_font_map (PangoFont *font)
{
if (G_UNLIKELY (!font))
- {
-
- if (!_pango_warning_history.get_font_map)
- {
- _pango_warning_history.get_font_map = TRUE;
- g_warning (bad_font_warning, "pango_font_get_font_map");
- }
- return NULL;
- }
+ return NULL;
if (PANGO_FONT_GET_CLASS (font)->get_font_map)
return PANGO_FONT_GET_CLASS (font)->get_font_map (font);
diff --git a/pango/modules.c b/pango/modules.c
index 5a9d6883..8fad375e 100644
--- a/pango/modules.c
+++ b/pango/modules.c
@@ -621,11 +621,14 @@ build_map (PangoMapInfo *info)
gchar *filename = g_build_filename (pango_get_sysconf_subdirectory (),
"pango.modules",
NULL);
- g_warning ("No builtin or dynamically\n"
- "loaded modules were found. Pango will not work correctly.\n"
- "This probably means there was an error in the creation of:\n"
- " '%s'\n"
- "You should create this file by running pango-querymodules.",
+ g_critical ("No modules found:\n"
+ "No builtin or dynamically loaded modules were found.\n"
+ "PangoFc will not work correctly.\n"
+ "This probably means there was an error in the creation of:\n"
+ " '%s'\n"
+ "You should create this file by running:\n"
+ " pango-querymodules > '%s'",
+ filename,
filename);
g_free (filename);
diff --git a/pango/pango-context.c b/pango/pango-context.c
index 6f588191..1da56fd2 100644
--- a/pango/pango-context.c
+++ b/pango/pango-context.c
@@ -1094,6 +1094,21 @@ get_base_font (ItemizeState *state)
return state->base_font;
}
+static PangoScript
+get_script (ItemizeState *state)
+{
+ /* Always use a basic shaper for vertical layout (ie, east/west gravity)
+ * as none of our script shapers support vertical shaping right now.
+ *
+ * XXX Should move the knowledge into the shaper interface.
+ */
+
+ if (PANGO_GRAVITY_IS_VERTICAL (state->resolved_gravity))
+ return PANGO_SCRIPT_COMMON;
+ else
+ return state->script;
+}
+
static gboolean
get_shaper_and_font (ItemizeState *state,
gunichar wc,
@@ -1108,20 +1123,8 @@ get_shaper_and_font (ItemizeState *state,
return *shape_engine != NULL;
if (!state->exact_engines && !state->fallback_engines)
- {
- /* Always use a basic shaper for vertical layout (ie, east/west gravity)
- * as we do not support vertical shaping as of now.
- */
- PangoScript script;
-
- if (PANGO_GRAVITY_IS_VERTICAL (state->resolved_gravity))
- script = PANGO_SCRIPT_COMMON;
- else
- script = state->script;
-
- get_engines (state->context, state->derived_lang, script,
- &state->exact_engines, &state->fallback_engines);
- }
+ get_engines (state->context, state->derived_lang, get_script (state),
+ &state->exact_engines, &state->fallback_engines);
info.lang = state->derived_lang;
info.wc = wc;
@@ -1289,6 +1292,21 @@ itemize_state_update_for_new_run (ItemizeState *state)
}
}
+static const char *
+string_from_script (PangoScript script)
+{
+ static GEnumClass *class = NULL;
+ GEnumValue *value;
+ if (!class)
+ class = g_type_class_ref (PANGO_TYPE_SCRIPT);
+
+ value = g_enum_get_value (class, script);
+ if (!value)
+ return string_from_script (PANGO_SCRIPT_INVALID_CODE);
+
+ return value->value_nick;
+}
+
static void
itemize_state_process_run (ItemizeState *state)
{
@@ -1351,8 +1369,30 @@ itemize_state_process_run (ItemizeState *state)
PangoEngineShape *shape_engine;
PangoFont *font;
- if (!get_shaper_and_font (state, ' ', &shape_engine, &font))
+ if (G_UNLIKELY (!get_shaper_and_font (state, ' ', &shape_engine, &font)))
{
+ /* If no shaper was found, warn only once per fontmap/script pair */
+ PangoFontMap *fontmap = state->context->font_map;
+ const char *script_name = string_from_script (get_script (state));
+
+ if (!g_object_get_data (G_OBJECT (fontmap), script_name))
+ {
+ const char *what;
+ if (shape_engine == NULL)
+ what = "shape engine";
+ else if (font == NULL)
+ what = "font";
+ else
+ what = "nothing (oops!)";
+
+ g_warning ("failed to find shape engine, expect ugly output. engine-type='%s', script='%s'",
+ pango_font_map_get_shape_engine_type (fontmap),
+ script_name);
+
+ g_object_set_data_full (G_OBJECT (fontmap), script_name,
+ GINT_TO_POINTER (1), NULL);
+ }
+
shape_engine = _pango_get_fallback_shaper ();
font = NULL;
}
diff --git a/pango/pango-coverage.c b/pango/pango-coverage.c
index 340ccf7c..4ecdaf78 100644
--- a/pango/pango-coverage.c
+++ b/pango/pango-coverage.c
@@ -170,7 +170,12 @@ pango_coverage_get (PangoCoverage *coverage,
int block_index;
g_return_val_if_fail (coverage != NULL, PANGO_COVERAGE_NONE);
- g_return_val_if_fail (index >= 0, PANGO_COVERAGE_NONE);
+
+ /* index should really have been defined unsigned. Work around
+ * it by just returning NONE.
+ */
+ if (G_UNLIKELY (index < 0))
+ return PANGO_COVERAGE_NONE;
block_index = index / 256;
diff --git a/pango/pango-font.h b/pango/pango-font.h
index 1309c557..66e68aa8 100644
--- a/pango/pango-font.h
+++ b/pango/pango-font.h
@@ -372,6 +372,7 @@ struct _PangoFontClass
#endif /* PANGO_ENABLE_BACKEND */
#define PANGO_GLYPH_EMPTY ((PangoGlyph)0x0FFFFFFF)
+#define PANGO_GLYPH_INVALID_INPUT ((PangoGlyph)0xFFFFFFFF)
#define PANGO_GLYPH_UNKNOWN_FLAG ((PangoGlyph)0x10000000)
#define PANGO_GET_UNKNOWN_GLYPH(wc) ((PangoGlyph)(wc)|PANGO_GLYPH_UNKNOWN_FLAG)
diff --git a/pango/pango-impl-utils.h b/pango/pango-impl-utils.h
index 1f60d84f..e21988f1 100644
--- a/pango/pango-impl-utils.h
+++ b/pango/pango-impl-utils.h
@@ -75,21 +75,6 @@ prefix ## _get_type (void) \
parent_type, G_TYPE_FLAG_ABSTRACT)
-
-/* Warning history. Used to not spew some warnings more than once. */
-typedef struct _PangoWarningHistory PangoWarningHistory;
-
-struct _PangoWarningHistory {
- guint shape_font : 1;
- guint shape_shape_engine : 1;
- guint get_glyph_extents : 1;
- guint get_metrics : 1;
- guint get_font_map : 1;
-};
-
-extern PangoWarningHistory _pango_warning_history;
-
-
/* String interning for static strings */
#define I_(string) g_intern_static_string (string)
diff --git a/pango/pango-layout.c b/pango/pango-layout.c
index 4ddb4b7c..55c8a1e1 100644
--- a/pango/pango-layout.c
+++ b/pango/pango-layout.c
@@ -961,8 +961,13 @@ pango_layout_set_text (PangoLayout *layout,
if (!*end)
break;
+ /* Replace invalid bytes with -1. The -1 will be converted to
+ * ((gunichar) -1) by glib, and that in turn yields a glyph value of
+ * ((PangoGlyph) -1) by PANGO_GET_UNKNOWN_GLYPH(-1),
+ * and that's PANGO_GLYPH_INVALID_INPUT.
+ */
if (!valid)
- *end++ = '?';
+ *end++ = -1;
start = end;
}
diff --git a/pango/pango-utils.c b/pango/pango-utils.c
index 0975af94..f4b52d71 100644
--- a/pango/pango-utils.c
+++ b/pango/pango-utils.c
@@ -59,8 +59,6 @@ struct PangoAlias
static GHashTable *pango_aliases_ht = NULL;
-PangoWarningHistory _pango_warning_history = { FALSE, FALSE, FALSE };
-
/**
* pango_version:
*
@@ -1585,7 +1583,7 @@ pango_is_zero_width (gunichar ch)
/**
* pango_quantize_line_geometry:
- * @thickness: pointer to the thickness of a line, in Pango scaled units
+ * @thickness: pointer to the thickness of a line, in Pango units
* @position: corresponding position
*
* Quantizes the thickness and position of a line, typically an
@@ -1593,8 +1591,9 @@ pango_is_zero_width (gunichar ch)
* multiples of %PANGO_SCALE. The purpose of this function is to avoid
* such lines looking blurry.
*
- * Care is taken to make sure @thickness is at least 1 when this function
- * returns, but returned @position may become zero as a result of rounding.
+ * Care is taken to make sure @thickness is at least one pixel when this
+ * function returns, but returned @position may become zero as a result
+ * of rounding.
*
* Since: 1.12
*/
diff --git a/pango/pangocairo-font.c b/pango/pangocairo-font.c
index c33d3fde..09255862 100644
--- a/pango/pangocairo-font.c
+++ b/pango/pangocairo-font.c
@@ -27,8 +27,6 @@
#include "pangocairo-private.h"
#include "pango-impl-utils.h"
-PangoCairoWarningHistory _pango_cairo_warning_history = { FALSE };
-
#define PANGO_CAIRO_FONT_PRIVATE(font) \
((PangoCairoFontPrivate *) \
(font == NULL ? NULL : \
@@ -151,7 +149,8 @@ done:
* The scaled font can be referenced and kept using
* cairo_scaled_font_reference().
*
- * Return value: the #cairo_scaled_font_t used by @font
+ * Return value: the #cairo_scaled_font_t used by @font,
+ * or %NULL if @font is %NULL.
*
* Since: 1.18
**/
@@ -160,15 +159,8 @@ pango_cairo_font_get_scaled_font (PangoCairoFont *cfont)
{
PangoCairoFontPrivate *cf_priv;
- if (G_UNLIKELY (!PANGO_IS_CAIRO_FONT (cfont)))
- {
- if (!_pango_cairo_warning_history.font_get_scaled_font)
- {
- _pango_cairo_warning_history.font_get_scaled_font = TRUE;
- g_warning ("pango_cairo_font_get_scaled_font called with bad font, expect ugly output");
- }
- return NULL;
- }
+ if (G_UNLIKELY (!cfont))
+ return NULL;
cf_priv = PANGO_CAIRO_FONT_PRIVATE (cfont);
@@ -408,7 +400,7 @@ _pango_cairo_font_private_get_hex_box_info (PangoCairoFontPrivate *cf_priv)
cairo_font_options_destroy (font_options);
- scaled_mini_font = pango_cairo_font_get_scaled_font (mini_font);
+ scaled_mini_font = pango_cairo_font_get_scaled_font ((PangoCairoFont *) mini_font);
for (i = 0 ; i < 16 ; i++)
{
@@ -576,6 +568,7 @@ _pango_cairo_font_private_get_glyph_extents_missing (PangoCairoFontPrivate *cf_p
PangoRectangle *logical_rect)
{
PangoCairoFontHexBoxInfo *hbi;
+ gunichar ch;
gint rows, cols;
hbi = _pango_cairo_font_private_get_hex_box_info (cf_priv);
@@ -585,8 +578,13 @@ _pango_cairo_font_private_get_glyph_extents_missing (PangoCairoFontPrivate *cf_p
return;
}
+ ch = glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
+
rows = hbi->rows;
- cols = ((glyph & ~PANGO_GLYPH_UNKNOWN_FLAG) > 0xffff ? 6 : 4) / rows;
+ if (G_UNLIKELY (glyph == PANGO_GLYPH_INVALID_INPUT || ch > 0x10FFFF))
+ cols = 1;
+ else
+ cols = ((glyph & ~PANGO_GLYPH_UNKNOWN_FLAG) > 0xffff ? 6 : 4) / rows;
if (ink_rect)
{
diff --git a/pango/pangocairo-private.h b/pango/pangocairo-private.h
index 05dbb5a2..bf53e1f9 100644
--- a/pango/pangocairo-private.h
+++ b/pango/pangocairo-private.h
@@ -132,14 +132,6 @@ GType pango_cairo_renderer_get_type (void) G_GNUC_CONST;
const cairo_font_options_t *_pango_cairo_context_get_merged_font_options (PangoContext *context);
-typedef struct _PangoCairoWarningHistory PangoCairoWarningHistory;
-
-struct _PangoCairoWarningHistory {
- guint font_get_scaled_font : 1;
-};
-
-extern PangoCairoWarningHistory _pango_cairo_warning_history;
-
G_END_DECLS
#endif /* __PANGOCAIRO_PRIVATE_H__ */
diff --git a/pango/pangocairo-render.c b/pango/pangocairo-render.c
index 21792cb1..17bf976f 100644
--- a/pango/pangocairo-render.c
+++ b/pango/pangocairo-render.c
@@ -21,6 +21,8 @@
#include <config.h>
+#include <math.h>
+
#include "pangocairo-private.h"
typedef struct _PangoCairoRendererClass PangoCairoRendererClass;
@@ -58,15 +60,18 @@ set_color (PangoCairoRenderer *crenderer,
color->blue / 65535.);
}
-/* modifies cairo_set_line_width() without doing cairo_save/restore() */
+/* note: modifies crenderer->cr without doing cairo_save/restore() */
static void
_pango_cairo_renderer_draw_frame (PangoCairoRenderer *crenderer,
double x,
double y,
double width,
double height,
- double line_width)
+ double line_width,
+ gboolean invalid)
{
+ cairo_t *cr = crenderer->cr;
+
if (crenderer->do_path)
{
double d2 = line_width * .5, d = line_width;
@@ -74,19 +79,95 @@ _pango_cairo_renderer_draw_frame (PangoCairoRenderer *crenderer,
/* we draw an outer box in one winding direction and an inner one in the
* opposite direction. This works for both cairo windings rules.
*
- * what we really want is cairo_stroke_to_path().
+ * what we really want is cairo_stroke_to_path(), but that's not
+ * implemented in cairo yet.
*/
/* outer */
- cairo_rectangle (crenderer->cr, x-d2, y-d2, width+d, height+d);
+ cairo_rectangle (cr, x-d2, y-d2, width+d, height+d);
+
/* inner */
- cairo_rectangle (crenderer->cr, x+d2 + (width-d), y+d2, - (width-d), height-d);
+ if (invalid)
+ {
+ /* delicacies of computing the joint... this is REALLY slow */
+
+ double alpha, tan_alpha2, cos_alpha;
+ double sx, sy;
+
+ alpha = atan2 (height, width);
+
+ tan_alpha2 = tan (alpha * .5);
+ if (tan_alpha2 < 1e-5 || (sx = d2 / tan_alpha2, 2. * sx > width - d))
+ sx = (width - d) * .5;
+
+ cos_alpha = cos (alpha);
+ if (cos_alpha < 1e-5 || (sy = d2 / cos_alpha, 2. * sy > height - d))
+ sy = (height - d) * .5;
+
+ /* top triangle */
+ cairo_new_sub_path (cr);
+ cairo_line_to (cr, x+width-sx, y+d2);
+ cairo_line_to (cr, x+sx, y+d2);
+ cairo_line_to (cr, x+.5*width, y+.5*height-sy);
+ cairo_close_path (cr);
+
+ /* bottom triangle */
+ cairo_new_sub_path (cr);
+ cairo_line_to (cr, x+width-sx, y+height-d2);
+ cairo_line_to (cr, x+.5*width, y+.5*height+sy);
+ cairo_line_to (cr, x+sx, y+height-d2);
+ cairo_close_path (cr);
+
+
+ alpha = G_PI_2 - alpha;
+ tan_alpha2 = tan (alpha * .5);
+ if (tan_alpha2 < 1e-5 || (sy = d2 / tan_alpha2, 2. * sy > height - d))
+ sy = (width - d) * .5;
+
+ cos_alpha = cos (alpha);
+ if (cos_alpha < 1e-5 || (sx = d2 / cos_alpha, 2. * sx > width - d))
+ sx = (width - d) * .5;
+
+ /* left triangle */
+ cairo_new_sub_path (cr);
+ cairo_line_to (cr, x+d2, y+sy);
+ cairo_line_to (cr, x+d2, y+height-sy);
+ cairo_line_to (cr, x+.5*width-sx, y+.5*height);
+ cairo_close_path (cr);
+
+ /* right triangle */
+ cairo_new_sub_path (cr);
+ cairo_line_to (cr, x+width-d2, y+sy);
+ cairo_line_to (cr, x+.5*width+sx, y+.5*height);
+ cairo_line_to (cr, x+width-d2, y+height-sy);
+ cairo_close_path (cr);
+ }
+ else
+ cairo_rectangle (cr, x+width-d2, y+d2, - (width-d), height-d);
}
else
{
- cairo_rectangle (crenderer->cr, x, y, width, height);
- cairo_set_line_width (crenderer->cr, line_width);
- cairo_stroke (crenderer->cr);
+ cairo_rectangle (cr, x, y, width, height);
+
+ if (invalid)
+ {
+ /* draw an X */
+
+ cairo_new_sub_path (cr);
+ cairo_move_to (cr, x, y);
+ cairo_rel_line_to (cr, width, height);
+
+ cairo_new_sub_path (cr);
+ cairo_move_to (cr, x + width, y);
+ cairo_rel_line_to (cr, -width, height);
+
+ cairo_set_line_cap (cr, CAIRO_LINE_CAP_BUTT);
+ }
+
+ cairo_set_line_width (cr, line_width);
+ cairo_set_line_join (cr, CAIRO_LINE_JOIN_MITER);
+ cairo_set_miter_limit (cr, 2.);
+ cairo_stroke (cr);
}
}
@@ -94,7 +175,8 @@ static void
_pango_cairo_renderer_draw_box_glyph (PangoCairoRenderer *crenderer,
PangoGlyphInfo *gi,
double cx,
- double cy)
+ double cy,
+ gboolean invalid)
{
double temp_x, temp_y;
@@ -107,7 +189,8 @@ _pango_cairo_renderer_draw_box_glyph (PangoCairoRenderer *crenderer,
cy + 1.5 - PANGO_UNKNOWN_GLYPH_HEIGHT,
(double)gi->geometry.width / PANGO_SCALE - 3.0,
PANGO_UNKNOWN_GLYPH_HEIGHT - 3.0,
- 1.0);
+ 1.0,
+ invalid);
cairo_move_to (crenderer->cr, temp_x, temp_y);
cairo_restore (crenderer->cr);
@@ -128,30 +211,42 @@ _pango_cairo_renderer_draw_unknown_glyph (PangoCairoRenderer *crenderer,
double temp_x, temp_y;
PangoCairoFontHexBoxInfo *hbi;
gunichar ch;
+ gboolean invalid_input;
cairo_save (crenderer->cr);
cairo_get_current_point (crenderer->cr, &temp_x, &temp_y);
- hbi = _pango_cairo_font_get_hex_box_info ((PangoCairoFont *)font);
+ ch = gi->glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
+ invalid_input = G_UNLIKELY (gi->glyph == PANGO_GLYPH_INVALID_INPUT || ch > 0x10FFFF);
+ hbi = _pango_cairo_font_get_hex_box_info ((PangoCairoFont *)font);
if (!hbi || !_pango_cairo_font_install ((PangoFont *)(hbi->font), crenderer->cr))
{
- _pango_cairo_renderer_draw_box_glyph (crenderer, gi, cx, cy);
+ _pango_cairo_renderer_draw_box_glyph (crenderer, gi, cx, cy, invalid_input);
goto done;
}
- ch = gi->glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
-
rows = hbi->rows;
- cols = (ch > 0xffff ? 6 : 4) / rows;
- g_snprintf (buf, sizeof(buf), (ch > 0xffff) ? "%06X" : "%04X", ch);
+ if (G_UNLIKELY (invalid_input))
+ {
+ cols = 1;
+ }
+ else
+ {
+ cols = (ch > 0xffff ? 6 : 4) / rows;
+ g_snprintf (buf, sizeof(buf), (ch > 0xffff) ? "%06X" : "%04X", ch);
+ }
_pango_cairo_renderer_draw_frame (crenderer,
cx + hbi->pad_x * 1.5,
cy + hbi->box_descent - hbi->box_height + hbi->pad_y * 0.5,
(double)gi->geometry.width / PANGO_SCALE - 3 * hbi->pad_x,
(hbi->box_height - hbi->pad_y),
- hbi->line_width);
+ hbi->line_width,
+ invalid_input);
+
+ if (invalid_input)
+ goto done;
x0 = cx + hbi->pad_x * 3.0;
y0 = cy + hbi->box_descent - hbi->pad_y * 2;
diff --git a/pango/pangofc-fontmap.c b/pango/pangofc-fontmap.c
index 4840a1f0..adc8c796 100644
--- a/pango/pangofc-fontmap.c
+++ b/pango/pangofc-fontmap.c
@@ -1072,18 +1072,14 @@ pango_fc_font_map_get_patterns (PangoFontMap *fontmap,
if (!font_patterns)
{
- g_printerr ("No fonts found; this probably means that the fontconfig\n"
+ g_critical ("No fonts found:\n"
+ "This probably means that the fontconfig\n"
"library is not correctly configured. You may need to\n"
"edit the fonts.conf configuration file. More information\n"
"about fontconfig can be found in the fontconfig(3) manual\n"
- "page and on http://fontconfig.org\n");
+ "page and on http://fontconfig.org");
- /* There is no point in proceeding; we'll just get a segfault later
- * on, and a bunch more possibly confusing error messages in between.
- */
-
- /* return NULL; */
- exit (1);
+ font_patterns = FcFontSetCreate ();
}
patterns = g_slice_new (PangoFcPatternSet);
diff --git a/pango/pangoft2-private.h b/pango/pangoft2-private.h
index 8388ec9f..cf00d38e 100644
--- a/pango/pangoft2-private.h
+++ b/pango/pangoft2-private.h
@@ -115,12 +115,4 @@ GType pango_ft2_renderer_get_type (void) G_GNUC_CONST;
PangoRenderer *_pango_ft2_font_map_get_renderer (PangoFT2FontMap *ft2fontmap);
-typedef struct _PangoFT2WarningHistory PangoFT2WarningHistory;
-
-struct _PangoFT2WarningHistory {
- guint get_face : 1;
-};
-
-extern PangoFT2WarningHistory _pango_ft2_warning_history;
-
#endif /* __PANGOFT2_PRIVATE_H__ */
diff --git a/pango/pangoft2-render.c b/pango/pangoft2-render.c
index ef052efa..5bf98a20 100644
--- a/pango/pangoft2-render.c
+++ b/pango/pangoft2-render.c
@@ -100,9 +100,10 @@ pango_ft2_free_rendered_glyph (PangoFT2RenderedGlyph *rendered)
}
static PangoFT2RenderedGlyph *
-pango_ft2_font_render_box_glyph (int width,
- int height,
- int top)
+pango_ft2_font_render_box_glyph (int width,
+ int height,
+ int top,
+ gboolean invalid)
{
PangoFT2RenderedGlyph *box;
int i, j, offset1, offset2, line_width;
@@ -150,14 +151,38 @@ pango_ft2_font_render_box_glyph (int width,
}
}
+ if (invalid)
+ {
+ /* XXX This may scrabble memory. Didn't check close enough */
+ int inc = PANGO_SCALE * MAX (width - line_width, 0) / (height + 1);
+ offset1 = PANGO_SCALE;
+ offset2 = PANGO_SCALE * MAX (width - line_width - 1, 0) ;
+ for (i = box->bitmap.pitch;
+ i < (box->bitmap.rows - 1) * box->bitmap.pitch;
+ i += box->bitmap.pitch)
+ {
+ for (j = 0; j < line_width; j++)
+ {
+ box->bitmap.buffer[PANGO_PIXELS (offset1) + i + j] = 0xff;
+ box->bitmap.buffer[PANGO_PIXELS (offset2) + i + j] = 0xff;
+ }
+ offset1 += inc;
+ offset2 -= inc;
+ }
+
+ }
+
return box;
}
static PangoFT2RenderedGlyph *
pango_ft2_font_render_glyph (PangoFont *font,
- int glyph_index)
+ PangoGlyph glyph_index)
{
FT_Face face;
+ gboolean invalid_input;
+
+ invalid_input = glyph_index == PANGO_GLYPH_INVALID_INPUT || (glyph_index & ~PANGO_GLYPH_UNKNOWN_FLAG) > 0x10FFFF;
if (glyph_index & PANGO_GLYPH_UNKNOWN_FLAG)
{
@@ -173,7 +198,8 @@ pango_ft2_font_render_glyph (PangoFont *font,
box = pango_ft2_font_render_box_glyph (PANGO_PIXELS (metrics->approximate_char_width),
PANGO_PIXELS (metrics->ascent + metrics->descent),
- PANGO_PIXELS (metrics->ascent));
+ PANGO_PIXELS (metrics->ascent),
+ invalid_input);
pango_font_metrics_unref (metrics);
return box;
@@ -207,7 +233,8 @@ pango_ft2_font_render_glyph (PangoFont *font,
generic_box:
return pango_ft2_font_render_box_glyph (PANGO_UNKNOWN_GLYPH_WIDTH,
PANGO_UNKNOWN_GLYPH_HEIGHT,
- PANGO_UNKNOWN_GLYPH_HEIGHT);
+ PANGO_UNKNOWN_GLYPH_HEIGHT,
+ invalid_input);
}
}
@@ -231,16 +258,17 @@ pango_ft2_renderer_draw_glyph (PangoRenderer *renderer,
if (glyph & PANGO_GLYPH_UNKNOWN_FLAG)
{
- glyph = pango_ft2_get_unknown_glyph (font);
- if (glyph == PANGO_GLYPH_EMPTY)
- {
- /* No unknown glyph found for the font, draw a box */
+ /* Since we don't draw hexbox for FT2 renderer,
+ * unifiy the rendered bitmap in the cache by converting
+ * all missing glyphs to either INVALID_INPUT or UNKNOWN_FLAG.
+ */
- /* Since we only draw an empty box for FT2 renderer,
- * we unify the rendered bitmaps in the cache.
- */
- glyph = PANGO_GLYPH_UNKNOWN_FLAG;
- }
+ gunichar wc = glyph & (~PANGO_GLYPH_UNKNOWN_FLAG);
+
+ if (G_UNLIKELY (glyph == PANGO_GLYPH_INVALID_INPUT || wc > 0x10FFFF))
+ glyph = PANGO_GLYPH_INVALID_INPUT;
+ else
+ glyph = PANGO_GLYPH_UNKNOWN_FLAG;
}
rendered_glyph = _pango_ft2_font_get_cache_glyph_data (font, glyph);
diff --git a/pango/pangoft2.c b/pango/pangoft2.c
index f2d85af9..ff3ca319 100644
--- a/pango/pangoft2.c
+++ b/pango/pangoft2.c
@@ -33,8 +33,6 @@
#include "pangofc-fontmap.h"
#include "pangofc-private.h"
-PangoFT2WarningHistory _pango_ft2_warning_history = { FALSE };
-
/* for compatibility with older freetype versions */
#ifndef FT_LOAD_TARGET_MONO
#define FT_LOAD_TARGET_MONO FT_LOAD_MONOCHROME
@@ -161,7 +159,8 @@ set_transform (PangoFT2Font *ft2font)
* face from pango_fc_font_lock_face() you must call
* pango_fc_font_unlock_face().
*
- * Return value: a pointer to a <type>FT_Face</type> structure, with the size set correctly
+ * Return value: a pointer to a <type>FT_Face</type> structure, with the size set correctly,
+ * or %NULL if @font is %NULL.
**/
FT_Face
pango_ft2_font_get_face (PangoFont *font)
@@ -175,15 +174,8 @@ pango_ft2_font_get_face (PangoFont *font)
int hintstyle;
int id;
- if (G_UNLIKELY (!PANGO_FT2_IS_FONT (font)))
- {
- if (!_pango_ft2_warning_history.get_face)
- {
- _pango_ft2_warning_history.get_face = TRUE;
- g_warning ("pango_ft2_font_get_face called with bad font, expect ugly output");
- }
- return NULL;
- }
+ if (G_UNLIKELY (!font))
+ return NULL;
pattern = fcfont->font_pattern;
@@ -336,40 +328,35 @@ pango_ft2_font_get_glyph_extents (PangoFont *font,
if (glyph & PANGO_GLYPH_UNKNOWN_FLAG)
{
- glyph = pango_ft2_get_unknown_glyph (font);
- if (glyph == PANGO_GLYPH_EMPTY)
- {
- /* No unknown glyph found for the font, draw a box */
- PangoFontMetrics *metrics = pango_font_get_metrics (font, NULL);
+ PangoFontMetrics *metrics = pango_font_get_metrics (font, NULL);
- if (metrics)
+ if (metrics)
+ {
+ if (ink_rect)
{
- if (ink_rect)
- {
- ink_rect->x = PANGO_SCALE;
- ink_rect->width = metrics->approximate_char_width - 2 * PANGO_SCALE;
- ink_rect->y = - (metrics->ascent - PANGO_SCALE);
- ink_rect->height = metrics->ascent + metrics->descent - 2 * PANGO_SCALE;
- }
- if (logical_rect)
- {
- logical_rect->x = 0;
- logical_rect->width = metrics->approximate_char_width;
- logical_rect->y = -metrics->ascent;
- logical_rect->height = metrics->ascent + metrics->descent;
- }
-
- pango_font_metrics_unref (metrics);
+ ink_rect->x = PANGO_SCALE;
+ ink_rect->width = metrics->approximate_char_width - 2 * PANGO_SCALE;
+ ink_rect->y = - (metrics->ascent - PANGO_SCALE);
+ ink_rect->height = metrics->ascent + metrics->descent - 2 * PANGO_SCALE;
}
- else
+ if (logical_rect)
{
- if (ink_rect)
- ink_rect->x = ink_rect->y = ink_rect->height = ink_rect->width = 0;
- if (logical_rect)
- logical_rect->x = logical_rect->y = logical_rect->height = logical_rect->width = 0;
+ logical_rect->x = 0;
+ logical_rect->width = metrics->approximate_char_width;
+ logical_rect->y = -metrics->ascent;
+ logical_rect->height = metrics->ascent + metrics->descent;
}
- return;
+
+ pango_font_metrics_unref (metrics);
+ }
+ else
+ {
+ if (ink_rect)
+ ink_rect->x = ink_rect->y = ink_rect->height = ink_rect->width = 0;
+ if (logical_rect)
+ logical_rect->x = logical_rect->y = logical_rect->height = logical_rect->width = 0;
}
+ return;
}
info = pango_ft2_font_get_glyph_info (font, glyph, TRUE);
diff --git a/pango/pangox.c b/pango/pangox.c
index 924164d3..bf2f12cd 100644
--- a/pango/pangox.c
+++ b/pango/pangox.c
@@ -117,10 +117,7 @@ pango_x_find_subfont (PangoFont *font,
PangoXFont *xfont = (PangoXFont *)font;
if (subfont_index < 1 || subfont_index > xfont->n_subfonts)
- {
- g_warning ("Invalid subfont %d", subfont_index);
- return NULL;
- }
+ return NULL;
return xfont->subfonts[subfont_index-1];
}
@@ -411,7 +408,7 @@ pango_x_render (Display *display,
glyph_y >= -16384 && glyph_y <= 32767))
goto next_glyph;
- if ((glyph & PANGO_GLYPH_UNKNOWN_FLAG) == 0)
+ if (G_LIKELY ((glyph & PANGO_GLYPH_UNKNOWN_FLAG) == 0))
{
guint16 index = PANGO_X_GLYPH_INDEX (glyph);
guint16 subfont_index = PANGO_X_GLYPH_SUBFONT (glyph);
@@ -455,6 +452,7 @@ pango_x_render (Display *display,
int baseline;
int stroke_thick;
gunichar wc;
+ gboolean invalid_input;
unknown_glyph:
FLUSH;
@@ -479,12 +477,13 @@ pango_x_render (Display *display,
x2 = x1 + PANGO_PIXELS (glyphs->glyphs[i].geometry.width);
baseline = glyph_y;
- stroke_thick = MAX ((int) (0.5 + 0.075 * (y2 - y1)), 1);
+ stroke_thick = MAX ((int) (0.5 + 0.025 * (y2 - y1)), 1);
if (glyph & PANGO_GLYPH_UNKNOWN_FLAG)
- wc = glyph & (~PANGO_GLYPH_UNKNOWN_FLAG);
+ wc = glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
else
wc = 0;
+ invalid_input = glyph == PANGO_GLYPH_INVALID_INPUT || wc > 0x10FFFF;
switch (wc)
{
@@ -544,7 +543,7 @@ pango_x_render (Display *display,
default:
{
/* Perhaps we should draw the box-with-numbers as in the
- * Xft backend, though we have no guarantee of having
+ * other backends, though we have no guarantee of having
* an appropriate size of font. Right now, we just
* draw an empty box. (To draw the box-with-numbers.
* the backends would have to be changed to use
@@ -572,6 +571,15 @@ pango_x_render (Display *display,
XFillRectangle (display, d, gc,
x1, y2 - stroke_thick,
x2 - x1, stroke_thick);
+ if (invalid_input)
+ {
+ XDrawLine (display, d, gc,
+ x1, y1,
+ x2-1, y2-1);
+ XDrawLine (display, d, gc,
+ x2-1, y1,
+ x1, y2-1);
+ }
break;
}
diff --git a/pango/pangoxft-font.c b/pango/pangoxft-font.c
index 73e87104..2dc14452 100644
--- a/pango/pangoxft-font.c
+++ b/pango/pangoxft-font.c
@@ -27,8 +27,6 @@
#include "pangoxft-private.h"
#include "pangofc-private.h"
-PangoXftWarningHistory _pango_xft_warning_history = { FALSE };
-
#define PANGO_XFT_FONT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_XFT_FONT, PangoXftFontClass))
#define PANGO_XFT_IS_FONT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_XFT_FONT))
#define PANGO_XFT_FONT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_XFT_FONT, PangoXftFontClass))
@@ -153,12 +151,12 @@ _pango_xft_font_get_mini_font (PangoXftFont *xfont)
pango_font_description_set_size (desc, new_size);
xfont->mini_font = pango_font_map_load_font (fcfont->fontmap, context, desc);
- if (!xfont->mini_font)
- return NULL;
-
pango_font_description_free (desc);
g_object_unref (context);
+ if (!xfont->mini_font)
+ return NULL;
+
mini_xft = xft_font_get_font (xfont->mini_font);
for (i = 0 ; i < 16 ; i++)
@@ -169,7 +167,6 @@ _pango_xft_font_get_mini_font (PangoXftFont *xfont)
height = MAX (height, extents.height);
}
-
xfont->mini_width = PANGO_SCALE * width;
xfont->mini_height = PANGO_SCALE * height;
xfont->mini_pad = PANGO_SCALE * MIN (height / 2, MAX ((int)(2.2 * height + 27) / 28, 1));
@@ -210,8 +207,15 @@ get_glyph_extents_missing (PangoXftFont *xfont,
{
PangoFont *font = PANGO_FONT (xfont);
XftFont *xft_font = xft_font_get_font (font);
+ gunichar ch;
+ gint cols;
+
+ ch = glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
- gint cols = (glyph & ~PANGO_GLYPH_UNKNOWN_FLAG) > 0xffff ? 3 : 2;
+ if (G_UNLIKELY (glyph == PANGO_GLYPH_INVALID_INPUT || ch > 0x10FFFF))
+ cols = 1;
+ else
+ cols = ch > 0xffff ? 3 : 2;
_pango_xft_font_get_mini_font (xfont);
@@ -463,20 +467,13 @@ pango_xft_font_real_shutdown (PangoFcFont *fcfont)
*
* Returns the XftFont of a font.
*
- * Return value: the XftFont associated to @font.
+ * Return value: the XftFont associated to @font, or %NULL if @font is %NULL.
**/
XftFont *
pango_xft_font_get_font (PangoFont *font)
{
- if (G_UNLIKELY (!PANGO_XFT_IS_FONT (font)))
- {
- if (!_pango_xft_warning_history.get_font)
- {
- _pango_xft_warning_history.get_font = TRUE;
- g_warning ("pango_xft_font_get_font called with bad font, expect ugly output");
- }
- return NULL;
- }
+ if (G_UNLIKELY (!font))
+ return NULL;
return xft_font_get_font (font);
}
diff --git a/pango/pangoxft-private.h b/pango/pangoxft-private.h
index 1ee2da68..fb1c2444 100644
--- a/pango/pangoxft-private.h
+++ b/pango/pangoxft-private.h
@@ -34,9 +34,9 @@ struct _PangoXftFont
XftFont *xft_font; /* created on demand */
PangoFont *mini_font; /* font used to display missing glyphs */
- guint16 mini_width; /* metrics for missing glyph drawing */
- guint16 mini_height;
- guint16 mini_pad;
+ guint mini_width; /* metrics for missing glyph drawing */
+ guint mini_height;
+ guint mini_pad;
GHashTable *glyph_info; /* Used only when we can't get
* glyph extents out of Xft because
@@ -55,14 +55,6 @@ PangoRenderer *_pango_xft_font_map_get_renderer (PangoXftFontMap *xftfontmap);
PangoFont *_pango_xft_font_get_mini_font (PangoXftFont *xfont);
-typedef struct _PangoXftWarningHistory PangoXftWarningHistory;
-
-struct _PangoXftWarningHistory {
- guint get_font : 1;
-};
-
-extern PangoXftWarningHistory _pango_xft_warning_history;
-
G_END_DECLS
#endif /* __PANGOXFT_PRIVATE_H__ */
diff --git a/pango/pangoxft-render.c b/pango/pangoxft-render.c
index efaae64e..5505ba5c 100644
--- a/pango/pangoxft-render.c
+++ b/pango/pangoxft-render.c
@@ -289,13 +289,32 @@ box_in_bounds (PangoRenderer *renderer,
}
}
+static void
+get_total_matrix (PangoMatrix *total,
+ const PangoMatrix *global,
+ double x,
+ double y,
+ double width,
+ double height)
+{
+ PangoMatrix local = PANGO_MATRIX_INIT;
+ gdouble angle = atan2 (height, width);
+
+ pango_matrix_translate (&local, x, y);
+ pango_matrix_rotate (&local, -angle * (180. / G_PI));
+
+ *total = *global;
+ pango_matrix_concat (total, &local);
+}
+
static void
draw_box (PangoRenderer *renderer,
gint line_width,
gint x,
gint y,
gint width,
- gint height)
+ gint height,
+ gboolean invalid)
{
pango_renderer_draw_rectangle (renderer, PANGO_RENDER_PART_FOREGROUND,
x, y, width, line_width);
@@ -305,13 +324,49 @@ draw_box (PangoRenderer *renderer,
x + width - line_width, y + line_width, line_width, height - line_width * 2);
pango_renderer_draw_rectangle (renderer, PANGO_RENDER_PART_FOREGROUND,
x, y + height - line_width, width, line_width);
+
+ if (invalid)
+ {
+ int length;
+ double in_width, in_height;
+ PangoMatrix orig_matrix = PANGO_MATRIX_INIT, new_matrix;
+ const PangoMatrix *porig_matrix;
+
+ in_width = pango_units_to_double (width - 2 * line_width);
+ in_height = pango_units_to_double (height - 2 * line_width);
+ length = PANGO_SCALE * sqrt (in_width*in_width + in_height*in_height);
+
+ porig_matrix = pango_renderer_get_matrix (renderer);
+ if (porig_matrix)
+ {
+ orig_matrix = *porig_matrix;
+ porig_matrix = &orig_matrix;
+ }
+
+ get_total_matrix (&new_matrix, &orig_matrix,
+ pango_units_to_double (x + line_width), pango_units_to_double (y + line_width),
+ in_width, in_height);
+ pango_renderer_set_matrix (renderer, &new_matrix);
+ pango_renderer_draw_rectangle (renderer, PANGO_RENDER_PART_FOREGROUND,
+ 0, -line_width / 2, length, line_width);
+
+ get_total_matrix (&new_matrix, &orig_matrix,
+ pango_units_to_double (x + line_width), pango_units_to_double (y + height - line_width),
+ in_width, -in_height);
+ pango_renderer_set_matrix (renderer, &new_matrix);
+ pango_renderer_draw_rectangle (renderer, PANGO_RENDER_PART_FOREGROUND,
+ 0, -line_width / 2, length, line_width);
+
+ pango_renderer_set_matrix (renderer, porig_matrix);
+ }
}
static void
_pango_xft_renderer_draw_box_glyph (PangoRenderer *renderer,
PangoGlyphInfo *gi,
int glyph_x,
- int glyph_y)
+ int glyph_y,
+ gboolean invalid)
{
int x = glyph_x + PANGO_SCALE;
int y = glyph_y - PANGO_SCALE * (PANGO_UNKNOWN_GLYPH_HEIGHT - 1);
@@ -319,7 +374,7 @@ _pango_xft_renderer_draw_box_glyph (PangoRenderer *renderer,
int height = PANGO_SCALE * (PANGO_UNKNOWN_GLYPH_HEIGHT - 2);
if (box_in_bounds (renderer, x, y, width, height))
- draw_box (renderer, PANGO_SCALE, x, y, width, height);
+ draw_box (renderer, PANGO_SCALE, x, y, width, height, invalid);
}
static void
@@ -335,17 +390,33 @@ _pango_xft_renderer_draw_unknown_glyph (PangoRenderer *renderer,
int xs[4];
int row, col;
int cols;
- PangoGlyph glyph;
+ gunichar ch;
+ gboolean invalid_input;
+
+ PangoFont *mini_font;
+ XftFont *mini_xft_font;
- PangoFont *mini_font = _pango_xft_font_get_mini_font (xfont);
- XftFont *mini_xft_font = pango_xft_font_get_font (mini_font);
+ ch = gi->glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
+ if (G_UNLIKELY (gi->glyph == PANGO_GLYPH_INVALID_INPUT || ch > 0x10FFFF))
+ {
+ invalid_input = TRUE;
+ cols = 1;
+ }
+ else
+ {
+ invalid_input = FALSE;
+ cols = ch > 0xffff ? 3 : 2;
+ g_snprintf (buf, sizeof(buf), (ch > 0xffff) ? "%06X" : "%04X", ch);
+ }
+
+ mini_font = _pango_xft_font_get_mini_font (xfont);
+ mini_xft_font = pango_xft_font_get_font (mini_font);
if (!mini_xft_font)
{
- _pango_xft_renderer_draw_box_glyph (renderer, gi, glyph_x, glyph_y);
+ _pango_xft_renderer_draw_box_glyph (renderer, gi, glyph_x, glyph_y, invalid_input);
return;
}
- glyph = gi->glyph & ~PANGO_GLYPH_UNKNOWN_FLAG;
ys[0] = glyph_y - PANGO_SCALE * xft_font->ascent + PANGO_SCALE * (((xft_font->ascent + xft_font->descent) - (xfont->mini_height * 2 + xfont->mini_pad * 5 + PANGO_SCALE / 2) / PANGO_SCALE) / 2);
ys[1] = ys[0] + 2 * xfont->mini_pad + xfont->mini_height;
@@ -356,17 +427,6 @@ _pango_xft_renderer_draw_unknown_glyph (PangoRenderer *renderer,
xs[2] = xs[1] + xfont->mini_width + xfont->mini_pad;
xs[3] = xs[2] + xfont->mini_width + xfont->mini_pad;
- if (glyph > 0xffff)
- {
- cols = 3;
- g_snprintf (buf, sizeof(buf), "%06X", glyph);
- }
- else
- {
- cols = 2;
- g_snprintf (buf, sizeof(buf), "%04X", glyph);
- }
-
if (box_in_bounds (renderer,
xs[0], ys[0],
xfont->mini_width * cols + xfont->mini_pad * (2 * cols + 1),
@@ -376,7 +436,11 @@ _pango_xft_renderer_draw_unknown_glyph (PangoRenderer *renderer,
draw_box (renderer, xfont->mini_pad,
xs[0], ys[0],
xfont->mini_width * cols + xfont->mini_pad * (2 * cols + 1),
- xfont->mini_height * 2 + xfont->mini_pad * 5);
+ xfont->mini_height * 2 + xfont->mini_pad * 5,
+ invalid_input);
+
+ if (invalid_input)
+ return;
for (row = 0; row < 2; row++)
for (col = 0; col < cols; col++)
@@ -414,7 +478,12 @@ pango_xft_renderer_draw_glyphs (PangoRenderer *renderer,
int glyph_x = x + x_off + gi->geometry.x_offset;
int glyph_y = y + gi->geometry.y_offset;
- _pango_xft_renderer_draw_box_glyph (renderer, gi, glyph_x, glyph_y);
+ _pango_xft_renderer_draw_unknown_glyph (renderer,
+ xfont,
+ xft_font,
+ gi,
+ glyph_x,
+ glyph_y);
}
x_off += gi->geometry.width;
diff --git a/pango/shape.c b/pango/shape.c
index 1fd2d814..d0be6da5 100644
--- a/pango/shape.c
+++ b/pango/shape.c
@@ -50,7 +50,7 @@ pango_shape (const gchar *text,
glyphs->num_glyphs = 0;
- if (G_LIKELY (PANGO_IS_ENGINE_SHAPE (analysis->shape_engine) && PANGO_IS_FONT (analysis->font)))
+ if (G_LIKELY (analysis->shape_engine && analysis->font))
{
_pango_engine_shape_shape (analysis->shape_engine, analysis->font,
text, length, analysis, glyphs);
@@ -106,22 +106,7 @@ pango_shape (const gchar *text,
}
}
else
- {
- if (!PANGO_IS_ENGINE_SHAPE (analysis->shape_engine) &&
- !_pango_warning_history.shape_shape_engine)
- {
- _pango_warning_history.shape_shape_engine = TRUE;
- g_warning ("pango_shape called with bad shape_engine, expect ugly output");
- }
- if (!PANGO_IS_FONT (analysis->font) &&
- !_pango_warning_history.shape_font)
- {
- _pango_warning_history.shape_font = TRUE;
- g_warning ("pango_shape called with bad font, expect ugly output");
- }
-
- glyphs->num_glyphs = 0;
- }
+ glyphs->num_glyphs = 0;
if (!glyphs->num_glyphs)
{
| 0 | 2 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
4de30e5500eaeb49f4bf0b7a07f718e149a2ed5e
|
[glyphstring] Handle overflow with very long glyphstrings
|
commit 4de30e5500eaeb49f4bf0b7a07f718e149a2ed5e
Author: Behdad Esfahbod <[email protected]>
Date: Mon Mar 2 12:00:52 2009 +0330
[glyphstring] Handle overflow with very long glyphstrings
diff --git a/pango/glyphstring.c b/pango/glyphstring.c
index 42601d52..8fb70313 100644
--- a/pango/glyphstring.c
+++ b/pango/glyphstring.c
@@ -61,14 +61,28 @@ pango_glyph_string_set_size (PangoGlyphString *string, gint new_len)
while (new_len > string->space)
{
if (string->space == 0)
- string->space = 1;
+ {
+ string->space = 4;
+ }
else
- string->space *= 2;
-
- if (string->space < 0)
{
- g_warning ("glyph string length overflows maximum integer size, truncated");
- new_len = string->space = G_MAXINT - 8;
+ const guint max_space =
+ MIN (G_MAXINT, G_MAXSIZE / MAX (sizeof(PangoGlyphInfo), sizeof(gint)));
+
+ guint more_space = (guint)string->space * 2;
+
+ if (more_space > max_space)
+ {
+ more_space = max_space;
+
+ if ((guint)new_len > max_space)
+ {
+ g_error ("%s: failed to allocate glyph string of length %i\n",
+ G_STRLOC, new_len);
+ }
+ }
+
+ string->space = more_space;
}
}
| 1 | 1 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
12091072940c4cd649d0230f45937f65adbfce46
|
Bug 488840 – harfbuzz: protect against ligid overflow
2007-10-21 Behdad Esfahbod <[email protected]>
Bug 488840 – harfbuzz: protect against ligid overflow
* pango/opentype/harfbuzz-buffer.c (_hb_buffer_allocate_ligid):
Never return zero, even in case of overflow.
* pango/opentype/harfbuzz-impl.h: Define dummy HB_LIKELY() and
HB_UNLIKELY(), to be filled later.
svn path=/trunk/; revision=2453
|
commit 12091072940c4cd649d0230f45937f65adbfce46
Author: Behdad Esfahbod <[email protected]>
Date: Sun Oct 21 18:17:02 2007 +0000
Bug 488840 – harfbuzz: protect against ligid overflow
2007-10-21 Behdad Esfahbod <[email protected]>
Bug 488840 – harfbuzz: protect against ligid overflow
* pango/opentype/harfbuzz-buffer.c (_hb_buffer_allocate_ligid):
Never return zero, even in case of overflow.
* pango/opentype/harfbuzz-impl.h: Define dummy HB_LIKELY() and
HB_UNLIKELY(), to be filled later.
svn path=/trunk/; revision=2453
diff --git a/ChangeLog b/ChangeLog
index aa9079ed..663891de 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,13 @@
+2007-10-21 Behdad Esfahbod <[email protected]>
+
+ Bug 488840 – harfbuzz: protect against ligid overflow
+
+ * pango/opentype/harfbuzz-buffer.c (_hb_buffer_allocate_ligid):
+ Never return zero, even in case of overflow.
+
+ * pango/opentype/harfbuzz-impl.h: Define dummy HB_LIKELY() and
+ HB_UNLIKELY(), to be filled later.
+
2007-10-20 Behdad Esfahbod <[email protected]>
* examples/cairotwisted.c (curve_length): Implement bezier curve
diff --git a/pango/opentype/harfbuzz-buffer.c b/pango/opentype/harfbuzz-buffer.c
index 8f9539a9..4b25a5f1 100644
--- a/pango/opentype/harfbuzz-buffer.c
+++ b/pango/opentype/harfbuzz-buffer.c
@@ -356,5 +356,9 @@ _hb_buffer_replace_output_glyph( HB_Buffer buffer,
HB_INTERNAL FT_UShort
_hb_buffer_allocate_ligid( HB_Buffer buffer )
{
- return ++buffer->max_ligID;
+ buffer->max_ligID++;
+ if (HB_UNLIKELY (buffer->max_ligID == 0))
+ buffer->max_ligID++;
+
+ return buffer->max_ligID;
}
diff --git a/pango/opentype/harfbuzz-impl.h b/pango/opentype/harfbuzz-impl.h
index 2215d2c4..dc89fa67 100644
--- a/pango/opentype/harfbuzz-impl.h
+++ b/pango/opentype/harfbuzz-impl.h
@@ -49,6 +49,9 @@ FT_BEGIN_HEADER
# define FT_UNUSED(arg) ((arg) = (arg))
#endif
+#define HB_LIKELY(cond) (cond)
+#define HB_UNLIKELY(cond) (cond)
+
#include "ftglue.h"
#define ARRAY_LEN(Array) ((int)(sizeof (Array) / sizeof (Array)[0]))
| 0 | 5 |
CVE-2009-1194
|
Integer overflow in the pango_glyph_string_set_size function in pango/glyphstring.c in Pango before 1.24 allows context-dependent attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a long glyph string that triggers a heap-based buffer overflow, as demonstrated by a long document.location value in Firefox.
|
bratsche/pango
|
8d45583fa1f13d77feb5d96abeae59d21ad5fe65
|
Fixes for signed/unsigned in PangoAttrIterator ((#166700, Morten Welinder)
2005-07-26 Owen Taylor <[email protected]>
Fixes for signed/unsigned in PangoAttrIterator ((#166700,
Morten Welinder)
* pango/pango-attributes.c (pango_attr_iterator_range):
Clamp results to G_MAXINT to avoid negative numbers from
signed/unsigned conversions.
* pango/pango-attributes.c: Make PangoAttrIterator
start_index/end_index unsigned to match PangoAttribute.
Change various local variables to match.
* pango/ellipsize.c (advance_iterator_to)
pango/pango-attributes.c (pango_attr_iterator_range)
pango/pango-glyph-item.c (pango_glyph_item_apply_attrs)
pango/pango-layout.c (pango_layout_line_get_empty_extents):
Always check the return value from pango_attr_iterator()
to deal with potential infinite loops when trying to
advance to position G_MAXINT.
* pango/pango-layout.c (pango_layout_set_text): Handle
the case where the text passed in is longer than
than G_MAXINT and length < 0.
* pango/pango-attributes.c (pango_attr_list_splice): Be
careful about integer overflow - clamp addition.
(#163246, Morten Welinder)
|
commit 8d45583fa1f13d77feb5d96abeae59d21ad5fe65
Author: Owen Taylor <[email protected]>
Date: Tue Jul 26 18:07:59 2005 +0000
Fixes for signed/unsigned in PangoAttrIterator ((#166700, Morten Welinder)
2005-07-26 Owen Taylor <[email protected]>
Fixes for signed/unsigned in PangoAttrIterator ((#166700,
Morten Welinder)
* pango/pango-attributes.c (pango_attr_iterator_range):
Clamp results to G_MAXINT to avoid negative numbers from
signed/unsigned conversions.
* pango/pango-attributes.c: Make PangoAttrIterator
start_index/end_index unsigned to match PangoAttribute.
Change various local variables to match.
* pango/ellipsize.c (advance_iterator_to)
pango/pango-attributes.c (pango_attr_iterator_range)
pango/pango-glyph-item.c (pango_glyph_item_apply_attrs)
pango/pango-layout.c (pango_layout_line_get_empty_extents):
Always check the return value from pango_attr_iterator()
to deal with potential infinite loops when trying to
advance to position G_MAXINT.
* pango/pango-layout.c (pango_layout_set_text): Handle
the case where the text passed in is longer than
than G_MAXINT and length < 0.
* pango/pango-attributes.c (pango_attr_list_splice): Be
careful about integer overflow - clamp addition.
(#163246, Morten Welinder)
diff --git a/ChangeLog b/ChangeLog
index 9f1b9e86..f44cd861 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,32 @@
+2005-07-26 Owen Taylor <[email protected]>
+
+ Fixes for signed/unsigned in PangoAttrIterator ((#166700,
+ Morten Welinder)
+
+ * pango/pango-attributes.c (pango_attr_iterator_range):
+ Clamp results to G_MAXINT to avoid negative numbers from
+ signed/unsigned conversions.
+
+ * pango/pango-attributes.c: Make PangoAttrIterator
+ start_index/end_index unsigned to match PangoAttribute.
+ Change various local variables to match.
+
+ * pango/ellipsize.c (advance_iterator_to)
+ pango/pango-attributes.c (pango_attr_iterator_range)
+ pango/pango-glyph-item.c (pango_glyph_item_apply_attrs)
+ pango/pango-layout.c (pango_layout_line_get_empty_extents):
+ Always check the return value from pango_attr_iterator()
+ to deal with potential infinite loops when trying to
+ advance to position G_MAXINT.
+
+ * pango/pango-layout.c (pango_layout_set_text): Handle
+ the case where the text passed in is longer than
+ than G_MAXINT and length < 0.
+
+ * pango/pango-attributes.c (pango_attr_list_splice): Be
+ careful about integer overflow - clamp addition.
+ (#163246, Morten Welinder)
+
2005-07-26 Owen Taylor <[email protected]>
* modules/indic/indic-ot-class-tables.c (oryaCharClasses):
diff --git a/ChangeLog.pre-1-10 b/ChangeLog.pre-1-10
index 9f1b9e86..f44cd861 100644
--- a/ChangeLog.pre-1-10
+++ b/ChangeLog.pre-1-10
@@ -1,3 +1,32 @@
+2005-07-26 Owen Taylor <[email protected]>
+
+ Fixes for signed/unsigned in PangoAttrIterator ((#166700,
+ Morten Welinder)
+
+ * pango/pango-attributes.c (pango_attr_iterator_range):
+ Clamp results to G_MAXINT to avoid negative numbers from
+ signed/unsigned conversions.
+
+ * pango/pango-attributes.c: Make PangoAttrIterator
+ start_index/end_index unsigned to match PangoAttribute.
+ Change various local variables to match.
+
+ * pango/ellipsize.c (advance_iterator_to)
+ pango/pango-attributes.c (pango_attr_iterator_range)
+ pango/pango-glyph-item.c (pango_glyph_item_apply_attrs)
+ pango/pango-layout.c (pango_layout_line_get_empty_extents):
+ Always check the return value from pango_attr_iterator()
+ to deal with potential infinite loops when trying to
+ advance to position G_MAXINT.
+
+ * pango/pango-layout.c (pango_layout_set_text): Handle
+ the case where the text passed in is longer than
+ than G_MAXINT and length < 0.
+
+ * pango/pango-attributes.c (pango_attr_list_splice): Be
+ careful about integer overflow - clamp addition.
+ (#163246, Morten Welinder)
+
2005-07-26 Owen Taylor <[email protected]>
* modules/indic/indic-ot-class-tables.c (oryaCharClasses):
diff --git a/pango/ellipsize.c b/pango/ellipsize.c
index 39649461..8a7b190a 100644
--- a/pango/ellipsize.c
+++ b/pango/ellipsize.c
@@ -386,14 +386,13 @@ advance_iterator_to (PangoAttrIterator *iter,
{
int start, end;
- while (TRUE)
+ do
{
pango_attr_iterator_range (iter, &start, &end);
if (end > new_index)
break;
-
- pango_attr_iterator_next (iter);
}
+ while (pango_attr_iterator_next (iter));
}
/* Updates the shaping of the ellipsis if necessary when we move the
diff --git a/pango/pango-attributes.c b/pango/pango-attributes.c
index ecf41e47..d2fe3ce2 100644
--- a/pango/pango-attributes.c
+++ b/pango/pango-attributes.c
@@ -36,8 +36,8 @@ struct _PangoAttrIterator
{
GSList *next_attribute;
GList *attribute_stack;
- int start_index;
- int end_index;
+ guint start_index;
+ guint end_index;
};
static PangoAttribute *pango_attr_color_new (const PangoAttrClass *klass,
@@ -1054,7 +1054,7 @@ pango_attr_list_insert_internal (PangoAttrList *list,
gboolean before)
{
GSList *tmp_list, *prev, *link;
- gint start_index = attr->start_index;
+ guint start_index = attr->start_index;
if (!list->attributes)
{
@@ -1161,8 +1161,8 @@ pango_attr_list_change (PangoAttrList *list,
PangoAttribute *attr)
{
GSList *tmp_list, *prev, *link;
- gint start_index = attr->start_index;
- gint end_index = attr->end_index;
+ guint start_index = attr->start_index;
+ guint end_index = attr->end_index;
g_return_if_fail (list != NULL);
@@ -1371,26 +1371,40 @@ pango_attr_list_splice (PangoAttrList *list,
gint len)
{
GSList *tmp_list;
+ guint upos, ulen;
g_return_if_fail (list != NULL);
g_return_if_fail (other != NULL);
g_return_if_fail (pos >= 0);
g_return_if_fail (len >= 0);
-
+
+ upos = (guint)pos;
+ ulen = (guint)len;
+
+/* This definition only works when a and b are unsigned; overflow
+ * isn't defined in the C standard for signed integers
+ */
+#define CLAMP_ADD(a,b) (((a) + (b) < (a)) ? G_MAXUINT : (a) + (b))
+
tmp_list = list->attributes;
while (tmp_list)
{
PangoAttribute *attr = tmp_list->data;
- if (attr->start_index <= pos)
+ if (attr->start_index <= upos)
{
- if (attr->end_index > pos)
- attr->end_index += len;
+ if (attr->end_index > upos)
+ attr->end_index = CLAMP_ADD (attr->end_index, ulen);
}
else
{
- attr->start_index += len;
- attr->end_index += len;
+ /* This could result in a zero length attribute if it
+ * gets squashed up against G_MAXUINT, but deleting such
+ * an element could (in theory) suprise the caller, so
+ * we don't delete it.
+ */
+ attr->start_index = CLAMP_ADD (attr->end_index, ulen);
+ attr->end_index = CLAMP_ADD (attr->end_index, ulen);
}
tmp_list = tmp_list->next;
@@ -1400,13 +1414,17 @@ pango_attr_list_splice (PangoAttrList *list,
while (tmp_list)
{
PangoAttribute *attr = pango_attribute_copy (tmp_list->data);
- attr->start_index += pos;
- attr->end_index += pos;
+ attr->start_index = CLAMP_ADD (attr->start_index, upos);
+ attr->end_index = CLAMP_ADD (attr->end_index, upos);
+ /* Same as above, the attribute could be squashed to zero-length; here
+ * pango_attr_list_change() will take care of deleting it.
+ */
pango_attr_list_change (list, attr);
tmp_list = tmp_list->next;
}
+#undef CLAMP_ADD
}
/**
@@ -1433,7 +1451,7 @@ pango_attr_list_get_iterator (PangoAttrList *list)
iterator->end_index = 0;
if (!pango_attr_iterator_next (iterator))
- iterator->end_index = G_MAXINT;
+ iterator->end_index = G_MAXUINT;
return iterator;
}
@@ -1444,7 +1462,11 @@ pango_attr_list_get_iterator (PangoAttrList *list)
* @start: location to store the start of the range
* @end: location to store the end of the range
*
- * Get the range of the current segment.
+ * Get the range of the current segment. Note that the
+ * stored return values are signed, not unsigned like
+ * the values in #PangoAttribute. To deal with this API
+ * oversight, stored return values that wouldn't fit into
+ * a signed integer are clamped to %G_MAXINT.
**/
void
pango_attr_iterator_range (PangoAttrIterator *iterator,
@@ -1454,9 +1476,9 @@ pango_attr_iterator_range (PangoAttrIterator *iterator,
g_return_if_fail (iterator != NULL);
if (start)
- *start = iterator->start_index;
+ *start = MIN (iterator->start_index, G_MAXINT);
if (end)
- *end = iterator->end_index;
+ *end = MIN (iterator->end_index, G_MAXINT);
}
/**
@@ -1478,7 +1500,7 @@ pango_attr_iterator_next (PangoAttrIterator *iterator)
return FALSE;
iterator->start_index = iterator->end_index;
- iterator->end_index = G_MAXINT;
+ iterator->end_index = G_MAXUINT;
tmp_list = iterator->attribute_stack;
while (tmp_list)
diff --git a/pango/pango-glyph-item.c b/pango/pango-glyph-item.c
index 1245ca8c..065871f8 100644
--- a/pango/pango-glyph-item.c
+++ b/pango/pango-glyph-item.c
@@ -483,14 +483,13 @@ pango_glyph_item_apply_attrs (PangoGlyphItem *glyph_item,
/* Advance the attr iterator to the start of the item
*/
- while (TRUE)
+ do
{
pango_attr_iterator_range (iter, &range_start, &range_end);
if (range_end > glyph_item->item->offset)
break;
-
- pango_attr_iterator_next (iter);
}
+ while (pango_attr_iterator_next (iter));
state.segment_attrs = pango_attr_iterator_get_attrs (iter);
@@ -505,6 +504,7 @@ pango_glyph_item_apply_attrs (PangoGlyphItem *glyph_item,
have_cluster;
have_cluster = _pango_glyph_item_iter_next_cluster (&state.iter))
{
+ gboolean have_next;
/* [range_start,range_end] is the first range that intersects
* the current cluster.
@@ -526,18 +526,17 @@ pango_glyph_item_apply_attrs (PangoGlyphItem *glyph_item,
* leaving [range_start,range_end] being the first range that
* intersects the next cluster.
*/
- while (TRUE)
+ do
{
- /* If any ranges end in this cluster, then the next cluster
- * goes into a separate segment
- */
- if (range_end <= state.iter.end_index)
- start_new_segment = TRUE;
-
if (range_end > state.iter.end_index) /* Range intersects next cluster */
break;
- pango_attr_iterator_next (iter);
+ /* Since ranges end in this cluster, the next cluster goes into a
+ * separate segment
+ */
+ start_new_segment = TRUE;
+
+ have_next = pango_attr_iterator_next (iter);
pango_attr_iterator_range (iter, &range_start, &range_end);
if (range_start >= state.iter.end_index) /* New range doesn't intersect this cluster */
@@ -564,6 +563,7 @@ pango_glyph_item_apply_attrs (PangoGlyphItem *glyph_item,
state.segment_attrs = g_slist_concat (state.segment_attrs,
pango_attr_iterator_get_attrs (iter));
}
+ while (have_next);
}
out:
diff --git a/pango/pango-layout.c b/pango/pango-layout.c
index 96a2f042..933d9f48 100644
--- a/pango/pango-layout.c
+++ b/pango/pango-layout.c
@@ -815,7 +815,10 @@ pango_layout_set_text (PangoLayout *layout,
{
if (!g_utf8_validate (text, length, &end))
g_warning ("Invalid UTF-8 string passed to pango_layout_set_text()");
-
+
+ while (end - text > G_MAXINT)
+ end = g_utf8_prev_char (end);
+
length = end - text;
}
@@ -3773,7 +3776,7 @@ pango_layout_line_get_empty_extents (PangoLayoutLine *line,
PangoAttrIterator *iter = pango_attr_list_get_iterator (layout->attrs);
int start, end;
- while (TRUE)
+ do
{
pango_attr_iterator_range (iter, &start, &end);
@@ -3796,9 +3799,9 @@ pango_layout_line_get_empty_extents (PangoLayoutLine *line,
break;
}
-
- pango_attr_iterator_next (iter);
+
}
+ while (pango_attr_iterator_next (iter));
pango_attr_iterator_destroy (iter);
}
| 0 | 3 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
91caaaf07953d150af744b55fc3496bcf0b0bcd0
|
Establish a version 2.0 tiles-config dtd.
SB-30
git-svn-id: https://svn.apache.org/repos/asf/struts/sandbox/trunk/tiles@442103 13f79535-47bb-0310-9956-ffa450edef68
|
commit 91caaaf07953d150af744b55fc3496bcf0b0bcd0
Author: Wendy Smoak <[email protected]>
Date: Mon Sep 11 05:12:59 2006 +0000
Establish a version 2.0 tiles-config dtd.
SB-30
git-svn-id: https://svn.apache.org/repos/asf/struts/sandbox/trunk/tiles@442103 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-core/src/main/resources/org/apache/tiles/resources/tiles-config_2_0.dtd b/tiles-core/src/main/resources/org/apache/tiles/resources/tiles-config_2_0.dtd
new file mode 100644
index 00000000..a3b2f70d
--- /dev/null
+++ b/tiles-core/src/main/resources/org/apache/tiles/resources/tiles-config_2_0.dtd
@@ -0,0 +1,281 @@
+<!--
+ DTD for the Tile Definition File, Version 1.1
+
+ To support validation of your configuration file, include the following
+ DOCTYPE element at the beginning (after the "xml" declaration):
+
+ <!DOCTYPE tiles-definitions PUBLIC
+ "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
+ "http://struts.apache.org/dtds/tiles-config_1_1.dtd">
+
+ $Id: tiles-config_1_1.dtd 51703 2004-09-01 10:41:11Z niallp $
+-->
+
+
+<!-- ========== Defined Types ============================================= -->
+
+
+<!-- A "Boolean" is the string representation of a boolean (true or false)
+ variable.
+-->
+<!ENTITY % Boolean "(true|false)">
+
+
+<!-- A "ContentType" is the content type of an attribute passed to a tile
+ component.
+-->
+<!ENTITY % ContentType "(string|page|template|definition)">
+
+<!-- A "ClassName" is the fully qualified name of a Java class that is
+ instantiated to provide the functionality of the enclosing element.
+-->
+<!ENTITY % ClassName "CDATA">
+
+<!-- A "RequestPath" is an module-relative URI path, beginning with a
+ slash, that identifies a mapped resource (such as a JSP page or a servlet)
+ within this web application.
+-->
+<!ENTITY % RequestPath "CDATA">
+
+<!-- A "DefinitionName" is the unique identifier of a definition. This identifier
+ is a logical name used to reference the definition.
+-->
+<!ENTITY % DefinitionName "CDATA">
+
+<!-- A "BeanName" is the identifier of a JavaBean, such as a form bean,
+ and also serves as the name of the corresponding scripting variable
+ and the name of the JSP attribute under which the bean is accessed.
+ Therefore, it must conform to the rules for a Java identifier.
+-->
+<!ENTITY % BeanName "CDATA">
+
+<!-- A "PropName" is the name of a JavaBeans property, and must begin with
+ a lower case letter and contain only characters that are legal in a
+ Java identifier.
+-->
+<!ENTITY % PropName "CDATA">
+
+<!-- A "Location" is a relative path, delimited by "/" characters, that
+ defines the location of a resource relative to the location of the
+ configuration file itself.
+-->
+<!ENTITY % Location "#PCDATA">
+
+
+
+<!-- ========== Top Level Elements ======================================== -->
+
+
+ <!-- deprecated: use tiles-definitions instead.-->
+<!ELEMENT component-definitions (definition+)>
+
+<!-- The "tiles-definitions" element is the root of the configuration file
+ hierarchy, and contains nested elements for all of the other
+ configuration settings.
+-->
+<!ELEMENT tiles-definitions (definition+)>
+
+<!-- The "definition" element describes a definition that can be inserted in a jsp
+ page. This definition is identified by its logical name. A definition allows
+ to define all the attributes that can be set in <insert> tag from a jsp page.
+
+ controllerClass The fully qualified Java class name of the controller
+ subclass to call immediately before the tiles is inserted.
+ Only one of controllerClass or controllerUrl should be
+ specified.
+
+ controllerUrl The context-relative path to the resource used as controller
+ called immediately before the tiles is inserted.
+ Only one of controllerClass or controllerUrl should be
+ specified.
+
+ extends Name of a definition that is used as ancestor of this definition.
+ All attributes from the ancestor are available to the new
+ definition. Any attribute inherited from the ancestor can
+ be overloaded by providing a new value.
+
+ name The unique identifier for this definition.
+
+ page Same as path.
+
+ path The context-relative path to the resource used as tiles to
+ insert. This tiles will be inserted and a tiles context
+ containing appropriate attributes will be available.
+
+ role Security role name that is allowed access to this definition
+ object. The definition is inserted only if the role name is
+ allowed.
+
+ template Same as path. For compatibility with the template tag library.
+-->
+<!ELEMENT definition (icon?, display-name?, description?, put*, putList*)>
+<!ATTLIST definition id ID #IMPLIED>
+<!ATTLIST definition controllerClass %ClassName; #IMPLIED>
+<!ATTLIST definition controllerUrl %RequestPath; #IMPLIED>
+<!ATTLIST definition extends %DefinitionName; #IMPLIED>
+<!ATTLIST definition name %DefinitionName; #REQUIRED>
+<!ATTLIST definition page %RequestPath; #IMPLIED>
+<!ATTLIST definition path %RequestPath; #IMPLIED>
+<!ATTLIST definition role CDATA #IMPLIED>
+<!ATTLIST definition template %RequestPath; #IMPLIED>
+
+
+<!-- The "put" element describes an attribute of a definition. It allows to
+ specify the tiles attribute name and its value. The tiles value can be
+ specified as an xml attribute, or in the body of the <put> tag.
+
+ content Same as value. For compatibility with the template tag library.
+
+ direct Same as type="string". For compatibility with the template
+ tag library.
+
+ name The unique identifier for this put.
+
+ type The type of the value. Can be: string, page, template or definition.
+ By default, no type is associated to a value. If a type is
+ associated, it will be used as a hint to process the value
+ when the attribute will be used in the inserted tiles.
+
+ value The value associated to this tiles attribute. The value should
+ be specified with this tag attribute, or in the body of the tag.
+-->
+<!ELEMENT put (#PCDATA)>
+<!ATTLIST put id ID #IMPLIED>
+<!ATTLIST put content CDATA #IMPLIED>
+<!ATTLIST put direct %Boolean; #IMPLIED>
+<!ATTLIST put name CDATA #REQUIRED>
+<!ATTLIST put type %ContentType; #IMPLIED>
+<!ATTLIST put value CDATA #IMPLIED>
+
+
+<!-- The "putList" element describes a list attribute of a definition. It allows to
+ specify an attribute that is a java List containing any kind of values. In
+ the config file, the list elements are specified by nested <add>, <item> or
+ <putList>.
+
+ name The unique identifier for this put list.
+-->
+<!ELEMENT putList ( (add* | item* | bean* | putList*)+) >
+<!ATTLIST putList id ID #IMPLIED>
+<!ATTLIST putList name CDATA #REQUIRED>
+
+<!-- ========== Subordinate Elements ====================================== -->
+
+<!-- The "add" element describes an element of a list. It is similar to the
+ <put> element.
+
+ content Same as value. For compatibility with the template tag library.
+
+ direct Same as type="string". For compatibility with the template
+ tag library.
+
+ type The type of the value. Can be: string, page, template or definition.
+ By default, no type is associated to a value. If a type is
+ associated, it will be used as a hint to process the value
+ when the attribute will be used in the inserted tiles.
+
+ value The value associated to this tiles attribute. The value should
+ be specified with this tag attribute, or in the body of the tag.
+-->
+<!ELEMENT add (#PCDATA)>
+<!ATTLIST add id ID #IMPLIED>
+<!ATTLIST add content CDATA #IMPLIED>
+<!ATTLIST add direct %Boolean; #IMPLIED>
+<!ATTLIST add type %ContentType; #IMPLIED>
+<!ATTLIST add value CDATA #IMPLIED>
+
+
+<!-- The "bean" element describes an element of a list. It create a bean of the
+ specified java classtype. This bean is initialized with appropriate nested
+ <set-property>.
+
+ classtype The fully qualified classname for this bean.
+-->
+<!ELEMENT bean (set-property*)>
+<!ATTLIST bean id ID #IMPLIED>
+<!ATTLIST bean classtype %ClassName; #REQUIRED>
+
+<!-- The "set-property" element specifies the method name and initial value of
+ a bean property. When the object representing
+ the surrounding element is instantiated, the accessor for the indicated
+ property is called and passed the indicated value.
+
+ property Name of the JavaBeans property whose setter method
+ will be called.
+
+ value String representation of the value to which this
+ property will be set, after suitable type conversion
+-->
+<!ELEMENT set-property EMPTY>
+<!ATTLIST set-property id ID #IMPLIED>
+<!ATTLIST set-property property %PropName; #REQUIRED>
+<!ATTLIST set-property value CDATA #REQUIRED>
+
+
+<!-- The "item" element describes an element of a list. It create a bean added as
+ element to the list. Each bean can contain different properties: value, link,
+ icon, tooltip. These properties are to be interpreted by the jsp page using
+ them.
+ By default the bean is of type
+ "org.apache.struts.tiles.beans.SimpleMenuItem". This bean is useful to
+ create a list of beans used as menu items.
+
+ classtype The fully qualified classtype for this bean.
+ If specified, the classtype must be a subclass of the interface
+ "org.apache.struts.tiles.beans.MenuItem".
+
+ icon The bean 'icon' property.
+
+ link The bean 'link' property.
+
+ tooltip The bean 'tooltip' property.
+
+ value The bean 'value' property.
+-->
+<!ELEMENT item (#PCDATA)>
+<!ATTLIST item id ID #IMPLIED>
+<!ATTLIST item classtype %ClassName; #IMPLIED>
+<!ATTLIST item icon CDATA #IMPLIED>
+<!ATTLIST item link CDATA #REQUIRED>
+<!ATTLIST item tooltip CDATA #IMPLIED>
+<!ATTLIST item value CDATA #REQUIRED>
+
+
+<!-- ========== Info Elements ====================================== -->
+
+<!-- The "description" element contains descriptive (paragraph length) text
+ about the surrounding element, suitable for use in GUI tools.
+-->
+<!ELEMENT description (#PCDATA)>
+<!ATTLIST description id ID #IMPLIED>
+
+
+<!-- The "display-name" element contains a short (one line) description of
+ the surrounding element, suitable for use in GUI tools.
+-->
+<!ELEMENT display-name (#PCDATA)>
+<!ATTLIST display-name id ID #IMPLIED>
+
+
+<!-- The "icon" element contains a small-icon and large-icon element which
+ specify the location, relative to the Struts configuration file, for small
+ and large images used to represent the surrounding element in GUI tools.
+-->
+<!ELEMENT icon (small-icon?, large-icon?)>
+<!ATTLIST icon id ID #IMPLIED>
+
+
+<!-- The "large-icon" element specifies the location, relative to the Struts
+ configuration file, of a resource containing a large (32x32 pixel)
+ icon image.
+-->
+<!ELEMENT large-icon (%Location;)>
+<!ATTLIST large-icon id ID #IMPLIED>
+
+
+<!-- The "small-icon" element specifies the location, relative to the Struts
+ configuration file, of a resource containing a small (16x16 pixel)
+ icon image.
+-->
+<!ELEMENT small-icon (%Location;)>
+<!ATTLIST small-icon id ID #IMPLIED>
| 0 | 5 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
2720827d886488f3ca12ebb03992de113571c135
|
further improvements from Michael Isvy, use tiles-3* dependencies in the example.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@1427704 13f79535-47bb-0310-9956-ffa450edef68
|
commit 2720827d886488f3ca12ebb03992de113571c135
Author: Michael Semb Wever <[email protected]>
Date: Wed Jan 2 08:47:11 2013 +0000
further improvements from Michael Isvy, use tiles-3* dependencies in the example.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@1427704 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/site/apt/tutorial/advanced/wildcard.apt b/src/site/apt/tutorial/advanced/wildcard.apt
index 38398310..6a716b0c 100644
--- a/src/site/apt/tutorial/advanced/wildcard.apt
+++ b/src/site/apt/tutorial/advanced/wildcard.apt
@@ -109,24 +109,31 @@ Wildcard support
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-extras</artifactId>
- <version>2.2.2</version>
+ <version>3.0.1</version>
</dependency>
------------------------------------
If you are using Spring, you should add the 'completeAutoload' attribute to your TilesConfigurer bean.
------------------------------------
-<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
+<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="completeAutoload" value="true"/>
</bean>
------------------------------------
-** Using prefixes for wildcards and Regular Expressions
+** Using prefixes
+ Here is an example of prefix using Regular Expressions:
- When using completeAutoload, you can use wildcard expressions and/or regexp. Each of them should be enabled using the dedicated prefix as follows.
+------------------------------------
+<definition name="REGEXP:test\.definition(.*)\.message(.*)" template="/layout{1}.jsp">
+ <put-attribute name="title" value="This definition has a message: {2}."/>
+ <put-attribute name="header" value="/header.jsp"/>
+ <put-attribute name="body" value="/body.jsp"/>
+</definition>
+------------------------------------
-*** WILDCARD
+ The below sample uses WILDCARD (this prefix is not needed when using wildcards solely, as shown in the 'Default Configuration' section).
------------------------------------
<definition name="WILDCARD:test.definition*.message*" template="/layout{1}.jsp">
@@ -141,18 +148,8 @@ Wildcard support
</definition>
------------------------------------
- And, if you want to use Regular Expressions:
-
-*** REGEXP
-------------------------------------
-<definition name="REGEXP:test\.definition(.*)\.message(.*)" template="/layout{1}.jsp">
- <put-attribute name="title" value="This definition has a message: {2}."/>
- <put-attribute name="header" value="/header.jsp"/>
- <put-attribute name="body" value="/body.jsp"/>
-</definition>
-------------------------------------
-*** tiles:insertDefinition
+* tiles:insertDefinition
In both cases, if you insert a definition that matches the definition, for example:
| 0 | 2 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
b3895f4105ddbb3e1de392c9d703fa42b4ce3464
|
TILES-458
Move of EL code from tiles-core and tiles-jsp to tiles-el.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@816358 13f79535-47bb-0310-9956-ffa450edef68
|
commit b3895f4105ddbb3e1de392c9d703fa42b4ce3464
Author: Antonio Petrelli <[email protected]>
Date: Thu Sep 17 19:54:15 2009 +0000
TILES-458
Move of EL code from tiles-core and tiles-jsp to tiles-el.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@816358 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-el/pom.xml b/tiles-el/pom.xml
index 9e4c3e63..f84be88a 100644
--- a/tiles-el/pom.xml
+++ b/tiles-el/pom.xml
@@ -30,7 +30,7 @@
<description>Tiles EL (Expression Language) support: Classes and tag libraries to use EL as an expression language in attribute expressions. </description>
<properties>
- <tiles.osgi.symbolicName>org.apache.tiles.mvel</tiles.osgi.symbolicName>
+ <tiles.osgi.symbolicName>org.apache.tiles.el</tiles.osgi.symbolicName>
</properties>
<build>
@@ -114,6 +114,18 @@
<version>1.0</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet.jsp</groupId>
+ <artifactId>jsp-api</artifactId>
+ <version>2.1</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELContextImpl.java b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/ELContextImpl.java
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELContextImpl.java
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/ELContextImpl.java
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ExpressionFactoryFactory.java b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/ExpressionFactoryFactory.java
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/ExpressionFactoryFactory.java
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/ExpressionFactoryFactory.java
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolver.java b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolver.java
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolver.java
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolver.java
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/TilesContextELResolver.java b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/TilesContextELResolver.java
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/TilesContextELResolver.java
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/TilesContextELResolver.java
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/TomcatExpressionFactoryFactory.java b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/TomcatExpressionFactoryFactory.java
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/TomcatExpressionFactoryFactory.java
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/TomcatExpressionFactoryFactory.java
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/package.html b/tiles-el/src/main/java/org/apache/tiles/evaluator/el/package.html
similarity index 100%
rename from tiles-core/src/main/java/org/apache/tiles/evaluator/el/package.html
rename to tiles-el/src/main/java/org/apache/tiles/evaluator/el/package.html
diff --git a/tiles-jsp/src/main/java/org/apache/tiles/jsp/evaluator/el/JspExpressionFactoryFactory.java b/tiles-el/src/main/java/org/apache/tiles/jsp/evaluator/el/JspExpressionFactoryFactory.java
similarity index 100%
rename from tiles-jsp/src/main/java/org/apache/tiles/jsp/evaluator/el/JspExpressionFactoryFactory.java
rename to tiles-el/src/main/java/org/apache/tiles/jsp/evaluator/el/JspExpressionFactoryFactory.java
diff --git a/tiles-jsp/src/main/java/org/apache/tiles/jsp/evaluator/el/package.html b/tiles-el/src/main/java/org/apache/tiles/jsp/evaluator/el/package.html
similarity index 100%
rename from tiles-jsp/src/main/java/org/apache/tiles/jsp/evaluator/el/package.html
rename to tiles-el/src/main/java/org/apache/tiles/jsp/evaluator/el/package.html
diff --git a/tiles-core/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java b/tiles-el/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java
similarity index 100%
rename from tiles-core/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java
rename to tiles-el/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java
diff --git a/tiles-core/src/test/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolverTest.java b/tiles-el/src/test/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolverTest.java
similarity index 100%
rename from tiles-core/src/test/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolverTest.java
rename to tiles-el/src/test/java/org/apache/tiles/evaluator/el/TilesContextBeanELResolverTest.java
diff --git a/tiles-core/src/test/java/org/apache/tiles/evaluator/el/TilesContextELResolverTest.java b/tiles-el/src/test/java/org/apache/tiles/evaluator/el/TilesContextELResolverTest.java
similarity index 100%
rename from tiles-core/src/test/java/org/apache/tiles/evaluator/el/TilesContextELResolverTest.java
rename to tiles-el/src/test/java/org/apache/tiles/evaluator/el/TilesContextELResolverTest.java
diff --git a/tiles-extras/pom.xml b/tiles-extras/pom.xml
index c2a8ae45..e1b8cf78 100644
--- a/tiles-extras/pom.xml
+++ b/tiles-extras/pom.xml
@@ -81,6 +81,11 @@
<artifactId>tiles-velocity</artifactId>
<version>${pom.version}</version>
</dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>tiles-el</artifactId>
+ <version>${pom.version}</version>
+ </dependency>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>tiles-mvel</artifactId>
| 0 | 7 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
cbe34a8e0f06d02b110049ad129a4a8089ce3edd
|
TILES-48
Added a new method in AttributeEvaluators. Fixed tests accordingly.
Added Selenium test.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@637208 13f79535-47bb-0310-9956-ffa450edef68
|
commit cbe34a8e0f06d02b110049ad129a4a8089ce3edd
Author: Antonio Petrelli <[email protected]>
Date: Fri Mar 14 18:49:39 2008 +0000
TILES-48
Added a new method in AttributeEvaluators. Fixed tests accordingly.
Added Selenium test.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@637208 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/AttributeEvaluator.java b/tiles-core/src/main/java/org/apache/tiles/evaluator/AttributeEvaluator.java
index 263184d8..1b9a8c3b 100644
--- a/tiles-core/src/main/java/org/apache/tiles/evaluator/AttributeEvaluator.java
+++ b/tiles-core/src/main/java/org/apache/tiles/evaluator/AttributeEvaluator.java
@@ -34,7 +34,16 @@ public interface AttributeEvaluator {
/**
* Evaluates an expression.
*
- * @param attribute The expression to evaluate.
+ * @param expression The expression to evaluate.
+ * @param request The request object.
+ * @return The evaluated object.
+ */
+ Object evaluate(String expression, TilesRequestContext request);
+
+ /**
+ * Evaluates an attribute value.
+ *
+ * @param attribute The attribute to evaluate.
* @param request The request object.
* @return The evaluated object.
*/
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java b/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java
index 94dfaee5..b0ec8323 100644
--- a/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java
+++ b/tiles-core/src/main/java/org/apache/tiles/evaluator/el/ELAttributeEvaluator.java
@@ -109,20 +109,24 @@ public class ELAttributeEvaluator implements AttributeEvaluator,
this.contextFactory = contextFactory;
}
+ /** {@inheritDoc} */
+ public Object evaluate(String expression, TilesRequestContext request) {
+ SimpleContext context = new SimpleContext(defaultResolver);
+ context.putContext(TilesRequestContext.class, request);
+ context.putContext(TilesApplicationContext.class,
+ applicationContext);
+ ValueExpression valueExpression = expressionFactory.createValueExpression(
+ context, expression.toString(), Object.class);
+
+ return valueExpression.getValue(context);
+ }
+
/** {@inheritDoc} */
public Object evaluate(Attribute attribute, TilesRequestContext request) {
Object retValue = attribute.getValue();
if (retValue instanceof String) {
- SimpleContext context = new SimpleContext(defaultResolver);
- context.putContext(TilesRequestContext.class, request);
- context.putContext(TilesApplicationContext.class,
- applicationContext);
- ValueExpression expression = expressionFactory
- .createValueExpression(context, attribute.getValue()
- .toString(), Object.class);
-
- retValue = expression.getValue(context);
+ retValue = evaluate((String) retValue, request);
}
return retValue;
diff --git a/tiles-core/src/main/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluator.java b/tiles-core/src/main/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluator.java
index 8c944ea9..e4396d2c 100644
--- a/tiles-core/src/main/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluator.java
+++ b/tiles-core/src/main/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluator.java
@@ -33,6 +33,11 @@ import org.apache.tiles.evaluator.AttributeEvaluator;
*/
public class DirectAttributeEvaluator implements AttributeEvaluator {
+ /** {@inheritDoc} */
+ public Object evaluate(String expression, TilesRequestContext request) {
+ return expression;
+ }
+
/** {@inheritDoc} */
public Object evaluate(Attribute attribute, TilesRequestContext request) {
if (attribute == null) {
diff --git a/tiles-core/src/main/java/org/apache/tiles/impl/BasicTilesContainer.java b/tiles-core/src/main/java/org/apache/tiles/impl/BasicTilesContainer.java
index 232b6c3e..c5d4092e 100644
--- a/tiles-core/src/main/java/org/apache/tiles/impl/BasicTilesContainer.java
+++ b/tiles-core/src/main/java/org/apache/tiles/impl/BasicTilesContainer.java
@@ -663,6 +663,22 @@ public class BasicTilesContainer implements TilesContainer {
String dispatchPath = attributeContext.getTemplate();
+ if (dispatchPath != null) {
+ Object value = evaluator.evaluate(dispatchPath, request);
+ if (value instanceof String) {
+ dispatchPath = (String) value;
+ } else {
+ throw new InvalidTemplateException(
+ "Cannot render a template that is not an object: "
+ + value.toString());
+ }
+ }
+
+ if (dispatchPath == null) {
+ throw new InvalidTemplateException(
+ "Cannot render a null template");
+ }
+
if (LOG.isDebugEnabled()) {
LOG.debug("Dispatching to definition path '"
+ attributeContext.getTemplate() + " '");
diff --git a/tiles-core/src/main/java/org/apache/tiles/impl/InvalidTemplateException.java b/tiles-core/src/main/java/org/apache/tiles/impl/InvalidTemplateException.java
new file mode 100644
index 00000000..443fdaaf
--- /dev/null
+++ b/tiles-core/src/main/java/org/apache/tiles/impl/InvalidTemplateException.java
@@ -0,0 +1,71 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tiles.impl;
+
+import org.apache.tiles.TilesRuntimeException;
+
+/**
+ * An invalid template has been identified.
+ *
+ * @version $Rev$ $Date$
+ * @since 2.1.0
+ */
+public class InvalidTemplateException extends TilesRuntimeException {
+
+ /**
+ * Constructor.
+ *
+ * @since 2.1.0
+ */
+ public InvalidTemplateException() {
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param message The detail message.
+ * @since 2.1.0
+ */
+ public InvalidTemplateException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param e The exception to be wrapped.
+ * @since 2.1.0
+ */
+ public InvalidTemplateException(Exception e) {
+ super(e);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param message The detail message.
+ * @param e The exception to be wrapped.
+ * @since 2.1.0
+ */
+ public InvalidTemplateException(String message, Exception e) {
+ super(message, e);
+ }
+}
diff --git a/tiles-core/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java b/tiles-core/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java
index d5370747..528a1936 100644
--- a/tiles-core/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java
+++ b/tiles-core/src/test/java/org/apache/tiles/evaluator/el/ELAttributeEvaluatorTest.java
@@ -106,4 +106,32 @@ public class ELAttributeEvaluatorTest extends TestCase {
assertEquals("The value is not correct", new Integer(2), evaluator
.evaluate(attribute, request));
}
+
+ /**
+ * Tests
+ * {@link ELAttributeEvaluator#evaluate(String, TilesRequestContext)}.
+ */
+ public void testEvaluateString() {
+ String expression = "${requestScope.object1}";
+ assertEquals("The value is not correct", "value", evaluator.evaluate(
+ expression, request));
+ expression = "${sessionScope.object2}";
+ assertEquals("The value is not correct", new Integer(1), evaluator
+ .evaluate(expression, request));
+ expression = "${applicationScope.object3}";
+ assertEquals("The value is not correct", new Float(2.0), evaluator
+ .evaluate(expression, request));
+ expression = "${object1}";
+ assertEquals("The value is not correct", "value", evaluator.evaluate(
+ expression, request));
+ expression = "${object2}";
+ assertEquals("The value is not correct", new Integer(1), evaluator
+ .evaluate(expression, request));
+ expression = "${object3}";
+ assertEquals("The value is not correct", new Float(2.0), evaluator
+ .evaluate(expression, request));
+ expression = "String literal";
+ assertEquals("The value is not correct", expression, evaluator
+ .evaluate(expression, request));
+ }
}
diff --git a/tiles-core/src/test/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluatorTest.java b/tiles-core/src/test/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluatorTest.java
index 0d7d3d9d..c796593a 100644
--- a/tiles-core/src/test/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluatorTest.java
+++ b/tiles-core/src/test/java/org/apache/tiles/evaluator/impl/DirectAttributeEvaluatorTest.java
@@ -57,4 +57,19 @@ public class DirectAttributeEvaluatorTest extends TestCase {
assertEquals("The expression has not been evaluated correctly", result,
expression);
}
+
+ /**
+ * Tests
+ * {@link DirectAttributeEvaluator#evaluate(String, org.apache.tiles.context.TilesRequestContext)}.
+ */
+ public void testEvaluateString() {
+ String expression = "This is an expression";
+ Object result = evaluator.evaluate(expression, null);
+ assertEquals("The expression has not been evaluated correctly", result,
+ expression);
+ expression = "${attributeName}";
+ result = evaluator.evaluate(expression, null);
+ assertEquals("The expression has not been evaluated correctly", result,
+ expression);
+ }
}
diff --git a/tiles-test/pom.xml b/tiles-test/pom.xml
index 964503e5..9835d95e 100644
--- a/tiles-test/pom.xml
+++ b/tiles-test/pom.xml
@@ -76,6 +76,11 @@
<artifactId>freemarker</artifactId>
<version>2.3.10</version>
</dependency>
+ <dependency>
+ <groupId>de.odysseus.juel</groupId>
+ <artifactId>juel</artifactId>
+ <version>2.1.0</version>
+ </dependency>
</dependencies>
<build>
diff --git a/tiles-test/src/main/java/org/apache/tiles/test/preparer/RequestSettingViewPreparer.java b/tiles-test/src/main/java/org/apache/tiles/test/preparer/RequestSettingViewPreparer.java
new file mode 100644
index 00000000..8e9744c1
--- /dev/null
+++ b/tiles-test/src/main/java/org/apache/tiles/test/preparer/RequestSettingViewPreparer.java
@@ -0,0 +1,42 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tiles.test.preparer;
+
+import org.apache.tiles.preparer.PreparerException;
+import org.apache.tiles.preparer.ViewPreparer;
+import org.apache.tiles.context.TilesRequestContext;
+import org.apache.tiles.AttributeContext;
+
+/**
+ * A simple test <code>ViewPreparer</code> to put a request attribute, that
+ * will be used with the EL evaluator.
+ *
+ * @version $Rev$ $Date$
+ */
+public class RequestSettingViewPreparer implements ViewPreparer {
+
+ /** {@inheritDoc} */
+ public void execute(TilesRequestContext tilesContext,
+ AttributeContext attributeContext) throws PreparerException {
+ tilesContext.getRequestScope().put("body", "test.inner.definition");
+ tilesContext.getRequestScope().put("layout", "/layout.jsp");
+ }
+}
diff --git a/tiles-test/src/main/webapp/WEB-INF/tiles-defs.xml b/tiles-test/src/main/webapp/WEB-INF/tiles-defs.xml
index b2318fc7..9c5fc9fa 100644
--- a/tiles-test/src/main/webapp/WEB-INF/tiles-defs.xml
+++ b/tiles-test/src/main/webapp/WEB-INF/tiles-defs.xml
@@ -196,4 +196,11 @@
</add-attribute>
</put-list-attribute>
</definition>
+
+ <definition name="test.composite.el.definition" template="${layout}"
+ preparer="org.apache.tiles.test.preparer.RequestSettingViewPreparer">
+ <put-attribute name="title" value="This is a configured composite definition."/>
+ <put-attribute name="header" value="/header.jsp"/>
+ <put-attribute name="body" value="${requestScope.body}"/>
+ </definition>
</tiles-definitions>
diff --git a/tiles-test/src/main/webapp/WEB-INF/web.xml b/tiles-test/src/main/webapp/WEB-INF/web.xml
index debb9f9e..bab8a206 100644
--- a/tiles-test/src/main/webapp/WEB-INF/web.xml
+++ b/tiles-test/src/main/webapp/WEB-INF/web.xml
@@ -45,6 +45,11 @@
<param-value>reversed,org.apache.tiles.test.renderer.ReverseStringAttributeRenderer</param-value>
</context-param>
+ <context-param>
+ <param-name>org.apache.tiles.evaluator.AttributeEvaluator</param-name>
+ <param-value>org.apache.tiles.evaluator.el.ELAttributeEvaluator</param-value>
+ </context-param>
+
<filter>
<filter-name>Tiles Decoration Filter</filter-name>
<filter-class>org.apache.tiles.web.util.TilesDecorationFilter</filter-class>
diff --git a/tiles-test/src/main/webapp/index.jsp b/tiles-test/src/main/webapp/index.jsp
index ca849b11..080e199c 100644
--- a/tiles-test/src/main/webapp/index.jsp
+++ b/tiles-test/src/main/webapp/index.jsp
@@ -56,6 +56,7 @@
<a href="testinsertnesteddefinition_tags.jsp">Test Insert Nested Definition only using JSP tags</a><br/>
<a href="testinsertnestedlistdefinition.jsp">Test Insert Nested List Definition</a><br/>
<a href="testinsertnestedlistdefinition_tags.jsp">Test Insert Nested List Definition only using JSP tags</a><br/>
+ <a href="testinsertdefinition_el.jsp">Test Insert Configured Definition with EL</a><br/>
<a href="testput.jsp">Test Put Tag</a><br/>
<a href="testput_flush.jsp">Test Put Tag with Flush</a><br/>
<a href="testput_el.jsp">Test Put Tag using EL</a><br/>
diff --git a/tiles-test/src/main/webapp/testinitcontainer.jsp b/tiles-test/src/main/webapp/testinitcontainer.jsp
index cd634f81..a3a0ad9c 100644
--- a/tiles-test/src/main/webapp/testinitcontainer.jsp
+++ b/tiles-test/src/main/webapp/testinitcontainer.jsp
@@ -36,6 +36,8 @@
value="org.apache.tiles.compat.definition.digester.CompatibilityDigesterDefinitionsReader"/>
<tiles:putAttribute name="org.apache.tiles.renderer.impl.BasicRendereFactory.TYPE_RENDERERS"
value="reversed,org.apache.tiles.test.renderer.ReverseStringAttributeRenderer"/>
+ <tiles:putAttribute name="org.apache.tiles.evaluator.AttributeEvaluator"
+ value="org.apache.tiles.evaluator.el.ELAttributeEvaluator"/>
</tiles:initContainer>
<tiles:insertDefinition name="test.definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_el.jsp b/tiles-test/src/main/webapp/testinsertdefinition_el.jsp
new file mode 100644
index 00000000..07797914
--- /dev/null
+++ b/tiles-test/src/main/webapp/testinsertdefinition_el.jsp
@@ -0,0 +1,27 @@
+<%@ page session="false" %>
+<%--
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+--%>
+<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insertDefinition name="test.composite.el.definition" />
diff --git a/tiles-test/src/test/selenium/ConfiguredDefinitionELTest.html b/tiles-test/src/test/selenium/ConfiguredDefinitionELTest.html
new file mode 100644
index 00000000..8b58e0b1
--- /dev/null
+++ b/tiles-test/src/test/selenium/ConfiguredDefinitionELTest.html
@@ -0,0 +1,71 @@
+<!--
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+-->
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Configured Definition EL Test</title>
+</head>
+<body>
+<table cellpadding="1" cellspacing="1" border="1">
+<thead>
+w<tr><td rowspan="1" colspan="3">Configured Definition EL Test</td></tr>
+</thead><tbody>
+<tr>
+ <td>open</td>
+ <td>/tiles-test/index.jsp</td>
+ <td></td>
+</tr>
+<tr>
+ <td>clickAndWait</td>
+ <td>link=Test Insert Configured Definition with EL</td>
+ <td></td>
+</tr>
+<tr>
+ <td>assertTextPresent</td>
+ <td>This is a configured composite definition.</td>
+ <td></td>
+</tr>
+<tr>
+ <td>assertTextPresent</td>
+ <td>This is the header</td>
+ <td></td>
+</tr>
+<tr>
+ <td>assertTextPresent</td>
+ <td>This is a configured inner definition.</td>
+ <td></td>
+</tr>
+<tr>
+ <td>assertTextPresent</td>
+ <td>This is the header</td>
+ <td></td>
+</tr>
+<tr>
+ <td>assertTextPresent</td>
+ <td>This is a body</td>
+ <td></td>
+</tr>
+
+</tbody></table>
+</body>
+</html>
diff --git a/tiles-test/src/test/selenium/TestSuite.html b/tiles-test/src/test/selenium/TestSuite.html
index d5653127..408f9411 100644
--- a/tiles-test/src/test/selenium/TestSuite.html
+++ b/tiles-test/src/test/selenium/TestSuite.html
@@ -93,6 +93,9 @@
<tr>
<td><a href="ConfiguredNestedListDefinitionTest.html">Configured Nested List Definition Test</a></td>
</tr>
+ <tr>
+ <td><a href="ConfiguredDefinitionELTest.html">Configured Definition EL Test</a></td>
+ </tr>
<tr>
<td><a href="PutTagTest.html">Put Tag Test</a></td>
</tr>
| 0 | 6 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
fc6b298402991eae5d729a865c7391f06f55e450
|
TILESSB-3
pom.xml and sources directories.
git-svn-id: https://svn.apache.org/repos/asf/tiles/sandbox/trunk@707110 13f79535-47bb-0310-9956-ffa450edef68
|
commit fc6b298402991eae5d729a865c7391f06f55e450
Author: Antonio Petrelli <[email protected]>
Date: Wed Oct 22 16:06:00 2008 +0000
TILESSB-3
pom.xml and sources directories.
git-svn-id: https://svn.apache.org/repos/asf/tiles/sandbox/trunk@707110 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-freemarker/pom.xml b/tiles-freemarker/pom.xml
new file mode 100644
index 00000000..4ff09c8e
--- /dev/null
+++ b/tiles-freemarker/pom.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+<!--
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.apache.tiles</groupId>
+ <artifactId>tiles-freemarker</artifactId>
+ <name>Tiles FreeMarker Support</name>
+ <version>1.0-SNAPSHOT</version>
+ <description>Support for FreeMarker in Tiles</description>
+ <parent>
+ <artifactId>tiles-sandbox</artifactId>
+ <groupId>org.apache.tiles</groupId>
+ <version>1.0-SNAPSHOT</version>
+ </parent>
+</project>
\ No newline at end of file
| 0 | 3 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
9103c763711371a60b88425c737921ab8da8aeef
|
TILESSB-40
First classes of tiles-eval-api.
git-svn-id: https://svn.apache.org/repos/asf/tiles/sandbox/trunk@1068494 13f79535-47bb-0310-9956-ffa450edef68
|
commit 9103c763711371a60b88425c737921ab8da8aeef
Author: Antonio Petrelli <[email protected]>
Date: Tue Feb 8 17:48:49 2011 +0000
TILESSB-40
First classes of tiles-eval-api.
git-svn-id: https://svn.apache.org/repos/asf/tiles/sandbox/trunk@1068494 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/BasicEvaluatorRegistry.java b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/BasicEvaluatorRegistry.java
new file mode 100644
index 00000000..ad959de2
--- /dev/null
+++ b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/BasicEvaluatorRegistry.java
@@ -0,0 +1,76 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tiles.eval;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Basic implementation of {@link AttributeEvaluatorFactory}. It supports a
+ * default attribute evaluator, in case the language is not recognized.
+ *
+ * @version $Rev$ $Date$
+ */
+public class BasicEvaluatorRegistry implements EvaluatorRegistry {
+
+ /**
+ * The default evaluator to return if it is not found in the map of known
+ * languages.
+ */
+ private Evaluator defaultEvaluator;
+
+ /**
+ * Maps names of expression languages to their attribute evaluator.
+ */
+ private Map<String, Evaluator> language2evaluator;
+
+ /**
+ * Constructor.
+ *
+ * @param defaultEvaluator The default evaluator to return if it is not
+ * found in the map of known languages.
+ * @since 2.2.0
+ */
+ public BasicEvaluatorRegistry(Evaluator defaultEvaluator) {
+ this.defaultEvaluator = defaultEvaluator;
+ language2evaluator = new HashMap<String, Evaluator>();
+ }
+
+ /**
+ * Registers a known expression language with its attribute evaluator.
+ *
+ * @param language The name of the expression language.
+ * @param evaluator The associated attribute evaluator.
+ */
+ public void registerAttributeEvaluator(String language, Evaluator evaluator) {
+ language2evaluator.put(language, evaluator);
+ }
+
+ /** {@inheritDoc} */
+ public Evaluator getAttributeEvaluator(String language) {
+ Evaluator retValue = language2evaluator.get(language);
+ if (retValue == null) {
+ retValue = defaultEvaluator;
+ }
+ return retValue;
+ }
+}
diff --git a/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/DirectEvaluator.java b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/DirectEvaluator.java
new file mode 100644
index 00000000..20343532
--- /dev/null
+++ b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/DirectEvaluator.java
@@ -0,0 +1,37 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tiles.eval;
+
+import org.apache.tiles.request.Request;
+
+/**
+ * Resolves a string and returns the string itself. It is useful for backward
+ * compatibility.
+ *
+ * @version $Rev$ $Date$
+ */
+public class DirectEvaluator implements Evaluator {
+
+ /** {@inheritDoc} */
+ public Object evaluate(String expression, Request request) {
+ return expression;
+ }
+}
diff --git a/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/Evaluator.java b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/Evaluator.java
new file mode 100644
index 00000000..7a6bcfe1
--- /dev/null
+++ b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/Evaluator.java
@@ -0,0 +1,40 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tiles.eval;
+
+import org.apache.tiles.request.Request;
+
+/**
+ * It represents an object that resolves a string to return an object.
+ *
+ * @version $Rev$ $Date$
+ */
+public interface Evaluator {
+
+ /**
+ * Evaluates an expression.
+ *
+ * @param expression The expression to evaluate.
+ * @param request The request object.
+ * @return The evaluated object.
+ */
+ Object evaluate(String expression, Request request);
+}
diff --git a/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/EvaluatorRegistry.java b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/EvaluatorRegistry.java
new file mode 100644
index 00000000..b89a435f
--- /dev/null
+++ b/tiles-eval/tiles-eval-api/src/main/java/org/apache/tiles/eval/EvaluatorRegistry.java
@@ -0,0 +1,39 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tiles.eval;
+
+
+/**
+ * Returns an evaluator for the given language code.
+ *
+ * @version $Rev$ $Date$
+ */
+public interface EvaluatorRegistry {
+
+ /**
+ * Returns an evaluator for the given expression language.
+ *
+ * @param languageCode The name of the expression language.
+ * @return The evaluator.
+ */
+ Evaluator getAttributeEvaluator(String languageCode);
+}
| 0 | 8 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
49073c6d86954bb219a1e2fbbe468fd0e470fd5b
|
TILESSB-38
Fixed tiles-el checkstyle.
git-svn-id: https://svn.apache.org/repos/asf/tiles/sandbox/trunk@1049676 13f79535-47bb-0310-9956-ffa450edef68
|
commit 49073c6d86954bb219a1e2fbbe468fd0e470fd5b
Author: Antonio Petrelli <[email protected]>
Date: Wed Dec 15 19:38:54 2010 +0000
TILESSB-38
Fixed tiles-el checkstyle.
git-svn-id: https://svn.apache.org/repos/asf/tiles/sandbox/trunk@1049676 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/ScopeELResolver.java b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/ScopeELResolver.java
index 445c0f37..578cd97b 100644
--- a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/ScopeELResolver.java
+++ b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/ScopeELResolver.java
@@ -40,6 +40,11 @@ import org.apache.tiles.request.Request;
*/
public class ScopeELResolver extends ELResolver {
+ /**
+ * The length of the suffix: "Scope".
+ */
+ private static final int SUFFIX_LENGTH = 5;
+
/** {@inheritDoc} */
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
@@ -64,7 +69,7 @@ public class ScopeELResolver extends ELResolver {
Request request = (Request) context
.getContext(Request.class);
- for (String scope: request.getAvailableScopes()) {
+ for (String scope : request.getAvailableScopes()) {
FeatureDescriptor descriptor = new FeatureDescriptor();
descriptor.setDisplayName(scope + "Scope");
descriptor.setExpert(false);
@@ -104,7 +109,7 @@ public class ScopeELResolver extends ELResolver {
Request request = (Request) context
.getContext(Request.class);
retValue = request.getContext(propertyString.substring(0,
- propertyString.length() - 5));
+ propertyString.length() - SUFFIX_LENGTH));
}
if (retValue != null) {
diff --git a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextBeanELResolver.java b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextBeanELResolver.java
index a58e6944..e03e4a06 100644
--- a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextBeanELResolver.java
+++ b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextBeanELResolver.java
@@ -58,7 +58,7 @@ public class TilesContextBeanELResolver extends ELResolver {
Request request = (Request) context
.getContext(Request.class);
- for (String scope: request.getAvailableScopes()) {
+ for (String scope : request.getAvailableScopes()) {
collectBeanInfo(request.getContext(scope), list);
}
return list.iterator();
diff --git a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextELResolver.java b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextELResolver.java
index c3985711..d3b59cac 100644
--- a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextELResolver.java
+++ b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/TilesContextELResolver.java
@@ -39,8 +39,16 @@ import org.apache.tiles.util.CombinedBeanInfo;
*/
public class TilesContextELResolver extends ELResolver {
+ /**
+ * Internal bean resolver to resolve beans in any context.
+ */
private ELResolver beanElResolver;
+ /**
+ * Constructor.
+ *
+ * @param beanElResolver The used bean resolver.
+ */
public TilesContextELResolver(ELResolver beanElResolver) {
this.beanElResolver = beanElResolver;
}
diff --git a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/package.html b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/package-info.java
similarity index 81%
rename from tiles3/tiles-el/src/main/java/org/apache/tiles/el/package.html
rename to tiles3/tiles-el/src/main/java/org/apache/tiles/el/package-info.java
index 5143051a..01731df4 100644
--- a/tiles3/tiles-el/src/main/java/org/apache/tiles/el/package.html
+++ b/tiles3/tiles-el/src/main/java/org/apache/tiles/el/package-info.java
@@ -1,4 +1,3 @@
-<!--
/*
* $Id$
*
@@ -19,12 +18,7 @@
* specific language governing permissions and limitations
* under the License.
*/
--->
-<html>
-<head>
- <title>Tiles attribute evaluator EL implementation</title>
-</head>
-<body>
-Attribute evaluator classes that can perform EL evaluation for attributes.
-</body>
-</html>
\ No newline at end of file
+/**
+ * Attribute evaluator classes that can perform EL evaluation for attributes.
+ */
+package org.apache.tiles.el;
diff --git a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ELContextImplTest.java b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ELContextImplTest.java
index 947684c7..520398ba 100644
--- a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ELContextImplTest.java
+++ b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ELContextImplTest.java
@@ -1,5 +1,22 @@
-/**
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.tiles.el;
@@ -21,8 +38,14 @@ import org.junit.Test;
*/
public class ELContextImplTest {
+ /**
+ * The EL context to test.
+ */
private ELContextImpl context;
+ /**
+ * The EL resolver.
+ */
private ELResolver resolver;
/**
diff --git a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/JspExpressionFactoryFactoryTest.java b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/JspExpressionFactoryFactoryTest.java
index ca82c9fd..65acdd27 100644
--- a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/JspExpressionFactoryFactoryTest.java
+++ b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/JspExpressionFactoryFactoryTest.java
@@ -1,5 +1,22 @@
-/**
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.tiles.el;
@@ -49,7 +66,7 @@ public class JspExpressionFactoryFactoryTest {
/**
* Test method for {@link org.apache.tiles.el.JspExpressionFactoryFactory#getExpressionFactory()}.
*/
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testSetApplicationContextIllegal() {
ApplicationContext applicationContext = createMock(ApplicationContext.class);
Integer servletContext = new Integer(1);
diff --git a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ScopeELResolverTest.java b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ScopeELResolverTest.java
index f74ced05..84a4bd24 100644
--- a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ScopeELResolverTest.java
+++ b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/ScopeELResolverTest.java
@@ -1,3 +1,23 @@
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
package org.apache.tiles.el;
import static org.easymock.classextension.EasyMock.*;
@@ -16,6 +36,11 @@ import org.junit.Before;
import org.junit.Test;
+/**
+ * Tests {@link ScopeELResolver}.
+ *
+ * @version $Rev$ $Date$
+ */
public class ScopeELResolverTest {
/**
diff --git a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextBeanELResolverTest.java b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextBeanELResolverTest.java
index 63ad32bc..86a92ad4 100644
--- a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextBeanELResolverTest.java
+++ b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextBeanELResolverTest.java
@@ -223,7 +223,7 @@ public class TilesContextBeanELResolverTest {
* Test method for
* {@link TilesContextBeanELResolver#isReadOnly(javax.el.ELContext, java.lang.Object, java.lang.Object)}.
*/
- @Test(expected=NullPointerException.class)
+ @Test(expected = NullPointerException.class)
public void testIsReadOnlyNPE() {
resolver.isReadOnly(null, null, null);
}
diff --git a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextELResolverTest.java b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextELResolverTest.java
index b1b555aa..e781b97d 100644
--- a/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextELResolverTest.java
+++ b/tiles3/tiles-el/src/test/java/org/apache/tiles/el/TilesContextELResolverTest.java
@@ -45,6 +45,9 @@ import org.junit.Test;
*/
public class TilesContextELResolverTest {
+ /**
+ * The bean resolver.
+ */
private ELResolver beanElResolver;
/**
@@ -101,7 +104,7 @@ public class TilesContextELResolverTest {
/**
* Tests {@link TilesContextBeanELResolver#getType(ELContext, Object, Object)}.
*/
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testGetType() {
ELContext elContext = createMock(ELContext.class);
@@ -125,12 +128,12 @@ public class TilesContextELResolverTest {
/**
* Tests {@link TilesContextBeanELResolver#getValue(ELContext, Object, Object)}.
*/
- @SuppressWarnings("unchecked")
@Test
public void testGetValue() {
ELContext elContext = createMock(ELContext.class);
Request request = createMock(Request.class);
ApplicationContext applicationContext = createMock(ApplicationContext.class);
+ @SuppressWarnings("rawtypes")
Map map = createMock(Map.class);
expect(elContext.getContext(Request.class)).andReturn(request);
@@ -164,7 +167,7 @@ public class TilesContextELResolverTest {
* Test method for
* {@link TilesContextELResolver#isReadOnly(javax.el.ELContext, java.lang.Object, java.lang.Object)}.
*/
- @Test(expected=NullPointerException.class)
+ @Test(expected = NullPointerException.class)
public void testIsReadOnlyNPE() {
replay(beanElResolver);
try {
| 0 | 1 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
ccd7ea759fc550e496f376ed355a81318b17da5f
|
Set svn:eol-style=native to files that have not this property.
git-svn-id: https://svn.apache.org/repos/asf/struts/sandbox/trunk/tiles@465598 13f79535-47bb-0310-9956-ffa450edef68
|
commit ccd7ea759fc550e496f376ed355a81318b17da5f
Author: Antonio Petrelli <[email protected]>
Date: Thu Oct 19 12:12:44 2006 +0000
Set svn:eol-style=native to files that have not this property.
git-svn-id: https://svn.apache.org/repos/asf/struts/sandbox/trunk/tiles@465598 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/site/fml/faq.fml b/src/site/fml/faq.fml
index b3de70c4..04f3d067 100644
--- a/src/site/fml/faq.fml
+++ b/src/site/fml/faq.fml
@@ -1,120 +1,120 @@
-<?xml version="1.0"?>
-<!--
-Copyright 2006 The Apache Software Foundation
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<!--
-// ======================================================================== 78
--->
-<faqs title="Tiles 2 FAQ">
- <part id="taglib-faq">
- <title>Tiles 2 Taglib</title>
- <faq id="get">
- <question>What happened to <code>&lt;tiles:get&gt;</code> tag?
- </question>
- <answer>
- <p>The <code>&lt;tiles:get&gt;</code> has been removed,
- along with its class GetTag. Use
- <code>&lt;tiles:insert&gt;</code> instead,
- eventually specifiying <code>ignore="true"</code>, that was
- the default in <code>&lt;tiles:get&gt;</code>.
- </p>
- </answer>
- </faq>
- <faq id="get-attribute-tag">
- <question>What happened to <code>GetAttributeTag</code> class?
- </question>
- <answer>
- <p>The <code>GetAttributeTag</code> class has been renamed to
- <code>GetAsStringTag</code> to conform to conventions on tag
- libraries.
- </p>
- </answer>
- </faq>
- <faq id="name">
- <question>What happened to 'attribute' and 'definition'?</question>
- <answer>
- <p>The 'attribute' and 'definition' tag attributes were removed.
- Use 'name' instead.
- </p>
- </answer>
- </faq>
- <faq id="template">
- <question>What happened to 'page' and 'component'?</question>
- <answer>
- <p>The 'page' and 'component' tag attributes were removed.
- Use 'template' instead.
- </p>
- </answer>
- </faq>
- <faq id="bean">
- <question>What happened to beanName, beanProperty and beanScope?
- </question>
- <answer>
- <p>The 'beanName', 'beanProperty', and 'beanScope' tag attributes
- were removed with no replacement. Use EL instead. For example:
- </p>
- <code><tiles:put name="foo" value="${foo.bar}"/></code>
- </answer>
- </faq>
- <faq id="put-add-direct">
- <question>What happened to the 'direct' attribute of PutTag and AddTag?
- </question>
- <answer>
- <p>It has been removed since you can specify the "direct"
- inclusion using <code>type="string"</code></p>
- </answer>
- </faq>
- <faq id="insert-type">
- <question>Is the insert tag's 'type' attribute required?
- </question>
- <answer>
- <p>The "type" attribute should not be required: it is useful only to
- distinguish between "definition" and "attribute" in the case that we
- have a definition and an attribute with the same name.</p>
- <p>However, we've seen reports of errors if it is not used.
- Please comment on <a href="http://issues.apache.org/struts/browse/SB-46">SB-46</a>
- if you have more information.</p>
- </answer>
- </faq>
- <faq id="controller">
- <question>What happened to controllerUrl and controllerClass and the
- <code>Controller</code> Java class?
- </question>
- <answer>
- <p>The "controller" concept has been replaced with "preparer",
- to avoid confusion with "controller" as in MVC model.
- <code>Controller</code> class has been renamed to
- <code>ViewPreparer</code>, while the attributes have been
- renamed to "preparerUrl" and "preparerClass".</p>
- </answer>
- </faq>
- <faq id="definition-id">
- <question>What happened to the 'id' attribute of DefinitionTag?
- </question>
- <answer>
- <p>TODO - Did this change to 'name'?</p>
- </answer>
- </faq>
- </part>
- <part id="dtd-faq">
- <title>Tiles 2 DTD</title>
- <faq id="todo">
- <question>What happened to ... ?</question>
- <answer>
- <p>TODO
- </p>
- </answer>
- </faq>
- </part>
-</faqs>
+<?xml version="1.0"?>
+<!--
+Copyright 2006 The Apache Software Foundation
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<!--
+// ======================================================================== 78
+-->
+<faqs title="Tiles 2 FAQ">
+ <part id="taglib-faq">
+ <title>Tiles 2 Taglib</title>
+ <faq id="get">
+ <question>What happened to <code>&lt;tiles:get&gt;</code> tag?
+ </question>
+ <answer>
+ <p>The <code>&lt;tiles:get&gt;</code> has been removed,
+ along with its class GetTag. Use
+ <code>&lt;tiles:insert&gt;</code> instead,
+ eventually specifiying <code>ignore="true"</code>, that was
+ the default in <code>&lt;tiles:get&gt;</code>.
+ </p>
+ </answer>
+ </faq>
+ <faq id="get-attribute-tag">
+ <question>What happened to <code>GetAttributeTag</code> class?
+ </question>
+ <answer>
+ <p>The <code>GetAttributeTag</code> class has been renamed to
+ <code>GetAsStringTag</code> to conform to conventions on tag
+ libraries.
+ </p>
+ </answer>
+ </faq>
+ <faq id="name">
+ <question>What happened to 'attribute' and 'definition'?</question>
+ <answer>
+ <p>The 'attribute' and 'definition' tag attributes were removed.
+ Use 'name' instead.
+ </p>
+ </answer>
+ </faq>
+ <faq id="template">
+ <question>What happened to 'page' and 'component'?</question>
+ <answer>
+ <p>The 'page' and 'component' tag attributes were removed.
+ Use 'template' instead.
+ </p>
+ </answer>
+ </faq>
+ <faq id="bean">
+ <question>What happened to beanName, beanProperty and beanScope?
+ </question>
+ <answer>
+ <p>The 'beanName', 'beanProperty', and 'beanScope' tag attributes
+ were removed with no replacement. Use EL instead. For example:
+ </p>
+ <code><tiles:put name="foo" value="${foo.bar}"/></code>
+ </answer>
+ </faq>
+ <faq id="put-add-direct">
+ <question>What happened to the 'direct' attribute of PutTag and AddTag?
+ </question>
+ <answer>
+ <p>It has been removed since you can specify the "direct"
+ inclusion using <code>type="string"</code></p>
+ </answer>
+ </faq>
+ <faq id="insert-type">
+ <question>Is the insert tag's 'type' attribute required?
+ </question>
+ <answer>
+ <p>The "type" attribute should not be required: it is useful only to
+ distinguish between "definition" and "attribute" in the case that we
+ have a definition and an attribute with the same name.</p>
+ <p>However, we've seen reports of errors if it is not used.
+ Please comment on <a href="http://issues.apache.org/struts/browse/SB-46">SB-46</a>
+ if you have more information.</p>
+ </answer>
+ </faq>
+ <faq id="controller">
+ <question>What happened to controllerUrl and controllerClass and the
+ <code>Controller</code> Java class?
+ </question>
+ <answer>
+ <p>The "controller" concept has been replaced with "preparer",
+ to avoid confusion with "controller" as in MVC model.
+ <code>Controller</code> class has been renamed to
+ <code>ViewPreparer</code>, while the attributes have been
+ renamed to "preparerUrl" and "preparerClass".</p>
+ </answer>
+ </faq>
+ <faq id="definition-id">
+ <question>What happened to the 'id' attribute of DefinitionTag?
+ </question>
+ <answer>
+ <p>TODO - Did this change to 'name'?</p>
+ </answer>
+ </faq>
+ </part>
+ <part id="dtd-faq">
+ <title>Tiles 2 DTD</title>
+ <faq id="todo">
+ <question>What happened to ... ?</question>
+ <answer>
+ <p>TODO
+ </p>
+ </answer>
+ </faq>
+ </part>
+</faqs>
diff --git a/tiles-core/src/test/java/org/apache/tiles/mock/MockOnlyLocaleTilesContext.java b/tiles-core/src/test/java/org/apache/tiles/mock/MockOnlyLocaleTilesContext.java
index 1445b2c5..ecf7ac7e 100644
--- a/tiles-core/src/test/java/org/apache/tiles/mock/MockOnlyLocaleTilesContext.java
+++ b/tiles-core/src/test/java/org/apache/tiles/mock/MockOnlyLocaleTilesContext.java
@@ -1,103 +1,103 @@
-/*
- * $Id$
- *
- * Copyright 1999-2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.tiles.mock;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Locale;
-import java.util.Map;
-
-import org.apache.tiles.TilesContext;
-
-/**
- * Creates a TilesContext that contains only a Locale
- *
- * @version $Rev$ $Date$
- */
-public class MockOnlyLocaleTilesContext implements TilesContext {
-
- /**
- * The locale object.
- */
- private Locale locale;
-
- /** Creates a new instance of MockOnlyLocaleTilesContext.
- *
- * @param locale The locale object to use.
- */
- public MockOnlyLocaleTilesContext(Locale locale) {
- this.locale = locale;
- }
-
- /**
- * Returns the locale specified in the constructor.
- *
- * @see org.apache.tiles.TilesContext#getRequestLocale()
- */
- public Locale getRequestLocale() {
- return locale;
- }
-
- // The rest of the implemented methods has a "dummy" behaviour, doing
- // nothing or returning null, because they are not needed at all in tests
- // that use this class.
-
- public void dispatch(String path) throws IOException, Exception {
- }
-
- public Map getApplicationScope() {
- return null;
- }
-
- public Map getHeader() {
- return null;
- }
-
- public Map getHeaderValues() {
- return null;
- }
-
- public Map getInitParams() {
- return null;
- }
-
- public Map getParam() {
- return null;
- }
-
- public Map getParamValues() {
- return null;
- }
-
- public Map getRequestScope() {
- return null;
- }
-
- public URL getResource(String path) throws MalformedURLException {
- return null;
- }
-
- public Map getSessionScope() {
- return null;
- }
-
- public void include(String path) throws IOException, Exception {
- }
-}
+/*
+ * $Id$
+ *
+ * Copyright 1999-2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.tiles.mock;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Locale;
+import java.util.Map;
+
+import org.apache.tiles.TilesContext;
+
+/**
+ * Creates a TilesContext that contains only a Locale
+ *
+ * @version $Rev$ $Date$
+ */
+public class MockOnlyLocaleTilesContext implements TilesContext {
+
+ /**
+ * The locale object.
+ */
+ private Locale locale;
+
+ /** Creates a new instance of MockOnlyLocaleTilesContext.
+ *
+ * @param locale The locale object to use.
+ */
+ public MockOnlyLocaleTilesContext(Locale locale) {
+ this.locale = locale;
+ }
+
+ /**
+ * Returns the locale specified in the constructor.
+ *
+ * @see org.apache.tiles.TilesContext#getRequestLocale()
+ */
+ public Locale getRequestLocale() {
+ return locale;
+ }
+
+ // The rest of the implemented methods has a "dummy" behaviour, doing
+ // nothing or returning null, because they are not needed at all in tests
+ // that use this class.
+
+ public void dispatch(String path) throws IOException, Exception {
+ }
+
+ public Map getApplicationScope() {
+ return null;
+ }
+
+ public Map getHeader() {
+ return null;
+ }
+
+ public Map getHeaderValues() {
+ return null;
+ }
+
+ public Map getInitParams() {
+ return null;
+ }
+
+ public Map getParam() {
+ return null;
+ }
+
+ public Map getParamValues() {
+ return null;
+ }
+
+ public Map getRequestScope() {
+ return null;
+ }
+
+ public URL getResource(String path) throws MalformedURLException {
+ return null;
+ }
+
+ public Map getSessionScope() {
+ return null;
+ }
+
+ public void include(String path) throws IOException, Exception {
+ }
+}
diff --git a/tiles-core/src/test/java/org/apache/tiles/mock/MockPublicUrlDefinitionsFactory.java b/tiles-core/src/test/java/org/apache/tiles/mock/MockPublicUrlDefinitionsFactory.java
index 9a0b3722..837284ec 100644
--- a/tiles-core/src/test/java/org/apache/tiles/mock/MockPublicUrlDefinitionsFactory.java
+++ b/tiles-core/src/test/java/org/apache/tiles/mock/MockPublicUrlDefinitionsFactory.java
@@ -1,56 +1,56 @@
-/*
- * $Id$
- *
- * Copyright 1999-2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.tiles.mock;
-
-import org.apache.tiles.ComponentDefinitions;
-import org.apache.tiles.DefinitionsFactoryException;
-import org.apache.tiles.TilesContext;
-import org.apache.tiles.definition.UrlDefinitionsFactory;
-
-/**
- * Mock implementation of UrlDefinitionsFactory that exposes two of its methods
- * as public instead of protected.
- *
- * @version $Rev$ $Date$
- */
-public class MockPublicUrlDefinitionsFactory extends UrlDefinitionsFactory {
-
- /**
- * Exposes the <code>addDefinitions</code> method of
- * <code>UrlDefinitionsFactory</code>
- *
- * @see org.apache.tiles.definition.UrlDefinitionsFactory#addDefinitions(org.apache.tiles.ComponentDefinitions,
- * org.apache.tiles.TilesContext)
- */
- public void addDefinitions(ComponentDefinitions definitions,
- TilesContext tilesContext) throws DefinitionsFactoryException {
- super.addDefinitions(definitions, tilesContext);
- }
-
- /**
- *
- * Exposes the <code>isContextProcessed</code> method of
- * <code>UrlDefinitionsFactory</code>
- *
- * @see org.apache.tiles.definition.UrlDefinitionsFactory#isContextProcessed(org.apache.tiles.TilesContext)
- */
- public boolean isContextProcessed(TilesContext tilesContext) {
- return super.isContextProcessed(tilesContext);
- }
-}
+/*
+ * $Id$
+ *
+ * Copyright 1999-2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.tiles.mock;
+
+import org.apache.tiles.ComponentDefinitions;
+import org.apache.tiles.DefinitionsFactoryException;
+import org.apache.tiles.TilesContext;
+import org.apache.tiles.definition.UrlDefinitionsFactory;
+
+/**
+ * Mock implementation of UrlDefinitionsFactory that exposes two of its methods
+ * as public instead of protected.
+ *
+ * @version $Rev$ $Date$
+ */
+public class MockPublicUrlDefinitionsFactory extends UrlDefinitionsFactory {
+
+ /**
+ * Exposes the <code>addDefinitions</code> method of
+ * <code>UrlDefinitionsFactory</code>
+ *
+ * @see org.apache.tiles.definition.UrlDefinitionsFactory#addDefinitions(org.apache.tiles.ComponentDefinitions,
+ * org.apache.tiles.TilesContext)
+ */
+ public void addDefinitions(ComponentDefinitions definitions,
+ TilesContext tilesContext) throws DefinitionsFactoryException {
+ super.addDefinitions(definitions, tilesContext);
+ }
+
+ /**
+ *
+ * Exposes the <code>isContextProcessed</code> method of
+ * <code>UrlDefinitionsFactory</code>
+ *
+ * @see org.apache.tiles.definition.UrlDefinitionsFactory#isContextProcessed(org.apache.tiles.TilesContext)
+ */
+ public boolean isContextProcessed(TilesContext tilesContext) {
+ return super.isContextProcessed(tilesContext);
+ }
+}
diff --git a/tiles-test/src/main/java/org/apache/tiles/test/servlet/IncludingServlet.java b/tiles-test/src/main/java/org/apache/tiles/test/servlet/IncludingServlet.java
index 68ca8fd3..a0e111b8 100644
--- a/tiles-test/src/main/java/org/apache/tiles/test/servlet/IncludingServlet.java
+++ b/tiles-test/src/main/java/org/apache/tiles/test/servlet/IncludingServlet.java
@@ -1,55 +1,55 @@
-/*
- * $Id$
- *
- * Copyright 1999-2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.tiles.test.servlet;
-
-import java.io.IOException;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * Sample servlet that includes a page specified by the <code>include</code>
- * init parameter.
- *
- * @version $Rev$ $Date$
- */
-public class IncludingServlet extends HttpServlet {
-
- private String include;
-
- /**
- * Initializes the servlet, reading the <code>include</code> init parameter
- */
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
-
- include = config.getInitParameter("include");
- }
-
- /**
- * Processes the request, including the specified page.
- */
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- request.getRequestDispatcher(include).include(request, response);
- }
-}
+/*
+ * $Id$
+ *
+ * Copyright 1999-2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.tiles.test.servlet;
+
+import java.io.IOException;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Sample servlet that includes a page specified by the <code>include</code>
+ * init parameter.
+ *
+ * @version $Rev$ $Date$
+ */
+public class IncludingServlet extends HttpServlet {
+
+ private String include;
+
+ /**
+ * Initializes the servlet, reading the <code>include</code> init parameter
+ */
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+
+ include = config.getInitParameter("include");
+ }
+
+ /**
+ * Processes the request, including the specified page.
+ */
+ protected void doGet(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ request.getRequestDispatcher(include).include(request, response);
+ }
+}
diff --git a/tiles-test/src/main/webapp/putattributeslayout.jsp b/tiles-test/src/main/webapp/putattributeslayout.jsp
index 0ab73722..5337f696 100644
--- a/tiles-test/src/main/webapp/putattributeslayout.jsp
+++ b/tiles-test/src/main/webapp/putattributeslayout.jsp
@@ -1,11 +1,11 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
-<tiles:importAttribute name="stringTest"/>
-<tiles:importAttribute name="list"/>
-Single attribute "stringTest" value: <c:out value="${stringTest}" /> <br/><br/>
-The attribute "list" contains these values:
-<ul>
-<c:forEach var="item" items="${list}">
-<li><c:out value="${item}" /></li>
-</c:forEach>
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
+<tiles:importAttribute name="stringTest"/>
+<tiles:importAttribute name="list"/>
+Single attribute "stringTest" value: <c:out value="${stringTest}" /> <br/><br/>
+The attribute "list" contains these values:
+<ul>
+<c:forEach var="item" items="${list}">
+<li><c:out value="${item}" /></li>
+</c:forEach>
</ul>
\ No newline at end of file
diff --git a/tiles-test/src/main/webapp/testimportattribute.jsp b/tiles-test/src/main/webapp/testimportattribute.jsp
index 208fffec..29233ad1 100644
--- a/tiles-test/src/main/webapp/testimportattribute.jsp
+++ b/tiles-test/src/main/webapp/testimportattribute.jsp
@@ -1,3 +1,3 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert name="test.putAttributes" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert name="test.putAttributes" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition.jsp b/tiles-test/src/main/webapp/testinsertdefinition.jsp
index 486ba495..249337f2 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition.jsp
@@ -1,3 +1,3 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert name="test.definition" type="definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert name="test.definition" type="definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_composite.jsp b/tiles-test/src/main/webapp/testinsertdefinition_composite.jsp
index c296e80e..8e4426b9 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_composite.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_composite.jsp
@@ -1,3 +1,3 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert name="test.composite.definition" type="definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert name="test.composite.definition" type="definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags.jsp b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags.jsp
index 7ebe2e28..d72e46ad 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags.jsp
@@ -1,13 +1,13 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is an inner definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="/body.jsp"/>
-</tiles:definition>
-<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is a composite definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="test.inner.definition.tags" type="definition"/>
-</tiles:definition>
-<tiles:insert name="test.composite.definition.tags" type="definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is an inner definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="/body.jsp"/>
+</tiles:definition>
+<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is a composite definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="test.inner.definition.tags" type="definition"/>
+</tiles:definition>
+<tiles:insert name="test.composite.definition.tags" type="definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured.jsp b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured.jsp
index 5afbfb7a..2a64c1ca 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured.jsp
@@ -1,13 +1,13 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is an inner definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="/body.jsp"/>
-</tiles:definition>
-<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is a composite definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="test.inner.definition" type="definition"/>
-</tiles:definition>
-<tiles:insert name="test.composite.definition.tags" type="definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is an inner definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="/body.jsp"/>
+</tiles:definition>
+<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is a composite definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="test.inner.definition" type="definition"/>
+</tiles:definition>
+<tiles:insert name="test.composite.definition.tags" type="definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured_notype.jsp b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured_notype.jsp
index a90343f0..ca2c98b4 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured_notype.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_includes_configured_notype.jsp
@@ -1,13 +1,13 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is an inner definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="/body.jsp"/>
-</tiles:definition>
-<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is a composite definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="test.inner.definition"/>
-</tiles:definition>
-<tiles:insert name="test.composite.definition.tags" type="definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is an inner definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="/body.jsp"/>
+</tiles:definition>
+<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is a composite definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="test.inner.definition"/>
+</tiles:definition>
+<tiles:insert name="test.composite.definition.tags" type="definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_notype.jsp b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_notype.jsp
index a02bacee..07c46438 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_notype.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_composite_tags_notype.jsp
@@ -1,13 +1,13 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is an inner definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="/body.jsp"/>
-</tiles:definition>
-<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
- <tiles:put name="title" value="This is a composite definition with tags."/>
- <tiles:put name="header" value="/header.jsp"/>
- <tiles:put name="body" value="test.inner.definition.tags"/>
-</tiles:definition>
-<tiles:insert name="test.composite.definition.tags" type="definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:definition name="test.inner.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is an inner definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="/body.jsp"/>
+</tiles:definition>
+<tiles:definition name="test.composite.definition.tags" template="/layout.jsp">
+ <tiles:put name="title" value="This is a composite definition with tags."/>
+ <tiles:put name="header" value="/header.jsp"/>
+ <tiles:put name="body" value="test.inner.definition.tags"/>
+</tiles:definition>
+<tiles:insert name="test.composite.definition.tags" type="definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_inline.jsp b/tiles-test/src/main/webapp/testinsertdefinition_inline.jsp
index 2830f5bb..d6271498 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_inline.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_inline.jsp
@@ -1,7 +1,7 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert name="test.definition" type="definition">
- <tiles:put name="body">
- <div align="center"><b><i>This is an inline content</i></b></div>
- </tiles:put>
-</tiles:insert>
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert name="test.definition" type="definition">
+ <tiles:put name="body">
+ <div align="center"><b><i>This is an inline content</i></b></div>
+ </tiles:put>
+</tiles:insert>
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_notype.jsp b/tiles-test/src/main/webapp/testinsertdefinition_notype.jsp
index f520c9e1..bea03959 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_notype.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_notype.jsp
@@ -1,3 +1,3 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert name="test.definition" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert name="test.definition" />
diff --git a/tiles-test/src/main/webapp/testinsertdefinition_override.jsp b/tiles-test/src/main/webapp/testinsertdefinition_override.jsp
index b74c80c2..568c51e2 100644
--- a/tiles-test/src/main/webapp/testinsertdefinition_override.jsp
+++ b/tiles-test/src/main/webapp/testinsertdefinition_override.jsp
@@ -1,5 +1,5 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert name="test.definition" type="definition">
- <tiles:put name="body" value="/override.jsp" />
-</tiles:insert>
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert name="test.definition" type="definition">
+ <tiles:put name="body" value="/override.jsp" />
+</tiles:insert>
diff --git a/tiles-test/src/main/webapp/testput_servlet.jsp b/tiles-test/src/main/webapp/testput_servlet.jsp
index 10c05fe2..91e1e631 100644
--- a/tiles-test/src/main/webapp/testput_servlet.jsp
+++ b/tiles-test/src/main/webapp/testput_servlet.jsp
@@ -1,7 +1,7 @@
-<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
-
-<tiles:insert template="/servlets/layoutServlet">
- <tiles:put name="title" value="This is the title." />
- <tiles:put name="header" value="/header.jsp" />
- <tiles:put name="body" value="/body.jsp" />
+<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
+
+<tiles:insert template="/servlets/layoutServlet">
+ <tiles:put name="title" value="This is the title." />
+ <tiles:put name="header" value="/header.jsp" />
+ <tiles:put name="body" value="/body.jsp" />
</tiles:insert>
\ No newline at end of file
| 0 | 10 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
927e12152b24a5b3926f9a6206a8ffa4a34dd840
|
TILES-432
Polished tiles-core (a missing file added).
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@787727 13f79535-47bb-0310-9956-ffa450edef68
|
commit 927e12152b24a5b3926f9a6206a8ffa4a34dd840
Author: Antonio Petrelli <[email protected]>
Date: Tue Jun 23 15:45:36 2009 +0000
TILES-432
Polished tiles-core (a missing file added).
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@787727 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-core/src/main/java/org/apache/tiles/definition/pattern/package.html b/tiles-core/src/main/java/org/apache/tiles/definition/pattern/package.html
new file mode 100644
index 00000000..e6963e91
--- /dev/null
+++ b/tiles-core/src/main/java/org/apache/tiles/definition/pattern/package.html
@@ -0,0 +1,30 @@
+<!--
+/*
+ * $Id$
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+-->
+<html>
+<head>
+ <title>Tiles support to wildcard patterns</title>
+</head>
+<body>
+In Tiles it is possible to use wildcard patterns thanks to this package.
+</body>
+</html>
\ No newline at end of file
| 0 | 9 |
CVE-2009-1275
|
Apache Tiles 2.1 before 2.1.2, as used in Apache Struts and other products, evaluates Expression Language (EL) expressions twice in certain circumstances, which allows remote attackers to conduct cross-site scripting (XSS) attacks or obtain sensitive information via unspecified vectors, related to the (1) tiles:putAttribute and (2) tiles:insertTemplate JSP tags.
|
apache/tiles
|
f8e58ae817fb4b8a9128df5c60bf432a3fe46ae1
|
TILES-428
Added expression property in AddAttributeTag and PutAttributeTag.
Added templateExpression attribute in insertDefinition, insertTemplate, addAttribute and putAttribute.
Added templateType in insertTemplate and insertDefinition.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@796822 13f79535-47bb-0310-9956-ffa450edef68
|
commit f8e58ae817fb4b8a9128df5c60bf432a3fe46ae1
Author: Antonio Petrelli <[email protected]>
Date: Wed Jul 22 18:25:50 2009 +0000
TILES-428
Added expression property in AddAttributeTag and PutAttributeTag.
Added templateExpression attribute in insertDefinition, insertTemplate, addAttribute and putAttribute.
Added templateType in insertTemplate and insertDefinition.
git-svn-id: https://svn.apache.org/repos/asf/tiles/framework/trunk@796822 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/AddAttributeTag.java b/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/AddAttributeTag.java
index 6ac65860..8712bca3 100644
--- a/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/AddAttributeTag.java
+++ b/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/AddAttributeTag.java
@@ -76,6 +76,12 @@ public class AddAttributeTag extends SimpleTagSupport {
*/
private Object value = null;
+ /**
+ * The expression to calculate the value from. Use this parameter, or value,
+ * or body.
+ */
+ private String expression = null;
+
/**
* Requested type for the value.
*/
@@ -119,6 +125,28 @@ public class AddAttributeTag extends SimpleTagSupport {
this.value = value;
}
+ /**
+ * Returns the expression to calculate the value from. Use this parameter,
+ * or value, or body.
+ *
+ * @return The expression
+ * @since 2.2.0
+ */
+ public String getExpression() {
+ return expression;
+ }
+
+ /**
+ * Sets the expression to calculate the value from. Use this parameter, or
+ * value, or body.
+ *
+ * @param expression The expression
+ * @since 2.2.0
+ */
+ public void setExpression(String expression) {
+ this.expression = expression;
+ }
+
/**
* <p>
* Returns content type: string, template or definition.
@@ -165,7 +193,7 @@ public class AddAttributeTag extends SimpleTagSupport {
JspContext pageContext = getJspContext();
model.start(JspUtil.getComposeStack(pageContext));
String body = JspUtil.evaluateFragmentAsString(getJspBody());
- model.end(JspUtil.getComposeStack(pageContext), value, null, body,
- role, type);
+ model.end(JspUtil.getComposeStack(pageContext), value, expression,
+ body, role, type);
}
}
diff --git a/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/PutAttributeTag.java b/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/PutAttributeTag.java
index 117cf810..1191b388 100644
--- a/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/PutAttributeTag.java
+++ b/tiles-jsp/src/main/java/org/apache/tiles/jsp/taglib/PutAttributeTag.java
@@ -98,6 +98,12 @@ public class PutAttributeTag extends SimpleTagSupport {
*/
private Object value = null;
+ /**
+ * The expression to calculate the value from. Use this parameter, or value,
+ * or body.
+ */
+ private String expression = null;
+
/**
* Requested type for the value.
*/
@@ -180,6 +186,28 @@ public class PutAttributeTag extends SimpleTagSupport {
this.value = value;
}
+ /**
+ * Returns the expression to calculate the value from. Use this parameter,
+ * or value, or body.
+ *
+ * @return The expression
+ * @since 2.2.0
+ */
+ public String getExpression() {
+ return expression;
+ }
+
+ /**
+ * Sets the expression to calculate the value from. Use this parameter, or
+ * value, or body.
+ *
+ * @param expression The expression
+ * @since 2.2.0
+ */
+ public void setExpression(String expression) {
+ this.expression = expression;
+ }
+
/**
* <p>
* Returns content type: string, template or definition.
@@ -227,7 +255,7 @@ public class PutAttributeTag extends SimpleTagSupport {
model.start(JspUtil.getComposeStack(jspContext));
String body = JspUtil.evaluateFragmentAsString(getJspBody());
model.end(JspUtil.getCurrentContainer(jspContext), JspUtil
- .getComposeStack(jspContext), name, value, null,
- body, role, type, cascade, jspContext);
+ .getComposeStack(jspContext), name, value, expression, body,
+ role, type, cascade, jspContext);
}
}
diff --git a/tiles-jsp/src/main/resources/META-INF/tld/tiles-jsp.tld b/tiles-jsp/src/main/resources/META-INF/tld/tiles-jsp.tld
index f1446c8e..cafaa09e 100644
--- a/tiles-jsp/src/main/resources/META-INF/tld/tiles-jsp.tld
+++ b/tiles-jsp/src/main/resources/META-INF/tld/tiles-jsp.tld
@@ -77,6 +77,30 @@
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
+ <attribute>
+ <description>
+ <![CDATA[
+ <p>The type of the template attribute.</p>
+ ]]>
+ </description>
+ <name>templateType</name>
+ <required>false</required>
+ <rtexprvalue>true</rtexprvalue>
+ <type>java.lang.String</type>
+ </attribute>
+ <attribute>
+ <description>
+ <![CDATA[
+ <p>The expression to evaluate to get the value of the template.
+ </p>
+ <p>If used together with <code>template</code>, this attribute will be ignored.</p>
+ ]]>
+ </description>
+ <name>templateExpression</name>
+ <required>false</required>
+ <rtexprvalue>false</rtexprvalue>
+ <type>java.lang.String</type>
+ </attribute>
<attribute>
<description>
<![CDATA[
@@ -178,6 +202,30 @@
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
+ <attribute>
+ <description>
+ <![CDATA[
+ <p>The type of the template attribute.</p>
+ ]]>
+ </description>
+ <name>templateType</name>
+ <required>false</required>
+ <rtexprvalue>true</rtexprvalue>
+ <type>java.lang.String</type>
+ </attribute>
+ <attribute>
+ <description>
+ <![CDATA[
+ <p>The expression to evaluate to get the value of the template.
+ </p>
+ <p>If used together with <code>template</code>, this attribute will be ignored.</p>
+ ]]>
+ </description>
+ <name>templateExpression</name>
+ <required>false</required>
+ <rtexprvalue>false</rtexprvalue>
+ <type>java.lang.String</type>
+ </attribute>
<attribute>
<description>
<![CDATA[
@@ -478,6 +526,17 @@
<rtexprvalue>true</rtexprvalue>
<type>java.lang.Object</type>
</attribute>
+ <attribute>
+ <description>
+ <![CDATA[
+ <p>The expression to calculate the value from. Use this parameter, or value, or body.</p>
+ ]]>
+ </description>
+ <name>expression</name>
+ <required>false</required>
+ <rtexprvalue>false</rtexprvalue>
+ <type>java.lang.String</type>
+ </attribute>
<attribute>
<description>
<![CDATA[
@@ -601,6 +660,17 @@
<rtexprvalue>true</rtexprvalue>
<type>java.lang.Object</type>
</attribute>
+ <attribute>
+ <description>
+ <![CDATA[
+ <p>The expression to calculate the value from. Use this parameter, or value, or body.</p>
+ ]]>
+ </description>
+ <name>expression</name>
+ <required>false</required>
+ <rtexprvalue>false</rtexprvalue>
+ <type>java.lang.String</type>
+ </attribute>
<attribute>
<description>
<![CDATA[
| 0 | 4 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
7bfb3b5b56e30b157cfb750657de104055fe6da3
|
eval_js: print file where the error occured
|
commit 7bfb3b5b56e30b157cfb750657de104055fe6da3
Author: Simon Lipp <[email protected]>
Date: Sun Feb 14 16:23:31 2010 +0100
eval_js: print file where the error occured
diff --git a/src/uzbl-core.c b/src/uzbl-core.c
index 2b473800..ebd8ef83 100644
--- a/src/uzbl-core.c
+++ b/src/uzbl-core.c
@@ -321,7 +321,7 @@ expand(const char *s, guint recurse) {
/* JS from string */
else {
mycmd = expand(ret, 2);
- eval_js(uzbl.gui.web_view, mycmd, js_ret);
+ eval_js(uzbl.gui.web_view, mycmd, js_ret, "(command)");
g_free(mycmd);
}
@@ -1047,11 +1047,11 @@ js_init() {
void
-eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
+eval_js(WebKitWebView * web_view, gchar *script, GString *result, const char *file) {
WebKitWebFrame *frame;
JSGlobalContextRef context;
JSObjectRef globalobject;
-
+ JSStringRef js_file;
JSStringRef js_script;
JSValueRef js_result;
JSValueRef js_exc = NULL;
@@ -1066,7 +1066,8 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
/* evaluate the script and get return value*/
js_script = JSStringCreateWithUTF8CString(script);
- js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, &js_exc);
+ js_file = JSStringCreateWithUTF8CString(file);
+ js_result = JSEvaluateScript(context, js_script, globalobject, js_file, 0, &js_exc);
if (js_result && !JSValueIsUndefined(context, js_result)) {
js_result_string = JSValueToStringCopy(context, js_result, NULL);
js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string);
@@ -1086,6 +1087,18 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
printf("Exception occured while executing script:\n");
+ /* Print file */
+ prop = JSStringCreateWithUTF8CString("sourceURL");
+ val = JSValueToStringCopy(context, JSObjectGetProperty(context, exc, prop, NULL), NULL);
+ size = JSStringGetMaximumUTF8CStringSize(val);
+ if(size) {
+ char cstr[size];
+ JSStringGetUTF8CString(val, cstr, size);
+ printf("At %s", cstr);
+ }
+ JSStringRelease(prop);
+ JSStringRelease(val);
+
/* Print line */
prop = JSStringCreateWithUTF8CString("line");
val = JSValueToStringCopy(context, JSObjectGetProperty(context, exc, prop, NULL), NULL);
@@ -1093,7 +1106,7 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
if(size) {
char cstr[size];
JSStringGetUTF8CString(val, cstr, size);
- printf("At line %s: ", cstr);
+ printf(":%s: ", cstr);
}
JSStringRelease(prop);
JSStringRelease(val);
@@ -1111,12 +1124,13 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
/* cleanup */
JSStringRelease(js_script);
+ JSStringRelease(js_file);
}
void
run_js (WebKitWebView * web_view, GArray *argv, GString *result) {
if (argv_idx(argv, 0))
- eval_js(web_view, argv_idx(argv, 0), result);
+ eval_js(web_view, argv_idx(argv, 0), result, "(command)");
}
void
@@ -1149,7 +1163,7 @@ run_external_js (WebKitWebView * web_view, GArray *argv, GString *result) {
g_free (js);
js = newjs;
- eval_js (web_view, js, result);
+ eval_js (web_view, js, result, path);
g_free (js);
g_array_free (lines, TRUE);
g_free(path);
@@ -2551,7 +2565,7 @@ load_uri_imp(gchar *uri) {
}
if (g_strstr_len (uri, 11, "javascript:") != NULL) {
- eval_js(uzbl.gui.web_view, uri, NULL);
+ eval_js(uzbl.gui.web_view, uri, NULL, "javascript:");
return;
}
newuri = g_string_new (uri);
diff --git a/src/uzbl-core.h b/src/uzbl-core.h
index e05fcdb9..23072e42 100644
--- a/src/uzbl-core.h
+++ b/src/uzbl-core.h
@@ -390,7 +390,7 @@ void
run_external_js (WebKitWebView * web_view, GArray *argv, GString *result);
void
-eval_js(WebKitWebView * web_view, gchar *script, GString *result);
+eval_js(WebKitWebView * web_view, gchar *script, GString *result, const gchar *script_file);
void
handle_authentication (SoupSession *session,
| 0 | 4 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
94fff950c6c2d388591233aaa08b5471607f001f
|
merge in Duclares stuff
|
commit 94fff950c6c2d388591233aaa08b5471607f001f (from 64a4f8d02c1e6900b8b46a7b3fd5bd5232e3b685)
Merge: 64a4f8d0 57665dc0
Author: Dieter Plaetinck <[email protected]>
Date: Sat May 16 16:24:59 2009 +0200
merge in Duclares stuff
diff --git a/uzbl.c b/uzbl.c
index 3e767de7..b2b996bc 100644
--- a/uzbl.c
+++ b/uzbl.c
@@ -107,7 +107,7 @@ const struct {
{ "SUPER", GDK_SUPER_MASK }, // super (since 2.10)
{ "HYPER", GDK_HYPER_MASK }, // hyper (since 2.10)
{ "META", GDK_META_MASK }, // meta (since 2.10)
- { NULL, NULL }
+ { NULL, 0 }
};
/* construct a hash from the var_name_to_ptr array for quick access */
@@ -224,7 +224,7 @@ download_cb (WebKitWebView *web_view, GObject *download, gpointer user_data) {
if (uzbl.behave.download_handler) {
const gchar* uri = webkit_download_get_uri ((WebKitDownload*)download);
printf("Download -> %s\n",uri);
- run_command_async(uzbl.behave.download_handler, uri);
+ run_command(uzbl.behave.download_handler, uri, FALSE, NULL);
}
return (FALSE);
}
@@ -326,7 +326,7 @@ load_finish_cb (WebKitWebView* page, WebKitWebFrame* frame, gpointer data) {
(void) frame;
(void) data;
if (uzbl.behave.load_finish_handler) {
- run_command_async(uzbl.behave.load_finish_handler, NULL);
+ run_command(uzbl.behave.load_finish_handler, NULL, FALSE, NULL);
}
}
@@ -362,7 +362,7 @@ log_history_cb () {
strftime (date, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
GString* args = g_string_new ("");
g_string_printf (args, "'%s'", date);
- run_command_async(uzbl.behave.history_handler, args->str);
+ run_command(uzbl.behave.history_handler, args->str, FALSE, NULL);
g_string_free (args, TRUE);
}
}
@@ -711,35 +711,21 @@ expand_template(const char *template) {
// make sure to put '' around args, so that if there is whitespace we can still keep arguments together.
static gboolean
-run_command_async(const char *command, const char *args) {
+run_command (const char *command, const char *args, const gboolean sync, char **stdout) {
//command <uzbl conf> <uzbl pid> <uzbl win id> <uzbl fifo file> <uzbl socket file> [args]
GString* to_execute = g_string_new ("");
gboolean result;
g_string_printf (to_execute, "%s '%s' '%i' '%i' '%s' '%s'",
- command, uzbl.state.config_file, (int) getpid() ,
- (int) uzbl.xwin, uzbl.comm.fifo_path, uzbl.comm.socket_path);
+ command, (uzbl.state.config_file ? uzbl.state.config_file : "(null)"),
+ (int) getpid(), (int) uzbl.xwin, uzbl.comm.fifo_path,
+ uzbl.comm.socket_path);
g_string_append_printf (to_execute, " '%s' '%s'",
uzbl.state.uri, uzbl.gui.main_title);
- if(args) {
- g_string_append_printf (to_execute, " %s", args);
- }
- result = g_spawn_command_line_async (to_execute->str, NULL);
- printf("Called %s. Result: %s\n", to_execute->str, (result ? "TRUE" : "FALSE" ));
- g_string_free (to_execute, TRUE);
- return result;
-}
+ if(args) g_string_append_printf (to_execute, " %s", args);
-static gboolean
-run_command_sync(const char *command, const char *args, char **stdout) {
- //command <uzbl conf> <uzbl pid> <uzbl win id> <uzbl fifo file> <uzbl socket file> [args]
- GString* to_execute = g_string_new ("");
- gboolean result;
- g_string_printf (to_execute, "%s '%s' '%i' '%i' '%s' '%s'", command, uzbl.state.config_file, (int) getpid() , (int) uzbl.xwin, uzbl.comm.fifo_path, uzbl.comm.socket_path);
- g_string_append_printf (to_execute, " '%s' '%s'", uzbl.state.uri, uzbl.gui.main_title);
- if(args) {
- g_string_append_printf (to_execute, " %s", args);
- }
- result = g_spawn_command_line_sync (to_execute->str, stdout, NULL, NULL, NULL);
+ if (sync) {
+ result = g_spawn_command_line_sync (to_execute->str, stdout, NULL, NULL, NULL);
+ } else result = g_spawn_command_line_async (to_execute->str, NULL);
printf("Called %s. Result: %s\n", to_execute->str, (result ? "TRUE" : "FALSE" ));
g_string_free (to_execute, TRUE);
return result;
@@ -748,7 +734,7 @@ run_command_sync(const char *command, const char *args, char **stdout) {
static void
spawn(WebKitWebView *web_view, const char *param) {
(void)web_view;
- run_command_async(param, NULL);
+ run_command(param, NULL, FALSE, NULL);
}
static void
@@ -772,7 +758,9 @@ setup_regex() {
G_REGEX_OPTIMIZE, 0, &err);
uzbl.comm.bind_regex = g_regex_new("^[Bb][a-zA-Z]*\\s+?(.*[^ ])\\s*?=\\s*([a-z][^\\n].+)$",
G_REGEX_UNGREEDY|G_REGEX_OPTIMIZE, 0, &err);
- uzbl.comm.cmd_regex = g_regex_new("^[Cc][a-zA-Z]*\\s+([^ \\n]+)\\s*([^\\n]*)?$",
+ uzbl.comm.act_regex = g_regex_new("^[Aa][a-zA-Z]*\\s+([^ \\n]+)\\s*([^\\n]*)?$",
+ G_REGEX_OPTIMIZE, 0, &err);
+ uzbl.comm.keycmd_regex = g_regex_new("^[Kk][a-zA-Z]*\\s+([^\\n]+)$",
G_REGEX_OPTIMIZE, 0, &err);
}
@@ -965,9 +953,9 @@ parse_cmd_line(const char *ctl_line) {
else
printf("Error in command: %s\n", tokens[0]);
}
- /* CMD command */
- else if(ctl_line[0] == 'C' || ctl_line[0] == 'c') {
- tokens = g_regex_split(uzbl.comm.cmd_regex, ctl_line, 0);
+ /* ACT command */
+ else if(ctl_line[0] == 'A' || ctl_line[0] == 'a') {
+ tokens = g_regex_split(uzbl.comm.act_regex, ctl_line, 0);
if(tokens[0][0] == 0) {
parse_command(tokens[1], tokens[2]);
g_strfreev(tokens);
@@ -975,6 +963,18 @@ parse_cmd_line(const char *ctl_line) {
else
printf("Error in command: %s\n", tokens[0]);
}
+ /* KEYCMD command */
+ else if(ctl_line[0] == 'K' || ctl_line[0] == 'k') {
+ tokens = g_regex_split(uzbl.comm.keycmd_regex, ctl_line, 0);
+ if(tokens[0][0] == 0) {
+ /* should incremental commands want each individual "keystroke"
+ sent in a loop or the whole string in one go like now? */
+ g_string_assign(uzbl.state.keycmd, tokens[1]);
+ run_keycmd(FALSE);
+ update_title();
+ g_strfreev(tokens);
+ }
+ }
/* Comments */
else if( (ctl_line[0] == '#')
|| (ctl_line[0] == ' ')
@@ -1265,7 +1265,6 @@ key_press_cb (WebKitWebView* page, GdkEventKey* event)
//TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.
(void) page;
- Action *action;
if (event->type != GDK_KEY_PRESS || event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down
|| event->keyval == GDK_Up || event->keyval == GDK_Down || event->keyval == GDK_Left || event->keyval == GDK_Right || event->keyval == GDK_Shift_L || event->keyval == GDK_Shift_R)
@@ -1296,7 +1295,7 @@ key_press_cb (WebKitWebView* page, GdkEventKey* event)
str = gtk_clipboard_wait_for_text (gtk_clipboard_get (GDK_SELECTION_CLIPBOARD));
}
if (str) {
- g_string_append_printf (uzbl.state.keycmd, "%s", str);
+ g_string_append (uzbl.state.keycmd, str);
update_title ();
free (str);
}
@@ -1311,13 +1310,25 @@ key_press_cb (WebKitWebView* page, GdkEventKey* event)
gboolean key_ret = FALSE;
if ((event->keyval == GDK_Return) || (event->keyval == GDK_KP_Enter))
key_ret = TRUE;
-
if (!key_ret) g_string_append(uzbl.state.keycmd, event->string);
+
+ run_keycmd(key_ret);
+ update_title();
+ if (key_ret) return (!uzbl.behave.insert_mode);
+ return TRUE;
+}
+
+static void
+run_keycmd(const gboolean key_ret) {
+ /* run the keycmd immediately if it isn't incremental and doesn't take args */
+ Action *action;
if ((action = g_hash_table_lookup(uzbl.bindings, uzbl.state.keycmd->str))) {
g_string_truncate(uzbl.state.keycmd, 0);
parse_command(action->name, action->param);
+ return;
}
+ /* try if it's an incremental keycmd or one that takes args, and run it */
GString* short_keys = g_string_new ("");
GString* short_keys_inc = g_string_new ("");
unsigned int i;
@@ -1329,12 +1340,12 @@ key_press_cb (WebKitWebView* page, GdkEventKey* event)
gboolean exec_now = FALSE;
if ((action = g_hash_table_lookup(uzbl.bindings, short_keys->str))) {
- if (key_ret) exec_now = TRUE; // run normal cmds only if return was pressed
+ if (key_ret) exec_now = TRUE; /* run normal cmds only if return was pressed */
} else if ((action = g_hash_table_lookup(uzbl.bindings, short_keys_inc->str))) {
- if (key_ret) { // just quit the incremental command on return
+ if (key_ret) { /* just quit the incremental command on return */
g_string_truncate(uzbl.state.keycmd, 0);
break;
- } else exec_now = TRUE; // always exec inc. commands on keys other than return
+ } else exec_now = TRUE; /* always exec incr. commands on keys other than return */
}
if (exec_now) {
@@ -1359,9 +1370,6 @@ key_press_cb (WebKitWebView* page, GdkEventKey* event)
}
g_string_free (short_keys, TRUE);
g_string_free (short_keys_inc, TRUE);
- update_title();
- if (key_ret) return (!uzbl.behave.insert_mode);
- return TRUE;
}
static GtkWidget*
@@ -1530,7 +1538,7 @@ static void handle_cookies (SoupSession *session, SoupMessage *msg, gpointer use
GString* args = g_string_new ("");
SoupURI * soup_uri = soup_message_get_uri(msg);
g_string_printf (args, "GET %s %s", soup_uri->host, soup_uri->path);
- run_command_sync(uzbl.behave.cookie_handler, args->str, &stdout);
+ run_command(uzbl.behave.cookie_handler, args->str, TRUE, &stdout);
if(stdout) {
soup_message_headers_replace (msg->request_headers, "Cookie", stdout);
}
@@ -1547,7 +1555,7 @@ save_cookies (SoupMessage *msg, gpointer user_data){
GString* args = g_string_new ("");
SoupURI * soup_uri = soup_message_get_uri(msg);
g_string_printf (args, "PUT %s %s \"%s\"", soup_uri->host, soup_uri->path, cookie);
- run_command_async(uzbl.behave.cookie_handler, args->str);
+ run_command(uzbl.behave.cookie_handler, args->str, FALSE, NULL);
g_string_free(args, TRUE);
free(cookie);
}
diff --git a/uzbl.h b/uzbl.h
index e23fa692..48b985ab 100644
--- a/uzbl.h
+++ b/uzbl.h
@@ -86,7 +86,8 @@ typedef struct {
GHashTable *proto_var;
/* command parsing regexes */
GRegex *set_regex;
- GRegex *cmd_regex;
+ GRegex *act_regex;
+ GRegex *keycmd_regex;
GRegex *get_regex;
GRegex *bind_regex;
} Communication;
@@ -238,10 +239,7 @@ static void
close_uzbl (WebKitWebView *page, const char *param);
static gboolean
-run_command_async(const char *command, const char *args);
-
-static gboolean
-run_command_sync(const char *command, const char *args, char **stdout);
+run_command(const char *command, const char *args, const gboolean sync, char **stdout);
static void
spawn(WebKitWebView *web_view, const char *param);
@@ -288,6 +286,9 @@ update_title (void);
static gboolean
key_press_cb (WebKitWebView* page, GdkEventKey* event);
+static void
+run_keycmd(const gboolean key_ret);
+
static GtkWidget*
create_browser ();
commit 94fff950c6c2d388591233aaa08b5471607f001f (from 57665dc053d0b13b1a448628d586aa200c649c67)
Merge: 64a4f8d0 57665dc0
Author: Dieter Plaetinck <[email protected]>
Date: Sat May 16 16:24:59 2009 +0200
merge in Duclares stuff
diff --git a/Makefile b/Makefile
index 2d6b8c9d..ebd6ab19 100644
--- a/Makefile
+++ b/Makefile
@@ -21,9 +21,10 @@ install:
install -d $(DESTDIR)/usr/share/uzbl/examples
install -D -m755 uzbl $(DESTDIR)/usr/bin/uzbl
install -D -m755 uzblctrl $(DESTDIR)/usr/bin/uzblctrl
+ cp -ax docs $(DESTDIR)/usr/share/uzbl/
cp -ax examples $(DESTDIR)/usr/share/uzbl/
- install -D -m644 CHECKLIST $(DESTDIR)/usr/share/uzbl/docs
- install -D -m644 README $(DESTDIR)/usr/share/uzbl/docs
+ install -D -m644 AUTHORS $(DESTDIR)/usr/share/uzbl/docs
+ install -D -m644 README $(DESTDIR)/usr/share/uzbl/docs
uninstall:
rm -rf $(DESTDIR)/usr/bin/uzbl
diff --git a/README b/README
index 60ed0898..61188798 100644
--- a/README
+++ b/README
@@ -1,104 +1,90 @@
THIS PROJECT IS NOT FOR:
- people want a browser that does everything
- people who want a browser with things like a built-in bookmark manager, address bar, forward/back buttons, ...
-
+- people who expect something that works by default. You'll need to read configs and write/edit scripts
TO NEW PEOPLE:
- - please read the README in /usr/share/uzbl/docs
+ - please read the documentation in /usr/share/uzbl/docs
- invoke uzbl --help
- to get you started: uzbl --uri 'http://www.archlinux.org' --config /usr/share/uzbl/examples/configs/sampleconfig
- study the sample config, have a look at all the bindings, and note how you can call the scripts to load new url from history and the bookmarks file
- note that there is no url bar. all url editing is supposed to happen _outside_ of uzbl.
- for now, you can use the load_from_* dmenu based scripts to pick a url or type a new one (we should have a dmenu-like that functions as a better editor) or write commands into the fifo (see /usr/share/uzbl/docs/CHECKLIST)
- - If you have questions, you are likely to find answers in the FAQ
-
-CURRENT STATE:
- alpha / prototype
+ for now, you can use the load_from_* dmenu based scripts to pick a url or type a new one or write commands into the fifo (see /usr/share/uzbl/docs/CHECKLIST)
+ - If you have questions, you are likely to find answers in the FAQ or in the other documentation.
-- Uzbl.
+INTRODUCTION
In my opinion, any program can only be really useful if it complies to the unix philosophy.
- Web browsers are frequent violators of this principle. Time to change that!
-
-Right now uzbl is in a very early state but here are some ideas I would like to (not) implement
-
-- each instance of uzbl renders 1 page (eg it's a small wrapper around webkit), no tabbing, tab previews, or speed dial things. we have window managers for that.
- -> well actually, there is lots of dicussion about this, i'll probably implement a basic form of tabbing.
-- simple ini config file ("profile") for keyboard, network,.. settings
-- implement some basic keyboard shortcuts for going up, down, refresh etc. preferably vim-like command style.
+ Web browsers are frequent violators of this principle.
+ -> They build in way too much things into the browser, dramatically decreasing the options to do things the way you want.
+ -> They store things in way too fancy formats (xml, rdf, sqlite, ... ) which are hard to store under version control, reuse in other scripts, ...
+
+Time to change that!
+
+ Here are the general ideas:
+- each instance of uzbl renders 1 page (eg it's a small wrapper around webkit), no tabbing, tab previews, or speed dial things.
+ For "multiple instances management" use your window managers, or scripts.
+ This way you can get something much more useful than tabbing (see rationale in docs)
+- very simple, plaintext , changeable at runtime configuration
+- various interfaces for (programmatic) interaction with uzbl (see below)
+- customizable keyboard shortcuts in vim or emacs style (whatever user wants)
+- "outsource" logic that is not browsing to external scripts under the users control:
+ - managing bookmarks
+ - loading a url from bookmarks, history,.. Editing the curent url
+ - control cookies
+ - handling of downloads, history logging, etc.
+ - management of cache.
+ - password management
+ Leverage the power of utilities such as grep, awk, dmenu, zenity, wget, gnupg (password file) etc.
- listen to signals and do useful stuff when triggered.
-- open up a socket file/fifo/.. so we can easily control each instance by writing things like 'uri <foo>' to /tmp/uzbl-windowid
-- MAYBE (if needed): 1 control application called uzblctrl or something. use this to modify the behavior of a uzbl instance (change url, refresh). use xdotool to get the window with focus. eg uzblctrl -win <id> -url <http://>.
- use xbindkeys to bind keys to call uzblctrl.
-- no bookmark management builtin. make your own solution. for pulling a bookmark a plaintxt-based program using dmenu would work great here. combine with uzbltcrl and xbindkeys.
- uzblctrl should support an option to query the current page so you can script something to add to your bookmarks. use zenity or something to add tags.
-- history: log 'Y-m-d H:M:S <url>' entries to a plaintext file. you can then use dmenu or whatever to select an entry and pipe the output to uzbl's fifo.
-- no ad blocking built in (I think).
+- no ad blocking built in
alternatives:
- -> /etc/hosts (not very good cause you need root and it affects the whole system)-> uzblctrl would need to support an option to list all images on a page, so you can easily pick the links to ads to add them to your /etc/hosts. (dmenu can again be great here to automate this)
-> privoxy looks cool and perfectly demonstrates the unix philosphy.
-> same for http://bfilter.sourceforge.net
-- no download manager. allow user to pick wget/curl/a custom script/...
-- no build in command interpreters like ubiquity. uzbl should be accessible and you should use a shell or similar.
-- no "clear cookies/cache/..." menu items. rm ~/$XDG_{DATA,CACHE}_DIR/uzbl/{cache,cookies}/*
+ -> /etc/hosts (not very good cause you need root and it affects the whole system)-> uzblctrl would need to support an option to list all images on a page, so you can easily pick the links to ads to add them to your /etc/hosts.
- vimperator/konqueror-like hyperlink following.
- password management. maybe an encrypted store that unlocks with an ssh key?
-- use the XDG basedir spec for separation of config, data and cache. and state will be a subdir in the config dir (not part of the spec yet) too.
-
-WIDGET ROADMAP:
-* statusbar? (the bar you see in pretty much every gtk program at the bottom. eg firefox)
- consumes too much space (if always visible) for the little it is used. (+ you can put only 1 message in it at a time!)
- -> option 1: no statusbar at all. when hovering over a link (or pressing key to preview the url without changing page) -> show url in tooltip on page.
- -> option 2: toggle visibility of statusbar on/off when hovering over a link. since it's at the bottom I don't think it will disturb too much.
-* viewing progress/state of pageload? most programs use statusbar for this.
- -> option 1: titlebar can show a percentage when it's loading a new page.
- -> option 2: toggle a statusbar everytime we start loading a new page.
-* uri bar -> yes, even though we can write stuff to the fifo, it can still be convenient to change the url manually and stuff, so a widget in uzbl itself is good.
-* tabs -> yes. you don't have to use them, but you can.
-* back/forward/.. buttons? -> no: use keyboard shortcuts.
-* searching in a page? not sure.. maybe we can abuse the statusbar for that too.
- eg toggle it on when the user wants to search for something and then do searching in some vim-like fashion.
- we don't need a gtk text entry widget, just a feedback display of what the current command is.
-* scrollbar? no: use keyboard shortcuts. we should however have some info about the page length and where we are.
- -> option 1: put a percentage in the window title
- -> option 2: everytime you hit a key to change position, temporarily make a statusbar visible and put the percentage in the statusbar.
- what will we do with pages who are too wide? horizontal scrolling?
-all of the above goes in 1 bar at the top of the program. there should be a key to toggle visibility of it and one to toggle visibilety + focus on the entrybar at once.
-
-input welcome!
-
-
-HISTORY FILE SIZE/PERFORMANCE
-each new pageload -> fopen(history_file, "a"), fwrite one line, fclose.
-I use utf8, so unless you use characters that are "special" (chinese etc)
-each character takes 1 byte.
-So, assume each entry is about 80 chars, you visit 100 pages per day (?), and you wonder when your history file will be 50MB big:
-(50 * 1000 * 1000 ) / ( 80 * 100 ) = 6250 days or 17 years.
-There is code to run a benchmark in the 'extra' dir. For results & interpretation, see http://dieter.plaetinck.be/poor_mans_dmenu_benchmark
-
-CONTROL:
-- FIFO opened in /tmp/uzbl_pid
-- See config file for commands
-- Press ESC/i to toggle command/insert mode
-
-NOTES:
-- My c skills are very rusty, it will take me a while to get back up to speed
-- For more thoughts & ideas see http://bbs.archlinux.org/viewtopic.php?id=67463
-
-REPO's:
-- http://github.com/Dieterbe/uzbl
- master -> uzbl stable branch
- experimental -> bleeding edge stuff that may break. after QA codes gets merged into master
-- various contributors also have their clones on github (http://github.com/dusanx, http://github.com/Barrucadu/uzbl, ...).
- They may be developing specific features, which get merged into Dieters experimental branch
+- no messing in the users $HOME: no writing of anything unless the users asks for it. We recommend using XDG basedir spec for separation of config, data and cache. and state should be a subdir in the config dir (not part of the spec yet) too.
+
+
+CONFIGURATION / CONTROL:
+The general idea is that uzbl by default is very bare bones. you can send it commands to update settings and perform actions, through various interfaces.
+For examples, please see the sample config(s).
+There are several interfaces to interact with uzbl:
+- uzbl --config <filename>: <filename> will be read line by line, and the commands in it will be executed. useful to configure uzbl at startup. If you have a file in $XDG\_CONFIG\_HOME/uzbl/config (this expands to ~/.config/uzbl/config on most systems) it will be automatically recognized
+- stdin: you can also write commands into stdin
+- interactive: you can enter commands (and bind them to shortcuts, even at runtime)
+ By default, the behaviour is modal (vi style):
+ command mode: every keystroke is interpreted to run commands
+ insert mode: keystrokes are not interpreted so you can enter text into html forms
+ Press ESC/i to toggle command/insert mode
+ But if you don't like modal interfaces, you can set always_insert_mode and configure a modkey to execute the commands. (emacs style).
+- FIFO & socket file: if enabled by setting their paths through one of the above means, you can have socket and fifo files available, which are very useful to programatically send commands to (coming from scripts etc)
+ The advantage of the fifo is you can write plaintxt commands to it, but it's half duplex only (uzbl cannot send a response to you).
+ The socket is full duplex but you need a socket-compatible wrapper such as netcat to work with it, or uzblctrl of course, an utitly we include with uzbl made especially for writing commnands to the socket (and at some point, it will be able to tell you the response too)
+
+COMMAND SYNTAX
+TODO
+
+VARIABLE REPLACEMENT
+Some of the variables are interpreted.
+- title bar: variable replacement (not yet actually)
+- user agent: variable replacement
+- statusbar: variable replacement + pango markup
+
+This means you can customize how these things appear, what's shown in them and for the statusbar you can even play with the layout.
+For examples, see the example config.
+For a list of possible variables, see uzbl.h
+For more info about the markup format see http://library.gnome.org/devel/pango/stable/PangoMarkupFormat.html
EXTERNAL SCRIPTS
You can use external scripts with uzbl the following ways:
1) let uzbl call them. these scripts are called handlers in the uzbl config. used for handling logging history, handling a new download,..
2) call them yourself from inside uzbl. you can bind keys for this. examples: add new bookmark, load new url,..
-3) if you want to call scripts that have no option, you can trigger them with something like xbindkeys. example: ? (we try to keep all possibilities inside option 1/2)
+3) You could also use xbindkeys or your WM config to trigger scripts if uzbl does not have focus
+Have a look at the sample configs and scripts!
Scripts that are called by uzbl are passed the following arguments:
$1 uzbl-config-file
@@ -123,21 +109,11 @@ The script specific arguments are this:
$10 request address path
$11 cookie (only with PUT requests)
-KNOWN BUGS
+
+BUGS
+known bugs:
- Segfaults when using zoom commands (happens when max zoom already reached?).
-- Something in the FIFO code causes CPU usage to jump.
Report new issues @ uzbl.org/bugs
-VALGRIND PROFILING
-add this to Makefile header: CFLAGS=-g
-recompile
-valgrind --tool=callgrind ./uzbl ....
-kcachegrind callgrind.out.foo
-
-CONFIG FILE
-** Variable replacement and markup format
-See http://library.gnome.org/devel/pango/stable/PangoMarkupFormat.html for
-what you can do, markup wise.
-TODO: document possible variables, and what you can do with useragent/title/statusbar
diff --git a/CHECKLIST b/docs/CHECKLIST
similarity index 97%
rename from CHECKLIST
rename to docs/CHECKLIST
index b2c7065f..6c4a4f75 100644
--- a/CHECKLIST
+++ b/docs/CHECKLIST
@@ -1,3 +1,6 @@
+THIS FILE IS DEPRECATED.
+TODO: make sure that all this gets merged into the documentation
+
This file contains all things that are/should be working.
When you have been working on something, use this list to verify that you did not cause any regressions (things that worked before, but got broken).
Also, when you finish a new feature, add it to this list so that everyone knows about it, can play with it, and can test it.
diff --git a/docs/CONTRIBUTING b/docs/CONTRIBUTING
new file mode 100644
index 00000000..8aba17e7
--- /dev/null
+++ b/docs/CONTRIBUTING
@@ -0,0 +1,24 @@
+Users
+
+Right now, the best way to contribute to Uzbl is to use it, hang around in
+our IRC channel, and tell us when things break. If you're feeling more
+adventerous, you can use one of the development branches and give bug
+reports and suggestions straight to the developer in charge of that, so the
+same problems don't occur when they get merged into the master branch. Have
+a look at the CHECKLIST file to see all the stuff that is supposed to work.
+Play around with the configs and scripts and see if you can improve things.
+
+Developers
+
+If you don't feel like just sending bug reports, by all means dive into the
+code and clone the code to start hacking. (github makes this really easy
+with their "fork" concept). But it's usually a good thing to tell us first
+what you want to do, to avoid unneeded or duplicate work.
+
+
+
+VALGRIND PROFILING
+add this to Makefile header: CFLAGS=-g
+recompile
+valgrind --tool=callgrind ./uzbl ....
+kcachegrind callgrind.out.foo
diff --git a/FAQ b/docs/FAQ
similarity index 100%
rename from FAQ
rename to docs/FAQ
diff --git a/INSTALL b/docs/INSTALL
similarity index 77%
rename from INSTALL
rename to docs/INSTALL
index c228f5c0..270c3430 100644
--- a/INSTALL
+++ b/docs/INSTALL
@@ -9,7 +9,7 @@ branch you want.
From source
-----------
$ git clone git://github.com/Dieterbe/uzbl.git
- [ $ git checkout master/experimental ] # master == fairly stable. experimental is more bleeding edge
+ [ $ git checkout master/experimental ] # optional. see below
$ cd uzbl
$ make
$ sudo make install
@@ -30,7 +30,7 @@ Optional/Recommended
The following tools are quite useful, and some of them are used in the
sample scripts:
-* dmenu
+* dmenu (with vertical patch
* zenity
* bash
@@ -50,4 +50,14 @@ You're free to store your personal stuff where you want, but we think the [XDG b
is very useful for keeping a clean home directory, so we recommend:
* $XDG\_CONFIG\_HOME/uzbl/config* (~/.config/uzbl/config on most systems): config file
-* $XDG\_DATA\_HOME/uzbl (~/.local/share/uzbl on most systems): bookmarks file, history file. and "scripts" directory with scripts
\ No newline at end of file
+* $XDG\_DATA\_HOME/uzbl (~/.local/share/uzbl on most systems): bookmarks file, history file. and "scripts" directory with scripts
+
+Git Repo's & branches
+--------------------
+* Main official repo:
+ http://github.com/Dieterbe/uzbl
+- master -> uzbl stable branch
+- experimental -> bleeding edge stuff that may break. after QA Dieter merges into his master
+
+* Most contributors & developers also have their clones on github (http://github.com/dusanx, http://github.com/Barrucadu/uzbl, ...).
+ They may be developing specific features, which get merged into Dieters experimental branch
diff --git a/TODO b/docs/TODO
similarity index 92%
rename from TODO
rename to docs/TODO
index 6e4004d3..39ea8494 100644
--- a/TODO
+++ b/docs/TODO
@@ -49,13 +49,15 @@
* configure script
* a variable that holds the page state: loading, pending, seen. this can be shown in titlebar/statusbar and used for multiple instances management
* proxy_url is not a good var name. it's not a url.
-
-
+* regex style page searching? so you can do 'or' and 'and' things. flags like case sensitive etc.
+* can we export uri/state/tag/.. as xorg window "properties" or "attributes" or do we need to put them in titlebar and parse that?
* config: check in the default place (XDG_CONFIG_HOME/..) for a config file, and if needed, do file reading (interpret line by line). not ini-based.
* readd the --config flag to allow entering the same commands either through the file/stdin/fifo/socket
* check for real command name, not just the first letter.
-
+* let users attach handlers to the most common events/signals in uzbl.
+* write little script to open new urls with the urxvt url thing +document.
+* add Rob/anydots trees on website
SOMEDAY:
check if we can make the settings loading less hard coded. eg( keep a list of all settings, and for each one, try to load it)
diff --git a/docs/multiple-instances-management b/docs/multiple-instances-management
new file mode 100644
index 00000000..da55002d
--- /dev/null
+++ b/docs/multiple-instances-management
@@ -0,0 +1,41 @@
+"multiple instance management" or: how to manage multiple open pages/instances of uzbl.
+
+The way we do MIM in uzbl will be better then what you can do with tabs in other programs.
+Tabs are just one specific gui implementation which aids in some aspects of "multiple instances management" but not all.
+We can get the same and even better features functionality wise, without limiting ourselves to the particular implementation that tabs are.
+We use a "use-case"/tasks driven approach, unlike tabs which is a "lets do this, and then see how we can use it" approach.
+
+The approach we are implementing in uzbl is like this:
+- 1 page per instance.
+- ability to spawn new windows ("open in new window"), keybinds for having the new window focused or not.
+- each instance keeps track of it's page state (loading, loaded but not seen, loaded and seen)
+- ability to "tag" instances (inherited when forking new instances) (eg tag "work" or tag "personal") so you can keep related instances together.
+ The tag can be made visible in the title / statusbar.
+- allow user to make keybinds to focus the next/previous:
+ - window
+ - unseen/seen window
+ - unseen/seen window from the same tag
+ - unseen/seen window from tag <foo> (dmenu)
+- have a program that lists all instances (optionally filtered, or categorized by tag, state, ...) and allow user to select one from it using smart matching techniques which require a minimal amount of keystrokes. (dmenu with vertical patch is great for this)
+
+Here's an overview what do tabs really do, whether we really need it, and if can improve it?
+
+
+* tabs keep multiple open pages together when moving the window other tag/workspace
+ -> in an ideal workspace, you assign windows to a tag/workspace and keep them there.
+ -> in practice, when I was still using Firefox, I noticed I moved my "group of bundled pages" (eg a FF window) sometimes, to aid in copy pasting between browser and another app, or doing something while watching/reading a webpage.
+ This means however I only really need that specific page, not the others. -> With the suggested approach, you can easily temporarily move one window.
+* tabs keep an oversight of which pages you have open
+ -> you should "know" more or less know which pages you have open. The gui is clutter. It should however be possible to show the list "on demand".
+ -> a horizontal list of tabs is also not very readable and lacks useful categorisation/grouping.
+ With the suggested approach we will have each url below each other, which is far more readable, and we can use additional text or color themes to denote the state/tag/...
+* tabs aid opening new pages in the background which you will open later and provide shortcuts to go to the previous/next tab.
+ -> our approach is more powerful.
+ -> With tab based browsers you can usually configure if you want new tabs to open "immediately after the current tab", or "at the end of the list". This is much less flexible/usable then what we are building.
+
+Conclusion
+---------
+I think our method is better then tabs. Bonus advantages:
+* single uzbl instances are simple to implement, no added clutter.
+* one crashing instance does not affect the rest
+* all this stuff is implemented outside of uzbl. You can even decide to not use it and you won't even know the feature was ever there. (though i guess most people will want this).
diff --git a/docs/performance b/docs/performance
new file mode 100644
index 00000000..0f9763ff
--- /dev/null
+++ b/docs/performance
@@ -0,0 +1,9 @@
+The usage of external scripts causes some slowdowns. (forking new processes, running interpreted scripts,...)
+It can be interesting to keep an eye on this, though I don't expect major problems.
+
+** History file size/performance
+each new pageload -> fopen(history_file, "a"), fwrite one line, fclose.
+I use utf8, so unless you use characters that are "special" (chinese etc) each character takes 1 byte.
+So, assume each entry is about 80 chars, you visit 100 pages per day (?), and you wonder when your history file will be 50MB big:
+(50 * 1000 * 1000 ) / ( 80 * 100 ) = 6250 days or 17 years.
+There is code to run a benchmark in the 'extra' dir. For results & interpretation, see http://dieter.plaetinck.be/poor_mans_dmenu_benchmark
diff --git a/docs/url-editing b/docs/url-editing
new file mode 100644
index 00000000..fae96c7a
--- /dev/null
+++ b/docs/url-editing
@@ -0,0 +1,7 @@
+* All url changing/editing happens outside of uzbl
+
+Use cases:
+* load url from history/bookmarks (dmenu-vertical is great for this)
+* edit current url or one from history/bookmarks: dmenu-vertical is relatively good for this, though it would be better if we had:
+- minimal editing helper key shortcuts (eg to go to beginning/end of input buffer)
+- copy/paste support
diff --git a/docs/widgets b/docs/widgets
new file mode 100644
index 00000000..dc7127a8
--- /dev/null
+++ b/docs/widgets
@@ -0,0 +1,33 @@
+
+* statusbar? (the bar you see in pretty much every gtk program at the
+* bottom. eg firefox)
+ consumes too much space (if always visible) for the little it is used. (+
+* you can put only 1 message in it at a time!)
+ -> option 1: no statusbar at all. when hovering over a link (or pressing
+ -> key to preview the url without changing page) -> show url in tooltip on
+ -> page.
+ -> option 2: toggle visibility of statusbar on/off when hovering over a
+ -> link. since it's at the bottom I don't think it will disturb too much.
+* viewing progress/state of pageload? most programs use statusbar for this.
+ -> option 1: titlebar can show a percentage when it's loading a new page.
+ -> option 2: toggle a statusbar everytime we start loading a new page.
+* uri bar -> yes, even though we can write stuff to the fifo, it can still
+* be convenient to change the url manually and stuff, so a widget in uzbl
+* itself is good.
+* tabs -> yes. you don't have to use them, but you can.
+* back/forward/.. buttons? -> no: use keyboard shortcuts.
+* searching in a page? not sure.. maybe we can abuse the statusbar for that
+* too.
+ eg toggle it on when the user wants to search for something and then do
+* searching in some vim-like fashion.
+ we don't need a gtk text entry widget, just a feedback display of what the
+* current command is.
+* scrollbar? no: use keyboard shortcuts. we should however have some info
+* about the page length and where we are.
+ -> option 1: put a percentage in the window title
+ -> option 2: everytime you hit a key to change position, temporarily make
+ -> a statusbar visible and put the percentage in the statusbar.
+ what will we do with pages who are too wide? horizontal scrolling?
+all of the above goes in 1 bar at the top of the program. there should be a
+key to toggle visibility of it and one to toggle visibilety + focus on the
+entrybar at once.
diff --git a/examples/configs/sampleconfig-dev b/examples/configs/sampleconfig-dev
index 38f12741..d196c920 100644
--- a/examples/configs/sampleconfig-dev
+++ b/examples/configs/sampleconfig-dev
@@ -8,9 +8,9 @@
# from insert mode by combining them with the modkey
# TODO: ability to attach misc things (spawn <foo>, script <bar>,.. to internal events)
-#set history_handler ./examples/scripts/history.sh
-#set download_handler ./examples/scripts/download.sh
-#set cookie_handler ./examples/scripts/cookies.sh
+set history_handler = ./examples/scripts/history.sh
+set download_handler = ./examples/scripts/download.sh
+set cookie_handler = ./examples/scripts/cookies.sh
@@ -19,7 +19,12 @@ set show_status = 1
# you can optionally use this setting to override the background color of the statusbar from your GTK theme.
set status_background = #303030
set status_format = <span font_family="monospace"><span background="khaki" foreground="black">MODE</span> [<span weight="bold" foreground="red">KEYCMD</span>] <span foreground="#606060"> LOAD_PROGRESSBAR </span><span foreground="#99FF66">URI</span> <span foreground="khaki">NAME</span> <span foreground="orange">MSG</span></span>
+set status_top = 0
+
set modkey = Mod1
+# reset to command mode when new page is loaded
+set reset_command_mode = 1
+# this var has precedence over reset_command_mode
set always_insert_mode = 0
# to start a local socks server, do : ssh -fND localhost:8118 localhost
#set proxy_url = http://127.0.0.1:8118
@@ -32,8 +37,7 @@ set always_insert_mode = 0
#set max_conns_host 0
set fifo_dir = /tmp
-#TODO socket dir
-#set status_top = 1
+set socket_dir = /tmp
# Key bindings
bind j = scroll_vert 20
@@ -60,8 +64,8 @@ bind gg _ = uri http://www.google.com/search?q=%s
bind i = insert_mode
#TODO: no 'toggle' command?
bind B = spawn ./examples/scripts/insert_bookmark.sh
-bind u = spawn ./examples/scripts/load_url_from_history.sh
-bind U = spawn ./examples/scripts/load_url_from_bookmarks.sh
+bind U = spawn ./examples/scripts/load_url_from_history.sh
+bind u = spawn ./examples/scripts/load_url_from_bookmarks.sh
bind ZZ = exit
bind S = script alert("hi");
# Keyboard based link following: work in progress! No C DOM bindings yet, no click() event for hyperlinks so no referrer set..Quite basic but does the job for now...
diff --git a/examples/scripts/cookies.sh b/examples/scripts/cookies.sh
index 9f6d2020..cd449dc8 100755
--- a/examples/scripts/cookies.sh
+++ b/examples/scripts/cookies.sh
@@ -5,7 +5,7 @@
# kb.mozillazine.org FALSE / FALSE 1146030396 wikiUserID 16993
# domain alow-read-other-subdomains path http-required expiration name value
# you probably want your cookies config file in your $XDG_CONFIG_HOME ( eg $HOME/.config/uzbl/cookies)
-
+# Note. in uzbl there is no strict definition on what a session is. it's YOUR job to clear cookies marked as end_session if you want to keep cookies only valid during a "session"
# MAYBE TODO: allow user to edit cookie before saving. this cannot be done with zenity :(
# TODO: different cookie paths per config (eg per group of uzbl instances)
@@ -19,6 +19,7 @@
# implement secure attribute.
# support blocking or not for 3rd parties
# http://kb.mozillazine.org/Cookies.txt
+# don't always append cookies, sometimes we need to overwrite
if [ -f /usr/share/uzbl/examples/configs/cookies ]
then
@@ -60,13 +61,13 @@ function parse_cookie () {
do
if [ "$first_pair" == 1 ]
then
- field_name=${i%%=*}
- field_value=${i#*=}
+ field_name=${pair%%=*}
+ field_value=${pair#*=}
first_pair=0
else
read -r pair <<< "$pair" #strip leading/trailing wite space
- key=${i%%=*}
- val=${i#*=}
+ key=${pair%%=*}
+ val=${pair#*=}
[ "$key" == expires ] && field_exp=`date -u -d "$val" +'%s'`
# TODO: domain
[ "$key" == path ] && field_path=$val
@@ -78,8 +79,16 @@ function parse_cookie () {
# match cookies in cookies.txt againsh hostname and path
function get_cookie () {
path_esc=${path//\//\\/}
- cookie=`awk "/^[^\t]*$host\t[^\t]*\t$path_esc/" cookie_file 2>/dev/null | tail -n 1`
- [ -n "$cookie" ]
+ cookie=`awk "/^[^\t]*$host\t[^\t]*\t$path_esc/" $cookie_file 2>/dev/null | tail -n 1`
+ if [ -z "$cookie" ]
+ then
+ false
+ else
+ read domain alow_read_other_subdomains path http_required expiration name value <<< "$cookie"
+ cookie="$name=$value"
+ #echo "COOKIE $cookie" >> $HOME/cookielog
+ true
+ fi
}
[ $action == PUT ] && parse_cookie && echo -e "$field_domain\tFALSE\t$field_path\tFALSE\t$field_exp\t$field_name\t$field_value" >> $cookie_file
diff --git a/examples/scripts/history.sh b/examples/scripts/history.sh
index b6671fe4..19b52182 100755
--- a/examples/scripts/history.sh
+++ b/examples/scripts/history.sh
@@ -1,4 +1,4 @@
#!/bin/bash
#TODO: strip 'http://' part
# you probably really want this in your $XDG_DATA_HOME (eg $HOME/.local/share/uzbl/history)
-echo "$8 $6" >> /tmp/uzbl.history
+echo "$8 $6 $7" >> /tmp/uzbl.history
diff --git a/examples/scripts/insert_bookmark.sh b/examples/scripts/insert_bookmark.sh
index fe18328b..180f4cdd 100755
--- a/examples/scripts/insert_bookmark.sh
+++ b/examples/scripts/insert_bookmark.sh
@@ -1,16 +1,17 @@
#!/bin/bash
# you probably want your bookmarks file in your $XDG_DATA_HOME ( eg $HOME/.local/share/uzbl/bookmarks)
-if [ -f /usr/share/uzbl/examples/data/bookmarks ]
-then
- file=/usr/share/uzbl/examples/data/bookmarks # you will probably get permission denied errors here. pick a file in your ~
-else
- file=./examples/data/bookmarks #useful when developing
-fi
+
+[ -f /usr/share/uzbl/examples/data/bookmarks ] && file=/usr/share/uzbl/examples/data/bookmarks # you will probably get permission denied errors here.
+[ -f $XDG_DATA_HOME/uzbl/bookmarks ] && file=$XDG_DATA_HOME/uzbl/bookmarks
+[ -f ./examples/data/bookmarks ] && file=./examples/data/bookmarks #useful when developing
+[ -z "$file" ] && exit 1
which zenity &>/dev/null || exit 2
-entry=`zenity --entry --text="Add bookmark. add tags at the end, separated by commas" --entry-text="$6"`
+entry=`zenity --entry --text="Add bookmark. add tags after the '\t', separated by spaces" --entry-text="$6 $7\t"`
url=`awk '{print $1}' <<< $entry`
# TODO: check if already exists, if so, and tags are different: ask if you want to replace tags
-echo "$entry" >> $file
+echo "$entry" >/dev/null #for some reason we need this.. don't ask me why
+echo -e "$entry" >> $file
+true
\ No newline at end of file
diff --git a/examples/scripts/load_url_from_bookmarks.sh b/examples/scripts/load_url_from_bookmarks.sh
index 35c772cb..5ceb52e0 100755
--- a/examples/scripts/load_url_from_bookmarks.sh
+++ b/examples/scripts/load_url_from_bookmarks.sh
@@ -1,13 +1,22 @@
#!/bin/bash
-# you probably want your bookmarks file in your $XDG_DATA_HOME ( eg $HOME/.local/share/uzbl/bookmarks)
-if [ -f /usr/share/uzbl/examples/data/bookmarks ]
+#NOTE: it's the job of the script that inserts bookmarks to make sure there are no dupes.
+
+[ -f /usr/share/uzbl/examples/data/bookmarks ] && file=/usr/share/uzbl/examples/data/bookmarks
+[ -f $XDG_DATA_HOME/uzbl/bookmarks ] && file=$XDG_DATA_HOME/uzbl/bookmarks
+[ -f ./examples/data/bookmarks ] && file=./examples/data/bookmarks #useful when developing
+[ -z "$file" ] && exit 1
+
+if dmenu --help 2>&1 | grep -q '\[-rs\] \[-ni\] \[-nl\] \[-xs\]'
then
- file=/usr/share/uzbl/examples/data/bookmarks
+ DMENU="dmenu -i -xs -rs -l 10" # vertical patch
+ # show tags as well
+ goto=`$DMENU < $file | awk '{print $1}'`
else
- file=./examples/data/bookmarks #useful when developing
+ DMENU="dmenu -i"
+ # because they are all after each other, just show the url, not their tags.
+ goto=`awk '{print $1}' $file | $DMENU`
fi
-goto=`awk '{print $1}' $file | dmenu -i` #NOTE: it's the job of the script that inserts bookmarks to make sure there are no dupes.
-#[ -n "$goto" ] && echo "uri $goto" > $4
-[ -n "$goto" ] && uzblctrl -s $5 -c "uri $goto"
+#[ -n "$goto" ] && echo "cmd uri $goto" > $4
+[ -n "$goto" ] && uzblctrl -s $5 -c "cmd uri $goto"
diff --git a/examples/scripts/load_url_from_history.sh b/examples/scripts/load_url_from_history.sh
index 3e2e2ee3..f79a0589 100755
--- a/examples/scripts/load_url_from_history.sh
+++ b/examples/scripts/load_url_from_history.sh
@@ -5,7 +5,17 @@ history_file=/tmp/uzbl.history
# choose from all entries, sorted and uniqued
# goto=`awk '{print $3}' $history_file | sort -u | dmenu -i`
-# choose from all entries, the first one being current url, and after that all others, sorted and uniqued.
-current=`tail -n 1 $history_file | awk '{print $3}'`; goto=`(echo $current; awk '{print $3}' $history_file | grep -v "^$current\$" | sort -u) | dmenu -i`
-#[ -n "$goto" ] && echo "uri $goto" > $4
-[ -n "$goto" ] && uzblctrl -s $5 -c "uri $goto"
+
+if dmenu --help 2>&1 | grep -q '\[-rs\] \[-ni\] \[-nl\] \[-xs\]'
+then
+ DMENU="dmenu -i -xs -rs -l 10" # vertical patch
+ # choose an item in reverse order, showing also the date and page titles
+ goto=`tac $history_file | $DMENU | awk '{print $3}'`
+else
+ DMENU="dmenu -i"
+ # choose from all entries (no date or title), the first one being current url, and after that all others, sorted and uniqued, in ascending order
+ current=`tail -n 1 $history_file | awk '{print $3}'`; goto=`(echo $current; awk '{print $3}' $history_file | grep -v "^$current\$" | sort -u) | $DMENU`
+fi
+
+#[ -n "$goto" ] && echo "cmd uri $goto" > $4
+[ -n "$goto" ] && uzblctrl -s $5 -c "cmd uri $goto"
diff --git a/uzbl.c b/uzbl.c
index d7d2baa3..b2b996bc 100644
--- a/uzbl.c
+++ b/uzbl.c
@@ -124,7 +124,7 @@ make_var_to_name_hash() {
static GOptionEntry entries[] =
{
{ "uri", 'u', 0, G_OPTION_ARG_STRING, &uzbl.state.uri, "Uri to load", "URI" },
- { "name", 'n', 0, G_OPTION_ARG_STRING, &uzbl.state.instance_name, "Name of the current instance", "NAME" },
+ { "name", 'n', 0, G_OPTION_ARG_STRING, &uzbl.state.instance_name, "Name of the current instance (defaults to Xorg window id)", "NAME" },
{ "config", 'c', 0, G_OPTION_ARG_STRING, &uzbl.state.config_file, "Config file", "FILE" },
{ NULL, 0, 0, 0, NULL, NULL, NULL }
};
@@ -181,6 +181,13 @@ catch_sigterm(int s) {
clean_up();
}
+static void
+catch_sigint(int s) {
+ (void) s;
+ clean_up();
+ exit(EXIT_SUCCESS);
+}
+
/* --- CALLBACKS --- */
static gboolean
@@ -519,13 +526,11 @@ build_progressbar_ascii(int percent) {
l = (double)percent*((double)width/100.);
l = (int)(l+.5)>=(int)l ? l+.5 : l;
- g_string_append(bar, "[");
for(i=0; i<(int)l; i++)
g_string_append(bar, "=");
for(; i<width; i++)
g_string_append(bar, "·");
- g_string_append(bar, "]");
return g_string_free(bar, FALSE);
}
@@ -715,7 +720,7 @@ run_command (const char *command, const char *args, const gboolean sync, char **
(int) getpid(), (int) uzbl.xwin, uzbl.comm.fifo_path,
uzbl.comm.socket_path);
g_string_append_printf (to_execute, " '%s' '%s'",
- uzbl.state.uri, "TODO title here");
+ uzbl.state.uri, uzbl.gui.main_title);
if(args) g_string_append_printf (to_execute, " %s", args);
if (sync) {
@@ -1101,7 +1106,7 @@ create_stdin () {
}
}
-static void
+static gboolean
control_socket(GIOChannel *chan) {
struct sockaddr_un remote;
char buffer[512], *ctl_line;
@@ -1152,7 +1157,7 @@ control_socket(GIOChannel *chan) {
*/
g_free(ctl_line);
- return;
+ return TRUE;
}
static gchar*
@@ -1381,7 +1386,7 @@ create_browser () {
g_signal_connect (G_OBJECT (g->web_view), "title-changed", G_CALLBACK (title_change_cb), g->web_view);
g_signal_connect (G_OBJECT (g->web_view), "load-progress-changed", G_CALLBACK (progress_change_cb), g->web_view);
g_signal_connect (G_OBJECT (g->web_view), "load-committed", G_CALLBACK (load_commit_cb), g->web_view);
- g_signal_connect (G_OBJECT (g->web_view), "load-committed", G_CALLBACK (log_history_cb), g->web_view);
+ g_signal_connect (G_OBJECT (g->web_view), "load-finished", G_CALLBACK (log_history_cb), g->web_view);
g_signal_connect (G_OBJECT (g->web_view), "load-finished", G_CALLBACK (load_finish_cb), g->web_view);
g_signal_connect (G_OBJECT (g->web_view), "hovering-over-link", G_CALLBACK (link_hover_cb), g->web_view);
g_signal_connect (G_OBJECT (g->web_view), "key-press-event", G_CALLBACK (key_press_cb), g->web_view);
@@ -1583,6 +1588,8 @@ main (int argc, char* argv[]) {
if(setup_signal(SIGTERM, catch_sigterm) == SIG_ERR)
fprintf(stderr, "uzbl: error hooking SIGTERM\n");
+ if(setup_signal(SIGINT, catch_sigint) == SIG_ERR)
+ fprintf(stderr, "uzbl: error hooking SIGINT\n");
if(uname(&uzbl.state.unameinfo) == -1)
g_printerr("Can't retrieve unameinfo. Your useragent might appear wrong.\n");
diff --git a/uzbl.h b/uzbl.h
index a23afe49..48b985ab 100644
--- a/uzbl.h
+++ b/uzbl.h
@@ -277,7 +277,7 @@ create_stdin();
static gchar*
init_socket(gchar *dir);
-static void
+static gboolean
control_socket(GIOChannel *chan);
static void
| 0 | 7 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
6653a8167ce787b0227e720a1b05cf17090009be
|
Cleanups after switching to hard wrapping.
Signed-off-by: Dan Hackney <[email protected]>
|
commit 6653a8167ce787b0227e720a1b05cf17090009be
Author: Dan Hackney <[email protected]>
Date: Sat Jan 2 21:45:24 2010 -0500
Cleanups after switching to hard wrapping.
Signed-off-by: Dan Hackney <[email protected]>
diff --git a/README b/README
index 358096cc..451cf34e 100644
--- a/README
+++ b/README
@@ -98,8 +98,9 @@ There are several interfaces to interact with Uzbl:
- The advantage of the FIFO is you can write plaintext commands to it, but
it's half duplex only (`uzbl` cannot send a response to you).
- The socket is full duplex but you need a socket-compatible wrapper such as
- `socat` to work with it. For example: `echo <command> | socat -
- unix-connect:<socketfile>`
+ `socat` to work with it. For example:
+
+ echo <command> | socat - unix-connect:<socketfile>
When `uzbl` forks a new instance (eg "open in new window") it will use the same
command line arguments (eg the same `--config <file>`), except `--uri` and
@@ -185,7 +186,7 @@ The following commands are recognized:
* `talk_to_socket <socketfile> <tokens>`
- Send a message to `<socketfile>` and wait for a response. `<tokens>` are
concatenated and separated by ASCII NUL bytes.
- - Expects the socket type to be `SOCK_SEQPACKET` (see connect(2) ).
+ - Expects the socket type to be `SOCK_SEQPACKET` (see `connect(2)`).
- Waits for 500ms for a response.
* `exit`
- Closes `uzbl`.
@@ -392,21 +393,25 @@ The above example demonstrates two things:
Command substitution will launch any commands and substitute the call with the
return value of the command. There are two methods:
-* Through a shell: enclose commands with @( )@ (quote escaping is handled by
- Uzbl): print Command substitution: @(uname -a)@
+* Through a shell: enclose commands with `@( )@` (quote escaping is handled by
+ Uzbl):
+
+ print Command substitution: @(uname -a)@
+
+This method allows you to use POSIX shell syntax in your commands.
-This method allows you to use posix shell syntax in your commands.
+* directly:
-* directly: print Command substitution: @(+uname -a)@
+ print Command substitution: @(+uname -a)@
This example will execute uname directly.
-Note that you can access any uzbl variable from within a command substitution:
+Note that you can access any `uzbl` variable from within a command substitution:
print @(echo -n 'Accessing the show_status var from an external script, value: @show_status')@
JavaScript substitution works in the exact same way as command substitution but
-you will need to enclose the java script in `@< >@`.
+you will need to enclose the JavaScript in `@< >@`.
print The currently viewed document contains @<document.links.length>@ links
@@ -465,15 +470,15 @@ You can use external scripts with Uzbl the following ways:
* Let `uzbl` call them. These scripts are called "handlers" in the `uzbl`
config. Used for handling cookies, starting a new download, and more.
* Call them yourself from inside `uzbl`. You can bind keys for this. Examples:
- add new bookmark, load new url.
+ add new bookmark, load new URL.
* You could also use `xbindkeys` or your WM config to trigger scripts if `uzbl`
does not have focus.
Have a look at the sample configs and scripts!
-Handler scripts that are called by uzbl are passed the following arguments:
+Handler scripts that are called by `uzbl` are passed the following arguments:
-* `$1 config-file`: The configuration file loaded by this `uzbl` instance.
+* `$1 config`: The configuration file loaded by this `uzbl` instance.
* `$2 pid`: The process ID of this `uzbl` instance.
* `$3 x_id`: The X Windows ID of the process.
* `$4 fifo`: The filename of the FIFO being used, if any.
@@ -532,11 +537,11 @@ object) as default, it is recommended to wrap your scripts like this:
(function(Uzbl) { ... })(Uzbl);
-This way, everything is kept private. It also turns Uzbl into a local variable,
-which can be accessed from callback functions defined inside. However for some
-situations, isolating everything isn't an option, for example, with binds. You
-can define them directly in the script body, and use `var Uzbl = window.Uzbl;`
-to make the Uzbl variable local, as in the following example:
+This way, everything is kept private. It also turns `Uzbl` into a local
+variable, which can be accessed from callback functions defined inside. However
+for some situations, isolating everything isn't an option, for example, with
+binds. You can define them directly in the script body, and use `var Uzbl =
+window.Uzbl;` to make the `Uzbl` variable local, as in the following example:
function f() {
var Uzbl = window.Uzbl;
@@ -548,7 +553,7 @@ to make the Uzbl variable local, as in the following example:
Copying the Uzbl object and creating public functions should be taken with care
to avoid creating security holes. Keep in mind that the `f` function above would
-be defined in the `window` object, and as such any javascript in the current
+be defined in the `window` object, and as such any JavaScript in the current
page can call it.
### EVENTS
@@ -583,8 +588,8 @@ Events have this format:
* `EVENT [uzbl_instance_name] INSTANCE_EXIT process_id`: `uzbl` shutdown
* `EVENT [uzbl_instance_name] VARIABLE_SET variable_name str|int|float
variable_value`: Note: `str|int|float` denote the type of `variable_value`.
-* `EVENT [uzbl_instance_name] COMMAND_EXECUTED command_name
- optional_command_arguments`: A command is executed.
+* `EVENT [uzbl_instance_name] COMMAND_EXECUTED command_name optional_arguments`:
+ A command is executed.
* `EVENT [uzbl_instance_name] COMMAND_ERROR command_name`: Tried to execute the
command `command_name`, but it does not exist.
* `EVENT [uzbl_instance_name] GEOMETRY_CHANGED
| 0 | 9 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
e3f6305e0455b6c88b7ff3fc140d7d520f344a0b
|
Make progress bar show empty on start of page load
Previously, when clicking on a link or opening a new URL, the user would
not get any feedback showing that the command was taken until after a
progress change, which could sometimes take a prolonged period of time.
Now, the user is immediately alerted via the statusbar going to zero.
|
commit e3f6305e0455b6c88b7ff3fc140d7d520f344a0b
Author: Jeremy O'Brien <[email protected]>
Date: Thu Jun 4 23:51:34 2009 -0400
Make progress bar show empty on start of page load
Previously, when clicking on a link or opening a new URL, the user would
not get any feedback showing that the command was taken until after a
progress change, which could sometimes take a prolonged period of time.
Now, the user is immediately alerted via the statusbar going to zero.
diff --git a/uzbl.c b/uzbl.c
index a1f1bab4..4c37f08b 100644
--- a/uzbl.c
+++ b/uzbl.c
@@ -545,6 +545,7 @@ load_start_cb (WebKitWebView* page, WebKitWebFrame* frame, gpointer data) {
(void) page;
(void) frame;
(void) data;
+ uzbl.gui.sbar.load_progress = 0;
g_string_truncate(uzbl.state.keycmd, 0); // don't need old commands to remain on new page?
if (uzbl.behave.load_start_handler)
run_handler(uzbl.behave.load_start_handler, "");
| 0 | 10 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
2926b0f55122b131e0b9d2cf857d2b78d202c5ab
|
Fixed array bug.
When e.g. spawn_sh modifies the array, invalid stuff is send to the
python script, which then breaks while decoding them.
|
commit 2926b0f55122b131e0b9d2cf857d2b78d202c5ab
Author: Olof-Joachim Frahm <[email protected]>
Date: Mon Mar 21 06:23:23 2011 +0100
Fixed array bug.
When e.g. spawn_sh modifies the array, invalid stuff is send to the
python script, which then breaks while decoding them.
diff --git a/src/uzbl-core.c b/src/uzbl-core.c
index c8796025..ba062b65 100644
--- a/src/uzbl-core.c
+++ b/src/uzbl-core.c
@@ -1129,8 +1129,6 @@ spawn_sh_sync(WebKitWebView *web_view, GArray *argv, GString *result) {
void
run_parsed_command(const CommandInfo *c, GArray *a, GString *result) {
- c->function(uzbl.gui.web_view, a, result);
-
/* send the COMMAND_EXECUTED event, except for set and event/request commands */
if(strcmp("set", c->key) &&
strcmp("event", c->key) &&
@@ -1141,12 +1139,18 @@ run_parsed_command(const CommandInfo *c, GArray *a, GString *result) {
guint i = 0;
while ((p = argv_idx(a, i++)))
g_string_append_printf(param, " '%s'", p);
+
+ /* might be destructive on array a */
+ c->function(uzbl.gui.web_view, a, result);
+
send_event(COMMAND_EXECUTED, NULL,
TYPE_NAME, c->key,
TYPE_FORMATTEDSTR, param->str,
NULL);
g_string_free(param, TRUE);
}
+ else
+ c->function(uzbl.gui.web_view, a, result);
if(result) {
g_free(uzbl.state.last_result);
| 0 | 5 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
0cd3f65d05e7d966ff66d2aa97908332eb2d6c06
|
merge in pawelz' authentication handler + some other fixes
|
commit 0cd3f65d05e7d966ff66d2aa97908332eb2d6c06 (from c3c4d481079f2a24ea16cd49b785b6f358a28fc9)
Merge: c3c4d481 67c68ee6
Author: Dieter Plaetinck <[email protected]>
Date: Sun Jan 24 16:21:11 2010 +0100
merge in pawelz' authentication handler + some other fixes
diff --git a/AUTHORS b/AUTHORS
index 165eae08..8e1602cc 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -50,7 +50,7 @@ In alphabetical order:
Moritz Lenz - small doc fix
Nicolas Pouillard - refactored scroll command
Olivier Schwander - auto file:// prepend
- Paweł Zuzelski (pawelz) - download handler proxy patch
+ Paweł Zuzelski (pawelz) - http auth handler, misc patches
Peter Suschlik - backwards searching
Přemysl Hrubý (anydot) <email is dfenze AT gmail.com> - several C contributions and cleanups
Robert Manea (robm) <email is rob DOT manea AT gmail DOT com> - C code all over the place
diff --git a/Makefile b/Makefile
index 626d21e1..eeb26225 100644
--- a/Makefile
+++ b/Makefile
@@ -34,9 +34,6 @@ uzbl-core: ${TOBJ} # why doesn't ${OBJ} work?
@echo LINKING object files
@${CC} -o $@ ${OBJ} ${LDFLAGS}
@echo ... done.
- @echo Stripping binary
- @strip $@
- @echo ... done.
uzbl-browser: uzbl-core
@@ -92,6 +89,11 @@ clean:
cd ./tests/; $(MAKE) clean
rm -rf ./sandbox/{examples,usr}/
+strip:
+ @echo Stripping binary
+ @strip uzbl-core
+ @echo ... done.
+
install: install-uzbl-core install-uzbl-browser install-uzbl-tabbed
install-uzbl-core: all
diff --git a/README b/README
index 0a22b556..56e58424 100644
--- a/README
+++ b/README
@@ -513,9 +513,52 @@ The script specific arguments are:
- `$8 URI` of the page to be navigated to
+* authentication handler:
+
+ $8 authentication zone unique identifier
+ $9 domain part of URL that requests authentication
+ $10 authentication realm
+ $11 FALSE if this is the first attempt to authenticate, TRUE otherwise
+
Custom, userdefined scripts (`spawn foo bar`) get first the arguments as
specified in the config and then the above 7 are added at the end.
+### HTTP/BASIC AUTHENTICATION ###
+
+If authentication_handler variable is not set, http authentication is handled
+internally by WebKit. If you want to use custom script for http authentication,
+set authentication_handler. For example:
+
+ set authentication_handler = sync_spawn /patch/to/your/script
+
+Script will be executed on each authentication request.
+It will receive four auth-related parameters:
+
+ $8 authentication zone unique identifier (may be used as 'key')
+ $9 domain part of URL that requests authentication
+ $10 authentication realm
+ $11 FALSE if this is the first attempt to authenticate, TRUE otherwise
+
+Script is expected to print exactly two lines of text on stdout (that means
+its output must contain exactly two '\n' bytes).
+The first line contains username, the second one - password.
+If authentication fails, script will be executed again (with $11 = TRUE).
+Non-interactive scripts should handle this case and do not try to
+authenticate again to avoid loops. If number of '\n' characters in scripts
+output does not equal 2, authentication will fail.
+That means 401 error will be displayed and uzbl won't try to authenticate anymore.
+
+The simplest example of authentication handler script is:
+
+#!/bin/sh
+[ "$11" == "TRUE ] && exit
+echo alice
+echo wonderland
+
+This script tries to authenticate as user alice with password wonderland once
+and never retries authentication.
+See examples for more sofisticated, interactive authentication handler.
+
### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
JavaScript code run from `uzbl` is given a special object in the global
diff --git a/docs/INSTALL b/docs/INSTALL
index 711ea973..c795502a 100644
--- a/docs/INSTALL
+++ b/docs/INSTALL
@@ -9,8 +9,8 @@ From source
You can pull the code from git or get a tagged tarball.
$ git clone git://github.com/Dieterbe/uzbl.git
- [ $ git checkout origin/experimental ] # optional. see below
$ cd uzbl
+ [ $ git checkout origin/experimental ] # optional. see below
$ make
$ sudo make install
If you want to remove uzbl again, you can issue:
diff --git a/examples/config/config b/examples/config/config
index d58d0a5c..929397df 100644
--- a/examples/config/config
+++ b/examples/config/config
@@ -35,7 +35,7 @@ set shell_cmd = sh -c
set scripts_dir = $XDG_DATA_HOME/uzbl:@prefix/share/uzbl/examples/data:scripts
# Javascipt helpers.
-set jsh = js var run=Uzbl.run; function get(k){return run("print \\\@"+k)}; function set(k, v) {run("set "+k+" = "+v)};
+#set jsh = js var run=Uzbl.run; function get(k){return run("print \\\@"+k)}; function set(k, v) {run("set "+k+" = "+v)};
# === Handlers ===============================================================
@@ -45,6 +45,7 @@ set jsh = js var run=Uzbl.run; function get(k){return run("print \\\@"+k)}; func
# support events that can wait for a response from a script.
set cookie_handler = talk_to_socket $XDG_CACHE_HOME/uzbl/cookie_daemon_socket
set scheme_handler = sync_spawn @scripts_dir/scheme.py
+set authentication_handler = sync_spawn @scripts_dir/auth.py
# Open in the same window.
#set new_window = sh 'echo uri "$8" > $4'
@@ -71,7 +72,7 @@ set new_window = sh 'uzbl-browser -u $8'
# Generate a FORM_ACTIVE event if an editable
# element on the loaded site has initial focus
-@on_event LOAD_FINISH js if(document.activeElement.type == 'text') {Uzbl.run("event FORM_ACTIVE");}
+#@on_event LOAD_FINISH js if(document.activeElement.type == 'text') {Uzbl.run("event FORM_ACTIVE");}
# Switch to insert mode if a (editable) html form is clicked
@on_event FORM_ACTIVE @set_mode insert
@@ -189,12 +190,8 @@ set ebind = @mode_bind global,-insert
# === Mouse bindings =========================================================
-# Middle click
-# if clicked on a link open the link in a new uzbl window
-# otherwise open the selection in the current window
-set load_from_xclip = sh 'echo "uri $(xclip -o)" > $4'
-set open_new_window = sh 'uzbl-browser -u \@SELECTED_URI'
-@bind <Button2> = @jsh if(get("SELECTED_URI")) { run("\@open_new_window"); } else { run("\\\@load_from_xclip"); }
+# Middle click open in new window
+@bind <Button2> = sh 'uzbl-browser -u \@SELECTED_URI'
# === Keyboard bindings ======================================================
@@ -276,7 +273,8 @@ set toggle_cmd_ins = @toggle_modes command insert
@cbind gh = uri http://www.uzbl.org
# --- Yanking & pasting binds ---
-@cbind y<Yank (t)itle or (u)rl:>* = @jsh if('%s' == 'u') { run("sh 'echo -n $6 | xclip'"); } else if('%s' == 't') { run("sh 'echo -n $7 | xclip'"); }; run('event SET_KEYCMD');
+@cbind yu = sh 'echo -n $6 | xclip'
+@cbind yy = sh 'echo -n $7 | xclip'
# Go the page from primary selection
@cbind p = sh 'echo "uri `xclip -selection primary -o`" > $4'
diff --git a/examples/data/scripts/auth.py b/examples/data/scripts/auth.py
new file mode 100644
index 00000000..4feb90be
--- /dev/null
+++ b/examples/data/scripts/auth.py
@@ -0,0 +1,53 @@
+#!/usr/bin/python
+
+import gtk
+import sys
+
+def responseToDialog(entry, dialog, response):
+ dialog.response(response)
+
+def getText(authInfo, authHost, authRealm):
+ dialog = gtk.MessageDialog(
+ None,
+ gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
+ gtk.MESSAGE_QUESTION,
+ gtk.BUTTONS_OK_CANCEL,
+ None)
+ dialog.set_markup('%s at %s' % (authRealm, authHost))
+
+ login = gtk.Entry()
+ password = gtk.Entry()
+ password.set_visibility(False)
+
+ login.connect("activate", responseToDialog, dialog, gtk.RESPONSE_OK)
+ password.connect("activate", responseToDialog, dialog, gtk.RESPONSE_OK)
+
+ hbox = gtk.HBox();
+
+ vbox_entries = gtk.VBox();
+ vbox_labels = gtk.VBox();
+
+ vbox_labels.pack_start(gtk.Label("Login:"), False, 5, 5)
+ vbox_labels.pack_end(gtk.Label("Password:"), False, 5, 5)
+
+ vbox_entries.pack_start(login)
+ vbox_entries.pack_end(password)
+
+ dialog.format_secondary_markup("Please enter username and password:")
+ hbox.pack_start(vbox_labels, True, True, 0)
+ hbox.pack_end(vbox_entries, True, True, 0)
+
+ dialog.vbox.pack_start(hbox)
+ dialog.show_all()
+ rv = dialog.run()
+
+ output = login.get_text() + "\n" + password.get_text()
+ dialog.destroy()
+ return rv, output
+
+if __name__ == '__main__':
+ rv, output = getText(sys.argv[8], sys.argv[9], sys.argv[10])
+ if (rv == gtk.RESPONSE_OK):
+ print output;
+ else:
+ exit(1)
diff --git a/examples/data/scripts/uzbl-event-manager b/examples/data/scripts/uzbl-event-manager
index 99b215ac..a92485f4 100755
--- a/examples/data/scripts/uzbl-event-manager
+++ b/examples/data/scripts/uzbl-event-manager
@@ -295,7 +295,7 @@ def parse_msg(uzbl, msg):
cmd = FINDSPACES.split(msg, 3)
if not cmd or cmd[0] != 'EVENT':
# Not an event message.
- print '---', msg
+ print '---', msg.encode('utf-8')
return
while len(cmd) < 4:
@@ -374,11 +374,11 @@ class UzblInstance(object):
msg = msg.strip()
if self.client_socket:
- print '%s<-- %s' % (' ' * self.depth, msg)
+ print (u'%s<-- %s' % (' ' * self.depth, msg)).encode('utf-8')
self.client_socket.send(("%s\n" % msg).encode('utf-8'))
else:
- print '%s!-- %s' % (' ' * self.depth, msg)
+ print (u'%s!-- %s' % (' ' * self.depth, msg)).encode('utf-8')
def export(self, name, function):
@@ -466,7 +466,7 @@ class UzblInstance(object):
elems = [event,]
if args: elems.append(unicode(args))
if kargs: elems.append(unicode(kargs))
- print "%s--> %s" % (' ' * self.depth, ' '.join(elems))
+ print (u'%s--> %s' % (' ' * self.depth, ' '.join(elems))).encode('utf-8')
if event == "INSTANCE_START" and args:
self.pid = int(args[0])
diff --git a/src/callbacks.c b/src/callbacks.c
index 9130f5fe..80846e32 100644
--- a/src/callbacks.c
+++ b/src/callbacks.c
@@ -26,6 +26,17 @@ set_proxy_url() {
return;
}
+void
+set_authentication_handler() {
+ if (uzbl.behave.authentication_handler)
+ soup_session_remove_feature_by_type
+ (uzbl.net.soup_session, (GType) WEBKIT_TYPE_SOUP_AUTH_DIALOG);
+ else
+ soup_session_add_feature_by_type
+ (uzbl.net.soup_session, (GType) WEBKIT_TYPE_SOUP_AUTH_DIALOG);
+ return;
+}
+
void
set_icon() {
if(file_exists(uzbl.gui.icon)) {
diff --git a/src/callbacks.h b/src/callbacks.h
index 882ffa43..242c5102 100644
--- a/src/callbacks.h
+++ b/src/callbacks.h
@@ -12,6 +12,9 @@ cmd_set_status();
void
set_proxy_url();
+void
+set_authentication_handler();
+
void
set_icon();
diff --git a/src/uzbl-core.c b/src/uzbl-core.c
index da61093e..15588828 100644
--- a/src/uzbl-core.c
+++ b/src/uzbl-core.c
@@ -101,6 +101,7 @@ const struct var_name_to_ptr_t {
{ "forward_keys", PTR_V_INT(uzbl.behave.forward_keys, 1, NULL)},
{ "download_handler", PTR_V_STR(uzbl.behave.download_handler, 1, NULL)},
{ "cookie_handler", PTR_V_STR(uzbl.behave.cookie_handler, 1, NULL)},
+ { "authentication_handler", PTR_V_STR(uzbl.behave.authentication_handler, 1, set_authentication_handler)},
{ "new_window", PTR_V_STR(uzbl.behave.new_window, 1, NULL)},
{ "scheme_handler", PTR_V_STR(uzbl.behave.scheme_handler, 1, NULL)},
{ "fifo_dir", PTR_V_STR(uzbl.behave.fifo_dir, 1, cmd_fifo_dir)},
@@ -2317,6 +2318,57 @@ settings_init () {
init_connect_socket();
g_signal_connect_after(n->soup_session, "request-started", G_CALLBACK(handle_cookies), NULL);
+ g_signal_connect(n->soup_session, "authenticate", G_CALLBACK(handle_authentication), NULL);
+}
+
+void handle_authentication (SoupSession *session, SoupMessage *msg, SoupAuth *auth, gboolean retrying, gpointer user_data) {
+
+ (void) user_data;
+
+ if(uzbl.behave.authentication_handler) {
+ char *username, *password;
+ gchar *info, *host, *realm;
+ int number_of_endls=0;
+ gchar *p;
+
+ soup_session_pause_message(session, msg);
+
+ /* Sanitize strings */
+ info = g_strdup(soup_auth_get_info(auth));
+ host = g_strdup(soup_auth_get_host(auth));
+ realm = g_strdup(soup_auth_get_realm(auth));
+ for (p = info; *p; p++) if (*p == '\'') *p = '\"';
+ for (p = host; *p; p++) if (*p == '\'') *p = '\"';
+ for (p = realm; *p; p++) if (*p == '\'') *p = '\"';
+
+ GString *s = g_string_new ("");
+ g_string_printf(s, "'%s' '%s' '%s' '%s'",
+ info, host, realm, retrying?"TRUE":"FALSE");
+
+ run_handler(uzbl.behave.authentication_handler, s->str);
+
+ username = uzbl.comm.sync_stdout;
+
+ for (p = uzbl.comm.sync_stdout; *p; p++) {
+ if (*p == '\n') {
+ *p = '\0';
+ if (++number_of_endls == 1)
+ password = p + 1;
+ }
+ }
+
+ /* If stdout was correct (contains exactly two lines of text) do
+ * authenticate. */
+ if (number_of_endls == 2)
+ soup_auth_authenticate(auth, username, password);
+
+ soup_session_unpause_message(session, msg);
+
+ g_string_free(s, TRUE);
+ g_free(info);
+ g_free(host);
+ g_free(realm);
+ }
}
void handle_cookies (SoupSession *session, SoupMessage *msg, gpointer user_data){
@@ -2467,9 +2519,9 @@ initialize(int argc, char *argv[]) {
}
event_buffer_timeout(10);
- uzbl.info.webkit_major = WEBKIT_MAJOR_VERSION;
- uzbl.info.webkit_minor = WEBKIT_MINOR_VERSION;
- uzbl.info.webkit_micro = WEBKIT_MICRO_VERSION;
+ uzbl.info.webkit_major = webkit_major_version();
+ uzbl.info.webkit_minor = webkit_minor_version();
+ uzbl.info.webkit_micro = webkit_micro_version();
uzbl.info.arch = ARCH;
uzbl.info.commit = COMMIT;
@@ -2483,6 +2535,13 @@ initialize(int argc, char *argv[]) {
void
load_uri_imp(gchar *uri) {
GString* newuri;
+
+ /* Strip leading whitespaces */
+ while (*uri) {
+ if (!isspace(*uri)) break;
+ uri++;
+ }
+
if (g_strstr_len (uri, 11, "javascript:") != NULL) {
eval_js(uzbl.gui.web_view, uri, NULL);
return;
diff --git a/src/uzbl-core.h b/src/uzbl-core.h
index 70a383c4..e05fcdb9 100644
--- a/src/uzbl-core.h
+++ b/src/uzbl-core.h
@@ -28,6 +28,7 @@
#include <stdio.h>
#include <string.h>
+#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
@@ -123,6 +124,7 @@ typedef struct {
gchar* socket_dir;
gchar* download_handler;
gchar* cookie_handler;
+ gchar* authentication_handler;
gchar* new_window;
gchar* default_font_family;
gchar* monospace_font_family;
@@ -390,6 +392,13 @@ run_external_js (WebKitWebView * web_view, GArray *argv, GString *result);
void
eval_js(WebKitWebView * web_view, gchar *script, GString *result);
+void
+handle_authentication (SoupSession *session,
+ SoupMessage *msg,
+ SoupAuth *auth,
+ gboolean retrying,
+ gpointer user_data);
+
void handle_cookies (SoupSession *session,
SoupMessage *msg,
gpointer user_data);
diff --git a/tests/test-expand.c b/tests/test-expand.c
index 4dcd82de..7ea3d611 100644
--- a/tests/test-expand.c
+++ b/tests/test-expand.c
@@ -72,11 +72,11 @@ test_useragent (void) {
void
test_WEBKIT_VERSION (void) {
GString* expected = g_string_new("");
- g_string_append(expected, itos(WEBKIT_MAJOR_VERSION));
+ g_string_append(expected, itos(webkit_major_version()));
g_string_append(expected, " ");
- g_string_append(expected, itos(WEBKIT_MINOR_VERSION));
+ g_string_append(expected, itos(webkit_minor_version()));
g_string_append(expected, " ");
- g_string_append(expected, itos(WEBKIT_MICRO_VERSION));
+ g_string_append(expected, itos(webkit_micro_version()));
g_assert_cmpstr(expand("@WEBKIT_MAJOR @WEBKIT_MINOR @WEBKIT_MICRO", 0), ==, g_string_free(expected, FALSE));
}
commit 0cd3f65d05e7d966ff66d2aa97908332eb2d6c06 (from 67c68ee643eaef16277fa614d873dd558bfdbd04)
Merge: c3c4d481 67c68ee6
Author: Dieter Plaetinck <[email protected]>
Date: Sun Jan 24 16:21:11 2010 +0100
merge in pawelz' authentication handler + some other fixes
diff --git a/AUTHORS b/AUTHORS
index 6f540d03..8e1602cc 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -29,6 +29,7 @@ In alphabetical order:
Chris Mason - code snippets such as basic cookie handler
Chris van Dijk (quigybo) - work on uzbl_tabbed.py
Damien Leon - misc
+ Daniel M. Hackney - documentation cleanups
David Keijser - various C and python patches.
Devon Jones <[email protected]> - uzbl_tabbed: bring_to_front
Dieter Plaetinck (Dieter@be) <dieter AT plaetinck.be> - several contributions
@@ -39,7 +40,7 @@ In alphabetical order:
Jake Probst <[email protected]> - uzbl_tabbed: multiline tablist
James S Wheaton (uranther) - zoom level, test framework
Jan Kolkmeier (jouz) - scrolling, link following
- Jason Woofenden (JasonWoof) - geometry=maximized
+ Jason Woofenden (JasonWoof) - geometry=maximized, link following
Laurence Withers (lwithers) - talk_to_socket
Mark Nevill - misc patches
Mason Larobina - uzbl-tabbed.py, cookie-daemon, event-manager&plugins, ...
@@ -49,7 +50,7 @@ In alphabetical order:
Moritz Lenz - small doc fix
Nicolas Pouillard - refactored scroll command
Olivier Schwander - auto file:// prepend
- Paweł Zuzelski (pawelz) - download handler proxy patch
+ Paweł Zuzelski (pawelz) - http auth handler, misc patches
Peter Suschlik - backwards searching
Přemysl Hrubý (anydot) <email is dfenze AT gmail.com> - several C contributions and cleanups
Robert Manea (robm) <email is rob DOT manea AT gmail DOT com> - C code all over the place
diff --git a/README b/README
index a0a5afab..56e58424 100644
--- a/README
+++ b/README
@@ -1,334 +1,449 @@
### INTRODUCTION
- Any program can only be really useful if it complies to the unix philosophy.
- Web browsers (and other tools that work with html, such as feedreaders) are frequent violators of this principle:
-* They build in way too much things into one (complex) program, dramatically decreasing the options to do things the way you want.
-* They store things in way too fancy formats (xml, rdf, sqlite, ... ) which are hard to store under version control, reuse in other scripts, ...
+Any program can only be really useful if it complies with the Unix
+philosophy. Web browsers (and other tools that work with HTML, such as feed
+readers) are frequent violators of this principle:
-The uzbl project was started as an attempt to resolve this.
+* They build in way too much things into one (complex) program, dramatically
+ decreasing the options to do things the way you want.
+* They store things in way too fancy formats (XML, RDF, SQLite, etc.) which are
+ hard to store under version control, reuse in other scripts, and so on.
+
+The Uzbl project was started as an attempt to resolve this.
### EDITIONS
-"Uzbl" is an umbrella-project consisting of different flavors.
-In the future more things may come, but for now:
+"Uzbl" is an umbrella project consisting of different flavors. In the future
+more things may come, but for now:
#### uzbl-core: main component meant for integration with other tools and scripts
- * Uses WebkitGtk+ for rendering, network interaction (libsoup). Css, javascript, plugin support etc come for free
- * Provides interfaces to get data in (commands/configuration) and out (events): stdin/stdout/fifo/unix sockets
- * You see a webkit view and (optionally) a statusbar which gets popuplated externally
- * No built-in means for url changing, loading/saving of bookmarks, saving history, keybinds, downloads, ...
- * Extra functionality: many sample scripts come with it, on <a href="http://www.uzbl.org/wiki/scripts">uzbl wiki</a> or write them yourself
- * Entire configuration/state can be changed at runtime
- * Uzbl keeps it simple, and puts <strong>you</strong> in charge.
+* Uses WebKitGtk+ for rendering and network interaction (libsoup). CSS,
+ JavaScript, and plugin support come for free.
+* Provides interfaces to get data in (commands/configuration) and out (events):
+ stdin/stdout/fifo/Unix sockets.
+* You see a WebKit view and (optionally) a statusbar which gets populated
+ externally.
+* No built-in means for URL changing, loading/saving of bookmarks, saving
+ history, keybinds, downloads, etc.
+* Extra functionality: many sample scripts come with it. More are available on
+ the [Uzbl wiki](http://www.uzbl.org/wiki/scripts) or you can write them
+ yourself.
+* Entire configuration/state can be changed at runtime.
+* Uzbl keeps it simple, and puts **you** in charge.
#### uzbl-browser: a complete browser experience based on uzbl-core
- * Uses a set of scripts (mostly python) that will fit most people, so things work out of the box. Yet plenty of room for customisation
- * Brings everything you expect: url changing, history, downloads, form filling, link navigation, cookies, event management etc. However: one page per instance
- * Advanced, customizable keyboard interface with support for modes, modkeys, multichars, variables (keywords) etc. (eg you can tweak the interface to be vim-like, emacs-like or any-other-program-like)
- * Adequate default configuration
- * Focus on plaintext storage for your data and configs in simple, parseable formats and adherence to the xdg basedir spec
- * Visually, similar to uzbl-core except that the statusbar contains useful things. One window per webpage
+* Uses a set of scripts (mostly Python) that will fit most people, so things
+ work out of the box; yet plenty of room for customization.
+* Brings everything you expect: URL changing, history, downloads, form filling,
+ link navigation, cookies, event management etc. However: one page per
+ instance.
+* Advanced, customizable keyboard interface with support for modes, modkeys,
+ multichars, variables (keywords) etc. (eg you can tweak the interface to be
+ Vi-like, Emacs-like or any-other-program-like).
+* Adequate default configuration.
+* Focus on plaintext storage for your data and configs in simple, parseable
+ formats and adherence to the XDG basedir spec.
+* Visually, similar to `uzbl-core` except that the statusbar contains useful
+ information. One window per webpage.
#### uzbl-tabbed: wraps around uzbl-browser and multiplexes it
- * Spawns one window containing multiple tabs, each tab containing a full embedded uzbl-browser
- * Ideal as a quick and simple solution to manage multiple uzbl-browser instances without getting lost
+* Spawns one window containing multiple tabs, each tab containing a full
+ embedded `uzbl-browser`.
+* Ideal as a quick and simple solution to manage multiple `uzbl-browser`
+ instances without getting lost.
+Throughout the documentation, when referring to `uzbl` we mean `uzbl-core`,
+unless otherwise specified.
-Throughout the documentation, when referring to `uzbl` we mean uzbl-core, unless otherwise specified.
+### CONFIGURATION / CONTROL:
+The general idea is that Uzbl by default is very bare bones. You can send it
+commands to update settings and perform actions, through various
+interfaces. There is a limited default configuration. Please see `config.h` to
+see what it contains. By default, there are *no* keybinds defined at
+all. (Default keybinds would work counterproductive when you try to
+customize). For examples of the possibilities what you can do, please see the
+sample config(s), and uzbl wiki page.
-### CONFIGURATION / CONTROL:
-The general idea is that uzbl by default is very bare bones. You can send it commands to update settings and perform actions, through various interfaces.
-There is a limited default configuration. Please see config.h to see what it contains.
-By default, there are *no* keybinds defined at all. (Default keybinds would work counterproductive when you try to customize)
-For examples of the possibilities what you can do, please see the sample config(s), and uzbl wiki page.
-There are several interfaces to interact with uzbl:
-
-* uzbl --config <filename>: <filename> will be read line by line, and the commands in it will be executed. Useful to configure uzbl at startup.
- If you have a file in `$XDG_CONFIG_HOME/uzbl/config` (this expands to ~/.config/uzbl/config on most systems) it will be automatically recognized
-* stdin: to write commands into stdin, use `--config -` (or `-c -`)
-* interactive: you can enter commands (and bind them to shortcuts, even at runtime)
- By default, the behaviour is modal (vi style):
- command mode: every keystroke is interpreted to run commands
- insert mode: keystrokes are not interpreted so you can enter text into html forms
- But if you don't like modal interfaces, you can set `always_insert_mode` and configure a modkey to execute the commands. (emacs style).
- There is also support for "chained" commands (multiple characters long) (with backspace/esc shortcuts), and keyworded commands.
- Also you can have incremental matching on commands or match after pressing return. (see sampleconfig for more info)
- Also, copy paste works when typing commands:
- * insert (paste X cliboard)
- * shift insert (paste primary selection buffer)
-* FIFO & socket file: if enabled by setting their paths through one of the above means, you can have socket and fifo files available which are very useful to programatically control uzbl (from scripts etc).
- The advantage of the fifo is you can write plaintxt commands to it, but it's half duplex only (uzbl cannot send a response to you).
- The socket is full duplex but you need a socket-compatible wrapper such as socat to work with it.
- For example: echo <command> | socat - unix-connect:<socketfile>
-
-When uzbl forks a new instance (eg "open in new window") it will use the same commandline arguments (eg the same --config <file>), except --uri and--name.
-If you made changes to the configuration at runtime, these are not passed on to the child.
+There are several interfaces to interact with Uzbl:
+
+* `uzbl --config <filename>`: `<filename>` will be read line by line, and the
+ commands in it will be executed. Useful to configure Uzbl at startup. If you
+ have a file in `$XDG_CONFIG_HOME/uzbl/config` (this expands to
+ `~/.config/uzbl/config` on most systems), it will be automatically recognized.
+* `stdin`: to write commands into `stdin`, use `--config -` (or `-c -`).
+* Interactive: you can enter commands (and bind them to shortcuts, even at
+ runtime) By default, the behaviour is modal (Vi style):
+
+ - command mode: every keystroke is interpreted to run commands
+ - insert mode: keystrokes are not interpreted so you can enter text into html
+ forms
+
+ There is also support for "chained" commands (multiple characters long), and
+ keyworded commands. Also you can have incremental matching on commands or
+ match after pressing return. See the sample configuration file for more info.
+ Also, copy and paste works when typing commands:
+
+ - `insert` (paste X cliboard)
+ - `shift insert` (paste primary selection buffer)
+
+* FIFO & socket files: If enabled by setting their paths through one of the
+ above means, you can have socket and fifo files available which are very
+ useful to programmatically control `uzbl` (from scripts etc).
+
+ - The advantage of the FIFO is you can write plaintext commands to it, but
+ it's half duplex only (`uzbl` cannot send a response to you).
+ - The socket is full duplex but you need a socket-compatible wrapper such as
+ `socat` to work with it. For example:
+
+ echo <command> | socat - unix-connect:<socketfile>
+
+When `uzbl` forks a new instance (eg "open in new window") it will use the same
+command line arguments (eg the same `--config <file>`), except `--uri` and
+`--name`. If you made changes to the configuration at runtime, these are not
+passed on to the child.
#### Uzbl-browser
-- default config
-- EM
-- EM plugins
-- bindings/events/requests
+
+* default config
+* Event Manager
+* Event Manager plugins
+* bindings/events/requests
#### Uzbl-tabbed
-- also has some own keybindings
+* also has some of its own keybindings.
### COMMAND SYNTAX
-Uzbl will read commands via standard input, named fifo pipe (if `fifo_dir` is set) and IPC socket (when `socket_dir` is set).
-For convenience, uzbl can also be instructed to read commands from a file on startup by using the `-c` option. Indeed, the config file is nothing more than a list of commands.
-Each command starts with the name of the command or an uzbl variable that expands to it. A command is terminated by a newline.
-Empty lines and lines that start with the hash sign are ignored by the parser. Command names are always written in lowercase.
+Uzbl will read commands via standard input, named FIFO pipe (if `fifo_dir` is
+set) and Unix socket (when `socket_dir` is set). For convenience, `uzbl` can
+also be instructed to read commands from a file on startup by using the
+`--config` option. Indeed, the config file is nothing more than a list of
+commands.
+
+Each command starts with the name of a command or a `uzbl` variable that expands
+to it. A command is terminated by a newline. Empty lines and lines that start
+with the hash sign are ignored by the parser. Command names are always written
+in lowercase.
The following commands are recognized:
-* `set <key> = <value>`
- - used for changing variables on the fly
- - the changes are effective immediately; for example, setting the variable `uri` will make uzbl start loading, and changing `status_format` will make the status bar react immediately
- - if you want to unset a string, use `set` with one space after the equals sign
-* `print @<key>`
- - use this to print the value of a variable.
* `back`
+ - Navigate to the previous URI in the history.
* `forward`
+ - Navigate to the next URI in the history.
* `scroll <vertical|horizontal> <argument>`
- - argument can be `begin`, `end`, or an amount given in pixels(?)
- or as a percentage of the size of the view
- - set the amount to 100% to scroll a whole page
+ - argument can be `begin`, `end`, or an amount given in pixels(?) or as a
+ percentage of the size of the view
+ - set the amount to 100% to scroll a whole page
* `reload`
+ - Reload the current page.
* `reload_ign_cache`
+ - Reload the current page, discarding any cached resources.
* `stop`
+ - Stop loading the current page.
* `zoom_in`
+ - Increase the zoom level.
* `zoom_out`
+ - Decrease the zoom level.
+* `toggle_zoom_type`
+ - Toggles the variable `zoom_type` between "full-content" and "text-only"
+ zoom. In "text-only" zoom, only the text of the page is zoomed, while in
+ "full-content" zoom, images and other page elements are zoomed along with
+ the text.
* `uri <address>`
+ - Attempt to load `<address>`. This is equivalent to `set uri = <address>`.
* `js <body>`
- - execute the javascript in `<body>`
- - remember that the commands must not contain line breaks
+ - Execute the JavaScript in `<body>`.
+ - Remember that the commands must not contain line breaks.
* `script <file>`
- - execute the javascript in `<file>`
+ - Execute the JavaScript in `<file>`.
* `toggle_status`
+ - Toggle the display of the status bar.
* `spawn <executable> <additional args>` TODO explain path-alike expansion
- - runs a command; see EXTERNAL SCRIPTS for details
- - PATH is searched so giving the full path to commands is not necessary
- - note that the arguments as specified in "EXTERNAL SCRIPTS" are appended at the end, so the argument numbers will be higher.
-* `sh <command>`
- - runs a shell command by expanding `%s` in the `shell_cmd` variable with the specified command; primarily useful as a shortcut for `spawn sh -c <body>`
- - note that the arguments as specified in "EXTERNAL SCRIPTS" are appended at the end, so the argument numbers will be higher.
+ - Runs a command; see EXTERNAL SCRIPTS for details.
+ - `$PATH` is searched, so giving the full path to commands is not necessary.
+ - Note that the arguments as specified in "EXTERNAL SCRIPTS" are appended at
+ the end, so the argument numbers will be higher.
* `sync_spawn <executable> <additional args>`
+ - A synchronous variant of `spawn`, which means `uzbl` will wait for it to
+ return.
+ - You should only need to use this manually if you want to use a `chain`
+ command in a handler that wants output from the command it runs.
+* `sh <command>`
+ - Runs a shell command by expanding `%s` in the `shell_cmd` variable with the
+ specified command; primarily useful as a shortcut for `spawn sh -c
+ <command>`
+ - Note that the arguments as specified in "EXTERNAL SCRIPTS" are appended at
+ the end, so the argument numbers will be higher.
* `sync_sh <command>`
- - these are synchronous variants of `spawn` and `sh`, which means uzbl will wait for them to return
- - you should only need to use these manually if you want to use a chain command in a handler that wants output from the command it runs
-* `talk_to_socket <socketfile> <tokens/command>`
- - lets uzbl talk to a socketfile
+ - Synchronous version of `sh`, See `sync_spawn`.
+* `talk_to_socket <socketfile> <tokens>`
+ - Send a message to `<socketfile>` and wait for a response. `<tokens>` are
+ concatenated and separated by ASCII NUL bytes.
+ - Expects the socket type to be `SOCK_SEQPACKET` (see `connect(2)`).
+ - Waits for 500ms for a response.
* `exit`
+ - Closes `uzbl`.
* `search <string>`
+ - Search forward for `<string>`. With no string, search for the next
+ occurrence of the previously searched string.
* `search_reverse <string>`
- - search with no string will search for the next/previous occurrence of the string previously searched for
+ - Like `search`, but searches backward.
* `search_clear`
- - unmark and clear the search string
-* `toggle_insert_mode <optional state>` TODO new plugin based syntax
- - if the optional state is 0, disable insert mode. If 1, enable insert mode.
+ - Dehighlight matches and clear the search string.
+* `dehilight`
+ - Remove highlighting of search matches.
+* `set <key> = <value>`
+ - Sets `<key>` to `<value>`.
+ - The changes are effective immediately; for example, setting the variable
+ `uri` will make `uzbl` start loading, and changing `status_format` will make
+ the status bar react immediately.
+ - If you want to unset a string, use `set` with one space after the equals
+ sign.
* `dump_config`
- - dumps your current config (which may have been changed at runtime) to stdout, in a format you can use to pipe into uzbl again (or use as config file)
-* `keycmd <string>`
-* `keycmd_nl <string>`
- - keycmd sets the interactive command buffer to `<string>`. If the given string is a valid binding, it will execute. `Keycmd_nl` is like `keycmd`, but it also emulates a press of return, causing bindings with a parameter to execute. For example, `keycmd_nl o google.com` would load the said url if you have a binding like `bind o _ = uri %s`.
-* `keycmd_bs`
- - erase (backspace) one character from the command buffer
-* `chain <command> <command> ..`
- - use for chaining multiple commands
- - remember to quote the commands; one command must come as one parameter
- - if you use `chain` with a handler script which must return some output (such as a cookie handler -- uzbl will wait for and use its output), use sync_spawn or sync_sh instead of spawn or sh in the command that should give the output
+ - Dumps the current config (which may have been changed at runtime) to stdout.
+ - Uses a format which can be piped into `uzbl` again or saved as a config
+ file.
+* `dump_config_as_events`
+ - Dump the current config as a series of `VARIABLE_SET` events, which can be
+ handled by an event manager.
+* `chain <command> <command> ...`
+ - Used for chaining multiple commands.
+ - Remember to quote the commands; one command must come as one parameter.
+ - If you use `chain` with a handler script which must return some output (such
+ as a cookie handler -- `uzbl` will wait for and use its output), use
+ `sync_spawn` or `sync_sh` instead of `spawn` or `sh` in the command that
+ should give the output.
+* `print <string>`
+ - Expands variables in `<string>` and prints its output to stdout. Is useful
+ for getting the value of variables.
* `event <event_name> [event_details]`
- - send custom event
+ - Send a custom event.
* `request <request_name> [request_details]`
- - send custom request (same idea as events, but to be processed by EM, not uzbl-core)
-* `menu_add <label> = <uzbl command>`
-* `menu_link_add <label> = <uzbl command>`
-* `menu_image_add <label> = <uzbl command>`
-* `menu_editable_add <label> = <uzbl command>`
- - add a new entry "label" that will execute "uzbl command" to one of the right click context menus
-* `menu_separator <label>`
-* `menu_link_separator <label>`
-* `menu_image_separator <label>`
+ - Send a custom request (same idea as events, but to be processed by the event
+ manager, not `uzbl-core`).
+* `menu_add <label> = <command>`
+ - Add a new entry `<label>` to the default right-click menu that will execute
+ `<command>`.
+* `menu_link_add <label> = <command>`
+ - Add a new entry `<label>`, executing `<command>` to the right-click menu for
+ links.
+* `menu_image_add <label> = <command>`
+ - Same as `menu_add`, but for images.
+* `menu_editable_add <label> = <command>`
+ - Same as `menu_add`, but for editable text areas.
+* `menu_separator <label>`
+ - Add a separator, named `<label>` to the default right-click menu.
+* `menu_link_separator <label>`
+ - Same as `menu_separator`, but for links.
+* `menu_image_separator <label>`
+ - Same as `menu_separator`, but for images.
* `menu_editable_separator <label>`
- - adds a separator line to one of the right click context menus
-* `menu_remove <label>`
-* `menu_link_remove <label>`
-* `menu_image_remove <label>`
+ - Same as `menu_separator`, but for editable text areas.
+* `menu_remove <label>`
+ - Removes the menu entry `<label>` from the default right-click menu.
+* `menu_link_remove <label>`
+ - Same as `menu_remove`, but for links.
+* `menu_image_remove <label>`
+ - Same as `menu_remove`, but for images.
* `menu_editable_remove <label>`
- - removes the entry "label" from one of the right click context menus
+ - Same as `menu_remove`, but for editable text areas.
* `hardcopy`
- - open print dialog
+ - Open the print dialog.
* `include <file>`
- - read contents of file and interpret commands
-
+ - Read contents of `<file>` and interpret as a set of `uzbl` commands.
### VARIABLES AND CONSTANTS
-Uzbl has a lot of internal variables and constants. You can get the values (using the `print` command, see above), and for variables you can also change the value at
-runtime. Some of the values can be passed at start up through commandline arguments, others need to be set by using commands (eg in config file).
-Some of them have default values (see config.h)
-Some variables have callback functions which will get called after setting the variable to perform some additional logic (see below)
-
-Besides the builtin variables you can also define your own ones and use them in the exact same way as the builtin ones.
-
-* Variables:
- - `uri`: (callback: load the uri)
- - `verbose`: affects output on stdout
- - `inject_html`
- - `keycmd`: holds the input buffer (callback: update input buffer)
- - `status_message`: (callback: update title)
- - `show_status`: show statusbar or not
- - `status_top`: statusbar on top?
- - `status_format`: marked up, to be expanded string for statusbar (callback: update statusbar)
- - `status_pbar_done`: character to denote done % of pageload
- - `status_pbar_pending`: character to denote pending % of pageload
- - `status_pbar_width`: width of progressbar
- - `status_background`: color which can be used to override Gtk theme.
- - `insert_indicator`: string to denote insert mode TODO plugin variable
- - `command_indicator`: string to denote command mode TODO plugin variable
- - `title_format_long`: titlebar string when no statusbar shown (will be expanded
- - `title_format_short`: titlebar string when statusbar shown (will be expanded)
- - `icon`: path to icon for Gtk
- - `forward_keys`: whether uzbl-core should send key events to the webkit view
- - `insert_mode`: whether insert mode is active TODO explain plugin variable
- - `always_insert_mode`: set this to true if you don't like modal (vim-like) interfaces TODO explain plugin variable
- - `reset_command_mode`: automatically revert to command mode on pageload (unless always_insert_mode is set) TODO explain plugin variable
- - `modkey`: modkey which can be pressed to activate keybind from inside insert mode
- - `download_handler`
- - `cookie_handler`
- - `new_window`: handler to execute to invoke new uzbl window (TODO better name)
- - `scheme_handler`: handler to execute for each URI navigated to - the navigation request will be ignored if handler prints "USED\n"
- - `authentication_handler`: command that handles http authentication
- - `fifo_dir`: location to store fifo's
- - `socket_dir`: location to store sockets
- - `print_events`: show events on stdout
- - `http_debug`: http debug mode (value 0-3)
- - `shell_cmd`: alias which will be expanded to use shell commands (eg sh -c)
- - `proxy_url`: http traffic socks proxy (eg: http://<host>:<port>)
- - `max_conns`: max simultaneous connections (default: 100)
- - `max_conns_host`: max simultaneous connections per hostname (default: 6)
- - `useragent`: to be expanded string
- - `zoom_level`
- - `font_size`
- - `monospace_size`
- - `minimum_font_size`
- - `disable_plugins` (TODO rename to enable)
- - `disable_scripts` (TODO rename to enable)
- - `autoload_images`
- - `autoshrink_images`: shrink images to window size (default 0)
- - `enable_spellcheck`
- - `enable_private`
- - `print_backgrounds`: print background images? (default 0)
- - `stylesheet_uri`: use this to override the pagelayout with a custom stylesheet
- - `resizable_text_areas`
- - `default_encoding`: iso-8859-1 by default
- - `enforce_96_dpi`: 1 by default
- - `caret_browsing`
- - `default_font_family` = sans-serif
- - `monospace_font_family` = monospace (example "Aerial Mono" )
- - `cursive_font_family` = sans
- - `fantasy_font_family` = "Pterra"
- - `serif_font_family` = serif (example "DejaVu Serif")
- - `sans_serif_font_family` = sans (example "DejaVu Sans")
- - `scrollbars_visible`: set to 1 to have GTK scrollbars if the document doesn't fit into the window (defaults to 0)
-
-
-* Constants (not dumpable or writeable):
- - WEBKIT_MAJOR: set at compile time
- - WEBKIT_MINOR: set at compile time
- - WEBKIT_MICRO: set at compile time
- - ARCH_UZBL: set at compile time
- - COMMIT: set at compile time
- - LOAD_PROGRESS
- - LOAD_PROGRESSBAR
- - TITLE
- - SELECTED_URI
- - MODE
- - NAME: name of the uzbl instance (TODO: can't we make this a variable?)
- * default: Xorg window id
- * overridable with cmdline arg
- * in GtkSocket mode, this is a random number to prevent name clashes
-
-
-### VARIABLE EXPANSION AND COMMAND/JAVA SCRIPT SUBSTITUTION
-
-Variable expansion works pretty much as known from shell interpreters (sh, bash, etc.). This means you can
-construct strings with uzbl variables in them and have uzbl replace the variable name with its contents.
-
-In order to let uzbl know what to expand you'll need to prepend @ to the variable name:
+
+Uzbl has a lot of internal variables and constants. You can get the values
+(using the `print` command, see above), and for variables you can also change
+the value at runtime. Some of the values can be passed at start up through
+commandline arguments, others need to be set by using commands (eg in config
+file).
+
+* Some of them have default values (see config.h)
+* Some variables have callback functions which will get called after setting the
+ variable to perform some additional logic (see below).
+* Besides the builtin variables you can also define your own ones and use them
+ in the exact same way as the builtin ones.
+
+#### Variables
+
+* `uri`: The URI of the current page. (callback: load the uri)
+* `verbose`: Controls the verbosity printed to `stdout`.
+* `inject_html`: Inject an HTML string, navigating to the URI "about:blank" and
+ rendering the HTML sting given.
+* `geometry`: Geometry and position of the Uzbl window. Format is
+ "<width>x<height>+<x-offset>+<y-offset>".
+* `keycmd`: Holds the input buffer (callback: update input buffer).
+* `show_status`: Show statusbar or not.
+* `status_top`: statusbar on top?
+* `status_format`: Marked up, to be expanded string for statusbar (callback:
+ update statusbar).
+* `status_background`: color which can be used to override Gtk theme.
+* `title_format_long`: titlebar string when no statusbar shown (will be
+ expanded).
+* `title_format_short`: titlebar string when statusbar shown (will be expanded).
+* `icon`: path to icon for Gtk.
+* `forward_keys`: Whether `uzbl-core` should send key events to the webkit view.
+* `download_handler`: Handler called when page requests a download. In addition
+ to the standard handler arguments, appends the following extra arguments:
+ - `url`: The URL of the item to be downloaded.
+ - `proxy`: (optional) The URL of an HTTP proxy.
+* `cookie_handler`: Handler called when the page requests a cookie to be
+ retrieved or set. Appends the following arguments to the standard handler
+ arguments.
+ - `op`: Either "GET" if the browser requests a cookie to be sent to the server
+ or "PUT" if the server requests the browser save a cookie.
+ - `scheme`: The request address scheme ("http" or "https").
+ - `host`: The host requesting the cookie.
+ - `path`: The request address path.
+ - `data`: The cookie data. Only included for "PUT" requests.
+* `new_window`: handler to execute to invoke new uzbl window (TODO better name)
+* `scheme_handler`: handler to execute for each URI navigated to - the
+ navigation request will be ignored if handler prints "USED\n"
+* `fifo_dir`: location to store FIFOs.
+* `socket_dir`: location to store sockets.
+* `http_debug`: HTTP debug mode (value 0-3).
+* `scrollbars_visible`: set to 1 to have GTK scrollbars if the document
+ doesn't fit into the window (defaults to 0)
+* `shell_cmd`: Alias which will be expanded to use shell commands (eg `sh -c`).
+* `print_events`: show events on stdout
+* `proxy_url`: HTTP traffic SOCKS proxy (eg: `http://<host>:<port>`).
+* `max_conns`: Max simultaneous connections (default: 100).
+* `max_conns_host`: max simultaneous connections per hostname (default: 6)
+* `view_source`: Set the browser in "view source" mode (default 0). Any URI
+ visited while "view_source" is 1 will display the page source rather than the
+ rendered content.
+* `useragent`: The User-Agent to send to the browser, expands variables in its
+ definition.
+* `zoom_level`: The factor by which elements in the page are scaled with respect
+ to their original size. Setting this will resize the currently displayed page.
+* `zoom_type`: Whether to use "full-content" zoom (defaults to true). With
+ full-content zoom on, all page content, not just text, is zoomed. When
+ full-content zoom is off, only the text of a page is zoomed.
+* `font_size`: The default font size.
+* `default_font_family`: The default font family used to display text.
+* `monospace_font_family`: The default font family used to display monospace
+ text.
+* `cursive_font_family`: The default Cursive font family used to display text.
+* `sans_serif_font_family`: The default Sans Serif font family used to display
+ text.
+* `serif_font_family`: The default Serif font family used to display text.
+* `fantasy_font_family`: The default Fantasy font family used to display text.
+* `monospace_size`: The default size of monospaced font (default 1).
+* `minimum_font_size`: The minimum font size used to display text (default 1).
+* `disable_plugins`: Disable embedded plugin objects (default 0).
+* `disable_scripts`: Disable embedded scripting languages (default 0).
+* `autoload_images`: Automatically load images (default 1).
+* `autoshrink_images`: Shrink images to window size (default 0).
+* `enable_spellcheck`: Whether to enable spell checking while typing (default
+ 0).
+* `enable_private`: Whether to enable private browsing mode (default 0).
+* `print_backgrounds`: Print background images? (default 0).
+* `stylesheet_uri`: Use this to override the pagelayout with a custom
+ stylesheet.
+* `resizable_text_areas`: Whether text areas can be resized (default 0).
+* `default_encoding`: The default text encoding (default "iso-8859-1").
+* `enforce_96_dpi`: Enforce a resolution of 96 DPI (default 1).
+* `caret_browsing`: Whether the caret is enabled in the text portion of pages
+ (default 0).
+* `follow_hint_keys`: keys for keyboard-based navigation and link
+ highlighting
+
+#### Constants (not dumpable or writeable)
+
+* `WEBKIT_MAJOR`: WebKit major version number, set at compile time.
+* `WEBKIT_MINOR`: WebKit minor version number, set at compile time.
+* `WEBKIT_MICRO`: WebKit micro version number, set at compile time
+* `ARCH_UZBL`: Processor architecture for which Uzbl is compiled, set at compile
+ time.
+* `COMMIT`: ID of the current Git commit, set at compile time.
+* `TITLE`: The current page title or "(no title)" if no title exists for the
+ current page.
+* `SELECTED_URI`: The URL currently hovered over by the mouse.
+* `NAME`: name of the uzbl instance (TODO: can't we make this a variable?)
+ - default: Xorg window id
+ - overridable with cmdline arg
+ - in GtkSocket mode, this is a random number to prevent name clashes
+* `PID`: The process ID of this Uzbl instance.
+
+### VARIABLE EXPANSION AND COMMAND / JAVASCRIPT SUBSTITUTION
+
+Variable expansion works pretty much as known from shell interpreters (sh, bash,
+etc.). This means you can construct strings with uzbl variables in them and have
+uzbl replace the variable name with its contents.
+
+In order to let uzbl know what to expand you'll need to prepend @ to the
+variable name:
print The variable \@show_status contains @show_status
The above example demonstrates two things:
- * '\' is treated as escape character and will use the character immediately following it literally
- this means '\@show_status' will not expand to the variable content but be rather printed as
- '@show_status'
-
- * prepending the variable with '@' will expand to its contents
-
- * like in the shell you can use @{uzbl_var} to denote the beginning/end of the variable name in
- cases where it is not obvious what belongs to the name and what not.
- E.g.: print @{show_status}foobar
+* `\` is treated as escape character and will use the character immediately
+ following it literally this means `\@show_status` will not expand to the
+ variable content but be rather printed as `@show_status`
+* prepending the variable with `@` will expand to its contents
+* like in the shell you can use `@{uzbl_var}` to denote the beginning/end of the
+ variable name in cases where it is not obvious what belongs to the name and
+ what not. E.g. `print @{show_status}foobar`
+Command substitution will launch any commands and substitute the call with the
+return value of the command. There are two methods:
-Command substitution will launch any commands and substitute the call with the return value of the command.
-There are two methods:
-
- * through a shell: enclose commands with @( )@ (quotes escaping is handled by uzbl):
+* Through a shell: enclose commands with `@( )@` (quote escaping is handled by
+ Uzbl):
print Command substitution: @(uname -a)@
-This method allows you to use posix shell syntax in your commands
+This method allows you to use POSIX shell syntax in your commands.
- * directly:
+* directly:
- print Command substitution: @(+uname -a)@
+ print Command substitution: @(+uname -a)@
-This example will execute uname directly
+This example will execute uname directly.
-Note that you can access any uzbl variable from within a command substitution:
+Note that you can access any `uzbl` variable from within a command substitution:
print @(echo -n 'Accessing the show_status var from an external script, value: @show_status')@
-
-Java script substitution works in the exact same way as command substitution but you will need to enclose
-the java script in @< >@.
+JavaScript substitution works in the exact same way as command substitution but
+you will need to enclose the JavaScript in `@< >@`.
print The currently viewed document contains @<document.links.length>@ links
-The @<>@ substitution can also load JavaScript from a file, syntax: @<+filename>@
+The `@<>@` substitution can also load JavaScript from a file, syntax: `@<+filename>@`
print JS return value from file: @<+/path/to/file.js>@
-Variable expansion also works within a java script substitution.
-
+Variable expansion also works within a JavaScript substitution.
When a piece of text needs to be XML escaped after it is expanded (for example,
-in the status bar format), you can use @[ ]@ substitution:
+in the status bar format), you can use `@[ ]@` substitution:
print This text is XML escaped: @[<&>]@
# prints: This text is XML escaped: <&>
-
-NOTE: If you need to use literal @ or \ characters you will need to escape them:
+NOTE: If you need to use literal `@` or `\` characters you will need to escape
+them:
print At sign: \@ and backslash: \\
-
### TITLE AND STATUS BAR EVALUATION
-The contents of the status bar can be customized by setting the status_format
+The contents of the status bar can be customized by setting the `status_format`
variable. The contents of the window title can be customized by setting the
-title_format_short variable (which is used when the status bar is displayed) and
-the title_format_long variable (which is used when the status bar is not
+`title_format_short` variable (which is used when the status bar is displayed)
+and the `title_format_long` variable (which is used when the status bar is not
displayed). Their values can be set using the expansion and substitution
techniques described above.
@@ -347,55 +462,56 @@ that should be evaluated on every update need to be escaped:
set title_format_short = \\\@(date)\\\@
# the title will stay constant as a literal "@(date)@"
-The status_format variable can contain Pango markup (see
-<http://library.gnome.org/devel/pango/stable/PangoMarkupFormat.html>). In the
-status_format, variables that might contain characters like '<', '&' and '>',
-should be wrapped in a @[]@ substitution so that they don't interfere with the
-status bar's markup; see the example config for examples.
-
+The `status_format` variable can contain
+[Pango](http://library.gnome.org/devel/pango/stable/PangoMarkupFormat.html)
+markup . In the `status_format`, variables that might contain characters like
+`<`, `&` and `>`, should be wrapped in a `@[ ]@` substitution so that they don't
+interfere with the status bar's markup; see the sample config for examples.
### EXTERNAL SCRIPTS
-You can use external scripts with uzbl the following ways:
-
-* let uzbl call them. these scripts are called handlers in the uzbl config. used for handling logging history, handling a new download,..
-* call them yourself from inside uzbl. you can bind keys for this. examples: add new bookmark, load new url,..
-* You could also use xbindkeys or your WM config to trigger scripts if uzbl does not have focus
-Have a look at the sample configs and scripts!
+You can use external scripts with Uzbl the following ways:
-Handler scripts that are called by uzbl are passed the following arguments:
+* Let `uzbl` call them. These scripts are called "handlers" in the `uzbl`
+ config. Used for handling cookies, starting a new download, and more.
+* Call them yourself from inside `uzbl`. You can bind keys for this. Examples:
+ add new bookmark, load new URL.
+* You could also use `xbindkeys` or your WM config to trigger scripts if `uzbl`
+ does not have focus.
- $1 uzbl-config-file
- $2 uzbl-pid
- $3 uzbl-x-window-id
- $4 uzbl_fifo-filename
- $5 uzbl_socket-filename
- $6 current page url
- $7 current page title
- .. [ script specific ] (optional)
+Have a look at the sample configs and scripts!
-The script specific arguments are this:
+Handler scripts that are called by `uzbl` are passed the following arguments:
-* add bookmark:
+* `$1 config`: The configuration file loaded by this `uzbl` instance.
+* `$2 pid`: The process ID of this `uzbl` instance.
+* `$3 x_id`: The X Windows ID of the process.
+* `$4 fifo`: The filename of the FIFO being used, if any.
+* `$5 socket`: The filename of the Unix socket being used, if any.
+* `$6 uri`: The URI of the current page.
+* `$7 title`: The current page title.
+* `.. [ script specific ] (optional)`
- none
+The script specific arguments are:
-* download:
+* download
- $8 url of item to download
- $9 url of http proxy (optional)
+ - `$8 url`: The URL of the item to be downloaded.
+ - `$9 proxy`: (optional) The URL of an HTTP proxy.
* cookie handler
- $8 GET/PUT
- $9 request address scheme (e.g. http or https)
- $10 request address host (if current page url is www.foo.com/somepage, this could be something else than foo, eg advertising from another host)
- $11 request address path
- $12 cookie (only with PUT requests)
+ - `$8 GET/PUT`: Whether a cookie should be sent to the server (`GET`) or
+ stored by the browser (`PUT`).
+ - `$9 scheme`: Either `http` or `https`.
+ - `$10 host`: If current page URL is `www.example.com/somepage`, this could be
+ something else than `example.com`, eg advertising from another host.
+ - `$11 path`: The request address path.
+ - `$12 data`: The cookie data. Only included for `PUT` requests.
-* scheme handler:
+* scheme handler
- $8 URI of the page to be navigated to
+ - `$8 URI` of the page to be navigated to
* authentication handler:
@@ -404,37 +520,33 @@ The script specific arguments are this:
$10 authentication realm
$11 FALSE if this is the first attempt to authenticate, TRUE otherwise
-Custom, userdefined scripts (`spawn foo bar`) get first the arguments as specified in the config and then the above 7 are added at the end.
-
-### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
-
-Javascript code run from uzbl is given a special object in the global namespace which gives special privileges to these scripts. This object is called `Uzbl`, and it is added and removed before and after the script execution so that it is hidden to web javascripts (There is no race condition, since all the javascript code runs in a single thread)
-
-Currently, the `Uzbl` object provides only one function:
-
-* `Uzbl.run( <command> )`
- - command is any uzbl command as defined above
- - return value: a string, either empty or containing the output of the command. Very few commands return their output currently, including js, script, and print.
- - Examples:
- * `Uzbl.run("spawn insert_bookmark.sh")`
- * `uri = Uzbl.run("print @uri")` (see variable expansion below)
+Custom, userdefined scripts (`spawn foo bar`) get first the arguments as
+specified in the config and then the above 7 are added at the end.
-### AUTHENTICATION ###
+### HTTP/BASIC AUTHENTICATION ###
-If authentication_handler variable is not set, http authentication is handled internally by WebKit. If you want to use custom script for http authentication, set authentication_handler. For example:
+If authentication_handler variable is not set, http authentication is handled
+internally by WebKit. If you want to use custom script for http authentication,
+set authentication_handler. For example:
set authentication_handler = sync_spawn /patch/to/your/script
-Script will be executed on each authentication request. It will receive four auth-related parameters:
-
- $8 authentication zone unique identifier (may be used as hash key in passwords database)
+Script will be executed on each authentication request.
+It will receive four auth-related parameters:
+
+ $8 authentication zone unique identifier (may be used as 'key')
$9 domain part of URL that requests authentication
$10 authentication realm
$11 FALSE if this is the first attempt to authenticate, TRUE otherwise
-Script is expected to print exactly two lines of text on stdout (that means its output must contain exactly two '\n' bytes). The first line contains username, the second one - password.
-If authentication fail, script will be executed again (with $11 = TRUE). Non-interactive scripts should handle this case and do not try to authenticate again to avoid loops.
-If number of '\n' characters in scripts output does not equal 2, authentication will fail. That means 401 error will be displayed and uzbl won't try to authenticate anymore.
+Script is expected to print exactly two lines of text on stdout (that means
+its output must contain exactly two '\n' bytes).
+The first line contains username, the second one - password.
+If authentication fails, script will be executed again (with $11 = TRUE).
+Non-interactive scripts should handle this case and do not try to
+authenticate again to avoid loops. If number of '\n' characters in scripts
+output does not equal 2, authentication will fail.
+That means 401 error will be displayed and uzbl won't try to authenticate anymore.
The simplest example of authentication handler script is:
@@ -443,124 +555,219 @@ The simplest example of authentication handler script is:
echo alice
echo wonderland
-This script tries to authenticate as user alice with password wonderland once and never retries authentication. See examples for more sofisticated, interactive authentication handler.
+This script tries to authenticate as user alice with password wonderland once
+and never retries authentication.
+See examples for more sofisticated, interactive authentication handler.
-### EVENTS ###
+### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
-Unlike commands, events are not handled in uzbl itself, but are propagated (dispatched) asynchronously through
-a text stream on stdout and/or through a socket. You'll usually use uzbl by piping it's output to a so called 'event manager'
-or by having the EM listen to a socket.
-- makes it possible to use whichever language you want for event handling (python, perl, bash, .. you name it).
- you'll usually send commands (see above) back to uzbl through its fifo or socket
-- keybindings use x keysyms
-- many finegrained events (hover_over_link, key_press, key_down,..)
-- see example event_handler.py
+JavaScript code run from `uzbl` is given a special object in the global
+namespace which gives special privileges to these scripts. This object is called
+`Uzbl`, and it is added and removed before and after the script execution so
+that it is hidden to web JavaScript code (there is no race condition, since all
+the JavaScript code runs in a single thread).
-Note: cookie events are not sent to an event handler but handled internally through the cookie handler because of their synchronous nature.
-Cookie events are really something completely different from all other events. Maybe someday we'll use HTTP proxies or something for cookies
-or synchronous events (which also have other nice use cases), but for now we still use the handler code)
+Currently, the `Uzbl` object provides only one function:
-Basically all events have this format:
+* `Uzbl.run( <command> )`
+ - Command is any `uzbl` command as defined above.
+ - Return value: a string, either empty or containing the output of the
+ command. Very few commands return their output currently, including `js`,
+ `script`, and `print`.
+ - Examples:
+ * `Uzbl.run("spawn insert_bookmark.sh")`
+ * `uri = Uzbl.run("print @uri")` (see variable expansion below)
+
+### EVENTS
+
+Unlike commands, events are not handled in `uzbl` itself, but are propagated
+(dispatched) asynchronously through a text stream on `stdout` and/or through a
+socket. You'll usually use uzbl by piping it's output to a so-called "event
+manager" (EM), or by having the EM listen to a socket.
+
+The EM allows:
+
+* Use of whichever language you want for event handling (Python, Perl, Bash,
+ ... you name it). You'll usually send commands (see above) back to `uzbl`
+ through its FIFO or socket.
+* Keybindings use X keysyms.
+* Many fine-grained events (`hover_over_link`, `key_press`, `key_release`,..)
+* See example `uzbl-event-manager`.
+
+**Note**: Cookie events are not sent to an event handler but handled internally
+ through the cookie handler because of their synchronous nature. Cookie events
+ are really something completely different from all other events. Maybe someday
+ we'll use HTTP proxies or synchronous events (which also have other nice use
+ cases), but for now we still use the handler code.
+
+Events have this format:
EVENT [uzbl_instance_name] EVENT_NAME event_details
+#### Reported events
+
+* `EVENT [uzbl_instance_name] INSTANCE_START process_id`: `uzbl` startup.
+* `EVENT [uzbl_instance_name] INSTANCE_EXIT process_id`: `uzbl` shutdown
+* `EVENT [uzbl_instance_name] VARIABLE_SET variable_name str|int|float
+ variable_value`: Note: `str|int|float` denote the type of `variable_value`.
+* `EVENT [uzbl_instance_name] COMMAND_EXECUTED command_name optional_arguments`:
+ A command is executed.
+* `EVENT [uzbl_instance_name] COMMAND_ERROR command_name`: Tried to execute the
+ command `command_name`, but it does not exist.
+* `EVENT [uzbl_instance_name] GEOMETRY_CHANGED
+ WIDTHxHEIGHT+X_POSITION+Y_POSITION`: When the size or position of the `uzbl`
+ window changes.
+* `EVENT [uzbl_instance_name] FIFO_SET path_to_fifo`: The path to the FIFO is
+ set.
+* `EVENT [uzbl_instance_name] SOCKET_SET path_to_socket`: The path to the socket
+ is set.
+* `EVENT [uzbl_instance_name] LOAD_COMMIT uri`: The first data of a page has
+ loaded. `uri` is the URI of the page being loaded.
+* `EVENT [uzbl_instance_name] LOAD_START uri`: A change of the page has been
+ requested. `uri` is the current URI; the one being departed.
+* `EVENT [uzbl_instance_name] LOAD_FINISHED uri`: Loading has finished for the
+ page at `uri`.
+* `EVENT [uzbl_instance_name] LOAD_ERROR uri reason_of_error`: The URI `uri`
+ could not be loaded for the reason described in `reason_of_error`.
+* `EVENT [uzbl_instance_name] LOAD_PROGRESS percentage` : While the page is
+ loading, gives the `percentage` of the page that has finished loading.
+* `EVENT [uzbl_instance_name] TITLE_CHANGED title_name`: When the title of the
+ page (and hence maybe, the window title) changed. `title_name` is the new
+ title.
+* `EVENT [uzbl_instance_name] DOWNLOAD_REQUEST download_uri`: When content needs
+ to be downloaded, `download_uri` is the URI to get.
+* `EVENT [uzbl_instance_name] LINK_HOVER uri`: The mouse hovers over the link
+ `uri`.
+* `EVENT [uzbl_instance_name] LINK_UNHOVER uri`: The mouse leaves the link
+ `uri`.
+* `EVENT [uzbl_instance_name] KEY_PRESS key_name`: The key (or mouse button)
+ `key_name` is pressed.
+* `EVENT [uzbl_instance_name] KEY_RELEASE key_name`: The key (or mouse button)
+ `key_name` is released.
+* `EVENT [uzbl_instance_name] SELECTION_CHANGED selected_text`: When text is
+ selected in the `uzbl` window.
+* `EVENT [uzbl_instance_name] NEW_WINDOW uri`: Creation of new `uzbl` window,
+ with URI `uri`.
+* `EVENT [uzbl_instance_name] WEBINSPECTOR open`: Upon opening webinspector
+ window.
+* `EVENT [uzbl_instance_name] WEBINSPECTOR close`: Upon closing webinspector
+ window.
+* `EVENT [uzbl_instance_name] FOCUS_GAINED`: When `uzbl` window gains keyboard
+ focus.
+* `EVENT [uzbl_instance_name] FOCUS_LOST`: When `uzbl` window loses keyboard
+ focus.
+* `EVENT [uzbl_instance_name] FORM_ACTIVE`: When an editable HTML is clicked.
+* `EVENT [uzbl_instance_name] ROOT_ACTIVE`: When the document body or any
+ non-editable element is clicked.
+* `EVENT [uzbl_instance_name] FILE_INCLUDED filename`: When the `include`
+ commands successfully loads a file, given by `filename`.
+* `EVENT [uzbl_instance_name] PLUG_CREATED plug_id`: When `uzbl-core` is in
+ Xembed mode, `plug_id` is the Xembed ID used.
+* `EVENT [uzbl_instance_name] BUILTINS command_list`: Shows a list of all `uzbl`
+ commands, whitespace separated, on startup.
+
+Events/requests which the EM and its plugins listens for
+
+* `BIND` and `MODE_BIND`: Define global and per-mode key/button binds.
+ - `request BIND <keycmd> = <command>` Set global binding (this is a shortcut
+ for `request MODE_BIND global <keycmd> = <command>`).
+ - `request MODE_BIND <modespec> <keycmd> = <command>` Set a local binding for
+ `<modespec>`. The `<modespec>` can be anything like `command`,
+ `insert,command`, `global`, `global,-insert`.
+
+ The `<keycmd>` has a special syntax:
+ - `<keycmd>` ends with a `_`: the command will only be invoked after pressing
+ return/enter. If the user enters text where `<string>` has the underscore,
+ `%s` in the `<command>` string will be replaced by this text (optional).
+ - `<keycmd>` ends with a `*`: similar behavior as with an underscore, but also
+ makes the binding incremental (i.e. the command will be invoked on every
+ keystroke).
+ - `<keycmd>` ends with a `!`: the command will only be invoked after pressing
+ return/enter, no replacement happens. this is useful for preventing `x` to
+ match when you want to bind `xx` also.
+ - `<keycmd>` ends on a different character: you need to type the full string,
+ which will trigger the command immediately, without pressing enter/return.
+ - TODO explain stacked bindings and multi-stage (is that the same?) and what
+ else am i missing? modkeys, showing a prompt mid-bind.
+
+ The `<keycmd>` can be any representation of a key on your keyboard or a
+ mousebutton. (note: not all mousebuttons work correctly yet). Examples:
+
+ - `event BIND o _ = uri %s`
+ - `uzbl` will load the url when you type: `o <url><enter>`
+ - `event BIND /* = search %s`
+ - A `search` command which is called on every character typed after the slash,
+ letting you see the search narrow down while typing.
+ - Hitting return, enter or esc will terminate the search.
+ - `event BIND ZZ = exit`
+ - When you type `ZZ` and nothing else, the `exit` command will be triggered
+ immediately.
+* `MODE_CONFIG`: Set mode specific configs. If the mode being modified is the
+ current mode then apply the changes immediately.
+ - `request MODE_CONFIG <mode> <key> = <value>`
+* `ON_EVENT`: Execute a command when a given event is fired.
+ - `request ON_EVENT <EVENT_NAME> <command>`
+* `PROGRESS_CONFIG`: Set a configuration option for `LOAD_PROGRESS` updates.
+ - `request PROGRESS_CONFIG <key> = <value>`: Set progress config variable
+ `key` to `value`.
+* `MODMAP`: Set an alternate name for a key or button.
+ - `request MODMAP <from> <to>`: Create an alias `<to>` for key command
+ `<from>`. This allows `<to>` to be bound to a command, which will be invoked
+ when the `<from>` key or button is pressed.
+* `IGNORE_KEY`: Ignore a key pattern, specified by `<glob>`.
+ - `request IGNORE_KEY <glob>`
+* `MODKEY_ADDITION`: Create a compound modkey from multiple individual keys.
+ - `request MODKEY_ADDITION <key1> <key2> <keyn> <result>`: The modkey
+ `<result>` is considered pressed when all of `<key1>`, `<key2>`, and
+ `<keyn>` are pressed.
+* `TOGGLE_MODES`
+ - `request TOGGLE_MODES <mode1> <mode2> ... <moden>`
+* `APPEND_KEYCMD`: Append a string to the current keycmd.
+ - `request APPEND_KEYCMD <string>`: Append `<string>` to the current keycmd.
+* `INJECT_KEYCMD`: Injecting a string into the keycmd at the cursor position.
+ - `request INJECT_KEYCMD <string>`: Inject `<string>` into the keycmd at the
+ current cursor position.
+* `KEYCMD_DELETE`: Removes the character after the cursor position in the
+ keycmd.
+* `KEYCMD_STRIP_WORD`: Removes the last word from the keycmd, similar to
+ readline `^W`.
+* `KEYCMD_EXEC_CURRENT`: (tries to) execute whatever is in the keycmd.
+* `SET_KEYCMD`: Allow setting of the keycmd externally.
+ - `request SET_KEYCMD <string>`: Set the keycmd to `<string>`.
+* `SET_CURSOR_POS`: Allow setting of the cursor position externally.
+ - `request SET_CURSOR_POS <index>`: Set the keycmd cursor to `<index>`. If
+ `<index>` is `+`, advance the cursor by one character, and if it is `-`,
+ move the cursor back by one character.
+* `START_COMPLETION`: TODO explain completion
-* Reported events:
- - `EVENT [uzbl_instance_name] INSTANCE_START process_id`: uzbl startup
- - `EVENT [uzbl_instance_name] INSTANCE_EXIT process_id`: uzbl shutdown
- - `EVENT [uzbl_instance_name] VARIABLE_SET variable_name str|int|float variable_value`. Note: str|int|float denote the type of variable_value
- - `EVENT [uzbl_instance_name] COMMAND_EXECUTED command_name optional_command_arguments`
- - `EVENT [uzbl_instance_name] COMMAND_ERROR command`
- - `EVENT [uzbl_instance_name] GEOMETRY_CHANGED WIDTHxHEIGHT+X_POSITION+Y_POSITION`: when the size or position of the uzbl window changes
- - `EVENT [uzbl_instance_name] FIFO_SET path_to_fifo`
- - `EVENT [uzbl_instance_name] SOCKET_SET path_to_socket`
- - `EVENT [uzbl_instance_name] LOAD_COMMIT uri`
- - `EVENT [uzbl_instance_name] LOAD_START uri`
- - `EVENT [uzbl_instance_name] LOAD_FINISHED uri`
- - `EVENT [uzbl_instance_name] LOAD_ERROR reason_of_error`
- - `EVENT [uzbl_instance_name] LOAD_PROGRESS percentage` : while the page is loading
- - `EVENT [uzbl_instance_name] TITLE_CHANGED title_name`: when the title of the webpage (and hence maybe, the window title) changed
- - `EVENT [uzbl_instance_name] DOWNLOAD_REQUEST download_uri`: when content needs to be downloaded
- - `EVENT [uzbl_instance_name] LINK_HOVER uri`: mouse hovers over a link
- - `EVENT [uzbl_instance_name] LINK_UNHOVER uri`: same but unhover.
- - `EVENT [uzbl_instance_name] KEY_PRESS key_name`: press of a keyboard key or mouse button
- - `EVENT [uzbl_instance_name] KEY_RELEASE key_name`: release of keyboard key or mouse button
- - `EVENT [uzbl_instance_name] SELECTION_CHANGED selected_text`: when you select text inside the uzbl window
- - `EVENT [uzbl_instance_name] NEW_WINDOW uri`: creation of new uzbl window
- - `EVENT [uzbl_instance_name] WEBINSPECTOR open`: upon opening webinspector window
- - `EVENT [uzbl_instance_name] WEBINSPECTOR close`: upon closing webinspector window
- - `EVENT [uzbl_instance_name] FOCUS_GAINED`: when uzbl window gained keyboard focus
- - `EVENT [uzbl_instance_name] FOCUS_LOST`: when uzbl window lost keyboard focus
- - `EVENT [uzbl_instance_name] FORM_ACTIVE`: when a editable HTML is clicked
- - `EVENT [uzbl_instance_name] ROOT_ACTIVE`: when the document body or any non-editable element is clicked
- - `EVENT [uzbl_instance_name] FILE_INCLUDED /path/to/file`: when the include commands succesfully loads a file
- - `EVENT [uzbl_instance_name] PLUG_CREATED plug-id`: when uzbl-core is in xembed mode
- - `EVENT [uzbl_instance_name] BUILTINS command_list`: shows a list of all uzbl commands, whitespace separated, on startup
-
-* Events/requests which the EM and its plugins listens for:
- - `BIND` and `MODE_BIND`: define global resp. per-mode key/button binds.
- `request BIND <keycmd> = <command>` # set global binding (this is a shortcut for `request MODE_BIND global <keycmd> = <command>`)
- `request MODE_BIND <modespec> <keycmd> = <command>`
- The `<modespec>` can be anything like 'command', 'insert,command', 'global', 'global,-insert'.
- The `<keycmd>` has a special syntax:
- * `<keycmd>` ends with an underscore: the command will only be invoked after pressing return/enter. If the user enters text where `<string>` has the underscore, `%s` in the `<command>` string will be replaced by this text. (optional)
- * `<keycmd>` ends with an asterisk: similar behavior as with an underscore, but also makes the binding incremental (i.e. the command will be invoked on every keystroke).
- * `<keycmd>` ends with an '!': the command will only be invoked after pressing return/enter, no replacement happens. this is useful for preventing 'x' to match when you want to bind 'xx' also.
- * `<keycmd>` ends on a different character: you need to type the full string, which will trigger the command immediately, without pressing enter/return.
- * TODO explain stacked bindings and multi-stage (is that the same?) and what else am i missing? modkeys, showing a prompt mid-bind.
- The `<keycmd>` can be any representation of a key on your keyboard or a mousebutton. (note: not all mousebuttons work correctly yet)
- examples:
- * `event BIND o _ = uri %s`
- - uzbl will load the url when you type: 'o <url><enter>'
- * `event BIND /* = search %s`
- - a search command which is called on every character typed after the slash, letting you see the search narrow down while typing.
- - Hitting return, enter or esc will terminate the search.
- * `event BIND ZZ = exit`
- - When you type `ZZ` and nothing else, the exit command will be triggered immediately.
- - `MODE_CONFIG`: ??
- request MODE_CONFIG <mode> <key> = <value
- - `ON_EVENT`: allows you to bind misc commands to misc events
- request ON_EVENT <EVENT_NAME> <command>
- - `PROGRESS_CONFIG`
- request PROGRESS_CONFIG <key> = <value>
- - `MODMAD`
- request MODMAP From To
- - `IGNORE_KEY`
- request IGNORE_KEY <glob>
- - `MODKEY_ADDITION`
- request MODKEY_ADDITION <key1> <key2> <keyn> <result>
- - `TOGGLE_MODES`
- event TOGGLE_MODES <mode1> <mode2> ... <moden>
- - `APPEND_KEYCMD`: append `<string> to keycmd
- - `INJECT_KEYCMD <string>`: replace keycmd by `<string>`
- - `KEYCMD_DELETE`
- - `KEYCMD_STRIP_WORD`
- - `KEYCMD_EXEC_CURRENT`: (tries to) execute whatever is in the keycmd
- - `SET_KEYCMD`
- - `SET_CURSOR_POS`
- - `START_COMPLETION`: TODO explain completion
+### COMMAND LINE ARGUMENTS
+`uzbl` is invoked as
+ uzbl-(core|browser|tabbed) [ arguments ] [ uri ]
-### COMMAND LINE ARGUMENTS
- uzbl-core [OPTION...] [ uri ]
- -u, --uri=URI Uri to load at startup (equivalent to 'uzbl <uri>' or 'set uri = URI' after uzbl has launched)
- -v, --verbose Whether to print all messages or just errors.
- -n, --name=NAME Name of the current instance (defaults to Xorg window id or random for GtkSocket mode)
- -c, --config=FILE Path to config file or '-' for stdin
- -s, --socket=SOCKET Socket ID
- --connect-socket=CSOCKET Connect to server socket
- -p, --print-events Whether to print events to stdout
- -g, --geometry=GEOMETRY Set window geometry (format: WIDTHxHEIGHT+-X+-Y or maximized)
- -V, --version Print the version and exit
- --display=DISPLAY X display to use
- --help Help
-
-uzbl scheme://address will work as you expect. If you don't provide the
-scheme:// part, it will check if the argument is an existing file in the
-filesystem: if it is, it will prepend file://, if not, it will
-prepend http://.
+where `arguments` and `uri` are both optional. `arguments` can be:
+* `-u`, `--uri=URI`: URI to load at startup. Equivalent to `uzbl <uri>` or `set
+ uri = URI` after `uzbl` has launched.
+* `-v`, `--verbose`: Whether to print all messages or just errors.
+* `-n`, `--name=NAME`: Name of the current instance (defaults to Xorg window
+ id or random for GtkSocket mode).
+* `-c`, `--config=FILE`: Path to config file or `-` for stdin.
+* `-s`, `--socket=SOCKET`: Xembed socket ID.
+* `--connect-socket=SOCKET`: Connect to server socket for event managing.
+* `-p`, `--print-events`: Whether to print events to stdout
+* `-g`, `--geometry=GEOMETRY`: Set window geometry (format: `WIDTHxHEIGHT+-X+-Y`
+ or `maximized`).
+* `-V`, `--version`: Print the version and exit.
+* `--display=DISPLAY`: X display to use.
+* `--help`: Display help.
+
+`uzbl-core scheme://address` will work as you expect. If you don't provide the
+`scheme://` part, it will check if the argument is an existing file in the
+filesystem, if it is, it will prepend `file://`, if not, it will prepend
+`http://`.
### BUGS
-Please report new issues @ uzbl.org/bugs
+
+Please report new issues to the [Uzbl bugtracker](http://uzbl.org/bugs).
diff --git a/examples/config/config b/examples/config/config
index 5dd0e720..929397df 100644
--- a/examples/config/config
+++ b/examples/config/config
@@ -293,9 +293,11 @@ set toggle_cmd_ins = @toggle_modes command insert
@cbind u = spawn @scripts_dir/load_url_from_bookmarks.sh
# --- Link following (similar to vimperator and konqueror) ---
-@cbind fl* = script @scripts_dir/follow_Numbers.js %s
-# Or number with strings instead of numbers:
-@cbind fL* = script @scripts_dir/follow_Numbers_Strings.js %s
+# Set custom keys you wish to use for navigation. Some common examples:
+set follow_hint_keys = qwerty
+#set follow_hint_keys = asdfghjkl;
+#set follow_hint_keys = thsnd-rcgmvwb/;789aefijkopquxyz234
+@cbind f* = script @scripts_dir/follow.js '%s @{follow_hint_keys}'
# --- Form filler binds ---
# this script allows you to configure (per domain) values to fill in form
diff --git a/examples/data/scripts/follow_Numbers.js b/examples/data/scripts/follow.js
similarity index 80%
rename from examples/data/scripts/follow_Numbers.js
rename to examples/data/scripts/follow.js
index 00b279e6..12b37655 100644
--- a/examples/data/scripts/follow_Numbers.js
+++ b/examples/data/scripts/follow.js
@@ -17,10 +17,6 @@ var doc = document;
var win = window;
var links = document.links;
var forms = document.forms;
-
-//Reset keycmd, modcmd and return to default mode.
-function clearKeycmd() { Uzbl.run('set mode ='); }
-
//Make onlick-links "clickable"
try {
HTMLElement.prototype.click = function() {
@@ -106,19 +102,21 @@ function generateHint(el, label) {
hint.style.fontWeight = 'bold';
hint.style.lineHeight = '9px';
hint.style.margin = '0px';
+ hint.style.width = 'auto'; // fix broken rendering on w3schools.com
hint.style.padding = '1px';
hint.style.position = 'absolute';
hint.style.zIndex = '1000';
+ // hint.style.textTransform = 'uppercase';
hint.style.left = pos[1] + 'px';
hint.style.top = pos[0] + 'px';
- var img = el.getElementsByTagName('img');
- if (img.length > 0) {
- hint.style.left = pos[1] + img[0].width / 2 + 'px';
- }
+ // var img = el.getElementsByTagName('img');
+ // if (img.length > 0) {
+ // hint.style.top = pos[1] + img[0].height / 2 - 6 + 'px';
+ // }
hint.style.textDecoration = 'none';
- hint.style.webkitBorderRadius = '6px';
+ // hint.style.webkitBorderRadius = '6px'; // slow
// Play around with this, pretty funny things to do :)
- hint.style.webkitTransform = 'scale(1) rotate(0deg) translate(-6px,-5px)';
+ // hint.style.webkitTransform = 'scale(1) rotate(0deg) translate(-6px,-5px)';
return hint;
}
//Here we choose what to do with an element if we
@@ -127,7 +125,6 @@ function generateHint(el, label) {
//but at least set the href of the link. (needs some improvements)
function clickElem(item) {
removeAllHints();
- clearKeycmd();
if (item) {
var name = item.tagName;
if (name == 'A') {
@@ -193,26 +190,66 @@ function reDrawHints(elems, chars) {
document.body.appendChild(hintdiv);
}
}
+// pass: number of keys
+// returns: key length
+function labelLength(n) {
+ var oldn = n;
+ var keylen = 0;
+ if(n < 2) {
+ return 1;
+ }
+ n -= 1; // our highest key will be n-1
+ while(n) {
+ keylen += 1;
+ n = Math.floor(n / charset.length);
+ }
+ return keylen;
+}
+// pass: number
+// returns: label
+function intToLabel(n) {
+ var label = '';
+ do {
+ label = charset.charAt(n % charset.length) + label;
+ n = Math.floor(n / charset.length);
+ } while(n);
+ return label;
+}
+// pass: label
+// returns: number
+function labelToInt(label) {
+ var n = 0;
+ var i;
+ for(i = 0; i < label.length; ++i) {
+ n *= charset.length;
+ n += charset.indexOf(label[i]);
+ }
+ return n;
+}
//Put it all together
function followLinks(follow) {
+ // if(follow.charAt(0) == 'l') {
+ // follow = follow.substr(1);
+ // charset = 'thsnlrcgfdbmwvz-/';
+ // }
var s = follow.split('');
- var linknr = parseInt(follow, 10);
+ var linknr = labelToInt(follow);
if (document.body) document.body.setAttribute('onkeyup', 'keyPressHandler(event)');
var linkelems = addLinks();
var formelems = addFormElems();
var elems = [linkelems[0].concat(formelems[0]), linkelems[1].concat(formelems[1])];
- var len = (elems[0].length + '').length;
+ var len = labelLength(elems[0].length);
var oldDiv = doc.getElementById(uzbldivid);
var leftover = [[], []];
- if (linknr + 1 && s.length == len && linknr < elems[0].length && linknr >= 0) {
+ if (s.length == len && linknr < elems[0].length && linknr >= 0) {
clickElem(elems[0][linknr]);
} else {
for (var j = 0; j < elems[0].length; j++) {
var b = true;
- var label = j + '';
+ var label = intToLabel(j);
var n = label.length;
for (n; n < len; n++) {
- label = '0' + label;
+ label = charset.charAt(0) + label;
}
for (var k = 0; k < s.length; k++) {
b = b && label.charAt(k) == s[k];
@@ -225,4 +262,9 @@ function followLinks(follow) {
reDrawHints(leftover, s.length);
}
}
-followLinks('%s');
+
+//Parse input: first argument is user input, second is defined hint keys.
+var args = '%s'.split(' ');
+var charset = args[1];
+
+followLinks(args[0]);
diff --git a/examples/data/scripts/follow_Numbers_Strings.js b/examples/data/scripts/follow_Numbers_Strings.js
deleted file mode 100644
index e50da5dc..00000000
--- a/examples/data/scripts/follow_Numbers_Strings.js
+++ /dev/null
@@ -1,212 +0,0 @@
-var uzblid = 'uzbl_link_hint';
-var uzbldivid = uzblid + '_div_container';
-var doc = document;
-var win = window;
-var links = document.links;
-var forms = document.forms;
-
-//Reset keycmd, modcmd and return to default mode.
-function clearKeycmd() { Uzbl.run('set mode ='); }
-
-try {
- HTMLElement.prototype.click = function() {
- if (typeof this.onclick == 'function') {
- this.onclick({
- type: 'click'
- });
- }
- };
-} catch(e) {}
-function keyPressHandler(e) {
- var kC = window.event ? event.keyCode: e.keyCode;
- var Esc = window.event ? 27 : e.DOM_VK_ESCAPE;
- if (kC == Esc) {
- removeAllHints();
- }
-}
-function elementPosition(el) {
- var up = el.offsetTop;
- var left = el.offsetLeft;
- var width = el.offsetWidth;
- var height = el.offsetHeight;
- while (el.offsetParent) {
- el = el.offsetParent;
- up += el.offsetTop;
- left += el.offsetLeft;
- }
- return [up, left, width, height];
-}
-function isVisible(el) {
- if (el == doc) {
- return true;
- }
- if (!el) {
- return false;
- }
- if (!el.parentNode) {
- return false;
- }
- if (el.style) {
- if (el.style.display == 'none') {
- return false;
- }
- if (el.style.visibility == 'hidden') {
- return false;
- }
- }
- return isVisible(el.parentNode);
-}
-function elementInViewport(el) {
- offset = elementPosition(el);
- var up = offset[0];
- var left = offset[1];
- var width = offset[2];
- var height = offset[3];
- return up < window.pageYOffset + window.innerHeight && left < window.pageXOffset + window.innerWidth && (up + height) > window.pageYOffset && (left + width) > window.pageXOffset;
-}
-function removeAllHints() {
- var elements = doc.getElementById(uzbldivid);
- if (elements) {
- elements.parentNode.removeChild(elements);
- }
-}
-function generateHint(el, label) {
- var pos = elementPosition(el);
- var hint = doc.createElement('div');
- hint.setAttribute('name', uzblid);
- hint.innerText = label;
- hint.style.display = 'inline';
- hint.style.backgroundColor = '#B9FF00';
- hint.style.border = '2px solid #4A6600';
- hint.style.color = 'black';
- hint.style.zIndex = '1000';
- hint.style.fontSize = '9px';
- hint.style.fontWeight = 'bold';
- hint.style.lineHeight = '9px';
- hint.style.margin = '0px';
- hint.style.padding = '1px';
- hint.style.position = 'absolute';
- hint.style.left = pos[1] + 'px';
- hint.style.top = pos[0] + 'px';
- var img = el.getElementsByTagName('img');
- if (img.length > 0) {
- hint.style.left = pos[1] + img[0].width / 2 + 'px';
- }
- hint.style.textDecoration = 'none';
- hint.style.webkitBorderRadius = '6px';
- hint.style.webkitTransform = 'scale(1) rotate(0deg) translate(-6px,-5px)';
- return hint;
-}
-
-function clickElem(item) {
- removeAllHints();
- clearKeycmd();
- if (item) {
- var name = item.tagName;
- if (name == 'A') {
- item.click();
- window.location = item.href;
- } else if (name == 'INPUT') {
- var type = item.getAttribute('type').toUpperCase();
- if (type == 'TEXT' || type == 'FILE' || type == 'PASSWORD') {
- item.focus();
- item.select();
- } else {
- item.click();
- }
- } else if (name == 'TEXTAREA' || name == 'SELECT') {
- item.focus();
- item.select();
- } else {
- item.click();
- window.location = item.href;
- }
- }
-}
-
-function addLinks() {
- res = [[], []];
- for (var l = 0; l < links.length; l++) {
- var li = links[l];
- if (isVisible(li) && elementInViewport(li)) {
- res[0].push(li);
- res[1].push(li.innerText.toLowerCase());
- }
- }
- return res;
-}
-function addFormElems() {
- res = [[], []];
- for (var f = 0; f < forms.length; f++) {
- for (var e = 0; e < forms[f].elements.length; e++) {
- var el = forms[f].elements[e];
- if (el && ['INPUT', 'TEXTAREA', 'SELECT'].indexOf(el.tagName) + 1 && isVisible(el) && elementInViewport(el)) {
- res[0].push(el);
- if (el.getAttribute('value')) {
- res[1].push(el.getAttribute('value').toLowerCase());
- } else {
- res[1].push(el.getAttribute('name').toLowerCase());
- }
- }
- }
- }
- return res;
-}
-function reDrawHints(elems, len) {
- var hintdiv = doc.createElement('div');
- hintdiv.setAttribute('id', uzbldivid);
- hintdiv.style.opacity = '0.0';
- for (var i = 0; i < elems[0].length; i++) {
- var label = i + '';
- var n = label.length;
- for (n; n < len; n++) {
- label = '0' + label;
- }
- if (elems[0][i]) {
- var h = generateHint(elems[0][i], label);
- hintdiv.appendChild(h);
- }
- }
- if (document.body) {
- document.body.appendChild(hintdiv);
- hintdiv.style.opacity = '0.7'
- }
-}
-function followLinks(follow) {
- var s = follow.split('');
- var linknr = parseInt(follow, 10);
- if (document.body) document.body.setAttribute('onkeyup', 'keyPressHandler(event)');
- var linkelems = addLinks();
- var formelems = addFormElems();
- var elems = [linkelems[0].concat(formelems[0]), linkelems[1].concat(formelems[1])];
- var len = (elems[0].length + '').length;
- var oldDiv = doc.getElementById(uzbldivid);
- var leftover = [[], []];
- if (linknr + 1 && s.length == len && linknr < elems[0].length && linknr >= 0) {
- clickElem(elems[0][linknr]);
- } else {
- for (var j = 0; j < elems[0].length; j++) {
- var b = true;
- for (var k = 0; k < s.length; k++) {
- b = b && elems[1][j].charAt(k) == s[k];
- }
- if (!b) {
- elems[0][j] = null;
- elems[1][j] = null;
- } else {
- leftover[0].push(elems[0][j]);
- leftover[1].push(elems[1][j]);
- }
- }
- if (leftover[0].length == 1) {
- clickElem(leftover[0][0]);
- } else if (!oldDiv) {
- if (linknr + 1 || s.length == 0) {
- reDrawHints(elems, len);
- } else {
- reDrawHints(leftover, len);
- }
- }
- }
-}
-followLinks('%s');
diff --git a/examples/data/scripts/follower.js b/examples/data/scripts/follower.js
new file mode 100644
index 00000000..604b7794
--- /dev/null
+++ b/examples/data/scripts/follower.js
@@ -0,0 +1,420 @@
+// A Link Follower for Uzbl.
+// P.C. Shyamshankar <[email protected]>
+//
+// WARNING: this script depends on the Uzbl object which is now disabled for
+// WARNING security reasons. So the script currently doesn't work but it's
+// WARNING interesting nonetheless
+//
+// Based extensively (like copy-paste) on the follow_numbers.js and
+// linkfollow.js included with uzbl, but modified to be more customizable and
+// extensible.
+//
+// Usage
+// -----
+//
+// First, you'll need to make sure the script is loaded on each page. This can
+// be done with:
+//
+// @on_event LOAD_COMMIT script /path/to/follower.js
+//
+// Then you can bind it to a key:
+//
+// @bind f* = js follower.follow('%s', matchSpec, handler, hintStyler)
+//
+// where matchSpec, handler and hintStyler are parameters which control the
+// operation of follower. If you don't want to customize any further, you can
+// set these to follower.genericMatchSpec, follower.genericHandler and
+// follower.genericHintStyler respectively.
+//
+// For example,
+//
+// @bind f* = js follower.follow('%s', follower.genericMatchSpec, follower.genericHandler, follower.genericHintStyler)
+// @bind F* = js follower.follow('%s', follower.onlyLinksMatchSpec, follower.newPageHandler, follower.newPageHintStyler)
+//
+// In order to make hints disappear when pressing a key (the Escape key, for
+// example), you can do this:
+//
+// @bind <Escape> = js follower.clearHints()
+//
+// If your Escape is already bound to something like command mode, chain it.
+//
+// Alternatively, you can tell your <Escape> key to emit an event, and handle
+// that instead.
+//
+// @bind <Escape> = event ESCAPE
+// @on_event ESCAPE js follower.clearHints()
+//
+// Customization
+// -------------
+//
+// If however you do want to customize, 3 Aspects of the link follower can be
+// customized with minimal pain or alteration to the existing code base:
+//
+// * What elements are hinted.
+// * The style of the hints displayed.
+// * How the hints are handled.
+//
+// In order to customize behavior, write an alternative, and pass that in to
+// follower.follow invocation. You _will_ have to modify this script, but only
+// locally, it beats having to copy the entire script under a new name and
+// modify.
+//
+// TODO:
+// * Whatever all the other TODOs in the file say.
+// * Find out how to do default arguments in Javascript.
+// * Abstract out the hints into a Hint object, make hintables a list of hint
+// objects instead of two lists.
+
+// Helpers
+String.prototype.lpad = function(padding, length) {
+ var padded = this;
+ while (padded.length < length) {
+ padded = padding + padded;
+ }
+
+ return padded;
+}
+
+function Follower() {
+
+ // Globals
+ var uzblID = 'uzbl-follow'; // ID to apply to each hint.
+ var uzblContainerID = 'uzbl-follow-container'; // ID to apply to the div containing hints.
+
+ // Translation table, used to display something other than numbers as hint
+ // labels. Typically set to the ten keys of the home row.
+ //
+ // Must have exactly 10 elements.
+ //
+ // I haven't parameterized this, to make it customizable. Should I? Do
+ // people really use more than one set of keys at a time?
+ var translation = ["a", "r", "s", "t", "d", "h", "n", "e", "i", "o"];
+
+ // MatchSpecs
+ // These are XPath expressions which indicate which elements will be hinted.
+ // Use multiple expressions for different situations, like hinting only form
+ // elements, or only links, etc.
+ //
+ // TODO: Check that these XPath expressions are correct, and optimize/make
+ // them more elegant. Preferably by someone who actually knows XPath, unlike
+ // me.
+
+ // Vimperator default (copy-pasted, I never used vimperator).
+ this.genericMatchSpec = " //*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @class='lk' or @role='link' or @href] | //input[not(@type='hidden')] | //a | //area | //iframe | //textarea | //button | //select";
+
+ // Matches only links, suitable for opening in a new instance (I think).
+ this.onlyLinksMatchSpec = " //*[@href] | //a | //area";
+
+ // Follow Handlers
+ // These decide how an element should be 'followed'. The handler is passed
+ // the element in question.
+
+ // Generic Handler, opens links in the same instance, emits the FORM_ACTIVE
+ // event if a form element was chosen. Also clears the keycmd.
+ this.genericHandler = function(node) {
+ if (node) {
+ if (window.itemClicker != undefined) {
+ window.itemClicker(node);
+ } else {
+ var tag = node.tagName.toLowerCase();
+ if (tag == 'a') {
+ node.click();
+ window.location = node.href;
+ } else if (tag == 'input') {
+ var inputType = node.getAttribute('type');
+ if (inputType == undefined)
+ inputType = 'text';
+
+ inputType = inputType.toLowerCase();
+
+ if (inputType == 'text' || inputType == 'file' || inputType == 'password') {
+ node.focus();
+ node.select();
+ } else {
+ node.click();
+ }
+ Uzbl.run("event FORM_ACTIVE");
+ } else if (tag == 'textarea'|| tag == 'select') {
+ node.focus();
+ node.select();
+ Uzbl.run("event FORM_ACTIVE");
+ } else {
+ node.click();
+ if ((node.href != undefined) && node.href)
+ window.location = node.href;
+ }
+ }
+ }
+ Uzbl.run("event SET_KEYCMD");
+ }
+
+ // Handler to open links in a new page. The rest is the same as before.
+ this.newPageHandler = function(node) {
+ if (node) {
+ if (window.itemClicker != undefined) {
+ window.itemClicker(node);
+ } else {
+ var tag = node.tagName.toLowerCase();
+ if (tag == 'a') {
+ node.click();
+ Uzbl.run("@new_window " + node.href);
+ } else if (tag == 'input') {
+ var inputType = node.getAttribute('type');
+ if (inputType == undefined)
+ inputType = 'text';
+
+ inputType = inputType.toLowerCase();
+
+ if (inputType == 'text' || inputType == 'file' || inputType == 'password') {
+ node.focus();
+ node.select();
+ } else {
+ node.click();
+ }
+ Uzbl.run("event FORM_ACTIVE");
+ } else if (tag == 'textarea'|| tag == 'select') {
+ node.focus();
+ node.select();
+ Uzbl.run("event FORM_ACTIVE");
+ } else {
+ node.click();
+ if ((node.href != undefined) && node.href)
+ window.location = node.href;
+ }
+ }
+ }
+ Uzbl.run("event SET_KEYCMD");
+ };
+
+ // Hint styling.
+ // Pretty much any attribute of the hint object can be modified here, but it
+ // was meant to change the styling. Useful to differentiate between hints
+ // with different handlers.
+ //
+ // Hint stylers are applied at the end of hint creation, so that they
+ // override the defaults.
+
+ this.genericHintStyler = function(hint) {
+ hint.style.backgroundColor = '#AAAAAA';
+ hint.style.border = '2px solid #4A6600';
+ hint.style.color = 'black';
+ hint.style.fontSize = '10px';
+ hint.style.fontWeight = 'bold';
+ hint.style.lineHeight = '12px';
+ return hint;
+ };
+
+ this.newPageHintStyler = function(hint) {
+ hint.style.backgroundColor = '#FFCC00';
+ hint.style.border = '2px solid #4A6600';
+ hint.style.color = 'black';
+ hint.style.fontSize = '10px';
+ hint.style.fontWeight = 'bold';
+ hint.style.lineHeight = '12px';
+ return hint;
+ };
+
+ // Beyond lies a jungle of pasta and verbosity.
+
+ // Translate a numeric label using the translation table.
+ function translate(digitLabel, translationTable) {
+ translatedLabel = '';
+ for (var i = 0; i < digitLabel.length; i++) {
+ translatedLabel += translationTable[digitLabel.charAt(i)];
+ }
+
+ return translatedLabel;
+ }
+
+ function computeElementPosition(element) {
+ var up = element.offsetTop;
+ var left = element.offsetLeft;
+ var width = element.offsetWidth;
+ var height = element.offsetHeight;
+
+ while (element.offsetParent) {
+ element = element.offsetParent;
+ up += element.offsetTop;
+ left += element.offsetLeft;
+ }
+
+ return {up: up, left: left, width: width, height: height};
+ }
+
+ // Pretty much copy-pasted from every other link following script.
+ function isInViewport(element) {
+ offset = computeElementPosition(element);
+
+ var up = offset.up;
+ var left = offset.left;
+ var width = offset.width;
+ var height = offset.height;
+
+ return up < window.pageYOffset + window.innerHeight &&
+ left < window.pageXOffset + window.innerWidth &&
+ (up + height) > window.pageYOffset &&
+ (left + width) > window.pageXOffset;
+ }
+
+ function isVisible(element) {
+ if (element == document) {
+ return true;
+ }
+
+ if (!element){
+ return false;
+ }
+
+ if (element.style) {
+ if (element.style.display == 'none' || element.style.visibiilty == 'hidden') {
+ return false;
+ }
+ }
+
+ return isVisible(element.parentNode);
+ }
+
+ function generateHintContainer() {
+ var container = document.getElementById(uzblContainerID);
+ if (container) {
+ container.parentNode.removeChild(container);
+ }
+
+ container = document.createElement('div');
+ container.id = uzblContainerID;
+
+ if (document.body) {
+ document.body.appendChild(container);
+ }
+ return container;
+ }
+
+ // Generate everything that is to be hinted, as per the given matchSpec.
+ // hintables[0] refers to the items, hintables[1] to their labels.
+ function generateHintables(matchSpec) {
+ var hintables = [[], []];
+
+ var itemsFromXPath = document.evaluate(matchSpec, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+
+ for (var i = 0; i < itemsFromXPath.snapshotLength; ++i) {
+ var element = itemsFromXPath.snapshotItem(i);
+ if (element && isVisible(element) && isInViewport(element)) {
+ hintables[0].push(element);
+ }
+ }
+
+ // Assign labels to each hintable. Can't be combined with the previous
+ // step, because we didn't know how many there were at that time.
+ var hintLength = hintables.length;
+ for (var i = 0; i < hintables[0].length; ++i) {
+ var code = translate(i.toString(), translation);
+ hintables[1].push(code.lpad(translation[0], hintLength));
+ }
+
+ return hintables;
+ }
+
+ // Filter the hintables based on input from the user. Makes the screen less
+ // cluttered after the user has typed some prefix of hint labels.
+ function filterHintables(hintables, target) {
+ var filtered = [[], []];
+
+ var targetPattern = new RegExp("^" + target);
+
+ for (var i = 0; i < hintables[0].length; i++) {
+ if (hintables[1][i].match(targetPattern)) {
+ filtered[0].push(hintables[0][i]);
+ filtered[1].push(hintables[1][i].substring(target.length));
+ }
+ }
+
+ return filtered;
+ }
+
+ // TODO make this use the container variable from main, instead of searching
+ // for it?
+ function clearHints() {
+ var container = document.getElementById(uzblContainerID);
+ if (container) {
+ container.parentNode.removeChild(container);
+ }
+ }
+
+ // So that we can offer this as a separate function.
+ this.clearHints = clearHints;
+
+ function makeHint(node, code, styler) {
+ var position = computeElementPosition(node);
+ var hint = document.createElement('div');
+
+ hint.name = uzblID;
+ hint.innerText = code;
+ hint.style.display = 'inline';
+
+ hint.style.margin = '0px';
+ hint.style.padding = '1px';
+ hint.style.position = 'absolute';
+ hint.style.zIndex = '10000';
+
+ hint.style.left = position.left + 'px';
+ hint.style.top = position.up + 'px';
+
+ var img = node.getElementsByTagName('img');
+ if (img.length > 0) {
+ hint.style.left = position.left + img[0].width / 2 + 'px';
+ }
+
+ hint.style.textDecoration = 'none';
+ hint.style.webkitBorderRadius = '6px';
+ hint.style.webkitTransform = 'scale(1) rotate(0deg) translate(-6px, -5px)';
+
+ hint = styler(hint); // So that custom hint stylers can override the above.
+ return hint;
+ }
+
+
+ function drawHints(container, hintables, styler) {
+ for (var i = 0; i < hintables[0].length; i++) {
+ hint = makeHint(hintables[0][i], hintables[1][i], styler);
+ container.appendChild(hint);
+ }
+
+ if (document.body) {
+ document.body.appendChild(container);
+ }
+ }
+
+ // The main hinting function. I don't know how to do default values to
+ // functions, so all arguments must be specified. Use generics if you must.
+ this.follow = function(target, matchSpec, handler, hintStyler) {
+ var container = generateHintContainer(); // Get a container to hold all hints.
+ var allHintables = generateHintables(matchSpec); // Get all items that can be hinted.
+ hintables = filterHintables(allHintables, target); // Filter them based on current input.
+
+ clearHints(); // Clear existing hints, if any.
+
+ if (hintables[0].length == 0) {
+ // Nothing was hinted, user pressed an unknown key, maybe?
+ // Do nothing.
+ } else if (hintables[0].length == 1) {
+ handler(hintables[0][0]); // Only one hint remains, handle it.
+ } else {
+ drawHints(container, hintables, hintStyler); // Draw whatever hints remain.
+ }
+
+ return;
+ };
+}
+
+// Make on-click links clickable.
+try {
+ HTMLElement.prototype.click = function() {
+ if (typeof this.onclick == 'function') {
+ this.onclick({
+ type: 'click'
+ });
+ }
+ };
+} catch(e) {}
+
+follower = new Follower();
diff --git a/src/uzbl-core.c b/src/uzbl-core.c
index f5b89df1..15588828 100644
--- a/src/uzbl-core.c
+++ b/src/uzbl-core.c
@@ -50,13 +50,13 @@ GOptionEntry entries[] =
{ "config", 'c', 0, G_OPTION_ARG_STRING, &uzbl.state.config_file,
"Path to config file or '-' for stdin", "FILE" },
{ "socket", 's', 0, G_OPTION_ARG_INT, &uzbl.state.socket_id,
- "Socket ID", "SOCKET" },
+ "Xembed Socket ID", "SOCKET" },
{ "connect-socket", 0, 0, G_OPTION_ARG_STRING_ARRAY, &uzbl.state.connect_socket_names,
- "Connect to server socket", "CSOCKET" },
+ "Connect to server socket for event managing", "CSOCKET" },
{ "print-events", 'p', 0, G_OPTION_ARG_NONE, &uzbl.state.events_stdout,
"Whether to print events to stdout.", NULL },
{ "geometry", 'g', 0, G_OPTION_ARG_STRING, &uzbl.gui.geometry,
- "Set window geometry (format: WIDTHxHEIGHT+-X+-Y or maximized)", "GEOMETRY" },
+ "Set window geometry (format: 'WIDTHxHEIGHT+-X+-Y' or 'maximized')", "GEOMETRY" },
{ "version", 'V', 0, G_OPTION_ARG_NONE, &uzbl.behave.print_version,
"Print the version and exit", NULL },
{ NULL, 0, 0, 0, NULL, NULL, NULL }
diff --git a/tests/test-command.c b/tests/test-command.c
index fc3b092e..61940812 100644
--- a/tests/test-command.c
+++ b/tests/test-command.c
@@ -22,8 +22,8 @@
#include <fcntl.h>
#include <signal.h>
-#include <uzbl-core.h>
-#include <config.h>
+#include <src/uzbl-core.h>
+#include <src/config.h>
extern UzblCore uzbl;
diff --git a/tests/test-expand.c b/tests/test-expand.c
index 01af4017..7ea3d611 100644
--- a/tests/test-expand.c
+++ b/tests/test-expand.c
@@ -22,8 +22,8 @@
#include <fcntl.h>
#include <signal.h>
-#include <uzbl-core.h>
-#include <config.h>
+#include <src/uzbl-core.h>
+#include <src/config.h>
extern UzblCore uzbl;
| 0 | 6 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
f7608a8fc48ad98e6d7227c10cf3786e37c4a2ab
|
Merge branch 'security-fix'
|
commit f7608a8fc48ad98e6d7227c10cf3786e37c4a2ab (from a5f014de5f76169a38ee67e46a0526e5d80a3433)
Merge: a5f014de 1958b52d
Author: Dieter Plaetinck <[email protected]>
Date: Tue Jan 5 20:37:08 2010 +0100
Merge branch 'security-fix'
diff --git a/README b/README
index 0d6ed046..a22e1059 100644
--- a/README
+++ b/README
@@ -397,7 +397,7 @@ The script specific arguments are this:
Custom, userdefined scripts (`spawn foo bar`) get first the arguments as specified in the config and then the above 7 are added at the end.
-### JAVASCRIPT HELPER OBJECT
+### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
Javascript code run from uzbl is given a special object in the global namespace which gives special privileges to these scripts. This object is called `Uzbl`, and it is added and removed before and after the script execution so that it is hidden to web javascripts (There is no race condition, since all the javascript code runs in a single thread)
@@ -410,25 +410,6 @@ Currently, the `Uzbl` object provides only one function:
* `Uzbl.run("spawn insert_bookmark.sh")`
* `uri = Uzbl.run("print @uri")` (see variable expansion below)
-### JAVASCRIPT SECURITY
-
-Since defined variables and functions are set in the global namespace (`window` object) as default, it is recommended to wrap your scripts like this:
-
- (function(Uzbl) {
- ...
- })(Uzbl);
-
-This way, everything is kept private. It also turns Uzbl into a local variable, which can be accessed from callback functions defined inside. However for some situations, isolating everything isn't an option, for example, with binds. You can define them directly in the script body, and use `var Uzbl = window.Uzbl;` to make the Uzbl variable local, as in the following example:
-
- function f() {
- var Uzbl = window.Uzbl;
- Uzbl.run(...);
- setTimeout(function() {
- Uzbl.run(...);
- }, 500);
- }
-
-Copying the Uzbl object and creating public functions should be taken with care to avoid creating security holes. Keep in mind that the "f" function above would be defined in the `window` object, and as such any javascript in the current page can call it.
### EVENTS ###
diff --git a/tests/test-command.c b/tests/test-command.c
index 49f3bb82..fc3b092e 100644
--- a/tests/test-command.c
+++ b/tests/test-command.c
@@ -305,11 +305,6 @@ test_js (void) {
parse_cmd_line("js ('x' + 345).toUpperCase()", result);
g_assert_cmpstr("X345", ==, result->str);
- /* uzbl commands can be run from javascript */
- uzbl.net.useragent = "Test useragent";
- parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result);
- g_assert_cmpstr("TEST USERAGENT", ==, result->str);
-
g_string_free(result, TRUE);
}
diff --git a/uzbl-core.c b/uzbl-core.c
index fd8ee417..fca293c1 100644
--- a/uzbl-core.c
+++ b/uzbl-core.c
@@ -1046,7 +1046,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
WebKitWebFrame *frame;
JSGlobalContextRef context;
JSObjectRef globalobject;
- JSStringRef var_name;
JSStringRef js_script;
JSValueRef js_result;
@@ -1059,12 +1058,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
context = webkit_web_frame_get_global_context(frame);
globalobject = JSContextGetGlobalObject(context);
- /* uzbl javascript namespace */
- var_name = JSStringCreateWithUTF8CString("Uzbl");
- JSObjectSetProperty(context, globalobject, var_name,
- JSObjectMake(context, uzbl.js.classref, NULL),
- kJSClassAttributeNone, NULL);
-
/* evaluate the script and get return value*/
js_script = JSStringCreateWithUTF8CString(script);
js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL);
@@ -1082,9 +1075,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
}
/* cleanup */
- JSObjectDeleteProperty(context, globalobject, var_name, NULL);
-
- JSStringRelease(var_name);
JSStringRelease(js_script);
}
commit f7608a8fc48ad98e6d7227c10cf3786e37c4a2ab (from 1958b52d41cba96956dc1995660de49525ed1047)
Merge: a5f014de 1958b52d
Author: Dieter Plaetinck <[email protected]>
Date: Tue Jan 5 20:37:08 2010 +0100
Merge branch 'security-fix'
diff --git a/AUTHORS b/AUTHORS
index 7d8d76ed..b63132cc 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -17,6 +17,7 @@ In alphabetical order:
(neutralinsomniac) - load_progress = 0 fix
(salinasv) - move some variables to heap
(sentientswitch) - Cleaned up code. Added some commands.
+ (tczy) - patches
Aaron Griffin (phrakture) - Makefile patches to build on OSX
Abel Camarillo (00z) - various portability fixes, such as BSD fixes for Makefile and posix shell scripts
Aldrik Dunbar (n30n) - scroll % script
diff --git a/examples/config/uzbl/config b/examples/config/uzbl/config
index 9dc4a355..3edb36c9 100644
--- a/examples/config/uzbl/config
+++ b/examples/config/uzbl/config
@@ -39,15 +39,24 @@ set jsh = js var run=Uzbl.run; function get(k){return run("print \\\@"+k)}; func
# === Handlers ===============================================================
-set download_handler = spawn @scripts_dir/download.sh
-set cookie_handler = talk_to_socket $XDG_CACHE_HOME/uzbl/cookie_daemon_socket
-set scheme_handler = sync_spawn @scripts_dir/scheme.py
+# --- Hardcoded event handlers -----------------------------------------------
-# New window handler options
-#set new_window = sh 'echo uri "$8" > $4' # open in same window
-set new_window = sh 'uzbl-browser -u $8' # equivalent to the default behaviour
+# These handlers can't be moved to the new event system yet as we don't
+# support events that can wait for a response from a script.
+set cookie_handler = talk_to_socket $XDG_CACHE_HOME/uzbl/cookie_daemon_socket
+set scheme_handler = sync_spawn @scripts_dir/scheme.py
-# Load start handlers
+# Open in the same window.
+#set new_window = sh 'echo uri "$8" > $4'
+# Open a link in a new window. equivalent to default behavior
+set new_window = sh 'uzbl-browser -u $8'
+
+# --- Optional dynamic event handlers ----------------------------------------
+
+# Download handler
+@on_event DOWNLOAD_REQUEST spawn @scripts_dir/download.sh %s \@proxy_url
+
+# Load start handler
@on_event LOAD_START @set_status <span foreground="khaki">wait</span>
# Load commit handlers
@@ -69,7 +78,7 @@ set new_window = sh 'uzbl-browser -u $8' # equivalent to the default beh
# Switch to command mode if anything else is clicked
@on_event ROOT_ACTIVE @set_mode command
-# Misc on_event handlers
+# Example CONFIG_CHANGED event handler
#@on_event CONFIG_CHANGED print Config changed: %1 = %2
# === Behaviour and appearance ===============================================
@@ -96,6 +105,8 @@ set selected_section = <span foreground="#606060">\@[\@SELECTED_URI]\@</span>
set status_format = <span font_family="monospace">@mode_section @keycmd_section @progress_section @uri_section @name_section @status_section @scroll_section @selected_section</span>
+set title_format_long = \@keycmd_prompt \@raw_modcmd \@raw_keycmd \@TITLE - Uzbl browser <\@NAME> \@SELECTED_URI
+
# Progress bar config
@progress width = 8
# %d = done, %p = pending %c = percent done, %i = int done, %s = spinner,
@@ -230,9 +241,9 @@ set open_new_window = sh 'uzbl-browser -u \@SELECTED_URI'
@cbind N = search_reverse
# --- Web searching binds ---
-@cbind gg<Google:>_ = uri http://www.google.com/search?q=%s
-@cbind \\awiki<Archwiki:>_ = uri http://wiki.archlinux.org/index.php/Special:Search?search=%s&go=Go
-@cbind \\wiki<Wikipedia:>_ = uri http://en.wikipedia.org/w/index.php?title=Special:Search&search=%s&go=Go
+@cbind gg<Google:>_ = uri http://www.google.com/search?q=\@<encodeURIComponent(%r)>\@
+@cbind \\awiki<Archwiki:>_ = uri http://wiki.archlinux.org/index.php/Special:Search?search=\@<encodeURIComponent(%r)>\@&go=Go
+@cbind \\wiki<Wikipedia:>_ = uri http://en.wikipedia.org/w/index.php?title=Special:Search&search=\@<encodeURIComponent(%r)>\@&go=Go
# --- Handy binds ---
# Set function shortcut
@@ -243,6 +254,9 @@ set open_new_window = sh 'uzbl-browser -u \@SELECTED_URI'
@cbind !dump = sh "echo dump_config > $4"
# Reload config
@cbind !reload = sh "sed '/^# === Post-load misc commands/,$d' $1 > $4"
+# Uzbl Terminal. TODO explain why this is useful
+@cbind <Ctrl><Alt>t = sh 'xterm -e "socat unix-connect:$5 -"'
+#@cbind <Ctrl><Alt>t = sh 'urxvt -e socat unix-connect:$5 -'
# --- Uri opening prompts ---
@cbind o<uri:>_ = uri %s
@@ -285,17 +299,6 @@ set toggle_cmd_ins = @toggle_modes command insert
# Or number with strings instead of numbers:
@cbind fL* = script @scripts_dir/follow_Numbers_Strings.js %s
-
-@cbind Xs = js alert("hi");
-# example showing how to use sh
-# it sends a command to the fifo, whose path is told via a positional param
-# if fifo_dir is not set, it'll echo to a file named (null) somewhere >:) remember to delete it
-# The body of the shell command should be one parameter, so if it has spaces like here,
-# you must enclose it in quotes. Remember to escape (and double-escape) quotes and backslashes
-# in the body. Any additional parameters you use will appear AFTER the default parameters (cfg file
-# path, fifo & socket dirs, etc.)
-@cbind XS = sh 'echo "js alert (\\"This is sent by the shell via a fifo\\")" > "$4"'
-
# --- Form filler binds ---
# this script allows you to configure (per domain) values to fill in form
# fields (eg login information) and to fill in these values automatically
diff --git a/examples/data/uzbl/plugins/bind.py b/examples/data/uzbl/plugins/bind.py
index 1cba7b28..9e093372 100644
--- a/examples/data/uzbl/plugins/bind.py
+++ b/examples/data/uzbl/plugins/bind.py
@@ -13,9 +13,6 @@
import re
import pprint
-# Export these functions to uzbl.<name>
-__export__ = ['bind', 'mode_bind', 'get_bindlet']
-
# Hold the bind dicts for each uzbl instance.
UZBLS = {}
@@ -303,20 +300,6 @@ def __repr__(self):
return self._repr_cache
-def expand(cmd, args):
- '''Replaces "%s %1 %2 %3..." with "<all args> <arg 0> <arg 1>...".'''
-
- if '%s' in cmd:
- cmd = cmd.replace('%s', ' '.join(map(unicode, args)))
-
- for (index, arg) in enumerate(args):
- index += 1
- if '%%%d' % index in cmd:
- cmd = cmd.replace('%%%d' % index, unicode(arg))
-
- return cmd
-
-
def exec_bind(uzbl, bind, *args, **kargs):
'''Execute bind objects.'''
@@ -332,8 +315,9 @@ def exec_bind(uzbl, bind, *args, **kargs):
raise ArgumentError('cannot supply kargs for uzbl commands')
commands = []
+ cmd_expand = uzbl.cmd_expand
for cmd in bind.commands:
- cmd = expand(cmd, args)
+ cmd = cmd_expand(cmd, args)
uzbl.send(cmd)
@@ -517,12 +501,21 @@ def modcmd_exec(uzbl, keylet):
def init(uzbl):
- connects = {'BIND': parse_bind,
- 'MODE_BIND': parse_mode_bind,
- 'KEYCMD_UPDATE': keycmd_update,
- 'MODCMD_UPDATE': modcmd_update,
- 'KEYCMD_EXEC': keycmd_exec,
- 'MODCMD_EXEC': modcmd_exec,
- 'MODE_CHANGED': mode_changed}
-
- uzbl.connect_dict(connects)
+ # Event handling hooks.
+ uzbl.connect_dict({
+ 'BIND': parse_bind,
+ 'KEYCMD_EXEC': keycmd_exec,
+ 'KEYCMD_UPDATE': keycmd_update,
+ 'MODCMD_EXEC': modcmd_exec,
+ 'MODCMD_UPDATE': modcmd_update,
+ 'MODE_BIND': parse_mode_bind,
+ 'MODE_CHANGED': mode_changed,
+ })
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export_dict({
+ 'bind': bind,
+ 'mode_bind': mode_bind,
+ 'get_bindlet': get_bindlet,
+ })
diff --git a/examples/data/uzbl/plugins/cmd_expand.py b/examples/data/uzbl/plugins/cmd_expand.py
new file mode 100644
index 00000000..3f6ae2b4
--- /dev/null
+++ b/examples/data/uzbl/plugins/cmd_expand.py
@@ -0,0 +1,42 @@
+def escape(str):
+ for (level, char) in [(3, '\\'), (2, "'"), (2, '"'), (1, '@')]:
+ str = str.replace(char, (level * '\\') + char)
+
+ return str
+
+
+def cmd_expand(uzbl, cmd, args):
+ '''Exports a function that provides the following
+ expansions in any uzbl command string:
+
+ %s = replace('%s', ' '.join(args))
+ %r = replace('%r', "'%s'" % escaped(' '.join(args)))
+ %1 = replace('%1', arg[0])
+ %2 = replace('%2', arg[1])
+ %n = replace('%n', arg[n-1])
+ '''
+
+ # Ensure (1) all string representable and (2) correct string encoding.
+ args = map(unicode, args)
+
+ # Direct string replace.
+ if '%s' in cmd:
+ cmd = cmd.replace('%s', ' '.join(args))
+
+ # Escaped and quoted string replace.
+ if '%r' in cmd:
+ cmd = cmd.replace('%r', "'%s'" % escape(' '.join(args)))
+
+ # Arg index string replace.
+ for (index, arg) in enumerate(args):
+ index += 1
+ if '%%%d' % index in cmd:
+ cmd = cmd.replace('%%%d' % index, unicode(arg))
+
+ return cmd
+
+
+def init(uzbl):
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export('cmd_expand', cmd_expand)
diff --git a/examples/data/uzbl/plugins/completion.py b/examples/data/uzbl/plugins/completion.py
index 8e055e14..8cea2030 100644
--- a/examples/data/uzbl/plugins/completion.py
+++ b/examples/data/uzbl/plugins/completion.py
@@ -185,17 +185,22 @@ def add_config_key(uzbl, key, value):
def init(uzbl):
- connects = {
- 'INSTANCE_START': add_instance,
- 'INSTANCE_EXIT': del_instance,
+ # Event handling hooks.
+ uzbl.connect_dict({
'BUILTINS': add_builtins,
'CONFIG_CHANGED': add_config_key,
+ 'INSTANCE_EXIT': del_instance,
+ 'INSTANCE_START': add_instance,
+ 'KEYCMD_CLEARED': stop_completion,
+ 'KEYCMD_EXEC': stop_completion,
'KEYCMD_UPDATE': update_completion_list,
'START_COMPLETION': start_completion,
- }
-
- # And connect the dicts event handlers to the handler stack.
- uzbl.connect_dict(connects)
-
- for event in ['STOP_COMPLETION', 'KEYCMD_EXEC', 'KEYCMD_CLEARED']:
- uzbl.connect(event, stop_completion)
+ 'STOP_COMPLETION': stop_completion,
+ })
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export_dict({
+ 'get_completion_dict': get_completion_dict,
+ 'start_completion': start_completion,
+ })
diff --git a/examples/data/uzbl/plugins/config.py b/examples/data/uzbl/plugins/config.py
index b43161b9..4a848a32 100644
--- a/examples/data/uzbl/plugins/config.py
+++ b/examples/data/uzbl/plugins/config.py
@@ -82,9 +82,16 @@ def variable_set(uzbl, args):
def init(uzbl):
-
- connects = {'VARIABLE_SET': variable_set,
- 'INSTANCE_START': add_instance,
- 'INSTANCE_EXIT': del_instance}
-
- uzbl.connect_dict(connects)
+ # Event handling hooks.
+ uzbl.connect_dict({
+ 'INSTANCE_EXIT': del_instance,
+ 'INSTANCE_START': add_instance,
+ 'VARIABLE_SET': variable_set,
+ })
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export_dict({
+ 'get_config': get_config,
+ 'set': set,
+ })
diff --git a/examples/data/uzbl/plugins/keycmd.py b/examples/data/uzbl/plugins/keycmd.py
index af6beffc..c119077c 100644
--- a/examples/data/uzbl/plugins/keycmd.py
+++ b/examples/data/uzbl/plugins/keycmd.py
@@ -1,29 +1,22 @@
import re
-# Map these functions/variables in the plugins namespace to the uzbl object.
-__export__ = ['clear_keycmd', 'set_keycmd', 'set_cursor_pos', 'get_keylet',
- 'clear_current', 'clear_modcmd', 'add_modmap', 'add_key_ignore',
- 'append_keycmd', 'inject_keycmd', 'add_modkey_addition']
-
# Hold the keylets.
UZBLS = {}
# Keycmd format which includes the markup for the cursor.
KEYCMD_FORMAT = "%s<span @cursor_style>%s</span>%s"
+MODCMD_FORMAT = "<span> %s </span>"
-def uzbl_escape(str):
- '''Prevent outgoing keycmd values from expanding inside the
- status_format.'''
+def escape(str):
+ for char in ['\\', '@']:
+ str = str.replace(char, '\\'+char)
- if not str:
- return ''
+ return str
- for char in ['\\', '@']:
- if char in str:
- str = str.replace(char, '\\'+char)
- return "@[%s]@" % str
+def uzbl_escape(str):
+ return "@[%s]@" % escape(str) if str else ''
class Keylet(object):
@@ -261,6 +254,7 @@ def clear_keycmd(uzbl):
k.cursor = 0
k._repr_cache = False
uzbl.set('keycmd')
+ uzbl.set('raw_keycmd')
uzbl.event('KEYCMD_CLEARED')
@@ -276,6 +270,7 @@ def clear_modcmd(uzbl, clear_held=False):
k.held = set()
uzbl.set('modcmd')
+ uzbl.set('raw_modcmd')
uzbl.event('MODCMD_CLEARED')
@@ -314,9 +309,11 @@ def update_event(uzbl, k, execute=True):
new_modcmd = k.get_modcmd()
if not new_modcmd:
uzbl.set('modcmd', config=config)
+ uzbl.set('raw_modcmd', config=config)
elif new_modcmd == modcmd:
- uzbl.set('modcmd', '<span> %s </span>' % uzbl_escape(new_modcmd),
+ uzbl.set('raw_modcmd', escape(modcmd), config=config)
+ uzbl.set('modcmd', MODCMD_FORMAT % uzbl_escape(modcmd),
config=config)
if 'keycmd_events' in config and config['keycmd_events'] != '1':
@@ -325,6 +322,7 @@ def update_event(uzbl, k, execute=True):
new_keycmd = k.get_keycmd()
if not new_keycmd:
uzbl.set('keycmd', config=config)
+ uzbl.set('raw_keycmd', config=config)
elif new_keycmd == keycmd:
# Generate the pango markup for the cursor in the keycmd.
@@ -332,6 +330,7 @@ def update_event(uzbl, k, execute=True):
chunks = [keycmd[:k.cursor], curchar, keycmd[k.cursor+1:]]
value = KEYCMD_FORMAT % tuple(map(uzbl_escape, chunks))
uzbl.set('keycmd', value, config=config)
+ uzbl.set('raw_keycmd', escape(keycmd), config=config)
def inject_str(str, index, inj):
@@ -391,6 +390,7 @@ def key_press(uzbl, key):
k.keycmd = ''
k.cursor = 0
uzbl.set('keycmd', config=config)
+ uzbl.set('raw_keycmd', config=config)
return
k.keycmd = inject_str(k.keycmd, k.cursor, key)
@@ -533,22 +533,39 @@ def set_cursor_pos(uzbl, index):
def init(uzbl):
'''Connect handlers to uzbl events.'''
- connects = {'INSTANCE_START': add_instance,
- 'INSTANCE_EXIT': del_instance,
- 'KEY_PRESS': key_press,
- 'KEY_RELEASE': key_release,
- 'SET_KEYCMD': set_keycmd,
- 'KEYCMD_STRIP_WORD': keycmd_strip_word,
- 'KEYCMD_BACKSPACE': keycmd_backspace,
- 'KEYCMD_DELETE': keycmd_delete,
- 'KEYCMD_EXEC_CURRENT': keycmd_exec_current,
- 'SET_CURSOR_POS': set_cursor_pos,
- 'FOCUS_LOST': focus_changed,
- 'FOCUS_GAINED': focus_changed,
- 'MODMAP': modmap_parse,
- 'APPEND_KEYCMD': append_keycmd,
- 'INJECT_KEYCMD': inject_keycmd,
- 'IGNORE_KEY': add_key_ignore,
- 'MODKEY_ADDITION': modkey_addition_parse}
-
- uzbl.connect_dict(connects)
+ # Event handling hooks.
+ uzbl.connect_dict({
+ 'APPEND_KEYCMD': append_keycmd,
+ 'FOCUS_GAINED': focus_changed,
+ 'FOCUS_LOST': focus_changed,
+ 'IGNORE_KEY': add_key_ignore,
+ 'INJECT_KEYCMD': inject_keycmd,
+ 'INSTANCE_EXIT': del_instance,
+ 'INSTANCE_START': add_instance,
+ 'KEYCMD_BACKSPACE': keycmd_backspace,
+ 'KEYCMD_DELETE': keycmd_delete,
+ 'KEYCMD_EXEC_CURRENT': keycmd_exec_current,
+ 'KEYCMD_STRIP_WORD': keycmd_strip_word,
+ 'KEY_PRESS': key_press,
+ 'KEY_RELEASE': key_release,
+ 'MODKEY_ADDITION': modkey_addition_parse,
+ 'MODMAP': modmap_parse,
+ 'SET_CURSOR_POS': set_cursor_pos,
+ 'SET_KEYCMD': set_keycmd,
+ })
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export_dict({
+ 'add_key_ignore': add_key_ignore,
+ 'add_modkey_addition': add_modkey_addition,
+ 'add_modmap': add_modmap,
+ 'append_keycmd': append_keycmd,
+ 'clear_current': clear_current,
+ 'clear_keycmd': clear_keycmd,
+ 'clear_modcmd': clear_modcmd,
+ 'get_keylet': get_keylet,
+ 'inject_keycmd': inject_keycmd,
+ 'set_cursor_pos': set_cursor_pos,
+ 'set_keycmd': set_keycmd,
+ })
diff --git a/examples/data/uzbl/plugins/mode.py b/examples/data/uzbl/plugins/mode.py
index f85d9997..54d865a7 100644
--- a/examples/data/uzbl/plugins/mode.py
+++ b/examples/data/uzbl/plugins/mode.py
@@ -156,12 +156,21 @@ def toggle_modes(uzbl, modes):
def init(uzbl):
-
- connects = {'CONFIG_CHANGED': config_changed,
- 'INSTANCE_EXIT': del_instance,
- 'INSTANCE_START': add_instance,
- 'MODE_CONFIG': mode_config,
- 'TOGGLE_MODES': toggle_modes,
- 'MODE_CHANGED': mode_changed}
-
- uzbl.connect_dict(connects)
+ # Event handling hooks.
+ uzbl.connect_dict({
+ 'CONFIG_CHANGED': config_changed,
+ 'INSTANCE_EXIT': del_instance,
+ 'INSTANCE_START': add_instance,
+ 'MODE_CHANGED': mode_changed,
+ 'MODE_CONFIG': mode_config,
+ 'TOGGLE_MODES': toggle_modes,
+ })
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export_dict({
+ 'get_mode': get_mode,
+ 'get_mode_config': get_mode_config,
+ 'set_mode': set_mode,
+ 'set_mode_config': set_mode_config,
+ })
diff --git a/examples/data/uzbl/plugins/on_event.py b/examples/data/uzbl/plugins/on_event.py
index afee4e6f..b9c504a4 100644
--- a/examples/data/uzbl/plugins/on_event.py
+++ b/examples/data/uzbl/plugins/on_event.py
@@ -2,6 +2,7 @@
Formatting options:
%s = space separated string of the arguments
+ %r = escaped and quoted version of %s
%1 = argument 1
%2 = argument 2
%n = argument n
@@ -44,20 +45,6 @@ def get_on_events(uzbl):
return UZBLS[uzbl]
-def expand(cmd, args):
- '''Replaces "%s %1 %2 %3..." with "<all args> <arg 0> <arg 1>...".'''
-
- if '%s' in cmd:
- cmd = cmd.replace('%s', ' '.join(map(unicode, args)))
-
- for (index, arg) in enumerate(args):
- index += 1
- if '%%%d' % index in cmd:
- cmd = cmd.replace('%%%d' % index, unicode(arg))
-
- return cmd
-
-
def event_handler(uzbl, *args, **kargs):
'''This function handles all the events being watched by various
on_event definitions and responds accordingly.'''
@@ -68,8 +55,9 @@ def event_handler(uzbl, *args, **kargs):
return
commands = events[event]
+ cmd_expand = uzbl.cmd_expand
for cmd in commands:
- cmd = expand(cmd, args)
+ cmd = cmd_expand(cmd, args)
uzbl.send(cmd)
@@ -104,9 +92,16 @@ def parse_on_event(uzbl, args):
def init(uzbl):
-
- connects = {'ON_EVENT': parse_on_event,
- 'INSTANCE_START': add_instance,
- 'INSTANCE_EXIT': del_instance}
-
- uzbl.connect_dict(connects)
+ # Event handling hooks.
+ uzbl.connect_dict({
+ 'INSTANCE_EXIT': del_instance,
+ 'INSTANCE_START': add_instance,
+ 'ON_EVENT': parse_on_event,
+ })
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.export_dict({
+ 'get_on_events': get_on_events,
+ 'on_event': on_event,
+ })
diff --git a/examples/data/uzbl/plugins/plugin_template.py b/examples/data/uzbl/plugins/plugin_template.py
index 03cb7487..565a9991 100644
--- a/examples/data/uzbl/plugins/plugin_template.py
+++ b/examples/data/uzbl/plugins/plugin_template.py
@@ -1,8 +1,5 @@
'''Plugin template.'''
-# A list of functions this plugin exports to be used via uzbl object.
-__export__ = ['myplugin_function',]
-
# Holds the per-instance data dict.
UZBLS = {}
@@ -60,16 +57,20 @@ def init(uzbl):
# Make a dictionary comprising of {"EVENT_NAME": handler, ..} to the event
# handler stack:
- connects = {
- 'INSTANCE_START': add_instance,
- 'INSTANCE_EXIT': del_instance,
- 'MYPLUGIN_EVENT': myplugin_event_parser,
- }
-
- # And connect the dicts event handlers to the handler stack.
- uzbl.connect_dict(connects)
+ uzbl.connect_dict({
+ # event name function
+ 'INSTANCE_START': add_instance,
+ 'INSTANCE_EXIT': del_instance,
+ 'MYPLUGIN_EVENT': myplugin_event_parser,
+ })
# Or connect a handler to an event manually and supply additional optional
# arguments:
-
#uzbl.connect("MYOTHER_EVENT", myother_event_parser, True, limit=20)
+
+ # Function exports to the uzbl object, `function(uzbl, *args, ..)`
+ # becomes `uzbl.function(*args, ..)`.
+ uzbl.connect_dict({
+ # external name function
+ 'myplugin_function': myplugin_function,
+ })
diff --git a/examples/data/uzbl/plugins/progress_bar.py b/examples/data/uzbl/plugins/progress_bar.py
index b6fcb1b1..89ba1752 100644
--- a/examples/data/uzbl/plugins/progress_bar.py
+++ b/examples/data/uzbl/plugins/progress_bar.py
@@ -149,10 +149,11 @@ def reset_progress(uzbl, args):
def init(uzbl):
- connects = {'LOAD_PROGRESS': update_progress,
- 'INSTANCE_START': add_instance,
- 'INSTANCE_EXIT': del_instance,
- 'PROGRESS_CONFIG': progress_config,
- 'LOAD_COMMIT': reset_progress}
-
- uzbl.connect_dict(connects)
+ # Event handling hooks.
+ uzbl.connect_dict({
+ 'INSTANCE_EXIT': del_instance,
+ 'INSTANCE_START': add_instance,
+ 'LOAD_COMMIT': reset_progress,
+ 'LOAD_PROGRESS': update_progress,
+ 'PROGRESS_CONFIG': progress_config,
+ })
diff --git a/examples/data/uzbl/scripts/insert_bookmark.sh b/examples/data/uzbl/scripts/insert_bookmark.sh
index e04e6d47..c34e7db3 100755
--- a/examples/data/uzbl/scripts/insert_bookmark.sh
+++ b/examples/data/uzbl/scripts/insert_bookmark.sh
@@ -6,6 +6,8 @@ file=${XDG_DATA_HOME:-$HOME/.local/share}/uzbl/bookmarks
which zenity &>/dev/null || exit 2
entry=`zenity --entry --text="Add bookmark. add tags after the '\t', separated by spaces" --entry-text="$6 $7\t"`
+exitstatus=$?
+if [ $exitstatus -ne 0 ]; then exit $exitstatus; fi
url=`echo $entry | awk '{print $1}'`
# TODO: check if already exists, if so, and tags are different: ask if you want to replace tags
diff --git a/examples/data/uzbl/scripts/uzbl-event-manager b/examples/data/uzbl/scripts/uzbl-event-manager
index 916259a7..afef6fd5 100755
--- a/examples/data/uzbl/scripts/uzbl-event-manager
+++ b/examples/data/uzbl/scripts/uzbl-event-manager
@@ -350,61 +350,23 @@ class UzblInstance(object):
def __init__(self, parent, client_socket):
# Internal variables.
- self._exports = {}
- self._handlers = {}
- self._parent = parent
- self._client_socket = client_socket
+ self.exports = {}
+ self.handlers = {}
+ self.parent = parent
+ self.client_socket = client_socket
self.depth = 0
self.buffer = ''
self.pid = None
- # Call the init() function in every plugin. Inside the init function
- # is where the plugins insert the hooks into the event system.
- self._init_plugins()
-
-
- def __getattribute__(self, attr):
- '''Expose any exported functions before class functions.'''
-
- if not attr.startswith('_'):
- exports = object.__getattribute__(self, '_exports')
- if attr in exports:
- return exports[attr]
-
- return object.__getattribute__(self, attr)
-
-
- def _init_plugins(self):
- '''Call the init() function in every plugin and expose all exposable
- functions in the plugins root namespace.'''
-
- plugins = self._parent['plugins']
-
- # Map all plugin exports
- for (name, plugin) in plugins.items():
- if not hasattr(plugin, '__export__'):
- continue
-
- for export in plugin.__export__:
- if export in self._exports:
- raise KeyError("conflicting export: %r" % export)
-
- obj = getattr(plugin, export)
- if callable(obj):
- obj = partial(obj, self)
-
- self._exports[export] = obj
-
- echo("exposed attribute(s): %s" % ', '.join(self._exports.keys()))
-
- # Now call the init function in all plugins.
- for (name, plugin) in plugins.items():
+ # Call the init function in every plugin. The init function in each
+ # plugin is where that plugin connects functions to events and exports
+ # functions to the uzbl object.
+ for plugin in self.parent['plugins'].values():
try:
plugin.init(self)
except:
- #print_exc()
raise
@@ -412,26 +374,43 @@ class UzblInstance(object):
'''Send a command to the uzbl instance via the socket file.'''
msg = msg.strip()
- if self._client_socket:
+ if self.client_socket:
print '%s<-- %s' % (' ' * self.depth, msg)
- self._client_socket.send(("%s\n" % msg).encode('utf-8'))
+ self.client_socket.send(("%s\n" % msg).encode('utf-8'))
else:
print '%s!-- %s' % (' ' * self.depth, msg)
+ def export(self, name, function):
+ '''Export `function(uzbl, *args, ..)` inside a plugin to the uzbl
+ object like so `uzbl.function(*args, ..)`. This will allow other
+ plugins to call functions inside the current plugin (which is currently
+ calling this function) via the uzbl object.'''
+
+ self.__dict__.__setitem__(name, partial(function, self))
+
+
+ def export_dict(self, export_dict):
+ '''Export multiple (name, function)'s at once inside a dict of the
+ form `{name1: function1, name2: function2, ...}`.'''
+
+ for (name, function) in export_dict.items():
+ self.export(name, function)
+
+
def connect(self, event, handler, *args, **kargs):
- '''Connect event with handler and return the newly created handler.
- Handlers can either be a function or a uzbl command string.'''
+ '''Connect a uzbl event with a handler. Handlers can either be a
+ function or a uzbl command string.'''
event = event.upper().strip()
assert event and ' ' not in event
- if event not in self._handlers.keys():
- self._handlers[event] = []
+ if event not in self.handlers.keys():
+ self.handlers[event] = []
handlerobj = EventHandler(event, handler, *args, **kargs)
- self._handlers[event].append(handlerobj)
+ self.handlers[event].append(handlerobj)
print handlerobj
@@ -449,7 +428,7 @@ class UzblInstance(object):
def remove_by_id(self, hid):
'''Remove connected event handler by unique handler id.'''
- for (event, handlers) in self._handlers.items():
+ for (event, handlers) in self.handlers.items():
for handler in list(handlers):
if hid != handler.hid:
continue
@@ -464,7 +443,7 @@ class UzblInstance(object):
def remove(self, handler):
'''Remove connected event handler.'''
- for (event, handlers) in self._handlers.items():
+ for (event, handlers) in self.handlers.items():
if handler in handlers:
echo("removed %r" % handler)
handlers.remove(handler)
@@ -493,10 +472,10 @@ class UzblInstance(object):
if event == "INSTANCE_START" and args:
self.pid = int(args[0])
- if event not in self._handlers:
+ if event not in self.handlers:
return
- for handler in self._handlers[event]:
+ for handler in self.handlers[event]:
self.depth += 1
try:
self.exec_handler(handler, *args, **kargs)
@@ -511,19 +490,15 @@ class UzblInstance(object):
'''Close the client socket and clean up.'''
try:
- self._client_socket.close()
+ self.client_socket.close()
except:
pass
- for (name, plugin) in self._parent['plugins'].items():
+ for (name, plugin) in self.parent['plugins'].items():
if hasattr(plugin, 'cleanup'):
plugin.cleanup(self)
- del self._exports
- del self._handlers
- del self._client_socket
-
class UzblEventDaemon(dict):
def __init__(self):
diff --git a/examples/data/uzbl/scripts/uzbl-tabbed b/examples/data/uzbl/scripts/uzbl-tabbed
index bb9b9a29..d93a3f4c 100755
--- a/examples/data/uzbl/scripts/uzbl-tabbed
+++ b/examples/data/uzbl/scripts/uzbl-tabbed
@@ -1010,7 +1010,7 @@ class UzblTabbed:
instance.'''
binds = []
- bind_format = r'bind %s = sh "echo \"%s\" > \"%s\""'
+ bind_format = r'@bind %s = sh "echo \"%s\" > \"%s\""'
bind = lambda key, action: binds.append(bind_format % (key, action,\
self.fifo_socket))
| 0 | 3 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
786744aea678a45136b2692b189ff96d225b9167
|
Merge branch 'master' of git://github.com/Dieterbe/uzbl
|
commit 786744aea678a45136b2692b189ff96d225b9167 (from 585226c1cb80488f1fbd4ad2635550a728bf2747)
Merge: 585226c1 f7608a8f
Author: Mason Larobina <[email protected]>
Date: Sat Jan 9 13:42:07 2010 +0800
Merge branch 'master' of git://github.com/Dieterbe/uzbl
diff --git a/README b/README
index 0d6ed046..a22e1059 100644
--- a/README
+++ b/README
@@ -397,7 +397,7 @@ The script specific arguments are this:
Custom, userdefined scripts (`spawn foo bar`) get first the arguments as specified in the config and then the above 7 are added at the end.
-### JAVASCRIPT HELPER OBJECT
+### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
Javascript code run from uzbl is given a special object in the global namespace which gives special privileges to these scripts. This object is called `Uzbl`, and it is added and removed before and after the script execution so that it is hidden to web javascripts (There is no race condition, since all the javascript code runs in a single thread)
@@ -410,25 +410,6 @@ Currently, the `Uzbl` object provides only one function:
* `Uzbl.run("spawn insert_bookmark.sh")`
* `uri = Uzbl.run("print @uri")` (see variable expansion below)
-### JAVASCRIPT SECURITY
-
-Since defined variables and functions are set in the global namespace (`window` object) as default, it is recommended to wrap your scripts like this:
-
- (function(Uzbl) {
- ...
- })(Uzbl);
-
-This way, everything is kept private. It also turns Uzbl into a local variable, which can be accessed from callback functions defined inside. However for some situations, isolating everything isn't an option, for example, with binds. You can define them directly in the script body, and use `var Uzbl = window.Uzbl;` to make the Uzbl variable local, as in the following example:
-
- function f() {
- var Uzbl = window.Uzbl;
- Uzbl.run(...);
- setTimeout(function() {
- Uzbl.run(...);
- }, 500);
- }
-
-Copying the Uzbl object and creating public functions should be taken with care to avoid creating security holes. Keep in mind that the "f" function above would be defined in the `window` object, and as such any javascript in the current page can call it.
### EVENTS ###
diff --git a/tests/test-command.c b/tests/test-command.c
index 49f3bb82..fc3b092e 100644
--- a/tests/test-command.c
+++ b/tests/test-command.c
@@ -305,11 +305,6 @@ test_js (void) {
parse_cmd_line("js ('x' + 345).toUpperCase()", result);
g_assert_cmpstr("X345", ==, result->str);
- /* uzbl commands can be run from javascript */
- uzbl.net.useragent = "Test useragent";
- parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result);
- g_assert_cmpstr("TEST USERAGENT", ==, result->str);
-
g_string_free(result, TRUE);
}
diff --git a/uzbl-core.c b/uzbl-core.c
index fd8ee417..fca293c1 100644
--- a/uzbl-core.c
+++ b/uzbl-core.c
@@ -1046,7 +1046,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
WebKitWebFrame *frame;
JSGlobalContextRef context;
JSObjectRef globalobject;
- JSStringRef var_name;
JSStringRef js_script;
JSValueRef js_result;
@@ -1059,12 +1058,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
context = webkit_web_frame_get_global_context(frame);
globalobject = JSContextGetGlobalObject(context);
- /* uzbl javascript namespace */
- var_name = JSStringCreateWithUTF8CString("Uzbl");
- JSObjectSetProperty(context, globalobject, var_name,
- JSObjectMake(context, uzbl.js.classref, NULL),
- kJSClassAttributeNone, NULL);
-
/* evaluate the script and get return value*/
js_script = JSStringCreateWithUTF8CString(script);
js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL);
@@ -1082,9 +1075,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
}
/* cleanup */
- JSObjectDeleteProperty(context, globalobject, var_name, NULL);
-
- JSStringRelease(var_name);
JSStringRelease(js_script);
}
commit 786744aea678a45136b2692b189ff96d225b9167 (from f7608a8fc48ad98e6d7227c10cf3786e37c4a2ab)
Merge: 585226c1 f7608a8f
Author: Mason Larobina <[email protected]>
Date: Sat Jan 9 13:42:07 2010 +0800
Merge branch 'master' of git://github.com/Dieterbe/uzbl
diff --git a/docs/INSTALL b/docs/INSTALL
index 711ea973..c795502a 100644
--- a/docs/INSTALL
+++ b/docs/INSTALL
@@ -9,8 +9,8 @@ From source
You can pull the code from git or get a tagged tarball.
$ git clone git://github.com/Dieterbe/uzbl.git
- [ $ git checkout origin/experimental ] # optional. see below
$ cd uzbl
+ [ $ git checkout origin/experimental ] # optional. see below
$ make
$ sudo make install
If you want to remove uzbl again, you can issue:
diff --git a/examples/data/uzbl/scripts/uzbl-event-manager b/examples/data/uzbl/scripts/uzbl-event-manager
index afef6fd5..2df3357e 100755
--- a/examples/data/uzbl/scripts/uzbl-event-manager
+++ b/examples/data/uzbl/scripts/uzbl-event-manager
@@ -296,7 +296,7 @@ def parse_msg(uzbl, msg):
cmd = FINDSPACES.split(msg, 3)
if not cmd or cmd[0] != 'EVENT':
# Not an event message.
- print '---', msg
+ print '---', msg.encode('utf-8')
return
while len(cmd) < 4:
@@ -375,11 +375,11 @@ class UzblInstance(object):
msg = msg.strip()
if self.client_socket:
- print '%s<-- %s' % (' ' * self.depth, msg)
+ print (u'%s<-- %s' % (' ' * self.depth, msg)).encode('utf-8')
self.client_socket.send(("%s\n" % msg).encode('utf-8'))
else:
- print '%s!-- %s' % (' ' * self.depth, msg)
+ print (u'%s!-- %s' % (' ' * self.depth, msg)).encode('utf-8')
def export(self, name, function):
@@ -467,7 +467,7 @@ class UzblInstance(object):
elems = [event,]
if args: elems.append(unicode(args))
if kargs: elems.append(unicode(kargs))
- print "%s--> %s" % (' ' * self.depth, ' '.join(elems))
+ print (u'%s--> %s' % (' ' * self.depth, ' '.join(elems))).encode('utf-8')
if event == "INSTANCE_START" and args:
self.pid = int(args[0])
| 0 | 8 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
f2c7c41f6cc70e1d509967c7487aec5126495557
|
remove the vestiges of Uzbl.run
|
commit f2c7c41f6cc70e1d509967c7487aec5126495557
Author: Brendan Taylor <[email protected]>
Date: Thu Jan 13 11:59:23 2011 -0700
remove the vestiges of Uzbl.run
diff --git a/README b/README
index 051fe6b6..d1f23572 100644
--- a/README
+++ b/README
@@ -602,25 +602,6 @@ This script tries to authenticate as user alice with password wonderland once
and never retries authentication.
See examples for more sofisticated, interactive authentication handler.
-### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
-
-JavaScript code run from `uzbl` is given a special object in the global
-namespace which gives special privileges to these scripts. This object is called
-`Uzbl`, and it is added and removed before and after the script execution so
-that it is hidden to web JavaScript code (there is no race condition, since all
-the JavaScript code runs in a single thread).
-
-Currently, the `Uzbl` object provides only one function:
-
-* `Uzbl.run( <command> )`
- - Command is any `uzbl` command as defined above.
- - Return value: a string, either empty or containing the output of the
- command. Very few commands return their output currently, including `js`,
- `script`, and `print`.
- - Examples:
- * `Uzbl.run("spawn insert_bookmark.sh")`
- * `uri = Uzbl.run("print @uri")` (see variable expansion below)
-
### EVENTS
Unlike commands, events are not handled in `uzbl` itself, but are propagated
diff --git a/src/uzbl-core.c b/src/uzbl-core.c
index 6bbed3cb..c6443ccc 100644
--- a/src/uzbl-core.c
+++ b/src/uzbl-core.c
@@ -979,52 +979,6 @@ load_uri (WebKitWebView *web_view, GArray *argv, GString *result) {
}
/* Javascript*/
-
-JSValueRef
-js_run_command (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
- size_t argumentCount, const JSValueRef arguments[],
- JSValueRef* exception) {
- (void) function;
- (void) thisObject;
- (void) exception;
-
- JSStringRef js_result_string;
- GString *result = g_string_new("");
-
- if (argumentCount >= 1) {
- JSStringRef arg = JSValueToStringCopy(ctx, arguments[0], NULL);
- size_t arg_size = JSStringGetMaximumUTF8CStringSize(arg);
- char ctl_line[arg_size];
- JSStringGetUTF8CString(arg, ctl_line, arg_size);
-
- parse_cmd_line(ctl_line, result);
-
- JSStringRelease(arg);
- }
- js_result_string = JSStringCreateWithUTF8CString(result->str);
-
- g_string_free(result, TRUE);
-
- return JSValueMakeString(ctx, js_result_string);
-}
-
-JSStaticFunction js_static_functions[] = {
- {"run", js_run_command, kJSPropertyAttributeNone},
-};
-
-void
-js_init() {
- /* This function creates the class and its definition, only once */
- if (!uzbl.js.initialized) {
- /* it would be pretty cool to make this dynamic */
- uzbl.js.classdef = kJSClassDefinitionEmpty;
- uzbl.js.classdef.staticFunctions = js_static_functions;
-
- uzbl.js.classref = JSClassCreate(&uzbl.js.classdef);
- }
-}
-
-
void
eval_js(WebKitWebView * web_view, gchar *script, GString *result, const char *file) {
WebKitWebFrame *frame;
@@ -1037,8 +991,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result, const char *fi
JSStringRef js_result_string;
size_t js_result_size;
- js_init();
-
frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view));
context = webkit_web_frame_get_global_context(frame);
globalobject = JSContextGetGlobalObject(context);
| 0 | 2 |
CVE-2010-0011
|
The eval_js function in uzbl-core.c in Uzbl before 2010.01.05 exposes the run method of the Uzbl object, which allows remote attackers to execute arbitrary commands via JavaScript code.
|
uzbl/uzbl
|
1958b52d41cba96956dc1995660de49525ed1047
|
disable Uzbl javascript object because of security problem.
|
commit 1958b52d41cba96956dc1995660de49525ed1047
Author: Dieter Plaetinck <[email protected]>
Date: Tue Jan 5 20:17:29 2010 +0100
disable Uzbl javascript object because of security problem.
diff --git a/README b/README
index 0d6ed046..a22e1059 100644
--- a/README
+++ b/README
@@ -397,7 +397,7 @@ The script specific arguments are this:
Custom, userdefined scripts (`spawn foo bar`) get first the arguments as specified in the config and then the above 7 are added at the end.
-### JAVASCRIPT HELPER OBJECT
+### JAVASCRIPT HELPER OBJECT DISABLED BECAUSE OF SECURITY LEAK
Javascript code run from uzbl is given a special object in the global namespace which gives special privileges to these scripts. This object is called `Uzbl`, and it is added and removed before and after the script execution so that it is hidden to web javascripts (There is no race condition, since all the javascript code runs in a single thread)
@@ -410,25 +410,6 @@ Currently, the `Uzbl` object provides only one function:
* `Uzbl.run("spawn insert_bookmark.sh")`
* `uri = Uzbl.run("print @uri")` (see variable expansion below)
-### JAVASCRIPT SECURITY
-
-Since defined variables and functions are set in the global namespace (`window` object) as default, it is recommended to wrap your scripts like this:
-
- (function(Uzbl) {
- ...
- })(Uzbl);
-
-This way, everything is kept private. It also turns Uzbl into a local variable, which can be accessed from callback functions defined inside. However for some situations, isolating everything isn't an option, for example, with binds. You can define them directly in the script body, and use `var Uzbl = window.Uzbl;` to make the Uzbl variable local, as in the following example:
-
- function f() {
- var Uzbl = window.Uzbl;
- Uzbl.run(...);
- setTimeout(function() {
- Uzbl.run(...);
- }, 500);
- }
-
-Copying the Uzbl object and creating public functions should be taken with care to avoid creating security holes. Keep in mind that the "f" function above would be defined in the `window` object, and as such any javascript in the current page can call it.
### EVENTS ###
diff --git a/tests/test-command.c b/tests/test-command.c
index 49f3bb82..fc3b092e 100644
--- a/tests/test-command.c
+++ b/tests/test-command.c
@@ -305,11 +305,6 @@ test_js (void) {
parse_cmd_line("js ('x' + 345).toUpperCase()", result);
g_assert_cmpstr("X345", ==, result->str);
- /* uzbl commands can be run from javascript */
- uzbl.net.useragent = "Test useragent";
- parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result);
- g_assert_cmpstr("TEST USERAGENT", ==, result->str);
-
g_string_free(result, TRUE);
}
diff --git a/uzbl-core.c b/uzbl-core.c
index fd8ee417..fca293c1 100644
--- a/uzbl-core.c
+++ b/uzbl-core.c
@@ -1046,7 +1046,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
WebKitWebFrame *frame;
JSGlobalContextRef context;
JSObjectRef globalobject;
- JSStringRef var_name;
JSStringRef js_script;
JSValueRef js_result;
@@ -1059,12 +1058,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
context = webkit_web_frame_get_global_context(frame);
globalobject = JSContextGetGlobalObject(context);
- /* uzbl javascript namespace */
- var_name = JSStringCreateWithUTF8CString("Uzbl");
- JSObjectSetProperty(context, globalobject, var_name,
- JSObjectMake(context, uzbl.js.classref, NULL),
- kJSClassAttributeNone, NULL);
-
/* evaluate the script and get return value*/
js_script = JSStringCreateWithUTF8CString(script);
js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL);
@@ -1082,9 +1075,6 @@ eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
}
/* cleanup */
- JSObjectDeleteProperty(context, globalobject, var_name, NULL);
-
- JSStringRelease(var_name);
JSStringRelease(js_script);
}
| 1 | 1 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
5fe446896a2d8847d506cd672f5c249c605335a3
|
More strict and faster check for numbers when decoding
|
commit 5fe446896a2d8847d506cd672f5c249c605335a3
Author: Dan Pascu <[email protected]>
Date: Wed May 7 12:46:45 2008 +0000
More strict and faster check for numbers when decoding
diff --git a/cjson.c b/cjson.c
index 5f0b81e..5f448a4 100644
--- a/cjson.c
+++ b/cjson.c
@@ -253,68 +253,71 @@ decode_nan(JSONData *jsondata)
}
+#define skipDigits(ptr) while(isdigit(*(ptr))) (ptr)++
+
static PyObject*
decode_number(JSONData *jsondata)
{
PyObject *object, *str;
- int c, is_float, should_stop;
+ int is_float;
char *ptr;
- // check if we got a floating point number
+ // validate number and check if it's floating point or not
ptr = jsondata->ptr;
- is_float = should_stop = False;
- while (True) {
- c = *ptr;
- if (c == 0)
- break;
- switch(c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '-':
- case '+':
- break;
- case '.':
- case 'e':
- case 'E':
- is_float = True;
- break;
- default:
- should_stop = True;
- }
- if (should_stop) {
- break;
- }
+ is_float = False;
+
+ if (*ptr == '-' || *ptr == '+')
+ ptr++;
+
+ if (*ptr == '0') {
ptr++;
+ if (isdigit(*ptr))
+ goto number_error;
+ } else if (isdigit(*ptr))
+ skipDigits(ptr);
+ else
+ goto number_error;
+
+ if (*ptr == '.') {
+ is_float = True;
+ ptr++;
+ if (!isdigit(*ptr))
+ goto number_error;
+ skipDigits(ptr);
+ }
+
+ if (*ptr == 'e' || *ptr == 'E') {
+ is_float = True;
+ ptr++;
+ if (*ptr == '+' || *ptr == '-')
+ ptr++;
+ if (!isdigit(*ptr))
+ goto number_error;
+ skipDigits(ptr);
}
str = PyString_FromStringAndSize(jsondata->ptr, ptr - jsondata->ptr);
if (str == NULL)
return NULL;
- if (is_float) {
+ if (is_float)
object = PyFloat_FromString(str, NULL);
- } else {
+ else
object = PyInt_FromString(PyString_AS_STRING(str), NULL, 10);
- }
Py_DECREF(str);
- if (object == NULL) {
- PyErr_Format(JSON_DecodeError, "invalid number starting at position "
- SSIZE_T_F, (Py_ssize_t)(jsondata->ptr - jsondata->str));
- } else {
- jsondata->ptr = ptr;
- }
+ if (object == NULL)
+ goto number_error;
+
+ jsondata->ptr = ptr;
return object;
+
+number_error:
+ PyErr_Format(JSON_DecodeError, "invalid number starting at position "
+ SSIZE_T_F, (Py_ssize_t)(jsondata->ptr - jsondata->str));
+ return NULL;
}
| 0 | 6 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
d6adf10ae863159a9e32f64115598c0d9a1324de
|
Fixed issue with core file regexp on OS X
|
commit d6adf10ae863159a9e32f64115598c0d9a1324de
Author: Dan Pascu <[email protected]>
Date: Fri Oct 30 13:06:59 2009 +0000
Fixed issue with core file regexp on OS X
diff --git a/.boring b/.boring
index 208f3ba..eab8aa8 100644
--- a/.boring
+++ b/.boring
@@ -6,7 +6,7 @@
(^|/)Thumbs\.db$
\#
~$
-(^|/)core(\.[0-9]+|)$
+(^|/)core(\.[0-9]+)?$
\.(pyc|pyo|o|so|orig|bak|BAK|prof|wpu|cvsignore)$
(^|/)(test|timer).*\.py$
(^|/)(build|dist)($|/)
| 0 | 4 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
b6e3c7edfe5b835e5d6407c568003093c3efe0e0
|
Fixed some list/dict decoding bugs. Use a state machine for decoding them.
|
commit b6e3c7edfe5b835e5d6407c568003093c3efe0e0
Author: Dan Pascu <[email protected]>
Date: Tue May 6 06:33:28 2008 +0000
Fixed some list/dict decoding bugs. Use a state machine for decoding them.
diff --git a/cjson.c b/cjson.c
index 7844924..37e1fb3 100644
--- a/cjson.c
+++ b/cjson.c
@@ -318,47 +318,51 @@ decode_number(JSONData *jsondata)
}
+typedef enum {
+ ArrayItem_or_ClosingBracket=0,
+ Comma_or_ClosingBracket,
+ ArrayItem,
+ ArrayDone
+} ArrayState;
+
static PyObject*
decode_array(JSONData *jsondata)
{
PyObject *object, *item;
- int c, expect_item, items, result;
+ ArrayState next_state;
+ int c, result;
char *start;
object = PyList_New(0);
start = jsondata->ptr;
jsondata->ptr++;
- expect_item = True;
- items = 0;
- while (True) {
+
+ next_state = ArrayItem_or_ClosingBracket;
+
+ while (next_state != ArrayDone) {
skipSpaces(jsondata);
c = *jsondata->ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError, "unterminated array starting at "
"position " SSIZE_T_F,
(Py_ssize_t)(start - jsondata->str));
- goto failure;;
- } else if (c == ']') {
- if (expect_item && items>0) {
- PyErr_Format(JSON_DecodeError, "expecting array item at "
- "position " SSIZE_T_F,
- (Py_ssize_t)(jsondata->ptr - jsondata->str));
- goto failure;
+ goto failure;
+ }
+ switch (next_state) {
+ case ArrayItem_or_ClosingBracket:
+ if (c == ']') {
+ jsondata->ptr++;
+ next_state = ArrayDone;
+ break;
}
- jsondata->ptr++;
- break;
- } else if (c == ',') {
- if (expect_item) {
+ case ArrayItem:
+ if (c==',' || c==']') {
PyErr_Format(JSON_DecodeError, "expecting array item at "
"position " SSIZE_T_F,
(Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
- expect_item = True;
- jsondata->ptr++;
- continue;
- } else {
item = decode_json(jsondata);
if (item == NULL)
goto failure;
@@ -366,8 +370,25 @@ decode_array(JSONData *jsondata)
Py_DECREF(item);
if (result == -1)
goto failure;
- expect_item = False;
- items++;
+ next_state = Comma_or_ClosingBracket;
+ break;
+ case Comma_or_ClosingBracket:
+ if (c == ']') {
+ jsondata->ptr++;
+ next_state = ArrayDone;
+ } else if (c == ',') {
+ jsondata->ptr++;
+ next_state = ArrayItem;
+ } else {
+ PyErr_Format(JSON_DecodeError, "expecting ',' or ']' at "
+ "position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
+ goto failure;
+ }
+ break;
+ case ArrayDone:
+ // this will never be reached, but keep compilers happy
+ break;
}
}
@@ -379,21 +400,29 @@ failure:
}
+typedef enum {
+ DictionaryKey_or_ClosingBrace=0,
+ Comma_or_ClosingBrace,
+ DictionaryKey,
+ DictionaryDone
+} DictionaryState;
+
static PyObject*
decode_object(JSONData *jsondata)
{
PyObject *object, *key, *value;
- int c, expect_key, items, result;
+ DictionaryState next_state;
+ int c, result;
char *start;
object = PyDict_New();
- expect_key = True;
- items = 0;
start = jsondata->ptr;
jsondata->ptr++;
- while (True) {
+ next_state = DictionaryKey_or_ClosingBrace;
+
+ while (next_state != DictionaryDone) {
skipSpaces(jsondata);
c = *jsondata->ptr;
if (c == 0) {
@@ -401,29 +430,19 @@ decode_object(JSONData *jsondata)
"position " SSIZE_T_F,
(Py_ssize_t)(start - jsondata->str));
goto failure;;
- } else if (c == '}') {
- if (expect_key && items>0) {
- PyErr_Format(JSON_DecodeError, "expecting object property name"
- " at position " SSIZE_T_F,
- (Py_ssize_t)(jsondata->ptr - jsondata->str));
- goto failure;
- }
- jsondata->ptr++;
- break;
- } else if (c == ',') {
- if (expect_key) {
- PyErr_Format(JSON_DecodeError, "expecting object property name"
- "at position " SSIZE_T_F,
- (Py_ssize_t)(jsondata->ptr - jsondata->str));
- goto failure;
+ }
+
+ switch (next_state) {
+ case DictionaryKey_or_ClosingBrace:
+ if (c == '}') {
+ jsondata->ptr++;
+ next_state = DictionaryDone;
+ break;
}
- expect_key = True;
- jsondata->ptr++;
- continue;
- } else {
+ case DictionaryKey:
if (c != '"') {
- PyErr_Format(JSON_DecodeError, "expecting property name in "
- "object at position " SSIZE_T_F,
+ PyErr_Format(JSON_DecodeError, "expecting object property name "
+ "at position " SSIZE_T_F,
(Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
@@ -443,6 +462,15 @@ decode_object(JSONData *jsondata)
jsondata->ptr++;
}
+ skipSpaces(jsondata);
+ if (*jsondata->ptr==',' || *jsondata->ptr=='}') {
+ PyErr_Format(JSON_DecodeError, "expecting object property "
+ "value at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
+ Py_DECREF(key);
+ goto failure;
+ }
+
value = decode_json(jsondata);
if (value == NULL) {
Py_DECREF(key);
@@ -454,8 +482,25 @@ decode_object(JSONData *jsondata)
Py_DECREF(value);
if (result == -1)
goto failure;
- expect_key = False;
- items++;
+ next_state = Comma_or_ClosingBrace;
+ break;
+ case Comma_or_ClosingBrace:
+ if (c == '}') {
+ jsondata->ptr++;
+ next_state = DictionaryDone;
+ } else if (c == ',') {
+ jsondata->ptr++;
+ next_state = DictionaryKey;
+ } else {
+ PyErr_Format(JSON_DecodeError, "expecting ',' or '}' at "
+ "position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
+ goto failure;
+ }
+ break;
+ case DictionaryDone:
+ // this will never be reached, but keep compilers happy
+ break;
}
}
| 0 | 7 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
6e916608ec8ccbc1e56d2f263a95f79127eeb685
|
Fixed 64-bit portability problems
|
commit 6e916608ec8ccbc1e56d2f263a95f79127eeb685
Author: Dan Pascu <[email protected]>
Date: Tue Jul 24 22:10:29 2007 +0000
Fixed 64-bit portability problems
diff --git a/ChangeLog b/ChangeLog
index 1f768a4..ad4bdf0 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -4,6 +4,8 @@ Changes in version 1.0.4
* Added licensing information.
* Fixed issue with decrementing a string reference too early
(Edouard Hinard <[email protected]>).
+ * Fixed 64-bit portability problems (based on a modified version of a
+ patch by David Rushby <[email protected]>).
Changes in version 1.0.3
------------------------
diff --git a/cjson.c b/cjson.c
index dc844a5..12bdb6e 100644
--- a/cjson.c
+++ b/cjson.c
@@ -6,7 +6,9 @@
*
*/
+
#include <Python.h>
+#include <stddef.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
@@ -42,6 +44,16 @@ static PyObject *JSON_EncodeError;
static PyObject *JSON_DecodeError;
+#if PY_VERSION_HEX < 0x02050000
+typedef int Py_ssize_t;
+#define PY_SSIZE_T_MAX INT_MAX
+#define PY_SSIZE_T_MIN INT_MIN
+
+#define SSIZE_T_F "%d"
+#else
+#define SSIZE_T_F "%zd"
+#endif
+
#define True 1
#define False 0
@@ -65,7 +77,7 @@ static PyObject *JSON_DecodeError;
static PyObject*
decode_null(JSONData *jsondata)
{
- int left;
+ ptrdiff_t left;
left = jsondata->end - jsondata->ptr;
@@ -84,7 +96,7 @@ decode_null(JSONData *jsondata)
static PyObject*
decode_bool(JSONData *jsondata)
{
- int left;
+ ptrdiff_t left;
left = jsondata->end - jsondata->ptr;
@@ -108,7 +120,8 @@ static PyObject*
decode_string(JSONData *jsondata)
{
PyObject *object;
- int c, escaping, len, has_unicode, string_escape;
+ int c, escaping, has_unicode, string_escape;
+ Py_ssize_t len;
char *ptr;
// look for the closing quote
@@ -118,8 +131,8 @@ decode_string(JSONData *jsondata)
c = *ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError,
- "unterminated string starting at position %d",
- jsondata->ptr - jsondata->str);
+ "unterminated string starting at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
return NULL;
}
if (!escaping) {
@@ -165,20 +178,20 @@ decode_string(JSONData *jsondata)
PyErr_Fetch(&type, &value, &tb);
if (type == NULL) {
PyErr_Format(JSON_DecodeError,
- "invalid string starting at position %d",
- jsondata->ptr - jsondata->str);
+ "invalid string starting at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
} else {
if (PyErr_GivenExceptionMatches(type, PyExc_UnicodeDecodeError)) {
reason = PyObject_GetAttrString(value, "reason");
PyErr_Format(JSON_DecodeError, "cannot decode string starting"
- " at position %d: %s",
- jsondata->ptr - jsondata->str,
+ " at position " SSIZE_T_F ": %s",
+ (Py_ssize_t)(jsondata->ptr - jsondata->str),
reason ? PyString_AsString(reason) : "bad format");
Py_XDECREF(reason);
} else {
PyErr_Format(JSON_DecodeError,
- "invalid string starting at position %d",
- jsondata->ptr - jsondata->str);
+ "invalid string starting at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
}
}
Py_XDECREF(type);
@@ -196,7 +209,7 @@ static PyObject*
decode_inf(JSONData *jsondata)
{
PyObject *object;
- int left;
+ ptrdiff_t left;
left = jsondata->end - jsondata->ptr;
@@ -224,7 +237,7 @@ static PyObject*
decode_nan(JSONData *jsondata)
{
PyObject *object;
- int left;
+ ptrdiff_t left;
left = jsondata->end - jsondata->ptr;
@@ -295,8 +308,8 @@ decode_number(JSONData *jsondata)
Py_DECREF(str);
if (object == NULL) {
- PyErr_Format(JSON_DecodeError, "invalid number starting at position %d",
- jsondata->ptr - jsondata->str);
+ PyErr_Format(JSON_DecodeError, "invalid number starting at position "
+ SSIZE_T_F, (Py_ssize_t)(jsondata->ptr - jsondata->str));
puts(ptr);
} else {
jsondata->ptr = ptr;
@@ -324,12 +337,14 @@ decode_array(JSONData *jsondata)
c = *jsondata->ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError, "unterminated array starting at "
- "position %d", start - jsondata->str);
+ "position " SSIZE_T_F,
+ (Py_ssize_t)(start - jsondata->str));
goto failure;;
} else if (c == ']') {
if (expect_item && items>0) {
PyErr_Format(JSON_DecodeError, "expecting array item at "
- "position %d", jsondata->ptr - jsondata->str);
+ "position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
jsondata->ptr++;
@@ -337,7 +352,8 @@ decode_array(JSONData *jsondata)
} else if (c == ',') {
if (expect_item) {
PyErr_Format(JSON_DecodeError, "expecting array item at "
- "position %d", jsondata->ptr - jsondata->str);
+ "position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
expect_item = True;
@@ -383,12 +399,14 @@ decode_object(JSONData *jsondata)
c = *jsondata->ptr;
if (c == 0) {
PyErr_Format(JSON_DecodeError, "unterminated object starting at "
- "position %d", start - jsondata->str);
+ "position " SSIZE_T_F,
+ (Py_ssize_t)(start - jsondata->str));
goto failure;;
} else if (c == '}') {
if (expect_key && items>0) {
PyErr_Format(JSON_DecodeError, "expecting object property name"
- " at position %d", jsondata->ptr - jsondata->str);
+ " at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
jsondata->ptr++;
@@ -396,7 +414,8 @@ decode_object(JSONData *jsondata)
} else if (c == ',') {
if (expect_key) {
PyErr_Format(JSON_DecodeError, "expecting object property name"
- "at position %d", jsondata->ptr - jsondata->str);
+ "at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
expect_key = True;
@@ -404,9 +423,9 @@ decode_object(JSONData *jsondata)
continue;
} else {
if (c != '"') {
- PyErr_Format(JSON_DecodeError,
- "expecting property name in object at "
- "position %d", jsondata->ptr - jsondata->str);
+ PyErr_Format(JSON_DecodeError, "expecting property name in "
+ "object at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
goto failure;
}
@@ -416,9 +435,9 @@ decode_object(JSONData *jsondata)
skipSpaces(jsondata);
if (*jsondata->ptr != ':') {
- PyErr_Format(JSON_DecodeError,
- "missing colon after object property name at "
- "position %d", jsondata->ptr - jsondata->str);
+ PyErr_Format(JSON_DecodeError, "missing colon after object "
+ "property name at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata->ptr - jsondata->str));
Py_DECREF(key);
goto failure;
} else {
@@ -527,7 +546,7 @@ encode_string(PyObject *string)
size_t newsize = 2 + 6 * op->ob_size;
PyObject *v;
- if (newsize > INT_MAX) {
+ if (newsize > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string is too large to make repr");
}
@@ -536,7 +555,7 @@ encode_string(PyObject *string)
return NULL;
}
else {
- register int i;
+ register Py_ssize_t i;
register char c;
register char *p;
int quote;
@@ -593,7 +612,7 @@ encode_unicode(PyObject *unicode)
{
PyObject *repr;
Py_UNICODE *s;
- int size;
+ Py_ssize_t size;
char *p;
static const char *hexdigit = "0123456789abcdef";
@@ -736,7 +755,7 @@ encode_unicode(PyObject *unicode)
static PyObject*
encode_tuple(PyObject *tuple)
{
- int i, n;
+ Py_ssize_t i, n;
PyObject *s, *temp;
PyObject *pieces, *result = NULL;
PyTupleObject *v = (PyTupleObject*) tuple;
@@ -801,7 +820,7 @@ Done:
static PyObject*
encode_list(PyObject *list)
{
- int i;
+ Py_ssize_t i;
PyObject *s, *temp;
PyObject *pieces = NULL, *result = NULL;
PyListObject *v = (PyListObject*) list;
@@ -884,7 +903,7 @@ Done:
static PyObject*
encode_dict(PyObject *dict)
{
- int i;
+ Py_ssize_t i;
PyObject *s, *temp, *colon = NULL;
PyObject *pieces = NULL, *result = NULL;
PyObject *key, *value;
@@ -1062,7 +1081,8 @@ JSON_decode(PyObject *self, PyObject *args, PyObject *kwargs)
skipSpaces(&jsondata);
if (jsondata.ptr < jsondata.end) {
PyErr_Format(JSON_DecodeError, "extra data after JSON description"
- " at position %d", jsondata.ptr-jsondata.str);
+ " at position " SSIZE_T_F,
+ (Py_ssize_t)(jsondata.ptr - jsondata.str));
Py_DECREF(str);
Py_DECREF(object);
return NULL;
| 0 | 5 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
61d86dc39dfc32e6b933d0c03594e53fe88d323e
|
Implemented recursion limit check for encoding/decoding arrays and objects
|
commit 61d86dc39dfc32e6b933d0c03594e53fe88d323e
Author: Dan Pascu <[email protected]>
Date: Tue Feb 28 13:02:18 2017 +0000
Implemented recursion limit check for encoding/decoding arrays and objects
diff --git a/cjson.c b/cjson.c
index 9084fb2..2a87de8 100644
--- a/cjson.c
+++ b/cjson.c
@@ -526,10 +526,16 @@ decode_json(JSONData *jsondata)
PyErr_SetString(JSON_DecodeError, "empty JSON description");
return NULL;
case '{':
+ if (Py_EnterRecursiveCall(" while decoding a JSON object"))
+ return NULL;
object = decode_object(jsondata);
+ Py_LeaveRecursiveCall();
break;
case '[':
+ if (Py_EnterRecursiveCall(" while decoding a JSON array"))
+ return NULL;
object = decode_array(jsondata);
+ Py_LeaveRecursiveCall();
break;
case '"':
object = decode_string(jsondata);
@@ -1084,11 +1090,26 @@ encode_object(PyObject *object)
} else if (PyInt_Check(object) || PyLong_Check(object)) {
return PyObject_Str(object);
} else if (PyList_Check(object)) {
- return encode_list(object);
+ PyObject *result;
+ if (Py_EnterRecursiveCall(" while encoding a JSON array from a Python list"))
+ return NULL;
+ result = encode_list(object);
+ Py_LeaveRecursiveCall();
+ return result;
} else if (PyTuple_Check(object)) {
- return encode_tuple(object);
+ PyObject *result;
+ if (Py_EnterRecursiveCall(" while encoding a JSON array from a Python tuple"))
+ return NULL;
+ result = encode_tuple(object);
+ Py_LeaveRecursiveCall();
+ return result;
} else if (PyDict_Check(object)) { // use PyMapping_Check(object) instead? -Dan
- return encode_dict(object);
+ PyObject *result;
+ if (Py_EnterRecursiveCall(" while encoding a JSON object"))
+ return NULL;
+ result = encode_dict(object);
+ Py_LeaveRecursiveCall();
+ return result;
} else {
PyErr_SetString(JSON_EncodeError, "object is not JSON encodable");
return NULL;
| 0 | 8 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
a454ab7c621f2e816fec9206feb4326d43ffe0d6
|
Fix encoding of UTF-16 surrogate pairs
UCS4 escape sequences aren't valid JSON, so when Py_UNICODE_WIDE
is defined, UTF-16 surrogate pairs need to be produced.
Decoding retains the surrogate pairs as separate code points
instead of joining them, something that perhaps should be
improved, but isn't invalid (just inconvenient)
|
commit a454ab7c621f2e816fec9206feb4326d43ffe0d6
Author: Claudio Freire <[email protected]>
Date: Tue Oct 2 16:56:22 2018 +0000
Fix encoding of UTF-16 surrogate pairs
UCS4 escape sequences aren't valid JSON, so when Py_UNICODE_WIDE
is defined, UTF-16 surrogate pairs need to be produced.
Decoding retains the surrogate pairs as separate code points
instead of joining them, something that perhaps should be
improved, but isn't invalid (just inconvenient)
diff --git a/cjson.c b/cjson.c
index d3ecc81..860162e 100644
--- a/cjson.c
+++ b/cjson.c
@@ -666,7 +666,7 @@ encode_unicode(PyObject *unicode)
static const char *hexdigit = "0123456789abcdef";
#ifdef Py_UNICODE_WIDE
- const Py_ssize_t expandsize = 10;
+ const Py_ssize_t expandsize = 12;
#else
const Py_ssize_t expandsize = 6;
#endif
@@ -713,46 +713,27 @@ encode_unicode(PyObject *unicode)
}
#ifdef Py_UNICODE_WIDE
- /* Map 21-bit characters to '\U00xxxxxx' */
+ /* Map 21-bit characters to UTF-16 surrogate pairs */
else if (ch >= 0x10000) {
+ unsigned short ucs1, ucs2;
+ ucs1 = (unsigned short)(((ch - 0x10000) >> 10) & 0x03FF) + 0xD800;
+ ucs2 = (unsigned short)((ch - 0x10000) & 0x03FF) + 0xDC00;
+
+ *p++ = '\\';
+ *p++ = 'u';
+ *p++ = hexdigit[(ucs1 >> 12) & 0x000F];
+ *p++ = hexdigit[(ucs1 >> 8) & 0x000F];
+ *p++ = hexdigit[(ucs1 >> 4) & 0x000F];
+ *p++ = hexdigit[ucs1 & 0x000F];
*p++ = '\\';
- *p++ = 'U';
- *p++ = hexdigit[(ch >> 28) & 0x0000000F];
- *p++ = hexdigit[(ch >> 24) & 0x0000000F];
- *p++ = hexdigit[(ch >> 20) & 0x0000000F];
- *p++ = hexdigit[(ch >> 16) & 0x0000000F];
- *p++ = hexdigit[(ch >> 12) & 0x0000000F];
- *p++ = hexdigit[(ch >> 8) & 0x0000000F];
- *p++ = hexdigit[(ch >> 4) & 0x0000000F];
- *p++ = hexdigit[ch & 0x0000000F];
+ *p++ = 'u';
+ *p++ = hexdigit[(ucs2 >> 12) & 0x000F];
+ *p++ = hexdigit[(ucs2 >> 8) & 0x000F];
+ *p++ = hexdigit[(ucs2 >> 4) & 0x000F];
+ *p++ = hexdigit[ucs2 & 0x000F];
continue;
}
#endif
- /* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
- else if (ch >= 0xD800 && ch < 0xDC00) {
- Py_UNICODE ch2;
- Py_UCS4 ucs;
-
- ch2 = *s++;
- size--;
- if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
- ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
- *p++ = '\\';
- *p++ = 'U';
- *p++ = hexdigit[(ucs >> 28) & 0x0000000F];
- *p++ = hexdigit[(ucs >> 24) & 0x0000000F];
- *p++ = hexdigit[(ucs >> 20) & 0x0000000F];
- *p++ = hexdigit[(ucs >> 16) & 0x0000000F];
- *p++ = hexdigit[(ucs >> 12) & 0x0000000F];
- *p++ = hexdigit[(ucs >> 8) & 0x0000000F];
- *p++ = hexdigit[(ucs >> 4) & 0x0000000F];
- *p++ = hexdigit[ucs & 0x0000000F];
- continue;
- }
- /* Fall through: isolated surrogates are copied as-is */
- s--;
- size++;
- }
/* Map 16-bit characters to '\uxxxx' */
if (ch >= 256) {
diff --git a/jsontest.py b/jsontest.py
index 0f79307..67aea38 100644
--- a/jsontest.py
+++ b/jsontest.py
@@ -325,9 +325,11 @@ class JsonTest(unittest.TestCase):
# narrow-but-escaped characters prevents string resizing.
# Note that u'\U0001D11E\u1234' also breaks, but sometimes goes
# undetected.
+ # In any case, in ECMA-404, only utf-16 surrogate pairs are
+ # valid, so \U0001D11E should be encoded as \ud834\udd1e
s = cjson.encode(u'\U0001D11E\U0001D11E\U0001D11E\U0001D11E'
u'\u1234\u1234\u1234\u1234\u1234\u1234')
- self.assertEqual(r'"\U0001d11e\U0001d11e\U0001d11e\U0001d11e'
+ self.assertEqual(r'"\ud834\udd1e\ud834\udd1e\ud834\udd1e\ud834\udd1e'
r'\u1234\u1234\u1234\u1234\u1234\u1234"', s)
def main():
| 0 | 2 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
dc2b8781b8666de5ca707318521f554904fdd690
|
Integrate modified 0001-fix-for-CVE-2010-1666 patch from Debian
|
commit dc2b8781b8666de5ca707318521f554904fdd690
Author: Saul Ibarra <[email protected]>
Date: Wed Jun 15 11:10:10 2011 +0000
Integrate modified 0001-fix-for-CVE-2010-1666 patch from Debian
diff --git a/cjson.c b/cjson.c
index 76ce8b4..9084fb2 100644
--- a/cjson.c
+++ b/cjson.c
@@ -663,17 +663,36 @@ encode_unicode(PyObject *unicode)
char *p;
static const char *hexdigit = "0123456789abcdef";
+#ifdef Py_UNICODE_WIDE
+ const Py_ssize_t expandsize = 10;
+#else
+ const Py_ssize_t expandsize = 6;
+#endif
+
+ /* Initial allocation is based on the longest-possible unichr
+ escape.
+
+ In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
+ unichr, so in this case it's the longest unichr escape. In
+ narrow (UTF-16) builds this is five chars per source unichr
+ since there are two unichrs in the surrogate pair, so in narrow
+ (UTF-16) builds it's not the longest unichr escape.
+
+ In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
+ so in the narrow (UTF-16) build case it's the longest unichr
+ escape.
+ */
s = PyUnicode_AS_UNICODE(unicode);
size = PyUnicode_GET_SIZE(unicode);
- if (size > (PY_SSIZE_T_MAX-2-1)/6) {
+ if (size > (PY_SSIZE_T_MAX-2-1)/expandsize) {
PyErr_SetString(PyExc_OverflowError,
"unicode object is too large to make repr");
return NULL;
}
- repr = PyString_FromStringAndSize(NULL, 2 + 6*size + 1);
+ repr = PyString_FromStringAndSize(NULL, 2 + expandsize*size + 1);
if (repr == NULL)
return NULL;
@@ -694,15 +713,6 @@ encode_unicode(PyObject *unicode)
#ifdef Py_UNICODE_WIDE
/* Map 21-bit characters to '\U00xxxxxx' */
else if (ch >= 0x10000) {
- int offset = p - PyString_AS_STRING(repr);
-
- /* Resize the string if necessary */
- if (offset + 12 > PyString_GET_SIZE(repr)) {
- if (_PyString_Resize(&repr, PyString_GET_SIZE(repr) + 100))
- return NULL;
- p = PyString_AS_STRING(repr) + offset;
- }
-
*p++ = '\\';
*p++ = 'U';
*p++ = hexdigit[(ch >> 28) & 0x0000000F];
diff --git a/jsontest.py b/jsontest.py
index b5ad0b2..0f79307 100644
--- a/jsontest.py
+++ b/jsontest.py
@@ -317,6 +317,18 @@ class JsonTest(unittest.TestCase):
def testWriteLong(self):
self.assertEqual("12345678901234567890", cjson.encode(12345678901234567890))
+
+ def testWriteLongUnicode(self):
+ # This test causes a buffer overrun in cjson 1.0.5, on UCS4 builds.
+ # The string length is only resized for wide unicode characters if
+ # there is less than 12 bytes of space left. Padding with
+ # narrow-but-escaped characters prevents string resizing.
+ # Note that u'\U0001D11E\u1234' also breaks, but sometimes goes
+ # undetected.
+ s = cjson.encode(u'\U0001D11E\U0001D11E\U0001D11E\U0001D11E'
+ u'\u1234\u1234\u1234\u1234\u1234\u1234')
+ self.assertEqual(r'"\U0001d11e\U0001d11e\U0001d11e\U0001d11e'
+ r'\u1234\u1234\u1234\u1234\u1234\u1234"', s)
def main():
unittest.main()
| 1 | 1 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
85bbce276950218c41e9d8d508ee1562e7ff0aff
|
Use repr instead of str when encoding floats to preserve full preicision
|
commit 85bbce276950218c41e9d8d508ee1562e7ff0aff
Author: Dan Pascu <[email protected]>
Date: Fri Mar 7 06:25:49 2008 +0000
Use repr instead of str when encoding floats to preserve full preicision
diff --git a/cjson.c b/cjson.c
index 04de52c..69aaf0f 100644
--- a/cjson.c
+++ b/cjson.c
@@ -1019,7 +1019,7 @@ encode_object(PyObject *object)
return PyString_FromString("-Infinity");
}
} else {
- return PyObject_Str(object);
+ return PyObject_Repr(object);
}
} else if (PyInt_Check(object) || PyLong_Check(object)) {
return PyObject_Str(object);
| 0 | 10 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
4067ad7e9e0b9783c290a9a7e04eb4498bd49a5e
|
Raised version and updated changelog
|
commit 4067ad7e9e0b9783c290a9a7e04eb4498bd49a5e
Author: Saul Ibarra <[email protected]>
Date: Wed Jun 15 12:02:05 2011 +0000
Raised version and updated changelog
diff --git a/debian/changelog b/debian/changelog
index 1bc4dc0..c9d2f73 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,15 @@
+python-cjson (1.0.5.1) unstable; urgency=low
+
+ * Use repr instead of str when encoding floats to preserve full preicision
+ * Fixed windows compilation problem introduced in 1.0.5
+ * Fixed float write test to work with latest high precision float encoding
+ * Fixed some list/dict decoding bugs. Use a state machine for decoding them.
+ * Improved decoding speed by using PyString_GET_SIZE instead of strlen
+ * Integrate modified 0001-fix-for-CVE-2010-1666 patch from Debian
+ * Reworked debian packaging
+
+ -- Saul Ibarra <[email protected]> Wed, 15 Jun 2011 13:23:55 +0200
+
python-cjson (1.0.5) unstable; urgency=low
* Check if module initialization failed.
diff --git a/setup.py b/setup.py
index 88b37a6..c315636 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@
from distutils.core import setup, Extension
-__version__ = "1.0.5"
+__version__ = "1.0.5.1"
macros = [('MODULE_VERSION', __version__)]
| 0 | 9 |
CVE-2010-1666
|
Buffer overflow in Dan Pascu python-cjson 1.0.5, when UCS-4 encoding is enabled, allows context-dependent attackers to cause a denial of service (application crash) or possibly have unspecified other impact via vectors involving crafted Unicode input to the cjson.encode function.
|
AGProjects/python-cjson
|
b477c18dca392fedb4c60df76ad8bf8db535786c
|
Fixed 2 potential buffer overflow errors when encoding string/unicode
|
commit b477c18dca392fedb4c60df76ad8bf8db535786c
Author: Dan Pascu <[email protected]>
Date: Wed Jul 25 13:45:51 2007 +0000
Fixed 2 potential buffer overflow errors when encoding string/unicode
diff --git a/ChangeLog b/ChangeLog
index 414dcc4..beed6d7 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -8,6 +8,8 @@ Changes in version 1.0.4
patch by David Rushby <[email protected]>).
* Fixed issue with not returning NULL after setting the OverflowError
when encoded strings would be too big.
+ * Fixed 2 potential buffer overflow errors when encoding string/unicode
+ (thanks to Ofer Faigon <[email protected]> for pointing them out).
Changes in version 1.0.3
------------------------
diff --git a/cjson.c b/cjson.c
index 50b580b..56bc669 100644
--- a/cjson.c
+++ b/cjson.c
@@ -542,7 +542,7 @@ encode_string(PyObject *string)
size_t newsize = 2 + 6 * op->ob_size;
PyObject *v;
- if (newsize > PY_SSIZE_T_MAX) {
+ if (op->ob_size > (PY_SSIZE_T_MAX-2)/6) {
PyErr_SetString(PyExc_OverflowError,
"string is too large to make repr");
return NULL;
@@ -617,6 +617,12 @@ encode_unicode(PyObject *unicode)
s = PyUnicode_AS_UNICODE(unicode);
size = PyUnicode_GET_SIZE(unicode);
+ if (size > (PY_SSIZE_T_MAX-2-1)/6) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unicode object is too large to make repr");
+ return NULL;
+ }
+
repr = PyString_FromStringAndSize(NULL, 2 + 6*size + 1);
if (repr == NULL)
return NULL;
| 0 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.