From 8d2aeb7082cca4a19b3700b62cae77cf50260217 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Fri, 24 Jul 2009 15:04:00 +0000 Subject: Cloudy theme IE (mostly 7/8) fixes --- theme/cloudy/css/display.css | 5 ++++- theme/cloudy/css/ie.css | 23 ++++++++++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/theme/cloudy/css/display.css b/theme/cloudy/css/display.css index 82a1a1e4e..ecf23fd74 100644 --- a/theme/cloudy/css/display.css +++ b/theme/cloudy/css/display.css @@ -934,7 +934,6 @@ float:left; font-size:0.95em; width:16px; float:right; -display:none; } .notices li:hover div.notice-options { display:block; @@ -984,6 +983,10 @@ text-decoration:none; padding-left:16px; } +.notice-options .notice_reply .notice_id { +display:none; +} + .notice-options form input.submit { width:16px; padding:2px 0; diff --git a/theme/cloudy/css/ie.css b/theme/cloudy/css/ie.css index 94c2093b1..dabadcd95 100644 --- a/theme/cloudy/css/ie.css +++ b/theme/cloudy/css/ie.css @@ -8,15 +8,32 @@ color:#fff; background-color:#ddffcc; } +#form_notice { +width:525px; +} +#form_notice .form_note { +top:-5px; +right:0; +} +#form_notice textarea { +width:97.75%; +} #form_notice .form_note + label { position:absolute; -top:25px; -left:83%; +top:87px; +left:77%; text-indent:-9999px; height:16px; width:16px; display:block; } +#form_notice #notice_data-attach { +filter: alpha(opacity = 0); +} + +#form_notice #notice_action-submit { +right:0; +} #aside_primary { width:181px; @@ -24,7 +41,7 @@ width:181px; #form_notice, #anon_notice { -top:158px; +top:190px; } #public #content, -- cgit v1.2.3-54-g00ecf From 932eab074d954b7f9add4a8b625c74a86b3bd8e1 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Fri, 24 Jul 2009 15:38:58 +0000 Subject: More IE fixes for Cloudy theme --- theme/cloudy/css/display.css | 16 +++++++++++----- theme/cloudy/css/ie.css | 1 + 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/theme/cloudy/css/display.css b/theme/cloudy/css/display.css index ecf23fd74..e3c5c3cc0 100644 --- a/theme/cloudy/css/display.css +++ b/theme/cloudy/css/display.css @@ -414,9 +414,12 @@ width:518px; min-height:322px; padding:20px; float:left; -border-radius-topleft:4px; --moz-border-radius-topleft:4px; --webkit-border-top-left-radius:4px; +border-radius:4px; +-moz-border-radius:4px; +-webkit-border-radius:4px; +border-radius-topright:0; +-moz-border-radius-topright:0; +-webkit-border-top-right-radius:0; border-style:solid; border-width:1px; } @@ -484,7 +487,7 @@ width:16px; height:16px; } #form_notice #notice_data-attach { -left:34.6%; +left:40%; padding:0; height:16px; } @@ -528,9 +531,12 @@ float:left; #form_notice .success { float:left; clear:both; -width:81.5%; +width:83.5%; margin-bottom:0; line-height:1.618; +position:absolute; +top:87px; +left:0; } #form_notice #notice_data-attach_selected code { float:left; diff --git a/theme/cloudy/css/ie.css b/theme/cloudy/css/ie.css index dabadcd95..a698676fb 100644 --- a/theme/cloudy/css/ie.css +++ b/theme/cloudy/css/ie.css @@ -29,6 +29,7 @@ display:block; } #form_notice #notice_data-attach { filter: alpha(opacity = 0); +left:33.5%; } #form_notice #notice_action-submit { -- cgit v1.2.3-54-g00ecf From 70cc09a5c2863f4a9a24f65db8830146becbc72a Mon Sep 17 00:00:00 2001 From: Brenda Wallace Date: Sat, 25 Jul 2009 15:58:42 +1200 Subject: check the postgresql database is UTF8 before allowing installation to proceed --- install.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/install.php b/install.php index 1d3a531c5..d5e8e8b61 100644 --- a/install.php +++ b/install.php @@ -243,6 +243,14 @@ function pgsql_db_installer($host, $database, $username, $password, $sitename) { updateStatus("Checking database..."); $conn = pg_connect($connstring); + //ensure database encoding is UTF8 + $record = pg_fetch_object(pg_query($conn, 'SHOW server_encoding')); + if ($record->server_encoding != 'UTF8') { + updateStatus("Laconica requires UTF8 character encoding. Your database is ". htmlentities($record->server_encoding)); + showForm(); + return false; + } + updateStatus("Running database script..."); //wrap in transaction; pg_query($conn, 'BEGIN'); -- cgit v1.2.3-54-g00ecf From f86faaf341ee6e6e8cfd264e1d645cc0d964d85b Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Sat, 25 Jul 2009 00:19:12 -0400 Subject: If cannot connect, then stop the installation --- install.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/install.php b/install.php index d5e8e8b61..901e502f1 100644 --- a/install.php +++ b/install.php @@ -242,6 +242,12 @@ function pgsql_db_installer($host, $database, $username, $password, $sitename) { updateStatus("Starting installation..."); updateStatus("Checking database..."); $conn = pg_connect($connstring); + + if ($conn ===false) { + updateStatus("Failed to connect to database: $connstring"); + showForm(); + return false; + } //ensure database encoding is UTF8 $record = pg_fetch_object(pg_query($conn, 'SHOW server_encoding')); -- cgit v1.2.3-54-g00ecf From e0b877b26c5e93809b2a53b6c46326d5e31fa0e8 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 17:37:37 +0000 Subject: Removed
structure from NoticeListItem::showDeleteLink. Reason: To speed up DOM load by cutting down 3 nodes in each notice list item. Generally each notice option should be a list item in a
    , however, there is no tangible benefit for the user using this approach. In this case, minimalism is favoured. Similarly, the new approach will make 5 fewer function calls on the server side. --- lib/noticelist.php | 6 +----- theme/base/css/display.css | 6 +----- theme/default/css/display.css | 2 +- theme/identica/css/display.css | 2 +- 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/lib/noticelist.php b/lib/noticelist.php index 44726a17b..d4d4fc711 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -479,13 +479,9 @@ class NoticeListItem extends Widget if ($user && $this->notice->profile_id == $user->id) { $deleteurl = common_local_url('deletenotice', array('notice' => $this->notice->id)); - $this->out->elementStart('dl', 'notice_delete'); - $this->out->element('dt', null, _('Delete this notice')); - $this->out->elementStart('dd'); $this->out->element('a', array('href' => $deleteurl, + 'class' => 'notice_delete', 'title' => _('Delete this notice')), _('Delete')); - $this->out->elementEnd('dd'); - $this->out->elementEnd('dl'); } } diff --git a/theme/base/css/display.css b/theme/base/css/display.css index 867dc0ef7..80ab397ee 100644 --- a/theme/base/css/display.css +++ b/theme/base/css/display.css @@ -937,22 +937,18 @@ display:block; border:0; } .notice-options .notice_reply a, -.notice-options .notice_delete a { +.notice-options .notice_delete { text-decoration:none; padding-left:16px; } - .notice-options form input.submit { width:16px; padding:2px 0; } - -.notice-options .notice_delete dt, .notice-options .form_favor legend, .notice-options .form_disfavor legend { display:none; } -.notice-options .notice_delete fieldset, .notice-options .form_favor fieldset, .notice-options .form_disfavor fieldset { border:0; diff --git a/theme/default/css/display.css b/theme/default/css/display.css index 251d6706b..e8df27718 100644 --- a/theme/default/css/display.css +++ b/theme/default/css/display.css @@ -227,7 +227,7 @@ background:transparent url(../../base/images/icons/twotone/green/favourite.gif) .notice-options form.form_disfavor input.submit { background:transparent url(../../base/images/icons/twotone/green/disfavourite.gif) no-repeat 0 45%; } -.notice-options .notice_delete a { +.notice-options .notice_delete { background:transparent url(../../base/images/icons/twotone/green/trash.gif) no-repeat 0 45%; } diff --git a/theme/identica/css/display.css b/theme/identica/css/display.css index 42a4573a7..7dd4256bf 100644 --- a/theme/identica/css/display.css +++ b/theme/identica/css/display.css @@ -227,7 +227,7 @@ background:transparent url(../../base/images/icons/twotone/green/favourite.gif) .notice-options form.form_disfavor input.submit { background:transparent url(../../base/images/icons/twotone/green/disfavourite.gif) no-repeat 0 45%; } -.notice-options .notice_delete a { +.notice-options .notice_delete { background:transparent url(../../base/images/icons/twotone/green/trash.gif) no-repeat 0 45%; } -- cgit v1.2.3-54-g00ecf From 66a959a7762474e00264ddf942fb7b681bdf2045 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 17:44:19 +0000 Subject: Removed
    structure from NoticeListItem::showReplyLink. Reason: Same as commit e0b877b26c5e93809b2a53b6c46326d5e31fa0e8. --- lib/noticelist.php | 7 +------ theme/base/css/display.css | 8 +------- theme/default/css/display.css | 6 +----- theme/identica/css/display.css | 6 +----- 4 files changed, 4 insertions(+), 23 deletions(-) diff --git a/lib/noticelist.php b/lib/noticelist.php index d4d4fc711..0bd98fef7 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -453,17 +453,12 @@ class NoticeListItem extends Widget if (common_logged_in()) { $reply_url = common_local_url('newnotice', array('replyto' => $this->profile->nickname)); - - $this->out->elementStart('dl', 'notice_reply'); - $this->out->element('dt', null, _('Reply to this notice')); - $this->out->elementStart('dd'); $this->out->elementStart('a', array('href' => $reply_url, + 'class' => 'notice_reply', 'title' => _('Reply to this notice'))); $this->out->text(_('Reply')); $this->out->element('span', 'notice_id', $this->notice->id); $this->out->elementEnd('a'); - $this->out->elementEnd('dd'); - $this->out->elementEnd('dl'); } } diff --git a/theme/base/css/display.css b/theme/base/css/display.css index 80ab397ee..41fc5c20e 100644 --- a/theme/base/css/display.css +++ b/theme/base/css/display.css @@ -921,22 +921,16 @@ left:29px; .notice-options .notice_delete { right:0; } -.notice-options .notice_reply dt { -display:none; -} - .notice-options input, .notice-options a { text-indent:-9999px; outline:none; } - -.notice-options .notice_reply a, .notice-options input.submit { display:block; border:0; } -.notice-options .notice_reply a, +.notice-options .notice_reply, .notice-options .notice_delete { text-decoration:none; padding-left:16px; diff --git a/theme/default/css/display.css b/theme/default/css/display.css index e8df27718..b7c86ae07 100644 --- a/theme/default/css/display.css +++ b/theme/default/css/display.css @@ -214,11 +214,7 @@ background:transparent url(../../base/images/icons/twotone/green/clip-02.gif) no #attachments .attachment { background:none; } -.notice-options .notice_reply a, -.notice-options form input.submit { -background-color:transparent; -} -.notice-options .notice_reply a { +.notice-options .notice_reply { background:transparent url(../../base/images/icons/twotone/green/reply.gif) no-repeat 0 45%; } .notice-options form.form_favor input.submit { diff --git a/theme/identica/css/display.css b/theme/identica/css/display.css index 7dd4256bf..6a8820495 100644 --- a/theme/identica/css/display.css +++ b/theme/identica/css/display.css @@ -214,11 +214,7 @@ background:transparent url(../../base/images/icons/twotone/green/clip-02.gif) no #attachments .attachment { background:none; } -.notice-options .notice_reply a, -.notice-options form input.submit { -background-color:transparent; -} -.notice-options .notice_reply a { +.notice-options .notice_reply { background:transparent url(../../base/images/icons/twotone/green/reply.gif) no-repeat 0 45%; } .notice-options form.form_favor input.submit { -- cgit v1.2.3-54-g00ecf From 89f32432bace26feb46299728ce2878fc5df4d20 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 17:53:37 +0000 Subject: Updated pigeonthoughts theme --- theme/pigeonthoughts/css/base.css | 14 ++------------ theme/pigeonthoughts/css/display.css | 8 ++------ 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/theme/pigeonthoughts/css/base.css b/theme/pigeonthoughts/css/base.css index 5d5eb9896..f2256b7ca 100644 --- a/theme/pigeonthoughts/css/base.css +++ b/theme/pigeonthoughts/css/base.css @@ -893,38 +893,28 @@ left:29px; .notice-options .notice_delete { right:0; } -.notice-options .notice_reply dt { -display:none; -} - .notice-options input, .notice-options a { text-indent:-9999px; outline:none; } - -.notice-options .notice_reply a, .notice-options input.submit { display:block; border:0; } -.notice-options .notice_reply a, -.notice-options .notice_delete a { +.notice-options .notice_reply, +.notice-options .notice_delete { text-decoration:none; padding-left:16px; } - .notice-options form input.submit { width:16px; padding:2px 0; } - -.notice-options .notice_delete dt, .notice-options .form_favor legend, .notice-options .form_disfavor legend { display:none; } -.notice-options .notice_delete fieldset, .notice-options .form_favor fieldset, .notice-options .form_disfavor fieldset { border:0; diff --git a/theme/pigeonthoughts/css/display.css b/theme/pigeonthoughts/css/display.css index f113225fb..1bf37bf73 100644 --- a/theme/pigeonthoughts/css/display.css +++ b/theme/pigeonthoughts/css/display.css @@ -269,11 +269,7 @@ background:transparent url(../../base/images/icons/twotone/green/clip-02.gif) no #attachments .attachment { background:none; } -.notice-options .notice_reply a, -.notice-options form input.submit { -background-color:transparent; -} -.notice-options .notice_reply a { +.notice-options .notice_reply { background:transparent url(../../base/images/icons/twotone/green/reply.gif) no-repeat 0 45%; } .notice-options form.form_favor input.submit { @@ -282,7 +278,7 @@ background:transparent url(../../base/images/icons/twotone/green/favourite.gif) .notice-options form.form_disfavor input.submit { background:transparent url(../../base/images/icons/twotone/green/disfavourite.gif) no-repeat 0 45%; } -.notice-options .notice_delete a { +.notice-options .notice_delete { background:transparent url(../../base/images/icons/twotone/green/trash.gif) no-repeat 0 45%; } -- cgit v1.2.3-54-g00ecf From 9c09bfe4d721a7a3be907dcba42eb6d31f50020d Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 18:04:45 +0000 Subject: Removed
    structure from NoticeListItem::showNoticeLink. Reason: Arguably, the earlier structure was unnecessarily verbose. Same as commit e0b877b26c5e93809b2a53b6c46326d5e31fa0e8. --- lib/noticelist.php | 7 +------ theme/base/css/display.css | 3 +-- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/lib/noticelist.php b/lib/noticelist.php index 0bd98fef7..a3d20025f 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -357,19 +357,14 @@ class NoticeListItem extends Widget preg_match('/^http/', $this->notice->uri)) { $noticeurl = $this->notice->uri; } - $this->out->elementStart('dl', 'timestamp'); - $this->out->element('dt', null, _('Published')); - $this->out->elementStart('dd', null); $this->out->elementStart('a', array('rel' => 'bookmark', + 'class' => 'timestamp', 'href' => $noticeurl)); $dt = common_date_iso8601($this->notice->created); $this->out->element('abbr', array('class' => 'published', 'title' => $dt), common_date_string($this->notice->created)); - $this->out->elementEnd('a'); - $this->out->elementEnd('dd'); - $this->out->elementEnd('dl'); } /** diff --git a/theme/base/css/display.css b/theme/base/css/display.css index 41fc5c20e..8b9fcd309 100644 --- a/theme/base/css/display.css +++ b/theme/base/css/display.css @@ -882,11 +882,10 @@ font-size:1.025em; display:inline; } -.notice div.entry-content .timestamp dt, .notice div.entry-content .response dt { display:none; } -.notice div.entry-content .timestamp a { +.notice div.entry-content a.timestamp { display:inline-block; } .notice div.entry-content .device dt { -- cgit v1.2.3-54-g00ecf From e37834191082a76370525b41ad57ae56f726fc65 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 18:22:05 +0000 Subject: Removed
    structure from NoticeListItem::showNoticeSource. Same as commit e0b877b26c5e93809b2a53b6c46326d5e31fa0e8. --- lib/noticelist.php | 14 +++++++------- theme/base/css/display.css | 3 --- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/noticelist.php b/lib/noticelist.php index a3d20025f..7d363a5a2 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -379,8 +379,8 @@ class NoticeListItem extends Widget function showNoticeSource() { if ($this->notice->source) { - $this->out->elementStart('dl', 'device'); - $this->out->element('dt', null, _('From')); + $this->out->elementStart('span', 'source'); + $this->out->text(_('from')); $source_name = _($this->notice->source); switch ($this->notice->source) { case 'web': @@ -389,22 +389,22 @@ class NoticeListItem extends Widget case 'omb': case 'system': case 'api': - $this->out->element('dd', null, $source_name); + $this->out->element('span', 'device', $source_name); break; default: $ns = Notice_source::staticGet($this->notice->source); if ($ns) { - $this->out->elementStart('dd', null); + $this->out->elementStart('span', 'device'); $this->out->element('a', array('href' => $ns->url, 'rel' => 'external'), $ns->name); - $this->out->elementEnd('dd'); + $this->out->elementEnd('span'); } else { - $this->out->element('dd', null, $source_name); + $this->out->element('span', 'device', $source_name); } break; } - $this->out->elementEnd('dl'); + $this->out->elementEnd('span'); } } diff --git a/theme/base/css/display.css b/theme/base/css/display.css index 8b9fcd309..3b3c0e19f 100644 --- a/theme/base/css/display.css +++ b/theme/base/css/display.css @@ -888,9 +888,6 @@ display:none; .notice div.entry-content a.timestamp { display:inline-block; } -.notice div.entry-content .device dt { -text-transform:lowercase; -} .notice-options { position:relative; -- cgit v1.2.3-54-g00ecf From 0b47e71e7a693b6bd9230043c6e1078059de16f6 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 18:26:00 +0000 Subject: Removed
    structure from NoticeListItem::showContext. Same as committ e0b877b26c5e93809b2a53b6c46326d5e31fa0e8. --- lib/noticelist.php | 8 ++------ theme/base/css/display.css | 9 --------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/lib/noticelist.php b/lib/noticelist.php index 7d363a5a2..a8d5059ca 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -424,13 +424,9 @@ class NoticeListItem extends Widget && $this->notice->conversation != $this->notice->id) { $convurl = common_local_url('conversation', array('id' => $this->notice->conversation)); - $this->out->elementStart('dl', 'response'); - $this->out->element('dt', null, _('To')); - $this->out->elementStart('dd'); - $this->out->element('a', array('href' => $convurl.'#notice-'.$this->notice->id), + $this->out->element('a', array('href' => $convurl.'#notice-'.$this->notice->id, + 'class' => 'response'), _('in context')); - $this->out->elementEnd('dd'); - $this->out->elementEnd('dl'); } } diff --git a/theme/base/css/display.css b/theme/base/css/display.css index 3b3c0e19f..1e4937473 100644 --- a/theme/base/css/display.css +++ b/theme/base/css/display.css @@ -876,15 +876,6 @@ float:left; font-size:1.025em; } -.notice div.entry-content dl, -.notice div.entry-content dt, -.notice div.entry-content dd { -display:inline; -} - -.notice div.entry-content .response dt { -display:none; -} .notice div.entry-content a.timestamp { display:inline-block; } -- cgit v1.2.3-54-g00ecf From cdf6d655b5a1f6378333c9a30aa40ff2f00b92fb Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 18:29:30 +0000 Subject: Minor change to timestamp selector --- theme/base/css/display.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/theme/base/css/display.css b/theme/base/css/display.css index 1e4937473..364ea0b62 100644 --- a/theme/base/css/display.css +++ b/theme/base/css/display.css @@ -876,7 +876,7 @@ float:left; font-size:1.025em; } -.notice div.entry-content a.timestamp { +.notice div.entry-content .timestamp { display:inline-block; } -- cgit v1.2.3-54-g00ecf From ef571f731c9a2706f16b969dabf78cae80e0e46d Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Sat, 25 Jul 2009 18:30:18 +0000 Subject: Updated pigeontheme to reflect the changes made to entry-content structure --- theme/pigeonthoughts/css/base.css | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/theme/pigeonthoughts/css/base.css b/theme/pigeonthoughts/css/base.css index f2256b7ca..980d7ddd7 100644 --- a/theme/pigeonthoughts/css/base.css +++ b/theme/pigeonthoughts/css/base.css @@ -847,23 +847,9 @@ margin-left:0; float:left; font-size:1.025em; } - -.notice div.entry-content dl, -.notice div.entry-content dt, -.notice div.entry-content dd { -display:inline; -} - -.notice div.entry-content .timestamp dt, -.notice div.entry-content .response dt { -display:none; -} -.notice div.entry-content .timestamp a { +.notice div.entry-content .timestamp { display:inline-block; } -.notice div.entry-content .device dt { -text-transform:lowercase; -} .notice-options { position:relative; -- cgit v1.2.3-54-g00ecf From d3a72431bef054217a71a97d3a13fd9b293fb86d Mon Sep 17 00:00:00 2001 From: Brenda Wallace Date: Sun, 26 Jul 2009 16:34:27 +1200 Subject: lowercase tags using mb_convert_case(), which understands many more alphabets than I do. --- lib/util.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/util.php b/lib/util.php index c7c82dba2..d784bb793 100644 --- a/lib/util.php +++ b/lib/util.php @@ -595,7 +595,8 @@ function common_tag_link($tag) function common_canonical_tag($tag) { - return strtolower(str_replace(array('-', '_', '.'), '', $tag)); + $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8"); + return str_replace(array('-', '_', '.'), '', $tag); } function common_valid_profile_tag($str) -- cgit v1.2.3-54-g00ecf From b9cf19a2ee4b483709f1e964860fcf9209c4ba05 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Mon, 27 Jul 2009 02:54:51 +0000 Subject: Better error handling when updating Facebook --- lib/facebookutil.php | 13 ++++++++----- lib/mail.php | 8 ++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/lib/facebookutil.php b/lib/facebookutil.php index 85077c254..b7688f04f 100644 --- a/lib/facebookutil.php +++ b/lib/facebookutil.php @@ -193,14 +193,16 @@ function facebookBroadcastNotice($notice) $facebook->api_client->users_setStatus($status, $fbuid, false, true); } } catch(FacebookRestClientException $e) { - common_log(LOG_ERR, $e->getMessage()); + + $code = $e->getCode(); + + common_log(LOG_ERR, 'Facebook returned error code ' . + $code . ': ' . $e->getMessage()); common_log(LOG_ERR, 'Unable to update Facebook status for ' . "$user->nickname (user id: $user->id)!"); - $code = $e->getCode(); - - if ($code >= 200) { + if ($code == 200 || $code == 250) { // 200 The application does not have permission to operate on the passed in uid parameter. // 250 Updating status requires the extended permission status_update or publish_stream. @@ -216,7 +218,8 @@ function facebookBroadcastNotice($notice) try { updateProfileBox($facebook, $flink, $notice); } catch(FacebookRestClientException $e) { - common_log(LOG_WARNING, $e->getMessage()); + common_log(LOG_ERR, 'Facebook returned error code ' . + $e->getCode() . ': ' . $e->getMessage()); common_log(LOG_WARNING, 'Unable to update Facebook profile box for ' . "$user->nickname (user id: $user->id)."); diff --git a/lib/mail.php b/lib/mail.php index 262f788ee..0050ad810 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -679,17 +679,17 @@ function mail_facebook_app_removed($user) $site_name = common_config('site', 'name'); $subject = sprintf( - _('Your %s Facebook application access has been disabled.', + _('Your %1\$s Facebook application access has been disabled.', $site_name)); $body = sprintf(_("Hi, %1\$s. We're sorry to inform you that we are " . - 'unable to update your Facebook status from %s, and have disabled ' . + 'unable to update your Facebook status from %2\$s, and have disabled ' . 'the Facebook application for your account. This may be because ' . 'you have removed the Facebook application\'s authorization, or ' . 'have deleted your Facebook account. You can re-enable the ' . 'Facebook application and automatic status updating by ' . - "re-installing the %1\$s Facebook application.\n\nRegards,\n\n%1\$s"), - $site_name); + "re-installing the %2\$s Facebook application.\n\nRegards,\n\n%2\$s"), + $user->nickname, $site_name); common_init_locale(); return mail_to_user($user, $subject, $body); -- cgit v1.2.3-54-g00ecf From 0c8d003d40fb947d2f79398137c039803e0a5966 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Mon, 27 Jul 2009 16:57:30 +0000 Subject: Added config options for site's default design value --- config.php.sample | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/config.php.sample b/config.php.sample index 57aa6a6c8..36e62f70f 100644 --- a/config.php.sample +++ b/config.php.sample @@ -18,6 +18,14 @@ $config['site']['server'] = 'localhost'; $config['site']['path'] = 'laconica'; // $config['site']['fancy'] = false; // $config['site']['theme'] = 'default'; +// Sets the site's default design values (match it with the values in the theme) +// $config['site']['design']['backgroundcolor'] = '#F0F2F5'; +// $config['site']['design']['contentcolor'] = '#FFFFFF'; +// $config['site']['design']['sidebarcolor'] = '#CEE1E9'; +// $config['site']['design']['textcolor'] = '#000000'; +// $config['site']['design']['linkcolor'] = '#002E6E'; +// $config['site']['design']['backgroundimage'] = null; +// $config['site']['design']['disposition'] = 1; // To enable the built-in mobile style sheet, defaults to false. // $config['site']['mobile'] = true; // For contact email, defaults to $_SERVER["SERVER_ADMIN"] -- cgit v1.2.3-54-g00ecf From 50a343bcf73d7ced643ce40ad31f479d584cb5c1 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 27 Jul 2009 13:11:46 -0400 Subject: script to create a simulation database --- scripts/createsim.php | 142 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 scripts/createsim.php diff --git a/scripts/createsim.php b/scripts/createsim.php new file mode 100644 index 000000000..eb97a624d --- /dev/null +++ b/scripts/createsim.php @@ -0,0 +1,142 @@ +#!/usr/bin/env php +. + */ + +define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); + +$shortoptions = 'u:n:b:t:x:'; +$longoptions = array('users=', 'notices=', 'subscriptions=', 'tags=', 'prefix='); + +$helptext = << sprintf('%s%d', $userprefix, $i), + 'password' => sprintf('password%d', $i), + 'fullname' => sprintf('Test User %d', $i))); +} + +function newNotice($i, $tagmax) +{ + global $userprefix; + + $n = rand(0, $i - 1); + $user = User::staticGet('nickname', sprintf('%s%d', $userprefix, $n)); + + $is_reply = rand(0, 4); + + $content = 'Test notice content'; + + if ($is_reply == 0) { + $n = rand(0, $i - 1); + $content = "@$userprefix$n " . $content; + } + + $has_hash = rand(0, 2); + + if ($has_hash == 0) { + $hashcount = rand(0, 2); + for ($j = 0; $j < $hashcount; $j++) { + $h = rand(0, $tagmax); + $content .= " #tag{$h}"; + } + } + + $notice = Notice::saveNew($user->id, $content, 'system'); +} + +function newSub($i) +{ + global $userprefix; + $f = rand(0, $i - 1); + + $fromnick = sprintf('%s%d', $userprefix, $f); + + $from = User::staticGet('nickname', $fromnick); + + if (empty($from)) { + throw new Exception("Can't find user '$fromnick'."); + } + + $t = rand(0, $i - 1); + + if ($t == $f) { + $t++; + if ($t > $i - 1) { + $t = 0; + } + } + + $tunic = sprintf('%s%d', $userprefix, $t); + + $to = User::staticGet('nickname', $tunic); + + if (empty($from)) { + throw new Exception("Can't find user '$tunic'."); + } + + subs_subscribe_to($from, $to); +} + +function main($usercount, $noticeavg, $subsavg, $tagmax) +{ + $n = 1; + + newUser(0); + + // # registrations + # notices + # subs + + $events = $usercount + ($usercount * ($noticeavg + $subsavg)); + + for ($i = 0; $i < $events; $i++) + { + $e = rand(0, 1 + $noticeavg + $subsavg); + + if ($e == 0) { + newUser($n); + $n++; + } else if ($e < $noticeavg + 1) { + newNotice($n, $tagmax); + } else { + newSub($n); + } + } +} + +$usercount = (have_option('u', 'users')) ? get_option_value('u', 'users') : 100; +$noticeavg = (have_option('n', 'notices')) ? get_option_value('n', 'notices') : 100; +$subsavg = (have_option('b', 'subscriptions')) ? get_option_value('b', 'subscriptions') : min($usercount/20, 10); +$tagmax = (have_option('t', 'tags')) ? get_option_value('t', 'tags') : 10000; +$userprefix = (have_option('x', 'prefix')) ? get_option_value('x', 'prefix') : 'testuser'; + +main($usercount, $noticeavg, $subsavg, $tagmax); -- cgit v1.2.3-54-g00ecf From ff7f6ea583ee835ee81ec8b00d20a9f72821411f Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 27 Jul 2009 13:26:53 -0400 Subject: want a minimum of 10 subs per user --- scripts/createsim.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/createsim.php b/scripts/createsim.php index eb97a624d..71827ba5b 100644 --- a/scripts/createsim.php +++ b/scripts/createsim.php @@ -135,7 +135,7 @@ function main($usercount, $noticeavg, $subsavg, $tagmax) $usercount = (have_option('u', 'users')) ? get_option_value('u', 'users') : 100; $noticeavg = (have_option('n', 'notices')) ? get_option_value('n', 'notices') : 100; -$subsavg = (have_option('b', 'subscriptions')) ? get_option_value('b', 'subscriptions') : min($usercount/20, 10); +$subsavg = (have_option('b', 'subscriptions')) ? get_option_value('b', 'subscriptions') : max($usercount/20, 10); $tagmax = (have_option('t', 'tags')) ? get_option_value('t', 'tags') : 10000; $userprefix = (have_option('x', 'prefix')) ? get_option_value('x', 'prefix') : 'testuser'; -- cgit v1.2.3-54-g00ecf From ac75772150c3fe9411408ac44db04e774d095aa0 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Mon, 27 Jul 2009 13:42:03 -0400 Subject: Sanitize html returned by oEmbed providers to protect laconica from XSS attacks --- extlib/htmLawed/htmLawed.php | 715 ++++++++++++ extlib/htmLawed/htmLawedTest.php | 592 ++++++++++ extlib/htmLawed/htmLawed_README.htm | 1979 +++++++++++++++++++++++++++++++++ extlib/htmLawed/htmLawed_README.txt | 1600 ++++++++++++++++++++++++++ extlib/htmLawed/htmLawed_TESTCASE.txt | 370 ++++++ lib/attachmentlist.php | 7 +- 6 files changed, 5262 insertions(+), 1 deletion(-) create mode 100644 extlib/htmLawed/htmLawed.php create mode 100644 extlib/htmLawed/htmLawedTest.php create mode 100644 extlib/htmLawed/htmLawed_README.htm create mode 100644 extlib/htmLawed/htmLawed_README.txt create mode 100644 extlib/htmLawed/htmLawed_TESTCASE.txt diff --git a/extlib/htmLawed/htmLawed.php b/extlib/htmLawed/htmLawed.php new file mode 100644 index 000000000..17f6e98ca --- /dev/null +++ b/extlib/htmLawed/htmLawed.php @@ -0,0 +1,715 @@ +1, 'abbr'=>1, 'acronym'=>1, 'address'=>1, 'applet'=>1, 'area'=>1, 'b'=>1, 'bdo'=>1, 'big'=>1, 'blockquote'=>1, 'br'=>1, 'button'=>1, 'caption'=>1, 'center'=>1, 'cite'=>1, 'code'=>1, 'col'=>1, 'colgroup'=>1, 'dd'=>1, 'del'=>1, 'dfn'=>1, 'dir'=>1, 'div'=>1, 'dl'=>1, 'dt'=>1, 'em'=>1, 'embed'=>1, 'fieldset'=>1, 'font'=>1, 'form'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'hr'=>1, 'i'=>1, 'iframe'=>1, 'img'=>1, 'input'=>1, 'ins'=>1, 'isindex'=>1, 'kbd'=>1, 'label'=>1, 'legend'=>1, 'li'=>1, 'map'=>1, 'menu'=>1, 'noscript'=>1, 'object'=>1, 'ol'=>1, 'optgroup'=>1, 'option'=>1, 'p'=>1, 'param'=>1, 'pre'=>1, 'q'=>1, 'rb'=>1, 'rbc'=>1, 'rp'=>1, 'rt'=>1, 'rtc'=>1, 'ruby'=>1, 's'=>1, 'samp'=>1, 'script'=>1, 'select'=>1, 'small'=>1, 'span'=>1, 'strike'=>1, 'strong'=>1, 'sub'=>1, 'sup'=>1, 'table'=>1, 'tbody'=>1, 'td'=>1, 'textarea'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1, 'tt'=>1, 'u'=>1, 'ul'=>1, 'var'=>1); // 86/deprecated+embed+ruby +if(!empty($C['safe'])){ + unset($e['applet'], $e['embed'], $e['iframe'], $e['object'], $e['script']); +} +$x = !empty($C['elements']) ? str_replace(array("\n", "\r", "\t", ' '), '', $C['elements']) : '*'; +if($x == '-*'){$e = array();} +elseif(strpos($x, '*') === false){$e = array_flip(explode(',', $x));} +else{ + if(isset($x[1])){ + preg_match_all('`(?:^|-|\+)[^\-+]+?(?=-|\+|$)`', $x, $m, PREG_SET_ORDER); + for($i=count($m); --$i>=0;){$m[$i] = $m[$i][0];} + foreach($m as $v){ + if($v[0] == '+'){$e[substr($v, 1)] = 1;} + if($v[0] == '-' && isset($e[($v = substr($v, 1))]) && !in_array('+'. $v, $m)){unset($e[$v]);} + } + } +} +$C['elements'] =& $e; +// config attrs +$x = !empty($C['deny_attribute']) ? str_replace(array("\n", "\r", "\t", ' '), '', $C['deny_attribute']) : ''; +$x = array_flip((isset($x[0]) && $x[0] == '*') ? explode('-', $x) : explode(',', $x. (!empty($C['safe']) ? ',on*' : ''))); +if(isset($x['on*'])){ + unset($x['on*']); + $x += array('onblur'=>1, 'onchange'=>1, 'onclick'=>1, 'ondblclick'=>1, 'onfocus'=>1, 'onkeydown'=>1, 'onkeypress'=>1, 'onkeyup'=>1, 'onmousedown'=>1, 'onmousemove'=>1, 'onmouseout'=>1, 'onmouseover'=>1, 'onmouseup'=>1, 'onreset'=>1, 'onselect'=>1, 'onsubmit'=>1); +} +$C['deny_attribute'] = $x; +// config URL +$x = (isset($C['schemes'][2]) && strpos($C['schemes'], ':')) ? strtolower($C['schemes']) : 'href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; *:file, http, https'; +$C['schemes'] = array(); +foreach(explode(';', str_replace(array(' ', "\t", "\r", "\n"), '', $x)) as $v){ + $x = $x2 = null; list($x, $x2) = explode(':', $v, 2); + if($x2){$C['schemes'][$x] = array_flip(explode(',', $x2));} +} +if(!isset($C['schemes']['*'])){$C['schemes']['*'] = array('file'=>1, 'http'=>1, 'https'=>1,);} +if(!empty($C['safe']) && empty($C['schemes']['style'])){$C['schemes']['style'] = array('nil'=>1);} +$C['abs_url'] = isset($C['abs_url']) ? $C['abs_url'] : 0; +if(!isset($C['base_url']) or !preg_match('`^[a-zA-Z\d.+\-]+://[^/]+/(.+?/)?$`', $C['base_url'])){ + $C['base_url'] = $C['abs_url'] = 0; +} +// config rest +$C['and_mark'] = empty($C['and_mark']) ? 0 : 1; +$C['anti_link_spam'] = (isset($C['anti_link_spam']) && is_array($C['anti_link_spam']) && count($C['anti_link_spam']) == 2 && (empty($C['anti_link_spam'][0]) or hl_regex($C['anti_link_spam'][0])) && (empty($C['anti_link_spam'][1]) or hl_regex($C['anti_link_spam'][1]))) ? $C['anti_link_spam'] : 0; +$C['anti_mail_spam'] = isset($C['anti_mail_spam']) ? $C['anti_mail_spam'] : 0; +$C['balance'] = isset($C['balance']) ? (bool)$C['balance'] : 1; +$C['cdata'] = isset($C['cdata']) ? $C['cdata'] : (empty($C['safe']) ? 3 : 0); +$C['clean_ms_char'] = empty($C['clean_ms_char']) ? 0 : $C['clean_ms_char']; +$C['comment'] = isset($C['comment']) ? $C['comment'] : (empty($C['safe']) ? 3 : 0); +$C['css_expression'] = empty($C['css_expression']) ? 0 : 1; +$C['hexdec_entity'] = isset($C['hexdec_entity']) ? $C['hexdec_entity'] : 1; +$C['hook'] = (!empty($C['hook']) && function_exists($C['hook'])) ? $C['hook'] : 0; +$C['hook_tag'] = (!empty($C['hook_tag']) && function_exists($C['hook_tag'])) ? $C['hook_tag'] : 0; +$C['keep_bad'] = isset($C['keep_bad']) ? $C['keep_bad'] : 6; +$C['lc_std_val'] = isset($C['lc_std_val']) ? (bool)$C['lc_std_val'] : 1; +$C['make_tag_strict'] = isset($C['make_tag_strict']) ? $C['make_tag_strict'] : 1; +$C['named_entity'] = isset($C['named_entity']) ? (bool)$C['named_entity'] : 1; +$C['no_deprecated_attr'] = isset($C['no_deprecated_attr']) ? $C['no_deprecated_attr'] : 1; +$C['parent'] = isset($C['parent'][0]) ? strtolower($C['parent']) : 'body'; +$C['show_setting'] = !empty($C['show_setting']) ? $C['show_setting'] : 0; +$C['style_pass'] = empty($C['style_pass']) ? 0 : 1; +$C['tidy'] = empty($C['tidy']) ? 0 : $C['tidy']; +$C['unique_ids'] = isset($C['unique_ids']) ? $C['unique_ids'] : 1; +$C['xml:lang'] = isset($C['xml:lang']) ? $C['xml:lang'] : 0; + +if(isset($GLOBALS['C'])){$reC = $GLOBALS['C'];} +$GLOBALS['C'] = $C; +$S = is_array($S) ? $S : hl_spec($S); +if(isset($GLOBALS['S'])){$reS = $GLOBALS['S'];} +$GLOBALS['S'] = $S; + +$t = preg_replace('`[\x00-\x08\x0b-\x0c\x0e-\x1f]`', '', $t); +if($C['clean_ms_char']){ + $x = array("\x7f"=>'', "\x80"=>'€', "\x81"=>'', "\x83"=>'ƒ', "\x85"=>'…', "\x86"=>'†', "\x87"=>'‡', "\x88"=>'ˆ', "\x89"=>'‰', "\x8a"=>'Š', "\x8b"=>'‹', "\x8c"=>'Œ', "\x8d"=>'', "\x8e"=>'Ž', "\x8f"=>'', "\x90"=>'', "\x95"=>'•', "\x96"=>'–', "\x97"=>'—', "\x98"=>'˜', "\x99"=>'™', "\x9a"=>'š', "\x9b"=>'›', "\x9c"=>'œ', "\x9d"=>'', "\x9e"=>'ž', "\x9f"=>'Ÿ'); + $x = $x + ($C['clean_ms_char'] == 1 ? array("\x82"=>'‚', "\x84"=>'„', "\x91"=>'‘', "\x92"=>'’', "\x93"=>'“', "\x94"=>'”') : array("\x82"=>'\'', "\x84"=>'"', "\x91"=>'\'', "\x92"=>'\'', "\x93"=>'"', "\x94"=>'"')); + $t = strtr($t, $x); +} +if($C['cdata'] or $C['comment']){$t = preg_replace_callback('``sm', 'hl_cmtcd', $t);} +$t = preg_replace_callback('`&([A-Za-z][A-Za-z0-9]{1,30}|#(?:[0-9]{1,8}|[Xx][0-9A-Fa-f]{1,7}));`', 'hl_ent', str_replace('&', '&', $t)); +if($C['unique_ids'] && !isset($GLOBALS['hl_Ids'])){$GLOBALS['hl_Ids'] = array();} +if($C['hook']){$t = $C['hook']($t, $C, $S);} +if($C['show_setting'] && preg_match('`^[a-z][a-z0-9_]*$`i', $C['show_setting'])){ + $GLOBALS[$C['show_setting']] = array('config'=>$C, 'spec'=>$S, 'time'=>microtime()); +} +// main +$t = preg_replace_callback('`<(?:(?:\s|$)|(?:[^>]*(?:>|$)))|>`m', 'hl_tag', $t); +$t = $C['balance'] ? hl_bal($t, $C['keep_bad'], $C['parent']) : $t; +$t = (($C['cdata'] or $C['comment']) && strpos($t, "\x01") !== false) ? str_replace(array("\x01", "\x02", "\x03", "\x04", "\x05"), array('', '', '&', '<', '>'), $t) : $t; +$t = $C['tidy'] ? hl_tidy($t, $C['tidy'], $C['parent']) : $t; +unset($C, $e); +if(isset($reC)){$GLOBALS['C'] = $reC;} +if(isset($reS)){$GLOBALS['S'] = $reS;} +return $t; +// eof +} + +function hl_attrval($t, $p){ +// check attr val against $S +$o = 1; $l = strlen($t); +foreach($p as $k=>$v){ + switch($k){ + case 'maxlen':if($l > $v){$o = 0;} + break; case 'minlen': if($l < $v){$o = 0;} + break; case 'maxval': if((float)($t) > $v){$o = 0;} + break; case 'minval': if((float)($t) < $v){$o = 0;} + break; case 'match': if(!preg_match($v, $t)){$o = 0;} + break; case 'nomatch': if(preg_match($v, $t)){$o = 0;} + break; case 'oneof': + $m = 0; + foreach(explode('|', $v) as $n){if($t == $n){$m = 1; break;}} + $o = $m; + break; case 'noneof': + $m = 1; + foreach(explode('|', $v) as $n){if($t == $n){$m = 0; break;}} + $o = $m; + break; default: + break; + } + if(!$o){break;} +} +return ($o ? $t : (isset($p['default']) ? $p['default'] : 0)); +// eof +} + +function hl_bal($t, $do=1, $in='div'){ +// balance tags +// by content +$cB = array('blockquote'=>1, 'form'=>1, 'map'=>1, 'noscript'=>1); // Block +$cE = array('area'=>1, 'br'=>1, 'col'=>1, 'embed'=>1, 'hr'=>1, 'img'=>1, 'input'=>1, 'isindex'=>1, 'param'=>1); // Empty +$cF = array('button'=>1, 'del'=>1, 'div'=>1, 'dd'=>1, 'fieldset'=>1, 'iframe'=>1, 'ins'=>1, 'li'=>1, 'noscript'=>1, 'object'=>1, 'td'=>1, 'th'=>1); // Flow; later context-wise dynamic move of ins & del to $cI +$cI = array('a'=>1, 'abbr'=>1, 'acronym'=>1, 'address'=>1, 'b'=>1, 'bdo'=>1, 'big'=>1, 'caption'=>1, 'cite'=>1, 'code'=>1, 'dfn'=>1, 'dt'=>1, 'em'=>1, 'font'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'i'=>1, 'kbd'=>1, 'label'=>1, 'legend'=>1, 'p'=>1, 'pre'=>1, 'q'=>1, 'rb'=>1, 'rt'=>1, 's'=>1, 'samp'=>1, 'small'=>1, 'span'=>1, 'strike'=>1, 'strong'=>1, 'sub'=>1, 'sup'=>1, 'tt'=>1, 'u'=>1, 'var'=>1); // Inline +$cN = array('a'=>array('a'=>1), 'button'=>array('a'=>1, 'button'=>1, 'fieldset'=>1, 'form'=>1, 'iframe'=>1, 'input'=>1, 'label'=>1, 'select'=>1, 'textarea'=>1), 'fieldset'=>array('fieldset'=>1), 'form'=>array('form'=>1), 'label'=>array('label'=>1), 'noscript'=>array('script'=>1), 'pre'=>array('big'=>1, 'font'=>1, 'img'=>1, 'object'=>1, 'script'=>1, 'small'=>1, 'sub'=>1, 'sup'=>1), 'rb'=>array('ruby'=>1), 'rt'=>array('ruby'=>1)); // Illegal +$cN2 = array_keys($cN); +$cR = array('blockquote'=>1, 'dir'=>1, 'dl'=>1, 'form'=>1, 'map'=>1, 'menu'=>1, 'noscript'=>1, 'ol'=>1, 'optgroup'=>1, 'rbc'=>1, 'rtc'=>1, 'ruby'=>1, 'select'=>1, 'table'=>1, 'tbody'=>1, 'tfoot'=>1, 'thead'=>1, 'tr'=>1, 'ul'=>1); +$cS = array('colgroup'=>array('col'=>1), 'dir'=>array('li'), 'dl'=>array('dd'=>1, 'dt'=>1), 'menu'=>array('li'=>1), 'ol'=>array('li'=>1), 'optgroup'=>array('option'=>1), 'option'=>array('#pcdata'=>1), 'rbc'=>array('rb'=>1), 'rp'=>array('#pcdata'=>1), 'rtc'=>array('rt'=>1), 'ruby'=>array('rb'=>1, 'rbc'=>1, 'rp'=>1, 'rt'=>1, 'rtc'=>1), 'select'=>array('optgroup'=>1, 'option'=>1), 'script'=>array('#pcdata'=>1), 'table'=>array('caption'=>1, 'col'=>1, 'colgroup'=>1, 'tfoot'=>1, 'tbody'=>1, 'tr'=>1, 'thead'=>1), 'tbody'=>array('tr'=>1), 'tfoot'=>array('tr'=>1), 'textarea'=>array('#pcdata'=>1), 'thead'=>array('tr'=>1), 'tr'=>array('td'=>1, 'th'=>1), 'ul'=>array('li'=>1)); // Specific - immediate parent-child +$cO = array('address'=>array('p'=>1), 'applet'=>array('param'=>1), 'blockquote'=>array('script'=>1), 'fieldset'=>array('legend'=>1, '#pcdata'=>1), 'form'=>array('script'=>1), 'map'=>array('area'=>1), 'object'=>array('param'=>1, 'embed'=>1)); // Other +$cT = array('colgroup'=>1, 'dd'=>1, 'dt'=>1, 'li'=>1, 'option'=>1, 'p'=>1, 'td'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1); // Omitable closing +// block/inline type; ins & del both type; #pcdata: text +$eB = array('address'=>1, 'blockquote'=>1, 'center'=>1, 'del'=>1, 'dir'=>1, 'dl'=>1, 'div'=>1, 'fieldset'=>1, 'form'=>1, 'ins'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'hr'=>1, 'isindex'=>1, 'menu'=>1, 'noscript'=>1, 'ol'=>1, 'p'=>1, 'pre'=>1, 'table'=>1, 'ul'=>1); +$eI = array('#pcdata'=>1, 'a'=>1, 'abbr'=>1, 'acronym'=>1, 'applet'=>1, 'b'=>1, 'bdo'=>1, 'big'=>1, 'br'=>1, 'button'=>1, 'cite'=>1, 'code'=>1, 'del'=>1, 'dfn'=>1, 'em'=>1, 'embed'=>1, 'font'=>1, 'i'=>1, 'iframe'=>1, 'img'=>1, 'input'=>1, 'ins'=>1, 'kbd'=>1, 'label'=>1, 'map'=>1, 'object'=>1, 'param'=>1, 'q'=>1, 'ruby'=>1, 's'=>1, 'samp'=>1, 'select'=>1, 'script'=>1, 'small'=>1, 'span'=>1, 'strike'=>1, 'strong'=>1, 'sub'=>1, 'sup'=>1, 'textarea'=>1, 'tt'=>1, 'u'=>1, 'var'=>1); +$eN = array('a'=>1, 'big'=>1, 'button'=>1, 'fieldset'=>1, 'font'=>1, 'form'=>1, 'iframe'=>1, 'img'=>1, 'input'=>1, 'label'=>1, 'object'=>1, 'ruby'=>1, 'script'=>1, 'select'=>1, 'small'=>1, 'sub'=>1, 'sup'=>1, 'textarea'=>1); // Exclude from specific ele; $cN values +$eO = array('area'=>1, 'caption'=>1, 'col'=>1, 'colgroup'=>1, 'dd'=>1, 'dt'=>1, 'legend'=>1, 'li'=>1, 'optgroup'=>1, 'option'=>1, 'rb'=>1, 'rbc'=>1, 'rp'=>1, 'rt'=>1, 'rtc'=>1, 'script'=>1, 'tbody'=>1, 'td'=>1, 'tfoot'=>1, 'thead'=>1, 'th'=>1, 'tr'=>1); // Missing in $eB & $eI +$eF = $eB + $eI; + +// $in sets allowed child +$in = ((isset($eF[$in]) && $in != '#pcdata') or isset($eO[$in])) ? $in : 'div'; +if(isset($cE[$in])){ + return (!$do ? '' : str_replace(array('<', '>'), array('<', '>'), $t)); +} +if(isset($cS[$in])){$inOk = $cS[$in];} +elseif(isset($cI[$in])){$inOk = $eI; $cI['del'] = 1; $cI['ins'] = 1;} +elseif(isset($cF[$in])){$inOk = $eF; unset($cI['del'], $cI['ins']);} +elseif(isset($cB[$in])){$inOk = $eB; unset($cI['del'], $cI['ins']);} +if(isset($cO[$in])){$inOk = $inOk + $cO[$in];} +if(isset($cN[$in])){$inOk = array_diff_assoc($inOk, $cN[$in]);} + +$t = explode('<', $t); +$ok = $q = array(); // $q seq list of open non-empty ele +ob_start(); + +for($i=-1, $ci=count($t); ++$i<$ci;){ + // allowed $ok in parent $p + if($ql = count($q)){ + $p = array_pop($q); + $q[] = $p; + if(isset($cS[$p])){$ok = $cS[$p];} + elseif(isset($cI[$p])){$ok = $eI; $cI['del'] = 1; $cI['ins'] = 1;} + elseif(isset($cF[$p])){$ok = $eF; unset($cI['del'], $cI['ins']);} + elseif(isset($cB[$p])){$ok = $eB; unset($cI['del'], $cI['ins']);} + if(isset($cO[$p])){$ok = $ok + $cO[$p];} + if(isset($cN[$p])){$ok = array_diff_assoc($ok, $cN[$p]);} + }else{$ok = $inOk; unset($cI['del'], $cI['ins']);} + // bad tags, & ele content + if(isset($e) && ($do == 1 or (isset($ok['#pcdata']) && ($do == 3 or $do == 5)))){ + echo '<', $s, $e, $a, '>'; + } + if(isset($x[0])){ + if($do < 3 or isset($ok['#pcdata'])){echo $x;} + elseif(strpos($x, "\x02\x04")){ + foreach(preg_split('`(\x01\x02[^\x01\x02]+\x02\x01)`', $x, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $v){ + echo (substr($v, 0, 2) == "\x01\x02" ? $v : ($do > 4 ? preg_replace('`\S`', '', $v) : '')); + } + }elseif($do > 4){echo preg_replace('`\S`', '', $x);} + } + // get markup + if(!preg_match('`^(/?)([a-zA-Z1-6]+)([^>]*)>(.*)`sm', $t[$i], $r)){$x = $t[$i]; continue;} + $s = null; $e = null; $a = null; $x = null; list($all, $s, $e, $a, $x) = $r; + // close tag + if($s){ + if(isset($cE[$e]) or !in_array($e, $q)){continue;} // Empty/unopen + if($p == $e){array_pop($q); echo ''; unset($e); continue;} // Last open + $add = ''; // Nesting - close open tags that need to be + for($j=-1, $cj=count($q); ++$j<$cj;){ + if(($d = array_pop($q)) == $e){break;} + else{$add .= "";} + } + echo $add, ''; unset($e); continue; + } + // open tag + // $cB ele needs $eB ele as child + if(isset($cB[$e]) && strlen(trim($x))){ + $t[$i] = "{$e}{$a}>"; + array_splice($t, $i+1, 0, 'div>'. $x); unset($e, $x); ++$ci; --$i; continue; + } + if((($ql && isset($cB[$p])) or (isset($cB[$in]) && !$ql)) && !isset($eB[$e]) && !isset($ok[$e])){ + array_splice($t, $i, 0, 'div>'); unset($e, $x); ++$ci; --$i; continue; + } + // if no open ele, $in = parent; mostly immediate parent-child relation should hold + if(!$ql or !isset($eN[$e]) or !array_intersect($q, $cN2)){ + if(!isset($ok[$e])){ + if($ql && isset($cT[$p])){echo ''; unset($e, $x); --$i;} + continue; + } + if(!isset($cE[$e])){$q[] = $e;} + echo '<', $e, $a, '>'; unset($e); continue; + } + // specific parent-child + if(isset($cS[$p][$e])){ + if(!isset($cE[$e])){$q[] = $e;} + echo '<', $e, $a, '>'; unset($e); continue; + } + // nesting + $add = ''; + $q2 = array(); + for($k=-1, $kc=count($q); ++$k<$kc;){ + $d = $q[$k]; + $ok2 = array(); + if(isset($cS[$d])){$q2[] = $d; continue;} + $ok2 = isset($cI[$d]) ? $eI : $eF; + if(isset($cO[$d])){$ok2 = $ok2 + $cO[$d];} + if(isset($cN[$d])){$ok2 = array_diff_assoc($ok2, $cN[$d]);} + if(!isset($ok2[$e])){ + if(!$k && !isset($inOk[$e])){continue 2;} + $add = ""; + for(;++$k<$kc;){$add = "{$add}";} + break; + } + else{$q2[] = $d;} + } + $q = $q2; + if(!isset($cE[$e])){$q[] = $e;} + echo $add, '<', $e, $a, '>'; unset($e); continue; +} + +// end +if($ql = count($q)){ + $p = array_pop($q); + $q[] = $p; + if(isset($cS[$p])){$ok = $cS[$p];} + elseif(isset($cI[$p])){$ok = $eI; $cI['del'] = 1; $cI['ins'] = 1;} + elseif(isset($cF[$p])){$ok = $eF; unset($cI['del'], $cI['ins']);} + elseif(isset($cB[$p])){$ok = $eB; unset($cI['del'], $cI['ins']);} + if(isset($cO[$p])){$ok = $ok + $cO[$p];} + if(isset($cN[$p])){$ok = array_diff_assoc($ok, $cN[$p]);} +}else{$ok = $inOk; unset($cI['del'], $cI['ins']);} +if(isset($e) && ($do == 1 or (isset($ok['#pcdata']) && ($do == 3 or $do == 5)))){ + echo '<', $s, $e, $a, '>'; +} +if(isset($x[0])){ + if(strlen(trim($x)) && (($ql && isset($cB[$p])) or (isset($cB[$in]) && !$ql))){ + echo '
    ', $x, '
    '; + } + elseif($do < 3 or isset($ok['#pcdata'])){echo $x;} + elseif(strpos($x, "\x02\x04")){ + foreach(preg_split('`(\x01\x02[^\x01\x02]+\x02\x01)`', $x, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $v){ + echo (substr($v, 0, 2) == "\x01\x02" ? $v : ($do > 4 ? preg_replace('`\S`', '', $v) : '')); + } + }elseif($do > 4){echo preg_replace('`\S`', '', $x);} +} +while(!empty($q) && ($e = array_pop($q))){echo '';} +$o = ob_get_contents(); +ob_end_clean(); +return $o; +// eof +} + +function hl_cmtcd($t){ +// comment/CDATA sec handler +$t = $t[0]; +global $C; +if($t[3] == '-'){ + if(!$C['comment']){return $t;} + if($C['comment'] == 1){return '';} + if(substr(($t = preg_replace('`--+`', '-', substr($t, 4, -3))), -1) != ' '){$t .= ' ';} + $t = $C['comment'] == 2 ? str_replace(array('&', '<', '>'), array('&', '<', '>'), $t) : $t; + $t = "\x01\x02\x04!--$t--\x05\x02\x01"; +}else{ // CDATA + if(!$C['cdata']){return $t;} + if($C['cdata'] == 1){return '';} + $t = substr($t, 1, -1); + $t = $C['cdata'] == 2 ? str_replace(array('&', '<', '>'), array('&', '<', '>'), $t) : $t; + $t = "\x01\x01\x04$t\x05\x01\x01"; +} +return str_replace(array('&', '<', '>'), array("\x03", "\x04", "\x05"), $t); +// eof +} + +function hl_ent($t){ +// entitity handler +global $C; +$t = $t[1]; +static $U = array('quot'=>1,'amp'=>1,'lt'=>1,'gt'=>1); +static $N = array('fnof'=>'402', 'Alpha'=>'913', 'Beta'=>'914', 'Gamma'=>'915', 'Delta'=>'916', 'Epsilon'=>'917', 'Zeta'=>'918', 'Eta'=>'919', 'Theta'=>'920', 'Iota'=>'921', 'Kappa'=>'922', 'Lambda'=>'923', 'Mu'=>'924', 'Nu'=>'925', 'Xi'=>'926', 'Omicron'=>'927', 'Pi'=>'928', 'Rho'=>'929', 'Sigma'=>'931', 'Tau'=>'932', 'Upsilon'=>'933', 'Phi'=>'934', 'Chi'=>'935', 'Psi'=>'936', 'Omega'=>'937', 'alpha'=>'945', 'beta'=>'946', 'gamma'=>'947', 'delta'=>'948', 'epsilon'=>'949', 'zeta'=>'950', 'eta'=>'951', 'theta'=>'952', 'iota'=>'953', 'kappa'=>'954', 'lambda'=>'955', 'mu'=>'956', 'nu'=>'957', 'xi'=>'958', 'omicron'=>'959', 'pi'=>'960', 'rho'=>'961', 'sigmaf'=>'962', 'sigma'=>'963', 'tau'=>'964', 'upsilon'=>'965', 'phi'=>'966', 'chi'=>'967', 'psi'=>'968', 'omega'=>'969', 'thetasym'=>'977', 'upsih'=>'978', 'piv'=>'982', 'bull'=>'8226', 'hellip'=>'8230', 'prime'=>'8242', 'Prime'=>'8243', 'oline'=>'8254', 'frasl'=>'8260', 'weierp'=>'8472', 'image'=>'8465', 'real'=>'8476', 'trade'=>'8482', 'alefsym'=>'8501', 'larr'=>'8592', 'uarr'=>'8593', 'rarr'=>'8594', 'darr'=>'8595', 'harr'=>'8596', 'crarr'=>'8629', 'lArr'=>'8656', 'uArr'=>'8657', 'rArr'=>'8658', 'dArr'=>'8659', 'hArr'=>'8660', 'forall'=>'8704', 'part'=>'8706', 'exist'=>'8707', 'empty'=>'8709', 'nabla'=>'8711', 'isin'=>'8712', 'notin'=>'8713', 'ni'=>'8715', 'prod'=>'8719', 'sum'=>'8721', 'minus'=>'8722', 'lowast'=>'8727', 'radic'=>'8730', 'prop'=>'8733', 'infin'=>'8734', 'ang'=>'8736', 'and'=>'8743', 'or'=>'8744', 'cap'=>'8745', 'cup'=>'8746', 'int'=>'8747', 'there4'=>'8756', 'sim'=>'8764', 'cong'=>'8773', 'asymp'=>'8776', 'ne'=>'8800', 'equiv'=>'8801', 'le'=>'8804', 'ge'=>'8805', 'sub'=>'8834', 'sup'=>'8835', 'nsub'=>'8836', 'sube'=>'8838', 'supe'=>'8839', 'oplus'=>'8853', 'otimes'=>'8855', 'perp'=>'8869', 'sdot'=>'8901', 'lceil'=>'8968', 'rceil'=>'8969', 'lfloor'=>'8970', 'rfloor'=>'8971', 'lang'=>'9001', 'rang'=>'9002', 'loz'=>'9674', 'spades'=>'9824', 'clubs'=>'9827', 'hearts'=>'9829', 'diams'=>'9830', 'apos'=>'39', 'OElig'=>'338', 'oelig'=>'339', 'Scaron'=>'352', 'scaron'=>'353', 'Yuml'=>'376', 'circ'=>'710', 'tilde'=>'732', 'ensp'=>'8194', 'emsp'=>'8195', 'thinsp'=>'8201', 'zwnj'=>'8204', 'zwj'=>'8205', 'lrm'=>'8206', 'rlm'=>'8207', 'ndash'=>'8211', 'mdash'=>'8212', 'lsquo'=>'8216', 'rsquo'=>'8217', 'sbquo'=>'8218', 'ldquo'=>'8220', 'rdquo'=>'8221', 'bdquo'=>'8222', 'dagger'=>'8224', 'Dagger'=>'8225', 'permil'=>'8240', 'lsaquo'=>'8249', 'rsaquo'=>'8250', 'euro'=>'8364', 'nbsp'=>'160', 'iexcl'=>'161', 'cent'=>'162', 'pound'=>'163', 'curren'=>'164', 'yen'=>'165', 'brvbar'=>'166', 'sect'=>'167', 'uml'=>'168', 'copy'=>'169', 'ordf'=>'170', 'laquo'=>'171', 'not'=>'172', 'shy'=>'173', 'reg'=>'174', 'macr'=>'175', 'deg'=>'176', 'plusmn'=>'177', 'sup2'=>'178', 'sup3'=>'179', 'acute'=>'180', 'micro'=>'181', 'para'=>'182', 'middot'=>'183', 'cedil'=>'184', 'sup1'=>'185', 'ordm'=>'186', 'raquo'=>'187', 'frac14'=>'188', 'frac12'=>'189', 'frac34'=>'190', 'iquest'=>'191', 'Agrave'=>'192', 'Aacute'=>'193', 'Acirc'=>'194', 'Atilde'=>'195', 'Auml'=>'196', 'Aring'=>'197', 'AElig'=>'198', 'Ccedil'=>'199', 'Egrave'=>'200', 'Eacute'=>'201', 'Ecirc'=>'202', 'Euml'=>'203', 'Igrave'=>'204', 'Iacute'=>'205', 'Icirc'=>'206', 'Iuml'=>'207', 'ETH'=>'208', 'Ntilde'=>'209', 'Ograve'=>'210', 'Oacute'=>'211', 'Ocirc'=>'212', 'Otilde'=>'213', 'Ouml'=>'214', 'times'=>'215', 'Oslash'=>'216', 'Ugrave'=>'217', 'Uacute'=>'218', 'Ucirc'=>'219', 'Uuml'=>'220', 'Yacute'=>'221', 'THORN'=>'222', 'szlig'=>'223', 'agrave'=>'224', 'aacute'=>'225', 'acirc'=>'226', 'atilde'=>'227', 'auml'=>'228', 'aring'=>'229', 'aelig'=>'230', 'ccedil'=>'231', 'egrave'=>'232', 'eacute'=>'233', 'ecirc'=>'234', 'euml'=>'235', 'igrave'=>'236', 'iacute'=>'237', 'icirc'=>'238', 'iuml'=>'239', 'eth'=>'240', 'ntilde'=>'241', 'ograve'=>'242', 'oacute'=>'243', 'ocirc'=>'244', 'otilde'=>'245', 'ouml'=>'246', 'divide'=>'247', 'oslash'=>'248', 'ugrave'=>'249', 'uacute'=>'250', 'ucirc'=>'251', 'uuml'=>'252', 'yacute'=>'253', 'thorn'=>'254', 'yuml'=>'255'); +if($t[0] != '#'){ + return ($C['and_mark'] ? "\x06" : '&'). (isset($U[$t]) ? $t : (isset($N[$t]) ? (!$C['named_entity'] ? '#'. ($C['hexdec_entity'] > 1 ? 'x'. dechex($N[$t]) : $N[$t]) : $t) : 'amp;'. $t)). ';'; +} +if(($n = ctype_digit($t = substr($t, 1)) ? intval($t) : hexdec(substr($t, 1))) < 9 or ($n > 13 && $n < 32) or $n == 11 or $n == 12 or ($n > 126 && $n < 160 && $n != 133) or ($n > 55295 && ($n < 57344 or ($n > 64975 && $n < 64992) or $n == 65534 or $n == 65535 or $n > 1114111))){ + return ($C['and_mark'] ? "\x06" : '&'). "amp;#{$t};"; +} +return ($C['and_mark'] ? "\x06" : '&'). '#'. (((ctype_digit($t) && $C['hexdec_entity'] < 2) or !$C['hexdec_entity']) ? $n : 'x'. dechex($n)). ';'; +// eof +} + +function hl_prot($p, $c=null){ +// check URL scheme +global $C; +$b = $a = ''; +if($c == null){$c = 'style'; $b = $p[1]; $a = $p[3]; $p = trim($p[2]);} +$c = isset($C['schemes'][$c]) ? $C['schemes'][$c] : $C['schemes']['*']; +if(isset($c['*']) or !strcspn($p, '#?;')){return "{$b}{$p}{$a}";} // All ok, frag, query, param +if(preg_match('`^([a-z\d\-+.&#; ]+?)(:|&#(58|x3a);|%3a|\\\\0{0,4}3a).`i', $p, $m) && !isset($c[strtolower($m[1])])){ // Denied prot + return "{$b}denied:{$p}{$a}"; +} +if($C['abs_url']){ + if($C['abs_url'] == -1 && strpos($p, $C['base_url']) === 0){ // Make url rel + $p = substr($p, strlen($C['base_url'])); + }elseif(empty($m[1])){ // Make URL abs + if(substr($p, 0, 2) == '//'){$p = substr($C['base_url'], 0, strpos($C['base_url'], ':')+1). $p;} + elseif($p[0] == '/'){$p = preg_replace('`(^.+?://[^/]+)(.*)`', '$1', $C['base_url']). $p;} + elseif(strcspn($p, './')){$p = $C['base_url']. $p;} + else{ + preg_match('`^([a-zA-Z\d\-+.]+://[^/]+)(.*)`', $C['base_url'], $m); + $p = preg_replace('`(?<=/)\./`', '', $m[2]. $p); + while(preg_match('`(?<=/)([^/]{3,}|[^/.]+?|\.[^/.]|[^/.]\.)/\.\./`', $p)){ + $p = preg_replace('`(?<=/)([^/]{3,}|[^/.]+?|\.[^/.]|[^/.]\.)/\.\./`', '', $p); + } + $p = $m[1]. $p; + } + } +} +return "{$b}{$p}{$a}"; +// eof +} + +function hl_regex($p){ +// ?regex +if(empty($p)){return 0;} +if($t = ini_get('track_errors')){$o = isset($php_errormsg) ? $php_errormsg : null;} +else{ini_set('track_errors', 1);} +unset($php_errormsg); +if(($d = ini_get('display_errors'))){ini_set('display_errors', 0);} +preg_match($p, ''); +if($d){ini_set('display_errors', 1);} +$r = isset($php_errormsg) ? 0 : 1; +if($t){$php_errormsg = isset($o) ? $o : null;} +else{ini_set('track_errors', 0);} +return $r; +// eof +} + +function hl_spec($t){ +// final $spec +$s = array(); +$t = str_replace(array("\t", "\r", "\n", ' '), '', preg_replace('/"(?>(`.|[^"])*)"/sme', 'substr(str_replace(array(";", "|", "~", " ", ",", "/", "(", ")", \'`"\'), array("\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\""), "$0"), 1, -1)', trim($t))); +for($i = count(($t = explode(';', $t))); --$i>=0;){ + $w = $t[$i]; + if(empty($w) or ($e = strpos($w, '=')) === false or !strlen(($a = substr($w, $e+1)))){continue;} + $y = $n = array(); + foreach(explode(',', $a) as $v){ + if(!preg_match('`^([a-z:\-\*]+)(?:\((.*?)\))?`i', $v, $m)){continue;} + if(($x = strtolower($m[1])) == '-*'){$n['*'] = 1; continue;} + if($x[0] == '-'){$n[substr($x, 1)] = 1; continue;} + if(!isset($m[2])){$y[$x] = 1; continue;} + foreach(explode('/', $m[2]) as $m){ + if(empty($m) or ($p = strpos($m, '=')) == 0 or $p < 5){$y[$x] = 1; continue;} + $y[$x][strtolower(substr($m, 0, $p))] = str_replace(array("\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08"), array(";", "|", "~", " ", ",", "/", "(", ")"), substr($m, $p+1)); + } + if(isset($y[$x]['match']) && !hl_regex($y[$x]['match'])){unset($y[$x]['match']);} + if(isset($y[$x]['nomatch']) && !hl_regex($y[$x]['nomatch'])){unset($y[$x]['nomatch']);} + } + if(!count($y) && !count($n)){continue;} + foreach(explode(',', substr($w, 0, $e)) as $v){ + if(!strlen(($v = strtolower($v)))){continue;} + if(count($y)){$s[$v] = $y;} + if(count($n)){$s[$v]['n'] = $n;} + } +} +return $s; +// eof +} + +function hl_tag($t){ +// tag/attribute handler +global $C; +$t = $t[0]; +// invalid < > +if($t == '< '){return '< ';} +if($t == '>'){return '>';} +if(!preg_match('`^<(/?)([a-zA-Z][a-zA-Z1-6]*)([^>]*?)\s?>$`m', $t, $m)){ + return str_replace(array('<', '>'), array('<', '>'), $t); +}elseif(!isset($C['elements'][($e = strtolower($m[2]))])){ + return (($C['keep_bad']%2) ? str_replace(array('<', '>'), array('<', '>'), $t) : ''); +} +// attr string +$a = str_replace(array("\xad", "\n", "\r", "\t"), ' ', trim($m[3])); +if(strpos($a, '&') !== false){ + str_replace(array('­', '­', '­'), ' ', $a); +} +// tag transform +static $eD = array('applet'=>1, 'center'=>1, 'dir'=>1, 'embed'=>1, 'font'=>1, 'isindex'=>1, 'menu'=>1, 's'=>1, 'strike'=>1, 'u'=>1); // Deprecated +if($C['make_tag_strict'] && isset($eD[$e])){ + $trt = hl_tag2($e, $a, $C['make_tag_strict']); + if(!$e){return (($C['keep_bad']%2) ? str_replace(array('<', '>'), array('<', '>'), $t) : '');} +} +// close tag +static $eE = array('area'=>1, 'br'=>1, 'col'=>1, 'embed'=>1, 'hr'=>1, 'img'=>1, 'input'=>1, 'isindex'=>1, 'param'=>1); // Empty ele +if(!empty($m[1])){ + return (!isset($eE[$e]) ? "" : (($C['keep_bad'])%2 ? str_replace(array('<', '>'), array('<', '>'), $t) : '')); +} + +// open tag & attr +static $aN = array('abbr'=>array('td'=>1, 'th'=>1), 'accept-charset'=>array('form'=>1), 'accept'=>array('form'=>1, 'input'=>1), 'accesskey'=>array('a'=>1, 'area'=>1, 'button'=>1, 'input'=>1, 'label'=>1, 'legend'=>1, 'textarea'=>1), 'action'=>array('form'=>1), 'align'=>array('caption'=>1, 'embed'=>1, 'applet'=>1, 'iframe'=>1, 'img'=>1, 'input'=>1, 'object'=>1, 'legend'=>1, 'table'=>1, 'hr'=>1, 'div'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'p'=>1, 'col'=>1, 'colgroup'=>1, 'tbody'=>1, 'td'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1), 'alt'=>array('applet'=>1, 'area'=>1, 'img'=>1, 'input'=>1), 'archive'=>array('applet'=>1, 'object'=>1), 'axis'=>array('td'=>1, 'th'=>1), 'bgcolor'=>array('embed'=>1, 'table'=>1, 'tr'=>1, 'td'=>1, 'th'=>1), 'border'=>array('table'=>1, 'img'=>1, 'object'=>1), 'bordercolor'=>array('table'=>1, 'td'=>1, 'tr'=>1), 'cellpadding'=>array('table'=>1), 'cellspacing'=>array('table'=>1), 'char'=>array('col'=>1, 'colgroup'=>1, 'tbody'=>1, 'td'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1), 'charoff'=>array('col'=>1, 'colgroup'=>1, 'tbody'=>1, 'td'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1), 'charset'=>array('a'=>1, 'script'=>1), 'checked'=>array('input'=>1), 'cite'=>array('blockquote'=>1, 'q'=>1, 'del'=>1, 'ins'=>1), 'classid'=>array('object'=>1), 'clear'=>array('br'=>1), 'code'=>array('applet'=>1), 'codebase'=>array('object'=>1, 'applet'=>1), 'codetype'=>array('object'=>1), 'color'=>array('font'=>1), 'cols'=>array('textarea'=>1), 'colspan'=>array('td'=>1, 'th'=>1), 'compact'=>array('dir'=>1, 'dl'=>1, 'menu'=>1, 'ol'=>1, 'ul'=>1), 'coords'=>array('area'=>1, 'a'=>1), 'data'=>array('object'=>1), 'datetime'=>array('del'=>1, 'ins'=>1), 'declare'=>array('object'=>1), 'defer'=>array('script'=>1), 'dir'=>array('bdo'=>1), 'disabled'=>array('button'=>1, 'input'=>1, 'optgroup'=>1, 'option'=>1, 'select'=>1, 'textarea'=>1), 'enctype'=>array('form'=>1), 'face'=>array('font'=>1), 'for'=>array('label'=>1), 'frame'=>array('table'=>1), 'frameborder'=>array('iframe'=>1), 'headers'=>array('td'=>1, 'th'=>1), 'height'=>array('embed'=>1, 'iframe'=>1, 'td'=>1, 'th'=>1, 'img'=>1, 'object'=>1, 'applet'=>1), 'href'=>array('a'=>1, 'area'=>1), 'hreflang'=>array('a'=>1), 'hspace'=>array('applet'=>1, 'img'=>1, 'object'=>1), 'ismap'=>array('img'=>1, 'input'=>1), 'label'=>array('option'=>1, 'optgroup'=>1), 'language'=>array('script'=>1), 'longdesc'=>array('img'=>1, 'iframe'=>1), 'marginheight'=>array('iframe'=>1), 'marginwidth'=>array('iframe'=>1), 'maxlength'=>array('input'=>1), 'method'=>array('form'=>1), 'model'=>array('embed'=>1), 'multiple'=>array('select'=>1), 'name'=>array('button'=>1, 'embed'=>1, 'textarea'=>1, 'applet'=>1, 'select'=>1, 'form'=>1, 'iframe'=>1, 'img'=>1, 'a'=>1, 'input'=>1, 'object'=>1, 'map'=>1, 'param'=>1), 'nohref'=>array('area'=>1), 'noshade'=>array('hr'=>1), 'nowrap'=>array('td'=>1, 'th'=>1), 'object'=>array('applet'=>1), 'onblur'=>array('a'=>1, 'area'=>1, 'button'=>1, 'input'=>1, 'label'=>1, 'select'=>1, 'textarea'=>1), 'onchange'=>array('input'=>1, 'select'=>1, 'textarea'=>1), 'onfocus'=>array('a'=>1, 'area'=>1, 'button'=>1, 'input'=>1, 'label'=>1, 'select'=>1, 'textarea'=>1), 'onreset'=>array('form'=>1), 'onselect'=>array('input'=>1, 'textarea'=>1), 'onsubmit'=>array('form'=>1), 'pluginspage'=>array('embed'=>1), 'pluginurl'=>array('embed'=>1), 'prompt'=>array('isindex'=>1), 'readonly'=>array('textarea'=>1, 'input'=>1), 'rel'=>array('a'=>1), 'rev'=>array('a'=>1), 'rows'=>array('textarea'=>1), 'rowspan'=>array('td'=>1, 'th'=>1), 'rules'=>array('table'=>1), 'scope'=>array('td'=>1, 'th'=>1), 'scrolling'=>array('iframe'=>1), 'selected'=>array('option'=>1), 'shape'=>array('area'=>1, 'a'=>1), 'size'=>array('hr'=>1, 'font'=>1, 'input'=>1, 'select'=>1), 'span'=>array('col'=>1, 'colgroup'=>1), 'src'=>array('embed'=>1, 'script'=>1, 'input'=>1, 'iframe'=>1, 'img'=>1), 'standby'=>array('object'=>1), 'start'=>array('ol'=>1), 'summary'=>array('table'=>1), 'tabindex'=>array('a'=>1, 'area'=>1, 'button'=>1, 'input'=>1, 'object'=>1, 'select'=>1, 'textarea'=>1), 'target'=>array('a'=>1, 'area'=>1, 'form'=>1), 'type'=>array('a'=>1, 'embed'=>1, 'object'=>1, 'param'=>1, 'script'=>1, 'input'=>1, 'li'=>1, 'ol'=>1, 'ul'=>1, 'button'=>1), 'usemap'=>array('img'=>1, 'input'=>1, 'object'=>1), 'valign'=>array('col'=>1, 'colgroup'=>1, 'tbody'=>1, 'td'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1), 'value'=>array('input'=>1, 'option'=>1, 'param'=>1, 'button'=>1, 'li'=>1), 'valuetype'=>array('param'=>1), 'vspace'=>array('applet'=>1, 'img'=>1, 'object'=>1), 'width'=>array('embed'=>1, 'hr'=>1, 'iframe'=>1, 'img'=>1, 'object'=>1, 'table'=>1, 'td'=>1, 'th'=>1, 'applet'=>1, 'col'=>1, 'colgroup'=>1, 'pre'=>1), 'wmode'=>array('embed'=>1), 'xml:space'=>array('pre'=>1, 'script'=>1, 'style'=>1)); // Ele-specific +static $aNE = array('checked'=>1, 'compact'=>1, 'declare'=>1, 'defer'=>1, 'disabled'=>1, 'ismap'=>1, 'multiple'=>1, 'nohref'=>1, 'noresize'=>1, 'noshade'=>1, 'nowrap'=>1, 'readonly'=>1, 'selected'=>1); // Empty +static $aNP = array('action'=>1, 'cite'=>1, 'classid'=>1, 'codebase'=>1, 'data'=>1, 'href'=>1, 'longdesc'=>1, 'model'=>1, 'pluginspage'=>1, 'pluginurl'=>1, 'usemap'=>1); // Need scheme check; excludes style, on* & src +static $aNU = array('class'=>array('param'=>1, 'script'=>1), 'dir'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'iframe'=>1, 'param'=>1, 'script'=>1), 'id'=>array('script'=>1), 'lang'=>array('applet'=>1, 'br'=>1, 'iframe'=>1, 'param'=>1, 'script'=>1), 'xml:lang'=>array('applet'=>1, 'br'=>1, 'iframe'=>1, 'param'=>1, 'script'=>1), 'onclick'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'ondblclick'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onkeydown'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onkeypress'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onkeyup'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onmousedown'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onmousemove'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onmouseout'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onmouseover'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'onmouseup'=>array('applet'=>1, 'bdo'=>1, 'br'=>1, 'font'=>1, 'iframe'=>1, 'isindex'=>1, 'param'=>1, 'script'=>1), 'style'=>array('param'=>1, 'script'=>1), 'title'=>array('param'=>1, 'script'=>1)); // Univ & exceptions + +if($C['lc_std_val']){ + // predef attr vals for $eAL & $aNE ele + static $aNL = array('all'=>1, 'baseline'=>1, 'bottom'=>1, 'button'=>1, 'center'=>1, 'char'=>1, 'checkbox'=>1, 'circle'=>1, 'col'=>1, 'colgroup'=>1, 'cols'=>1, 'data'=>1, 'default'=>1, 'file'=>1, 'get'=>1, 'groups'=>1, 'hidden'=>1, 'image'=>1, 'justify'=>1, 'left'=>1, 'ltr'=>1, 'middle'=>1, 'none'=>1, 'object'=>1, 'password'=>1, 'poly'=>1, 'post'=>1, 'preserve'=>1, 'radio'=>1, 'rect'=>1, 'ref'=>1, 'reset'=>1, 'right'=>1, 'row'=>1, 'rowgroup'=>1, 'rows'=>1, 'rtl'=>1, 'submit'=>1, 'text'=>1, 'top'=>1); + static $eAL = array('a'=>1, 'area'=>1, 'bdo'=>1, 'button'=>1, 'col'=>1, 'form'=>1, 'img'=>1, 'input'=>1, 'object'=>1, 'optgroup'=>1, 'option'=>1, 'param'=>1, 'script'=>1, 'select'=>1, 'table'=>1, 'td'=>1, 'tfoot'=>1, 'th'=>1, 'thead'=>1, 'tr'=>1, 'xml:space'=>1); + $lcase = isset($eAL[$e]) ? 1 : 0; +} + +$depTr = 0; +if($C['no_deprecated_attr']){ + // dep attr:applicable ele + static $aND = array('align'=>array('caption'=>1, 'div'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'hr'=>1, 'img'=>1, 'input'=>1, 'legend'=>1, 'object'=>1, 'p'=>1, 'table'=>1), 'bgcolor'=>array('table'=>1, 'td'=>1, 'th'=>1, 'tr'=>1), 'border'=>array('img'=>1, 'object'=>1), 'bordercolor'=>array('table'=>1, 'td'=>1, 'tr'=>1), 'clear'=>array('br'=>1), 'compact'=>array('dl'=>1, 'ol'=>1, 'ul'=>1), 'height'=>array('td'=>1, 'th'=>1), 'hspace'=>array('img'=>1, 'object'=>1), 'language'=>array('script'=>1), 'name'=>array('a'=>1, 'form'=>1, 'iframe'=>1, 'img'=>1, 'map'=>1), 'noshade'=>array('hr'=>1), 'nowrap'=>array('td'=>1, 'th'=>1), 'size'=>array('hr'=>1), 'start'=>array('ol'=>1), 'type'=>array('li'=>1, 'ol'=>1, 'ul'=>1), 'value'=>array('li'=>1), 'vspace'=>array('img'=>1, 'object'=>1), 'width'=>array('hr'=>1, 'pre'=>1, 'td'=>1, 'th'=>1)); + static $eAD = array('a'=>1, 'br'=>1, 'caption'=>1, 'div'=>1, 'dl'=>1, 'form'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'hr'=>1, 'iframe'=>1, 'img'=>1, 'input'=>1, 'legend'=>1, 'li'=>1, 'map'=>1, 'object'=>1, 'ol'=>1, 'p'=>1, 'pre'=>1, 'script'=>1, 'table'=>1, 'td'=>1, 'th'=>1, 'tr'=>1, 'ul'=>1); + $depTr = isset($eAD[$e]) ? 1 : 0; +} + +// attr name-vals +if(strpos($a, "\x01") !== false){$a = preg_replace('`\x01[^\x01]*\x01`', '', $a);} // No comment/CDATA sec +$mode = 0; $a = trim($a, ' /'); $aA = array(); +while(strlen($a)){ + $w = 0; + switch($mode){ + case 0: // Name + if(preg_match('`^[a-zA-Z][\-a-zA-Z:]+`', $a, $m)){ + $nm = strtolower($m[0]); + $w = $mode = 1; $a = ltrim(substr_replace($a, '', 0, strlen($m[0]))); + } + break; case 1: + if($a[0] == '='){ // = + $w = 1; $mode = 2; $a = ltrim($a, '= '); + }else{ // No val + $w = 1; $mode = 0; $a = ltrim($a); + $aA[$nm] = ''; + } + break; case 2: // Val + if(preg_match('`^"[^"]*"`', $a, $m) or preg_match("`^'[^']*'`", $a, $m) or preg_match("`^\s*[^\s\"']+`", $a, $m)){ + $m = $m[0]; $w = 1; $mode = 0; $a = ltrim(substr_replace($a, '', 0, strlen($m))); + $aA[$nm] = trim(($m[0] == '"' or $m[0] == '\'') ? substr($m, 1, -1) : $m); + } + break; + } + if($w == 0){ // Parse errs, deal with space, " & ' + $a = preg_replace('`^(?:"[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*`', '', $a); + $mode = 0; + } +} +if($mode == 1){$aA[$nm] = '';} + +// clean attrs +global $S; +$rl = isset($S[$e]) ? $S[$e] : array(); +$a = array(); $nfr = 0; +foreach($aA as $k=>$v){ + if(((isset($C['deny_attribute']['*']) ? isset($C['deny_attribute'][$k]) : !isset($C['deny_attribute'][$k])) or isset($rl[$k])) && ((!isset($rl['n'][$k]) && !isset($rl['n']['*'])) or isset($rl[$k])) && (isset($aN[$k][$e]) or (isset($aNU[$k]) && !isset($aNU[$k][$e])))){ + if(isset($aNE[$k])){$v = $k;} + elseif(!empty($lcase) && (($e != 'button' or $e != 'input') or $k == 'type')){ // Rather loose but ?not cause issues + $v = (isset($aNL[($v2 = strtolower($v))])) ? $v2 : $v; + } + if($k == 'style' && !$C['style_pass']){ + if(false !== strpos($v, '&#')){ + static $sC = array(' '=>' ', ' '=>' ', 'E'=>'e', 'E'=>'e', 'e'=>'e', 'e'=>'e', 'X'=>'x', 'X'=>'x', 'x'=>'x', 'x'=>'x', 'P'=>'p', 'P'=>'p', 'p'=>'p', 'p'=>'p', 'S'=>'s', 'S'=>'s', 's'=>'s', 's'=>'s', 'I'=>'i', 'I'=>'i', 'i'=>'i', 'i'=>'i', 'O'=>'o', 'O'=>'o', 'o'=>'o', 'o'=>'o', 'N'=>'n', 'N'=>'n', 'n'=>'n', 'n'=>'n', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'u'=>'u', 'R'=>'r', 'R'=>'r', 'r'=>'r', 'r'=>'r', 'L'=>'l', 'L'=>'l', 'l'=>'l', 'l'=>'l', '('=>'(', '('=>'(', ')'=>')', ')'=>')', ' '=>':', ' '=>':', '"'=>'"', '"'=>'"', '''=>"'", '''=>"'", '/'=>'/', '/'=>'/', '*'=>'*', '*'=>'*', '\'=>'\\', '\'=>'\\'); + $v = strtr($v, $sC); + } + $v = preg_replace_callback('`(url(?:\()(?: )*(?:\'|"|&(?:quot|apos);)?)(.+)((?:\'|"|&(?:quot|apos);)?(?: )*(?:\)))`iS', 'hl_prot', $v); + $v = !$C['css_expression'] ? preg_replace('`expression`i', ' ', preg_replace('`\\\\\S|(/|(%2f))(\*|(%2a))`i', ' ', $v)) : $v; + }elseif(isset($aNP[$k]) or strpos($k, 'src') !== false or $k[0] == 'o'){ + $v = hl_prot($v, $k); + if($k == 'href'){ // X-spam + if($C['anti_mail_spam'] && strpos($v, 'mailto:') === 0){ + $v = str_replace('@', htmlspecialchars($C['anti_mail_spam']), $v); + }elseif($C['anti_link_spam']){ + $r1 = $C['anti_link_spam'][1]; + if(!empty($r1) && preg_match($r1, $v)){continue;} + $r0 = $C['anti_link_spam'][0]; + if(!empty($r0) && preg_match($r0, $v)){ + if(isset($a['rel'])){ + if(!preg_match('`\bnofollow\b`i', $a['rel'])){$a['rel'] .= ' nofollow';} + }elseif(isset($aA['rel'])){ + if(!preg_match('`\bnofollow\b`i', $aA['rel'])){$nfr = 1;} + }else{$a['rel'] = 'nofollow';} + } + } + } + } + if(isset($rl[$k]) && is_array($rl[$k]) && ($v = hl_attrval($v, $rl[$k])) === 0){continue;} + $a[$k] = str_replace('"', '"', $v); + } +} +if($nfr){$a['rel'] = isset($a['rel']) ? $a['rel']. ' nofollow' : 'nofollow';} + +// rqd attr +static $eAR = array('area'=>array('alt'=>'area'), 'bdo'=>array('dir'=>'ltr'), 'form'=>array('action'=>''), 'img'=>array('src'=>'', 'alt'=>'image'), 'map'=>array('name'=>''), 'optgroup'=>array('label'=>''), 'param'=>array('name'=>''), 'script'=>array('type'=>'text/javascript'), 'textarea'=>array('rows'=>'10', 'cols'=>'50')); +if(isset($eAR[$e])){ + foreach($eAR[$e] as $k=>$v){ + if(!isset($a[$k])){$a[$k] = isset($v[0]) ? $v : $k;} + } +} + +// depr attrs +if($depTr){ + $c = array(); + foreach($a as $k=>$v){ + if($k == 'style' or !isset($aND[$k][$e])){continue;} + if($k == 'align'){ + unset($a['align']); + if($e == 'img' && ($v == 'left' or $v == 'right')){$c[] = 'float: '. $v;} + elseif(($e == 'div' or $e == 'table') && $v == 'center'){$c[] = 'margin: auto';} + else{$c[] = 'text-align: '. $v;} + }elseif($k == 'bgcolor'){ + unset($a['bgcolor']); + $c[] = 'background-color: '. $v; + }elseif($k == 'border'){ + unset($a['border']); $c[] = "border: {$v}px"; + }elseif($k == 'bordercolor'){ + unset($a['bordercolor']); $c[] = 'border-color: '. $v; + }elseif($k == 'clear'){ + unset($a['clear']); $c[] = 'clear: '. ($v != 'all' ? $v : 'both'); + }elseif($k == 'compact'){ + unset($a['compact']); $c[] = 'font-size: 85%'; + }elseif($k == 'height' or $k == 'width'){ + unset($a[$k]); $c[] = $k. ': '. ($v[0] != '*' ? $v. (ctype_digit($v) ? 'px' : '') : 'auto'); + }elseif($k == 'hspace'){ + unset($a['hspace']); $c[] = "margin-left: {$v}px; margin-right: {$v}px"; + }elseif($k == 'language' && !isset($a['type'])){ + unset($a['language']); + $a['type'] = 'text/'. strtolower($v); + }elseif($k == 'name'){ + if($C['no_deprecated_attr'] == 2 or ($e != 'a' && $e != 'map')){unset($a['name']);} + if(!isset($a['id']) && preg_match('`[a-zA-Z][a-zA-Z\d.:_\-]*`', $v)){$a['id'] = $v;} + }elseif($k == 'noshade'){ + unset($a['noshade']); $c[] = 'border-style: none; border: 0; background-color: gray; color: gray'; + }elseif($k == 'nowrap'){ + unset($a['nowrap']); $c[] = 'white-space: nowrap'; + }elseif($k == 'size'){ + unset($a['size']); $c[] = 'size: '. $v. 'px'; + }elseif($k == 'start' or $k == 'value'){ + unset($a[$k]); + }elseif($k == 'type'){ + unset($a['type']); + static $ol_type = array('i'=>'lower-roman', 'I'=>'upper-roman', 'a'=>'lower-latin', 'A'=>'upper-latin', '1'=>'decimal'); + $c[] = 'list-style-type: '. (isset($ol_type[$v]) ? $ol_type[$v] : 'decimal'); + }elseif($k == 'vspace'){ + unset($a['vspace']); $c[] = "margin-top: {$v}px; margin-bottom: {$v}px"; + } + } + if(count($c)){ + $c = implode('; ', $c); + $a['style'] = isset($a['style']) ? rtrim($a['style'], ' ;'). '; '. $c. ';': $c. ';'; + } +} +// unique ID +if($C['unique_ids'] && isset($a['id'])){ + if(!preg_match('`^[A-Za-z][A-Za-z0-9_\-.:]*$`', ($id = $a['id'])) or (isset($GLOBALS['hl_Ids'][$id]) && $C['unique_ids'] == 1)){unset($a['id']); + }else{ + while(isset($GLOBALS['hl_Ids'][$id])){$id = $C['unique_ids']. $id;} + $GLOBALS['hl_Ids'][($a['id'] = $id)] = 1; + } +} +// xml:lang +if($C['xml:lang'] && isset($a['lang'])){ + $a['xml:lang'] = isset($a['xml:lang']) ? $a['xml:lang'] : $a['lang']; + if($C['xml:lang'] == 2){unset($a['lang']);} +} +// for transformed tag +if(!empty($trt)){ + $a['style'] = isset($a['style']) ? rtrim($a['style'], ' ;'). '; '. $trt : $trt; +} +// return with empty ele / +if(empty($C['hook_tag'])){ + $aA = ''; + foreach($a as $k=>$v){$aA .= " {$k}=\"{$v}\"";} + return "<{$e}{$aA}". (isset($eE[$e]) ? ' /' : ''). '>'; +} +else{return $C['hook_tag']($e, $a);} +// eof +} + +function hl_tag2(&$e, &$a, $t=1){ +// transform tag +if($e == 'center'){$e = 'div'; return 'text-align: center;';} +if($e == 'dir' or $e == 'menu'){$e = 'ul'; return '';} +if($e == 's' or $e == 'strike'){$e = 'span'; return 'text-decoration: line-through;';} +if($e == 'u'){$e = 'span'; return 'text-decoration: underline;';} +static $fs = array('0'=>'xx-small', '1'=>'xx-small', '2'=>'small', '3'=>'medium', '4'=>'large', '5'=>'x-large', '6'=>'xx-large', '7'=>'300%', '-1'=>'smaller', '-2'=>'60%', '+1'=>'larger', '+2'=>'150%', '+3'=>'200%', '+4'=>'300%'); +if($e == 'font'){ + $a2 = ''; + if(preg_match('`face\s*=\s*(\'|")([^=]+?)\\1`i', $a, $m) or preg_match('`face\s*=\s*([^"])(\S+)`i', $a, $m)){ + $a2 .= ' font-family: '. str_replace('"', '\'', trim($m[2])). ';'; + } + if(preg_match('`color\s*=\s*(\'|")?(.+?)(\\1|\s|$)`i', $a, $m)){ + $a2 .= ' color: '. trim($m[2]). ';'; + } + if(preg_match('`size\s*=\s*(\'|")?(.+?)(\\1|\s|$)`i', $a, $m) && isset($fs[($m = trim($m[2]))])){ + $a2 .= ' font-size: '. $fs[$m]. ';'; + } + $e = 'span'; return ltrim($a2); +} +if($t == 2){$e = 0; return 0;} +return ''; +// eof +} + +function hl_tidy($t, $w, $p){ +// Tidy/compact HTM +if(strpos(' pre,script,textarea', "$p,")){return $t;} +$t = str_replace(' ]*(?)\s+`', '`\s+`', '`(<\w[^>]*(?) `'), array(' $1', ' ', '$1'), preg_replace_callback(array('`(<(!\[CDATA\[))(.+?)(\]\]>)`sm', '`(<(!--))(.+?)(-->)`sm', '`(<(pre|script|textarea).*?>)(.+?)()`sm'), create_function('$m', 'return $m[1]. str_replace(array("<", ">", "\n", "\r", "\t", " "), array("\x01", "\x02", "\x03", "\x04", "\x05", "\x07"), $m[3]). $m[4];'), $t))); +if(($w = strtolower($w)) == -1){ + return str_replace(array("\x01", "\x02", "\x03", "\x04", "\x05", "\x07"), array('<', '>', "\n", "\r", "\t", ' '), $t); +} +$s = strpos(" $w", 't') ? "\t" : ' '; +$s = preg_match('`\d`', $w, $m) ? str_repeat($s, $m[0]) : str_repeat($s, ($s == "\t" ? 1 : 2)); +$n = preg_match('`[ts]([1-9])`', $w, $m) ? $m[1] : 0; +$a = array('br'=>1); +$b = array('button'=>1, 'input'=>1, 'option'=>1); +$c = array('caption'=>1, 'dd'=>1, 'dt'=>1, 'h1'=>1, 'h2'=>1, 'h3'=>1, 'h4'=>1, 'h5'=>1, 'h6'=>1, 'isindex'=>1, 'label'=>1, 'legend'=>1, 'li'=>1, 'object'=>1, 'p'=>1, 'pre'=>1, 'td'=>1, 'textarea'=>1, 'th'=>1); +$d = array('address'=>1, 'blockquote'=>1, 'center'=>1, 'colgroup'=>1, 'dir'=>1, 'div'=>1, 'dl'=>1, 'fieldset'=>1, 'form'=>1, 'hr'=>1, 'iframe'=>1, 'map'=>1, 'menu'=>1, 'noscript'=>1, 'ol'=>1, 'optgroup'=>1, 'rbc'=>1, 'rtc'=>1, 'ruby'=>1, 'script'=>1, 'select'=>1, 'table'=>1, 'tfoot'=>1, 'thead'=>1, 'tr'=>1, 'ul'=>1); +ob_start(); +if(isset($d[$p])){echo str_repeat($s, ++$n);} +$t = explode('<', $t); +echo ltrim(array_shift($t)); +for($i=-1, $j=count($t); ++$i<$j;){ + $r = ''; list($e, $r) = explode('>', $t[$i]); + $x = $e[0] == '/' ? 0 : (substr($e, -1) == '/' ? 1 : ($e[0] != '!' ? 2 : -1)); + $y = !$x ? ltrim($e, '/') : ($x > 0 ? substr($e, 0, strcspn($e, ' ')) : 0); + $e = "<$e>"; + if(isset($d[$y])){ + if(!$x){echo "\n", str_repeat($s, --$n), "$e\n", str_repeat($s, $n);} + else{echo "\n", str_repeat($s, $n), "$e\n", str_repeat($s, ($x != 1 ? ++$n : $n));} + echo ltrim($r); continue; + } + $f = "\n". str_repeat($s, $n); + if(isset($c[$y])){ + if(!$x){echo $e, $f, ltrim($r);} + else{echo $f, $e, $r;} + }elseif(isset($b[$y])){echo $f, $e, $r; + }elseif(isset($a[$y])){echo $e, $f, ltrim($r); + }elseif(!$y){echo $f, $e, $f, ltrim($r); + }else{echo $e, $r;} +} +$t = preg_replace('`[\n]\s*?[\n]+`', "\n", ob_get_contents()); +ob_end_clean(); +if(($l = strpos(" $w", 'r') ? (strpos(" $w", 'n') ? "\r\n" : "\r") : 0)){ + $t = str_replace("\n", $l, $t); +} +return str_replace(array("\x01", "\x02", "\x03", "\x04", "\x05", "\x07"), array('<', '>', "\n", "\r", "\t", ' '), $t); +// eof +} + +function hl_version(){ +// rel +return '1.1.8.1'; +// eof +} + +function kses($t, $h, $p=array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'gopher', 'mailto')){ +// kses compat +foreach($h as $k=>$v){ + $h[$k]['n']['*'] = 1; +} +$C['cdata'] = $C['comment'] = $C['make_tag_strict'] = $C['no_deprecated_attr'] = $C['unique_ids'] = 0; +$C['keep_bad'] = 1; +$C['elements'] = count($h) ? strtolower(implode(',', array_keys($h))) : '-*'; +$C['hook'] = 'kses_hook'; +$C['schemes'] = '*:'. implode(',', $p); +return htmLawed($t, $C, $h); +// eof +} + +function kses_hook($t, &$C, &$S){ +// kses compat +return $t; +// eof +} \ No newline at end of file diff --git a/extlib/htmLawed/htmLawedTest.php b/extlib/htmLawed/htmLawedTest.php new file mode 100644 index 000000000..776828699 --- /dev/null +++ b/extlib/htmLawed/htmLawedTest.php @@ -0,0 +1,592 @@ + $v){ + $_POST[$k] = stripslashes($v); + } + ini_set('magic_quotes_gpc', 0); +} +set_magic_quotes_runtime(0); + +$_POST['enc'] = (isset($_POST['enc']) and preg_match('`^[-\w]+$`', $_POST['enc'])) ? $_POST['enc'] : 'utf-8'; + +// token for anti-CSRF +if(count($_POST)){ + if((empty($_GET['pre']) and ((!empty($_POST['token']) and !empty($_SESSION['token']) and $_POST['token'] != $_SESSION['token']) or empty($_POST[$_sid]) or $_POST[$_sid] != session_id() or empty($_COOKIE[$_sid]) or $_COOKIE[$_sid] != session_id())) or ($_POST[$_sid] != session_id())){ + $_POST = array('enc'=>'utf-8'); + } +} +if(empty($_GET['pre'])){ + $_SESSION['token'] = md5(uniqid(rand(), 1)); + $token = $_SESSION['token']; + session_regenerate_id(1); +} + +// compress +if(function_exists('gzencode') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && preg_match('`gzip|deflate`i', $_SERVER['HTTP_ACCEPT_ENCODING']) && !ini_get('zlib.output_compression')){ + ob_start('ob_gzhandler'); +} + +// HTM for unprocessed +if(isset($_POST['inputH'])){ + echo 'htmLawed test: HTML view of unprocessed input

      Rendering of unprocessed input without an HTML doctype or charset declaration     close window | htmLawed test page

    ', $_POST['inputH'], '
    '; + exit; +} + +// main +$_POST['text'] = isset($_POST['text']) ? $_POST['text'] : 'text to process; < '. $_limit. ' characters'. ($_hlimit ? ' (for binary hexdump view, < '. $_hlimit. ')' : ''); +$do = (!empty($_POST[$_sid]) && isset($_POST['text'][0]) && !isset($_POST['text'][$_limit])) ? 1 : 0; +$limit_exceeded = isset($_POST['text'][$_limit]) ? 1 : 0; +$pre_mem = memory_get_usage(); +$validation = (!empty($_POST[$_sid]) and isset($_POST['w3c_validate'][0])) ? 1 : 0; +include './htmLawed.php'; + +function format($t){ + $t = "\n". str_replace(array("\t", "\r\n", "\r", '&', '<', '>', "\n"), array(' ', "\n", "\n", '&', '<', '>', "¬
    \n"), $t); + return str_replace(array('
    ', "\n ", ' '), array("\n
    \n", "\n ", '  '), $t); +} + +function hexdump($d){ +// Mainly by Aidan Lister , Peter Waller + $hexi = ''; + $ascii = ''; + ob_start(); + echo '
    ';
    + $offset = 0;
    + $len = strlen($d);
    + for($i=$j=0; $i<$len; $i++)
    + {
    +  // Convert to hexidecimal
    +  $hexi .= sprintf("%02X ", ord($d[$i]));
    +  // Replace non-viewable bytes with '.'
    +  if(ord($d[$i]) >= 32){
    +   $ascii .= htmlspecialchars($d[$i]);
    +  }else{
    +   $ascii .= '.';
    +  } 
    +  // Add extra column spacing
    +  if($j == 7){
    +   $hexi .= ' ';
    +   $ascii .= '  ';
    +  }
    +  // Add row
    +  if(++$j == 16 || $i == $len-1){
    +   // Join the hexi / ascii output
    +   echo sprintf("%04X   %-49s   %s", $offset, $hexi, $ascii);   
    +   // Reset vars
    +   $hexi = $ascii = '';
    +   $offset += 16;
    +   $j = 0;  
    +   // Add newline   
    +   if ($i !== $len-1){
    +    echo "\n";
    +   }
    +  }
    + }
    + echo '
    '; + $o = ob_get_contents(); + ob_end_clean(); + return $o; +} +?> + + + + + + + + +htmLawed (<?php echo hl_version();?>) test + + +
    + +
    HTMLAWED TEST
    +htm / txt documentation
    + +Input » (max. chars) + +
    + +
    + + +
    + + +'; + } +?> + + + + + + + + + + Validator tools: '; + } +} +?> + +Encoding: + +
    +
    + +Input text is too long!
    '; +} +?> + +
    + +Settings » + + +
    + +$v){ + if($k[0] == 'h' && $v != 'nil'){ + $cfg[substr($k, 1)] = $v; + } + } + + if($cfg['anti_link_spam'] && (!empty($cfg['anti_link_spam11']) or !empty($cfg['anti_link_spam12']))){ + $cfg['anti_link_spam'] = array($cfg['anti_link_spam11'], $cfg['anti_link_spam12']); + } + unset($cfg['anti_link_spam11'], $cfg['anti_link_spam12']); + if($cfg['anti_mail_spam'] == 1){ + $cfg['anti_mail_spam'] = isset($cfg['anti_mail_spam1'][0]) ? $cfg['anti_mail_spam1'] : 0; + } + unset($cfg['anti_mail_spam11']); + if($cfg['deny_attribute'] == 1){ + $cfg['deny_attribute'] = isset($cfg['deny_attribute1'][0]) ? $cfg['deny_attribute1'] : 0; + } + unset($cfg['deny_attribute1']); + if($cfg['tidy'] == 2){ + $cfg['tidy'] = isset($cfg['tidy2'][0]) ? $cfg['tidy2'] : 0; + } + unset($cfg['tidy2']); + if($cfg['unique_ids'] == 2){ + $cfg['unique_ids'] = isset($cfg['unique_ids2'][0]) ? $cfg['unique_ids2'] : 1; + } + unset($cfg['unique_ids2']); + unset($cfg['and_mark']); // disabling and_mark + + $cfg['show_setting'] = 'hlcfg'; + $st = microtime(); + $out = htmLawed($_POST['text'], $cfg, str_replace(array('$', '{'), '', $_POST['spec'])); + $et = microtime(); + echo '
    Input code » ', strlen($_POST['text']), ' chars, ~', round((substr_count($_POST['text'], '>') + substr_count($_POST['text'], '<'))/2), ' tags ', (!isset($_POST['text'][$_hlimit]) ? ' Input binary » ' : ''), ' Finalized internal settings »  ', '
    Output » htmLawed processing time ', number_format(((substr($et,0,9)) + (substr($et,-10)) - (substr($st,0,9)) - (substr($st,-10))),4), ' s', (($mem = memory_get_peak_usage()) !== false ? ', peak memory usage '. round(($mem-$pre_mem)/1048576, 2). ' MB' : ''), '
    '; + if($_w3c_validate && $validation) + { +?> + + + + +
    Output code »
    ', format($out), '
    ', (!isset($_POST['text'][$_hlimit]) ? '
    Output binary »' : ''), '
    Output rendered »
    ', $out, '
    '; +} +else{ +?> + +
    + +
    Use with a Javascript- and cookie-enabled, relatively new version of a common browser. Submitted input will also be HTML-rendered (XHTML 1) after htmLawed-filtering. + +
    You can use text from this collection of test-cases in the input. Set the character encoding of the browser to Unicode/utf-8 before copying.' : ''); ?> + +

    For anti-XSS tests, try the special test-page or see these results. + +

    Change Encoding to reflect the character encoding of the input text. Even then, it may not work or some characters may not display properly because of variable browser support and because of the form interface. Developers can write some PHP code to capture the filtered input to a file if this is important. +

    Refer to the htmLawed documentation (htm/txt) for details about Settings, and htmLawed's behavior and limitations. For Settings, incorrectly-specified values like regular expressions are silently ignored. One or more settings form-fields may have been disabled. Some characters are not allowed in the Spec field. + + +

    Hovering the mouse over some of the text can provide additional information in some browsers.
    + + + +

    Because of character-encoding issues, the W3C validator (anyway not perfect) may reject validation requests or invalidate otherwise-valid code, esp. if text was copy-pasted in the input box. Local applications like the HTML Validator Firefox browser add-on may be useful in such cases.
    + + + +
    + + + +
    + + \ No newline at end of file diff --git a/extlib/htmLawed/htmLawed_README.htm b/extlib/htmLawed/htmLawed_README.htm new file mode 100644 index 000000000..e560e2eb2 --- /dev/null +++ b/extlib/htmLawed/htmLawed_README.htm @@ -0,0 +1,1979 @@ + + + + + + + + +htmLawed documentation | htmLawed PHP software is a free, open-source, customizable HTML input purifier and filter + + +
    +

    htmLawed documentation

    + +
    1  About htmLawed
    1.1  Example uses
    1.2  Features
    1.3  History
    1.4  License & copyright
    1.5  Terms used here
    +2  Usage
    2.1  Simple
    2.2  Configuring htmLawed using the $config parameter
    2.3  Extra HTML specifications using the $spec parameter
    2.4  Performance time & memory usage
    2.5  Some security risks to keep in mind
    2.6  Use without modifying old kses() code
    2.7  Tolerance for ill-written HTML
    2.8  Limitations & work-arounds
    2.9  Examples
    +3  Details
    3.1  Invalid/dangerous characters
    3.2  Character references/entities
    3.3  HTML elements
    +    3.3.1  HTML comments and CDATA sections
    +    3.3.2  Tag-transformation for better XHTML-Strict
    +    3.3.3  Tag balancing and proper nesting
    +    3.3.4  Elements requiring child elements
    +    3.3.5  Beautify or compact HTML
    3.4  Attributes
    +    3.4.1  Auto-addition of XHTML-required attributes
    +    3.4.2  Duplicate/invalid id values
    +    3.4.3  URL schemes (protocols) and scripts in attribute values
    +    3.4.4  Absolute & relative URLs
    +    3.4.5  Lower-cased, standard attribute values
    +    3.4.6  Transformation of deprecated attributes
    +    3.4.7  Anti-spam & href
    +    3.4.8  Inline style properties
    +    3.4.9  Hook function for tag content
    3.5  Simple configuration directive for most valid XHTML
    3.6  Simple configuration directive for most safe HTML
    3.7  Using a hook function
    3.8  Obtaining finalized parameter values
    3.9  Retaining non-HTML tags in input with mixed markup
    +4  Other
    4.1  Support
    4.2  Known issues
    4.3  Change-log
    4.4  Testing
    4.5  Upgrade, & old versions
    4.6  Comparison with HTMLPurifier
    4.7  Use through application plug-ins/modules
    4.8  Use in non-PHP applications
    4.9  Donate
    4.10  Acknowledgements
    +5  Appendices
    5.1  Characters discouraged in HTML
    5.2  Valid attribute-element combinations
    5.3  CSS 2.1 properties accepting URLs
    5.4  Microsoft Windows 1252 character replacements
    5.5  URL format
    5.6  Brief on htmLawed code
    + +
    +
    +
    htmLawed_README.txt, 16 July 2009
    +htmLawed 1.1.8.1, 16 July 2009
    +Copyright Santosh Patnaik
    +GPL v3 license
    +A PHP Labware internal utility - http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed 
    +
    + +

    +1  About htmLawed +

    (to top)
    +
    +  htmLawed is a highly customizable single-file PHP script to make text secure, and standard- and admin policy-compliant for use in the body of HTML 4, XHTML 1 or 1.1, or generic XML documents. It is thus a configurable input (X)HTML filter, processor, purifier, sanitizer, beautifier, etc., and an alternative to the HTMLTidy application.
    +
    +  The lawing in of input text is needed to ensure that HTML code in the text is standard-compliant, does not introduce security vulnerabilities, and does not break the aesthetics, design or layout of web-pages. htmLawed tries to do this by, for example, making HTML well-formed with balanced and properly nested tags, neutralizing code that may be used for cross-site scripting (XSS) attacks, and allowing only specified HTML elements/tags and attributes.
    + +

    +1.1  Example uses +

    (to top)
    +
    +  *  Filtering of text submitted as comments on blogs to allow only certain HTML elements
    +
    +  *  Making RSS/Atom newsfeed item-content standard-compliant: often one uses an excerpt from an HTML document for the content, and with unbalanced tags, non-numerical entities, etc., such excerpts may not be XML-compliant
    +
    +  *  Text processing for stricter XML standard-compliance: e.g., to have lowercased x in hexadecimal numeric entities becomes necessary if an XHTML document with MathML content needs to be served as application/xml
    +
    +  *  Scraping text or data from web-pages
    +
    +  *  Pretty-printing HTML code
    + +
    +

    +1.2  Features +

    (to top)
    +
    +  Key: * security feature, ^ standard compliance, ~ requires setting right options, ` different from Kses
    +
    +  *  make input more secure and standard-compliant
    +  *  use for HTML 4, XHTML 1.0 or 1.1, or even generic XML documents  ^~`
    +
    +  *  beautify or compact HTML  ^~`
    +
    +  *  restrict elements  ^~`
    +  *  proper closure of empty elements like img  ^`
    +  *  transform deprecated elements like u  ^~`
    +  *  HTML comments and CDATA sections can be permitted  ^~`
    +  *  elements like script, object and form can be permitted  ~
    +
    +  *  restrict attributes, including element-specifically  ^~`
    +  *  remove invalid attributes  ^`
    +  *  element and attribute names are lower-cased  ^
    +  *  provide required attributes, like alt for image  ^`
    +  *  transform deprecated attributes  ^~`
    +  *  attributes declared only once  ^`
    +
    +  *  restrict attribute values, including element-specifically  ^~`
    +  *  a value is declared for empty (minimized) attributes like checked  ^
    +  *  check for potentially dangerous attribute values  *~
    +  *  ensure unique id attribute values  ^~`
    +  *  double-quote attribute values  ^
    +  *  lower-case standard attribute values like password  ^`
    +
    +  *  attribute-specific URL protocol/scheme restriction  *~`
    +  *  disable dynamic expressions in style values  *~`
    +
    +  *  neutralize invalid named character entities  ^`
    +  *  convert hexadecimal numeric entities to decimal ones, or vice versa  ^~`
    +  *  convert named entities to numeric ones for generic XML use  ^~`
    +
    +  *  remove null characters  *
    +  *  neutralize potentially dangerous proprietary Netscape Javascript entities  *
    +  *  replace potentially dangerous soft-hyphen character in attribute values with spaces  *
    +
    +  *  remove common invalid characters not allowed in HTML or XML  ^`
    +  *  replace characters from Microsoft applications like Word that are discouraged in HTML or XML  ^~`
    +  *  neutralize entities for characters invalid or discouraged in HTML or XML  ^`
    +  *  appropriately neutralize <, &, ", and > characters  ^*`
    +
    +  *  understands improperly spaced tag content (like, spread over more than a line) and properly spaces them  `
    +  *  attempts to balance tags for well-formedness  ^~`
    +  *  understands when omitable closing tags like </p> (allowed in HTML 4, transitional, e.g.) are missing  ^~`
    +  *  attempts to permit only validly nested tags  ^~`
    +  *  option to remove or neutralize bad content ^~`
    +  *  attempts to rectify common errors of plain-text misplacement (e.g., directly inside blockquote) ^~`
    +
    +  *  fast, non-OOP code of ~45 kb incurring peak basal memory usage of ~0.5 MB
    +  *  compatible with pre-existing code using Kses (the filter used by WordPress)
    +
    +  *  optional anti-spam measures such as addition of rel="nofollow" and link-disabling  ~`
    +  *  optionally makes relative URLs absolute, and vice versa  ~`
    +
    +  *  optionally mark & to identify the entities for &, < and > introduced by htmLawed  ~`
    +
    +  *  allows deployment of powerful hook functions to inject HTML, consolidate style attributes to class, finely check attribute values, etc.  ~`
    +
    +  *  independent of character encoding of input and does not affect it
    +
    +  *  tolerance for ill-written HTML to a certain degree
    + +
    +

    +1.3  History +

    (to top)
    +
    +  htmLawed was developed for use with LabWiki, a wiki software developed at PHP Labware, as a suitable software could not be found. Existing PHP software like Kses and HTMLPurifier were deemed inadequate, slow, resource-intensive, or dependent on external applications like HTML Tidy.
    +
    +  htmLawed started as a modification of Ulf Harnhammar's Kses (version 0.2.2) software, and is compatible with code that uses Kses; see section 2.6.
    + +
    +

    +1.4  License & copyright +

    (to top)
    +
    +  htmLawed is free and open-source software licensed under GPL license version 3, and copyrighted by Santosh Patnaik, MD, PhD.
    + +
    +

    +1.5  Terms used here +

    (to top)
    +
    +  *  administrator - or admin; person setting up the code to pass input through htmLawed; also, user
    +  *  attributes - name-value pairs like href="http://x.com" in opening tags
    +  *  author - writer
    +  *  character - atomic unit of text; internally represented by a numeric code-point as specified by the encoding or charset in use
    +  *  entity - markup like &gt; and &#160; used to refer to a character
    +  *  element - HTML element like a and img
    +  *  element content -  content between the opening and closing tags of an element, like click of <a href="x">click</a>
    +  *  HTML - implies XHTML unless specified otherwise
    +  *  input - text string given to htmLawed to process
    +  *  processing - involves filtering, correction, etc., of input
    +  *  safe - absence or reduction of certain characters and HTML elements and attributes in the input that can otherwise potentially and circumstantially expose web-site users to security vulnerabilities like cross-site scripting attacks (XSS)
    +  *  scheme - URL protocol like http and ftp
    +  *  specs - standard specifications
    +  *  style property - terms like border and height for which declarations are made in values for the style attribute of elements
    +  *  tag - markers like <a href="x"> and </a> delineating element content; the opening tag can contain attributes
    +  *  tag content - consists of tag markers < and >, element names like div, and possibly attributes
    +  *  user - administrator
    +  *  writer - end-user like a blog commenter providing the input that is to be processed; also, author
    + +
    +
    +

    +2  Usage +

    (to top)
    +
    +  htmLawed should work with PHP 4.3 and higher. Either include() the htmLawed.php file or copy-paste the entire code.
    +
    +  To easily test htmLawed using a form-based interface, use the provided demo (htmLawed.php and htmLawedTest.php should be in the same directory on the web-server).
    + +

    +2.1  Simple +

    (to top)
    +
    +  The input text to be processed, $text, is passed as an argument of type string; htmLawed() returns the processed string:
    +
    + +    $processed = htmLawed($text); +
    +
    Note: If input is from a $_GET or $_POST value, and magic quotes are enabled on the PHP setup, run stripslashes() on the input before passing to htmLawed.
    +
    +  By default, htmLawed will process the text allowing all valid HTML elements/tags, secure URL scheme/CSS style properties, etc. It will allow CDATA sections and HTML comments, balance tags, and ensure proper nesting of elements. Such actions can be configured using two other optional arguments -- $config and $spec:
    +
    + +    $processed = htmLawed($text, $config, $spec); +
    +
    +  These extra parameters are detailed below. Some examples are shown in section 2.9.
    +
    Note: For maximum protection against XSS and other scripting attacks (e.g., by disallowing Javascript code), consider using the safe parameter; see section 3.6.
    + +
    +

    +2.2  Configuring htmLawed using the $config parameter +

    (to top)
    +
    $config instructs htmLawed on how to tackle certain tasks. When $config is not specified, or not set as an array (e.g., $config = 1), htmLawed will take default actions. One or many of the task-action or value-specification pairs can be specified in $config as array key-value pairs. If a parameter is not specified, htmLawed will use the default value/action indicated further below.
    +
    + +    $config = array('comment'=>0, 'cdata'=>1); +
    + +    $processed = htmLawed($text, $config); +
    +
    +  Or,
    +
    + +    $processed = htmLawed($text, array('comment'=>0, 'cdata'=>1)); +
    +
    +  Below are the possible value-specification combinations. In PHP code, values that are integers should not be quoted and should be used as numeric types (unless meant as string/text).
    +
    +  Key: * default, ^ different default when htmLawed is used in the Kses-compatible mode (see section 2.6), ~ different default when valid_xhtml is set to 1 (see section 3.5), " different default when safe is set to 1 (see section 3.6)
    +
    abs_url
    +  Make URLs absolute or relative; $config["base_url"] needs to be set; see section 3.4.4
    +
    -1 - make relative
    0 - no action  *
    1 - make absolute
    +
    and_mark
    +  Mark & characters in the original input; see section 3.2
    +
    anti_link_spam
    +  Anti-link-spam measure; see section 3.4.7
    +
    0 - no measure taken  *
    array("regex1", "regex2") - will ensure a rel attribute with nofollow in its value in case the href attribute value matches the regular expression pattern regex1, and/or will remove href if its value matches the regular expression pattern regex2. E.g., array("/./", "/://\W*(?!(abc\.com|xyz\.org))/"); see section 3.4.7 for more.
    +
    anti_mail_spam
    +  Anti-mail-spam measure; see section 3.4.7
    +
    0 - no measure taken  *
    word - @ in mail address in href attribute value is replaced with specified word
    +
    balance
    +  Balance tags for well-formedness and proper nesting; see section 3.3.3
    +
    0 - no
    1 - yes  *
    +
    base_url
    +  Base URL value that needs to be set if $config["abs_url"] is not 0; see section 3.4.4
    +
    cdata
    +  Handling of CDATA sections; see section 3.3.1
    +
    0 - don't consider CDATA sections as markup and proceed as if plain text  ^"
    1 - remove
    2 - allow, but neutralize any <, >, and & inside by converting them to named entities
    3 - allow  *
    +
    clean_ms_char
    +  Replace discouraged characters introduced by Microsoft Word, etc.; see section 3.1
    +
    0 - no  *
    1 - yes
    2 - yes, but replace special single & double quotes with ordinary ones
    +
    comment
    +  Handling of HTML comments; see section 3.3.1
    +
    0 - don't consider comments as markup and proceed as if plain text  ^"
    1 - remove
    2 - allow, but neutralize any <, >, and & inside by converting to named entities
    3 - allow  *
    +
    css_expression
    +  Allow dynamic CSS expression by not removing the expression from CSS property values in style attributes; see section 3.4.8
    +
    0 - remove  *
    1 - allow
    +
    deny_attribute
    +  Denied HTML attributes; see section 3.4
    +
    0 - none  *
    string - dictated by values in string
    on* (like onfocus) attributes not allowed - "
    +
    elements
    +  Allowed HTML elements; see section 3.3
    +
    * -center -dir -font -isindex -menu -s -strike -u -  ~
    applet, embed, iframe, object, script not allowed - "
    +
    hexdec_entity
    +  Allow hexadecimal numeric entities and do not convert to the more widely accepted decimal ones, or convert decimal to hexadecimal ones; see section 3.2
    +
    0 - no
    1 - yes  *
    2 - convert decimal to hexadecimal ones
    +
    hook
    +  Name of an optional hook function to alter the input string, $config or $spec before htmLawed starts its main work; see section 3.7
    +
    0 - no hook function  *
    name - name is name of the hook function (kses_hook  ^)
    +
    hook_tag
    +  Name of an optional hook function to alter tag content finalized by htmLawed; see section 3.4.9
    +
    0 - no hook function  *
    name - name is name of the hook function
    +
    keep_bad
    +  Neutralize bad tags by converting < and > to entities, or remove them; see section 3.3.3
    +
    0 - remove  ^
    1 - neutralize both tags and element content
    2 - remove tags but neutralize element content
    3 and 4 - like 1 and 2 but remove if text (pcdata) is invalid in parent element
    5 and 6 * -  like 3 and 4 but line-breaks, tabs and spaces are left
    +
    lc_std_val
    +  For XHTML compliance, predefined, standard attribute values, like get for the method attribute of form, must be lowercased; see section 3.4.5
    +
    0 - no
    1 - yes  *
    +
    make_tag_strict
    +  Transform/remove these non-strict XHTML elements, even if they are allowed by the admin: applet center dir embed font isindex menu s strike u; see section 3.3.2
    +
    0 - no  ^
    1 - yes, but leave applet, embed and isindex elements that currently can't be transformed  *
    2 - yes, removing applet, embed and isindex elements and their contents (nested elements remain)  ~
    +
    named_entity
    +  Allow non-universal named HTML entities, or convert to numeric ones; see section 3.2
    +
    0 - convert
    1 - allow  *
    +
    no_deprecated_attr
    +  Allow deprecated attributes or transform them; see section 3.4.6
    +
    0 - allow  ^
    1 - transform, but name attributes for a and map are retained  *
    2 - transform
    +
    parent
    +  Name of the parent element, possibly imagined, that will hold the input; see section 3.3
    +
    safe
    +  Magic parameter to make input the most secure against XSS without needing to specify other relevant $config parameters; see section 3.6
    +
    0 - no  *
    1 - will auto-adjust other relevant $config parameters (indicated by " in this list)
    +
    schemes
    +  Array of attribute-specific, comma-separated, lower-cased list of schemes (protocols) allowed in attributes accepting URLs; * covers all unspecified attributes; see section 3.4.3
    +
    href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; *:file, http, https  *
    *: ftp, gopher, http, https, mailto, news, nntp, telnet  ^
    href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https  "
    +
    show_setting
    +  Name of a PHP variable to assign the finalized $config and $spec values; see section 3.8
    +
    style_pass
    +  Do not look at style attribute values, letting them through without any alteration
    +
    0 - no *
    1 - htmLawed will let through any style value; see section 3.4.8
    +
    tidy
    +  Beautify or compact HTML code; see section 3.3.5
    +
    -1 - compact
    0 - no  *
    1 or string - beautify (custom format specified by string)
    +
    unique_ids
    id attribute value checks; see section 3.4.2
    +
    0 - no  ^
    1 - remove duplicate and/or invalid ones  *
    word - remove invalid ones and replace duplicate ones with new and unique ones based on the word; the admin-specified word, like my_, should begin with a letter (a-z) and can contain letters, digits, ., _, -, and :.
    +
    valid_xhtml
    +  Magic parameter to make input the most valid XHTML without needing to specify other relevant $config parameters; see section 3.5
    +
    0 - no  *
    1 - will auto-adjust other relevant $config parameters (indicated by ~ in this list)
    +
    xml:lang
    +  Auto-adding xml:lang attribute; see section 3.4.1
    +
    0 - no  *
    1 - add if lang attribute is present
    2 - add if lang attribute is present, and remove lang  ~
    + +
    +

    +2.3  Extra HTML specifications using the $spec parameter +

    (to top)
    +
    +  The $spec argument can be used to disallow an otherwise legal attribute for an element, or to restrict the attribute's values. This can also be helpful as a security measure (e.g., in certain versions of browsers, certain values can cause buffer overflows and denial of service attacks), or in enforcing admin policy compliance. $spec is specified as a string of text containing one or more rules, with multiple rules separated from each other by a semi-colon (;). E.g.,
    +
    + +    $spec = 'i=-*; td, tr=style, id, -*; a=id(match="/[a-z][a-z\d.:\-`"]*/i"/minval=2), href(maxlen=100/minlen=34); img=-width,-alt'; +
    + +    $processed = htmLawed($text, $config, $spec); +
    +
    +  Or,
    +
    + +    $processed = htmLawed($text, $config, 'i=-*; td, tr=style, id, -*; a=id(match="/[a-z][a-z\d.:\-`"]*/i"/minval=2), href(maxlen=100/minlen=34); img=-width,-alt'); +
    +
    +  A rule begins with an HTML element name(s) (rule-element), for which the rule applies, followed by an equal (=) sign. A rule-element may represent multiple elements if comma (,)-separated element names are used. E.g., th,td,tr=.
    +
    +  Rest of the rule consists of comma-separated HTML attribute names. A minus (-) character before an attribute means that the attribute is not permitted inside the rule-element. E.g., -width. To deny all attributes, -* can be used.
    +
    +  Following shows examples of rule excerpts with rule-element a and the attributes that are being permitted:
    +
    +  *  a= - all
    +  *  a=id - all
    +  *  a=href, title, -id, -onclick - all except id and onclick
    +  *  a=*, id, -id - all except id
    +  *  a=-* - none
    +  *  a=-*, href, title - none except href and title
    +  *  a=-*, -id, href, title - none except href and title
    +
    +  Rules regarding attribute values are optionally specified inside round brackets after attribute names in slash ('/')-separated parameter = value pairs. E.g., title(maxlen=30/minlen=5). None, or one or more of the following parameters may be specified:
    +
    +  *  oneof - one or more choices separated by | that the value should match; if only one choice is provided, then the value must match that choice
    +
    +  *  noneof - one or more choices separated by | that the value should not match
    +
    +  *  maxlen and minlen - upper and lower limits for the number of characters in the attribute value; specified in numbers
    +
    +  *  maxval and minval - upper and lower limits for the numerical value specified in the attribute value; specified in numbers
    +
    +  *  match and nomatch - pattern that the attribute value should or should not match; specified as PHP/PCRE-compatible regular expressions with delimiters and possibly modifiers
    +
    +  *  default - a value to force on the attribute if the value provided by the writer does not fit any of the specified parameters
    +
    +  If default is not set and the attribute value does not satisfy any of the specified parameters, then the attribute is removed. The default value can also be used to force all attribute declarations to take the same value (by getting the values declared illegal by setting, e.g., maxlen to -1).
    +
    +  Examples with input <input title="WIDTH" value="10em" /><input title="length" value="5" /> are shown below.
    +
    Rule: input=title(maxlen=60/minlen=6), value
    Output: <input value="10em" /><input title="length" value="5" />
    +
    Rule: input=title(), value(maxval=8/default=6)
    Output: <input title="WIDTH" value="6" /><input title="length" value="5" />
    +
    Rule: input=title(nomatch=$w.d$i), value(match=$em$/default=6em)
    Output: <input value="10em" /><input title="length" value="6em" />
    +
    Rule: input=title(oneof=height|depth/default=depth), value(noneof=5|6)
    Output: <input title="depth" value="10em" /><input title="depth" />
    +
    Special characters: The characters ;, ,, /, (, ), |, ~ and space have special meanings in the rules. Words in the rules that use such characters, or the characters themselves, should be escaped by enclosing in pairs of double-quotes ("). A back-tick (`) can be used to escape a literal ". An example rule illustrating this is input=value(maxlen=30/match="/^\w/"/default="your `"ID`"").
    +
    Note: To deny an attribute for all elements for which it is legal, $config["deny_attribute"] (see section 3.4) can be used instead of $spec. Also, attributes can be allowed element-specifically through $spec while being denied globally through $config["deny_attribute"]. The hook_tag parameter (section 3.4.9) can also be used to implement the $spec functionality.
    + +
    +

    +2.4  Performance time & memory usage +

    (to top)
    +
    +  The time and memory used by htmLawed depends on its configuration and the size of the input, and the amount, nestedness and well-formedness of the HTML markup within it. In particular, tag balancing and beautification each can increase the processing time by about a quarter.
    +
    +  The htmLawed demo can be used to evaluate the performance and effects of different types of input and $config.
    + +
    +

    +2.5  Some security risks to keep in mind +

    (to top)
    +
    +  When setting the parameters/arguments (like those to allow certain HTML elements) for use with htmLawed, one should bear in mind that the setting may let through potentially dangerous HTML code. (This may not be a problem if the authors are trusted.)
    +
    +  For example, following increase security risks:
    +
    +  *  Allowing script, applet, embed, iframe or object elements, or certain of their attributes like allowscriptaccess
    +
    +  *  Allowing HTML comments (some Internet Explorer versions are vulnerable with, e.g., <!--[if gte IE 4]><script>alert("xss");</script><![endif]-->
    +
    +  *  Allowing dynamic CSS expressions (a feature of the IE browser)
    +
    Unsafe HTML can be removed by setting $config appropriately. E.g., $config["elements"] = "* -script" (section 3.3), $config["safe"] = 1 (section 3.6), etc.
    + +
    +

    +2.6  Use without modifying old kses() code +

    (to top)
    +
    +  The Kses PHP script is used by many applications (like WordPress). It is possible to have such applications use htmLawed instead, since it is compatible with code that calls the kses() function declared in the Kses file (usually named kses.php). E.g., application code like this will continue to work after replacing Kses with htmLawed:
    +
    + +    $comment_filtered = kses($comment_input, array('a'=>array(), 'b'=>array(), 'i'=>array())); +
    +
    +  For some of the $config parameters, htmLawed will use values other than the default ones. These are indicated by ^ in section 2.2. To force htmLawed to use other values, function kses() in the htmLawed code should be edited -- a few configurable parameters/variables need to be changed.
    +
    +  If the application uses a Kses file that has the kses() function declared, then, to have the application use htmLawed instead of Kses, simply rename htmLawed.php (to kses.php, e.g.) and replace the Kses file (or just replace the code in the Kses file with the htmLawed code). If the kses() function in the Kses file had been renamed by the application developer (e.g., in WordPress, it is named wp_kses()), then appropriately rename the kses() function in the htmLawed code.
    +
    +  If the Kses file used by the application has been highly altered by the application developers, then one may need a different approach. E.g., with WordPress, it is best to copy the htmLawed code to wp_includes/kses.php, rename the newly added function kses() to wp_kses(), and delete the code for the original wp_kses() function.
    +
    +  If the Kses code has a non-empty hook function (e.g., wp_kses_hook() in case of WordPress), then the code for htmLawed's kses_hook() function should be appropriately edited. However, the requirement of the hook function should be re-evaluated considering that htmLawed has extra capabilities. With WordPress, the hook function is an essential one. The following code is suggested for the htmLawed kses_hook() in case of WordPress:
    +
    + +    function kses_hook($string, &$cf, &$spec){ +
    + +    // kses compatibility +
    + +    $allowed_html = $spec; +
    + +    $allowed_protocols = array(); +
    + +    foreach($cf['schemes'] as $v){ +
    + +     foreach($v as $k2=>$v2){ +
    + +      if(!in_array($k2, $allowed_protocols)){ +
    + +       $allowed_protocols[] = $k2; +
    + +      } +
    + +     } +
    + +    } +
    + +    return wp_kses_hook($string, $allowed_html, $allowed_protocols); +
    + +    // eof +
    + +    } +
    + +
    +

    +2.7  Tolerance for ill-written HTML +

    (to top)
    +
    +  htmLawed can work with ill-written HTML code in the input. However, HTML that is too ill-written may not be read as HTML, and be considered mere plain text instead. Following statements indicate the degree of looseness that htmLawed can work with, and can be provided in instructions to writers:
    +
    +  *  Tags must be flanked by < and > with no > inside -- any needed > should be put in as &gt;. It is possible for tag content (element name and attributes) to be spread over many lines instead of being on one. A space may be present between the tag content and >, like <div > and <img / >, but not after the <.
    +
    +  *  Element and attribute names need not be lower-cased.
    +
    +  *  Attribute string of elements may be liberally spaced with tabs, line-breaks, etc.
    +
    +  *  Attribute values may not be double-quoted, or may be single-quoted.
    +
    +  *  Left-padding of numeric entities (like, &#0160;, &x07ff;) with 0 is okay as long as the number of characters between between the & and the ; does not exceed 8. All entities must end with ; though.
    +
    +  *  Named character entities must be properly cased. E.g., &Lt; or &TILDE; will not be let through without modification.
    +
    +  *  HTML comments should not be inside element tags (okay between tags), and should begin with <!-- and end with -->. Characters like <, >, and & may be allowed inside depending on $config, but any --> inside should be put in as --&gt;. Any -- inside will be automatically converted to -, and a space will be added before the comment delimiter -->.
    +
    +  *  CDATA sections should not be inside element tags, and can be in element content only if plain text is allowed for that element. They should begin with <[CDATA[ and end with ]]>. Characters like <, >, and & may be allowed inside depending on $config, but any ]]> inside should be put in as ]]&gt;.
    +
    +  *  For attribute values, character entities &lt;, &gt; and &amp; should be used instead of characters < and >, and & (when & is not part of a character entity). This applies even for Javascript code in values of attributes like onclick.
    +
    +  *  Characters <, >, & and " that are part of actual Javascript, etc., code in script elements should be used as such and not be put in as entities like &gt;. Otherwise, though the HTML will be valid, the code may fail to work. Further, if such characters have to be used, then they should be put inside CDATA sections.
    +
    +  *  Simple instructions like "an opening tag cannot be present between two closing tags" and "nested elements should be closed in the reverse order of how they were opened" can help authors write balanced HTML. If tags are imbalanced, htmLawed will try to balance them, but in the process, depending on $config["keep_bad"], some code/text may be lost.
    +
    +  *  Input authors should be notified of admin-specified allowed elements, attributes, configuration values (like conversion of named entities to numeric ones), etc.
    +
    +  *  With $config["unique_ids"] not 0 and the id attribute being permitted, writers should carefully avoid using duplicate or invalid id values as even though htmLawed will correct/remove the values, the final output may not be the one desired. E.g., when <a id="home"></a><input id="home" /><label for="home"></label> is processed into
    +<a id="home"></a><input id="prefix_home" /><label for="home"></label>.
    +
    +  *  Note that even if intended HTML is lost in a highly ill-written input, the processed output will be more secure and standard-compliant.
    +
    +  *  For URLs, unless $config["scheme"] is appropriately set, writers should avoid using escape characters or entities in schemes. E.g., htt&#112; (which many browsers will read as the harmless http) may be considered bad by htmLawed.
    +
    +  *  htmLawed will attempt to put plain text present directly inside blockquote, form, map and noscript elements (illegal as per the specs) inside auto-generated div elements.
    + +
    +

    +2.8  Limitations & work-arounds +

    (to top)
    +
    +  htmLawed's main objective is to make the input text more standard-compliant, secure for web-page readers, and free of HTML elements and attributes considered undesirable by the administrator. Some of its current limitations, regardless of this objective, are noted below along with work-arounds.
    +
    +  It should be borne in mind that no browser application is 100% standard-compliant, and that some of the standard specs (like asking for normalization of white-spacing within textarea elements) are clearly wrong. Regarding security, note that unsafe HTML code is not necessarily legally invalid.
    +
    +  *  htmLawed is meant for input that goes into the body of HTML documents. HTML's head-level elements are not supported, nor are the frameset elements frameset, frame and noframes.
    +
    +  *  It cannot transform the non-standard embed elements to the standard-compliant object elements. Yet, it can allow embed elements if permitted (embed is widely used and supported). Admins can certainly use the hook_tag parameter (section 3.4.9) to deploy a custom embed-to-object converter function.
    +
    +  *  The only non-standard element that may be permitted is embed; others like noembed and nobr cannot be permitted without modifying the htmLawed code.
    +
    +  *  It cannot handle input that has non-HTML code like SVG and MathML. One way around is to break the input into pieces and passing only those without non-HTML code to htmLawed. Another is described in section 3.9. A third way may be to some how take advantage of the $config["and_mark"] parameter (see section 3.2).
    +
    +  *  By default, htmLawed won't check many attribute values for standard compliance. E.g., width="20m" with the dimension in non-standard m is let through. Implementing universal and strict attribute value checks can make htmLawed slow and resource-intensive. Admins should look at the hook_tag parameter (section 3.4.9) or $spec to enforce finer checks.
    +
    +  *  The attributes, deprecated (which can be transformed too) or not, that it supports are largely those that are in the specs. Only a few of the proprietary attributes are supported.
    +
    +  *  Except for contained URLs and dynamic expressions (also optional), htmLawed does not check CSS style property values. Admins should look at using the hook_tag parameter (section 3.4.9) or $spec for finer checks. Perhaps the best option is to disallow style but allow class attributes with the right oneof or match values for class, and have the various class style properties in .css CSS stylesheet files.
    +
    +  *  htmLawed does not parse emoticons, decode BBcode, or wikify, auto-converting text to proper HTML. Similarly, it won't convert line-breaks to br elements. Such functions are beyond its purview. Admins should use other code to pre- or post-process the input for such purposes.
    +
    +  *  htmLawed cannot be used to have links force-opened in new windows (by auto-adding appropriate target and onclick attributes to a). Admins should look at Javascript-based DOM-modifying solutions for this. Admins may also be able to use a custom hook function to enforce such checks (hook_tag parameter; see section 3.4.9).
    +
    +  *  Nesting-based checks are not possible. E.g., one cannot disallow p elements specifically inside td while permitting it elsewhere. Admins may be able to use a custom hook function to enforce such checks (hook_tag parameter; see section 3.4.9).
    +
    +  *  Except for optionally converting absolute or relative URLs to the other type, htmLawed will not alter URLs (e.g., to change the value of query strings or to convert http to https. Having absolute URLs may be a standard-requirement, e.g., when HTML is embedded in email messages, whereas altering URLs for other purposes is beyond htmLawed's goals. Admins may be able to use a custom hook function to enforce such checks (hook_tag parameter; see section 3.4.9).
    +
    +  *  Pairs of opening and closing tags that do not enclose any content (like <em></em>) are not removed. This may be against the standard specs for certain elements (e.g., table). However, presence of such standard-incompliant code will not break the display or layout of content. Admins can also use simple regex-based code to filter out such code.
    +
    +  *  htmLawed does not check for certain element orderings described in the standard specs (e.g., in a table, tbody is allowed before tfoot). Admins may be able to use a custom hook function to enforce such checks (hook_tag parameter; see section 3.4.9).
    +
    +  *  htmLawed does not check the number of nested elements. E.g., it will allow two caption elements in a table element, illegal as per the specs. Admins may be able to use a custom hook function to enforce such checks (hook_tag parameter; see section 3.4.9).
    +
    +  *  htmLawed might convert certain entities to actual characters and remove backslashes and CSS comment-markers (/*) in style attribute values in order to detect malicious HTML like crafted IE-specific dynamic expressions like &#101;xpression.... If this is too harsh, admins can allow CSS expressions through htmLawed core but then use a custom function through the hook_tag parameter (section 3.4.9) to more specifically identify CSS expressions in the style attribute values. Also, using $config["style_pass"], it is possible to have htmLawed pass style attribute values without even looking at them (section 3.4.8).
    +
    +  *  htmLawed does not correct certain possible attribute-based security vulnerabilities (e.g., <a href="http://x%22+style=%22background-image:xss">x</a>). These arise when browsers mis-identify markup in escaped text, defeating the very purpose of escaping text (a bad browser will read the given example as <a href="http://x" style="background-image:xss">x</a>).
    +
    +  *  Because of poor Unicode support in PHP, htmLawed does not remove the high value HTML-invalid characters with multi-byte code-points. Such characters however are extremely unlikely to be in the input. (see section 3.1).
    +
    +  *  Like any script using PHP's PCRE regex functions, PHP setup-specific low PCRE limit values can cause htmLawed to at least partially fail with very long input texts.
    + +
    +

    +2.9  Examples +

    (to top)
    +
    1. A blog administrator wants to allow only a, em, strike, strong and u in comments, but needs strike and u transformed to span for better XHTML 1-strict compliance, and, he wants the a links to be to http or https resources:
    +
    + +    $processed = htmLawed($in, array('elements'=>'a, em, strike, strong, u', 'make_tag_strict'=>1, 'safe'=>1, 'schemes'=>'*:http, https'), 'a=href'); +
    +
    2. An author uses a custom-made web application to load content on his web-site. He is the only one using that application and the content he generates has all types of HTML, including scripts. The web application uses htmLawed primarily as a tool to correct errors that creep in while writing HTML and to take care of the occasional bad characters in copy-paste text introduced by Microsoft Office. The web application provides a preview before submitted input is added to the content. For the previewing process, htmLawed is set up as follows:
    +
    + +    $processed = htmLawed($in, array('css_expression'=>1, 'keep_bad'=>1, 'make_tag_strict'=>1, 'schemes'=>'*:*', 'valid_xhtml'=>1)); +
    +
    +  For the final submission process, keep_bad is set to 6. A value of 1 for the preview process allows the author to note and correct any HTML mistake without losing any of the typed text.
    +
    3. A data-miner is scraping information in a specific table of similar web-pages and is collating the data rows, and uses htmLawed to reduce unnecessary markup and white-spaces:
    +
    + +    $processed = htmLawed($in, array('elements'=>'tr, td', 'tidy'=>-1), 'tr, td ='); +
    + +
    +
    +

    +3  Details +

    (to top)
    +

    +3.1  Invalid/dangerous characters +

    (to top)
    +
    +  Valid characters (more correctly, their code-points) in HTML or XML are, hexadecimally, 9, a, d, 20 to d7ff, and e000 to 10ffff, except fffe and ffff (decimally, 9, 10, 13, 32 to 55295, and 57344 to 1114111, except 65534 and 65535). htmLawed removes the invalid characters 0 to 8, b, c, and e to 1f.
    +
    +  Because of PHP's poor native support for multi-byte characters, htmLawed cannot check for the remaining invalid code-points. However, for various reasons, it is very unlikely for any of those characters to be in the input.
    +
    +  Characters that are discouraged (see section 5.1) but not invalid are not removed by htmLawed.
    +
    +  It (function hl_tag()) also replaces the potentially dangerous (in some Mozilla [Firefox] and Opera browsers) soft-hyphen character (code-point, hexadecimally, ad, or decimally, 173) in attribute values with spaces. Where required, the characters <, >, &, and " are converted to entities.
    +
    +  With $config["clean_ms_char"] set as 1 or 2, many of the discouraged characters (decimal code-points 127 to 159 except 133) that many Microsoft applications incorrectly use (as per the Windows 1252 [Cp-1252] or a similar encoding system), and the character for decimal code-point 133, are converted to appropriate decimal numerical entities (or removed for a few cases)-- see appendix in section 5.4. This can help avoid some display issues arising from copying-pasting of content.
    +
    +  With $config["clean_ms_char"] set as 2, characters for the hexadecimal code-points 82, 91, and 92 (for special single-quotes), and 84, 93, and 94 (for special double-quotes) are converted to ordinary single and double quotes respectively and not to entities.
    +
    +  The character values are replaced with entities/characters and not character values referred to by the entities/characters to keep this task independent of the character-encoding of input text.
    +
    +  The $config["clean_ms_char"] parameter need not be used if authors do not copy-paste Microsoft-created text or if the input text is not believed to use the Windows 1252 or a similar encoding. Further, the input form and the web-pages displaying it or its content should have the character encoding appropriately marked-up.
    + +
    +

    +3.2  Character references/entities +

    (to top)
    +
    +  Valid character entities take the form &*; where * is #x followed by a hexadecimal number (hexadecimal numeric entity; like &#xA0; for non-breaking space), or alphanumeric like gt (external or named entity; like &nbsp; for non-breaking space), or # followed by a number (decimal numeric entity; like &#160; for non-breaking space). Character entities referring to the soft-hyphen character (the &shy; or \xad character; hexadecimal code-point ad [decimal 173]) in attribute values are always replaced with spaces; soft-hyphens in attribute values introduce vulnerabilities in some older versions of the Opera and Mozilla [Firefox] browsers.
    +
    +  htmLawed (function hl_ent()):
    +
    +  *  Neutralizes entities with multiple leading zeroes or missing semi-colons (potentially dangerous)
    +
    +  *  Lowercases the X (for XML-compliance) and A-F of hexadecimal numeric entities
    +
    +  *  Neutralizes entities referring to characters that are HTML-invalid (see section 3.1)
    +
    +  *  Neutralizes entities referring to characters that are HTML-discouraged (code-points, hexadecimally, 7f to 84, 86 to 9f, and fdd0 to fddf, or decimally, 127 to 132, 134 to 159, and 64991 to 64976). Entities referring to the remaining discouraged characters (see section 5.1 for a full list) are let through.
    +
    +  *  Neutralizes named entities that are not in the specs.
    +
    +  *  Optionally converts valid HTML-specific named entities except &gt;, &lt;, &quot;, and &amp; to decimal numeric ones (hexadecimal if $config["hexdec_entity"] is 2) for generic XML-compliance. For this, $config["named_entity"] should be 1.
    +
    +  *  Optionally converts hexadecimal numeric entities to the more widely supported decimal ones. For this, $config["hexdec_entity"] should be 0.
    +
    +  *  Optionally converts decimal numeric entities to the hexadecimal ones. For this, $config["hexdec_entity"] should be 2.
    +
    Neutralization refers to the entitification of & to &amp;.
    +
    Note: htmLawed does not convert entities to the actual characters represented by them; one can pass the htmLawed output through PHP's html_entity_decode function for that.
    +
    Note: If $config["and_mark"] is set, and set to a value other than 0, then the & characters in the original input are replaced with the control character for the hexadecimal code-point 6 (\x06; & characters introduced by htmLawed, e.g., after converting < to &lt;, are not affected). This allows one to distinguish, say, an &gt; introduced by htmLawed and an &gt; put in by the input writer, and can be helpful in further processing of the htmLawed-processed text (e.g., to identify the character sequence o(><)o to generate an emoticon image). When this feature is active, admins should ensure that the htmLawed output is not directly used in web pages or XML documents as the presence of the \x06 can break documents. Before use in such documents, and preferably before any storage, any remaining \x06 should be changed back to &, e.g., with:
    +
    + +    $final = str_replace("\x06", '&', $prelim); +
    +
    +  Also, see section 3.9.
    + +
    +

    +3.3  HTML elements +

    (to top)
    +
    +  htmLawed can be configured to allow only certain HTML elements (tags) in the input. Disallowed elements (just tag-content, and not element-content), based on $config["keep_bad"], are either neutralized (converted to plain text by entitification of < and >) or removed.
    +
    +  E.g., with only em permitted:
    +
    +  Input:
    +
    + +      <em>My</em> website is <a href="http://a.com>a.com</a>. +
    +
    +  Output, with $config["keep_bad"] = 0:
    +
    + +      <em>My</em> website is a.com. +
    +
    +  Output, with $config["keep_bad"] not 0:
    +
    + +      <em>My</em> website is &lt;a href=""&gt;a.com&lt;/a&gt;. +
    +
    +  See section 3.3.3 for differences between the various non-zero $config["keep_bad"] values.
    +
    +  htmLawed by default permits these 86 elements:
    +
    + +    a, abbr, acronym, address, applet, area, b, bdo, big, blockquote, br, button, caption, center, cite, code, col, colgroup, dd, del, dfn, dir, div, dl, dt, em, embed, fieldset, font, form, h1, h2, h3, h4, h5, h6, hr, i, iframe, img, input, ins, isindex, kbd, label, legend, li, map, menu, noscript, object, ol, optgroup, option, p, param, pre, q, rb, rbc, rp, rt, rtc, ruby, s, samp, script, select, small, span, strike, strong, sub, sup, table, tbody, td, textarea, tfoot, th, thead, tr, tt, u, ul, var +
    +
    +  Except for embed (included because of its wide-spread use) and the Ruby elements (rb, rbc, rp, rt, rtc, ruby; part of XHTML 1.1), these are all the elements in the HTML 4/XHTML 1 specs. Strict-specific specs. exclude center, dir, font, isindex, menu, s, strike, and u.
    +
    +  With $config["safe"] = 1, the default set will exclude applet, embed, iframe, object and script; see section 3.6.
    +
    +  When $config["elements"], which specifies allowed elements, is properly defined, and neither empty nor set to 0 or *, the default set is not used. To have elements added to or removed from the default set, a +/- notation is used. E.g., *-script-object implies that only script and object are disallowed, whereas *+embed means that noembed is also allowed. Elements can also be specified as comma separated names. E.g., a, b, i means only a, b and i are permitted. In this notation, *, + and - have no significance and can actually cause a mis-reading.
    +
    +  Some more examples of $config["elements"] values indicating permitted elements (note that empty spaces are liberally allowed for clarity):
    +
    +  *  a, blockquote, code, em, strong -- only a, blockquote, code, em, and strong
    +  *  *-script -- all excluding script
    +  *  * -center -dir -font -isindex -menu -s -strike -u -- only XHTML-Strict elements
    +  *  *+noembed-script -- all including noembed excluding script
    +
    +  Some mis-usages (and the resulting permitted elements) that can be avoided:
    +
    +  *  -* -- none; instead of htmLawed, one might just use, e.g., the htmlspecialchars() PHP function
    +  *  *, -script -- all except script; admin probably meant *-script
    +  *  -*, a, em, strong -- all; admin probably meant a, em, strong
    +  *  * -- all; admin need not have set elements
    +  *  *-form+form -- all; a + will always over-ride any -
    +  *  *, noembed -- only noembed; admin probably meant *+noembed
    +  *  a, +b, i -- only a and i; admin probably meant a, b, i
    +
    +  Basically, when using the +/- notation, commas (,) should not be used, and vice versa, and * should be used with the former but not the latter.
    +
    Note: Even if an element that is not in the default set is allowed through $config["elements"], like noembed in the last example, it will eventually be removed during tag balancing unless such balancing is turned off ($config["balance"] set to 0). Currently, the only way around this, which actually is simple, is to edit the various arrays in the function hl_bal() to accommodate the element and its nesting properties.
    +
    A possibly second way to specify allowed elements is to set $config["parent"] to an element name that supposedly will hold the input, and to set $config["balance"] to 1. During tag balancing (see section 3.3.3), all elements that cannot legally nest inside the parent element will be removed. The parent element is auto-reset to div if $config["parent"] is empty, body, or an element not in htmLawed's default set of 86 elements.
    +
    Tag transformation is possible for improving XHTML-Strict compliance -- most of the deprecated elements are removed or converted to valid XHTML-Strict ones; see section 3.3.2.
    + +

    +3.3.1  Handling of comments and CDATA sections +

    (to top)
    +
    CDATA sections have the format <![CDATA[...anything but not "]]>"...]]>, and HTML comments, <!--...anything but not "-->"... -->. Neither HTML comments nor CDATA sections can reside inside tags. HTML comments can exist anywhere else, but CDATA sections can exist only where plain text is allowed (e.g., immediately inside td element content but not immediately inside tr element content).
    +
    +  htmLawed (function hl_cmtcd()) handles HTML comments or CDATA sections depending on the values of $config["comment"] or $config["cdata"]. If 0, such markup is not looked for and the text is processed like plain text. If 1, it is removed completely. If 2, it is preserved but any <, > and & inside are changed to entities. If 3, they are left as such.
    +
    +  Note that for the last two cases, HTML comments and CDATA sections will always be removed from tag content (function hl_tag()).
    +
    +  Examples:
    +
    +  Input:
    + +    <!-- home link --><a href="home.htm"><![CDATA[x=&y]]>Home</a> +
    +  Output ($config["comment"] = 0, $config["cdata"] = 2):
    + +    &lt;-- home link --&gt;<a href="home.htm"><![CDATA[x=&amp;y]]>Home</a> +
    +  Output ($config["comment"] = 1, $config["cdata"] = 2):
    + +    <a href="home.htm"><![CDATA[x=&amp;y]]>Home</a> +
    +  Output ($config["comment"] = 2, $config["cdata"] = 2):
    + +    <!-- home link --><a href="home.htm"><![CDATA[x=&amp;y]]>Home</a> +
    +  Output ($config["comment"] = 2, $config["cdata"] = 1):
    + +    <!-- home link --><a href="home.htm">Home</a> +
    +  Output ($config["comment"] = 3, $config["cdata"] = 3):
    + +    <!-- home link --><a href="home.htm"><![CDATA[x=&y]]>Home</a> +
    +
    +  For standard-compliance, comments are given the form <!--comment -->, and any -- in the content is made -.
    +
    +  When $config["safe"] = 1, CDATA sections and comments are considered plain text unless $config["comment"] or $config["cdata"] is explicitly specified; see section 3.6.
    + +
    +

    +3.3.2  Tag-transformation for better XHTML-Strict +

    (to top)
    +
    +  If $config["make_tag_strict"] is set and not 0, following non-XHTML-Strict elements (and attributes), even if admin-permitted, are mutated as indicated (element content remains intact; function hl_tag2()):
    +
    +  *  applet - (based on $config["make_tag_strict"], unchanged (1) or removed (2))
    +  *  center - div style="text-align: center;"
    +  *  dir - ul
    +  *  embed - (based on $config["make_tag_strict"], unchanged (1) or removed (2))
    +  *  font (face, size, color) -    span style="font-family: ; font-size: ; color: ;" (size transformation reference)
    +  *  isindex - (based on $config["make_tag_strict"], unchanged (1) or removed (2))
    +  *  menu - ul
    +  *  s - span style="text-decoration: line-through;"
    +  *  strike - span style="text-decoration: line-through;"
    +  *  u - span style="text-decoration: underline;"
    +
    +  For an element with a pre-existing style attribute value, the extra style properties are appended.
    +
    +  Example input:
    +
    + +    <center> +
    + +     The PHP <s>software</s> script used for this <strike>web-page</strike> web-page is <font style="font-weight: bold " face=arial size='+3' color   =  "red  ">htmLawedTest.php</font>, from <u style= 'color:green'>PHP Labware</u>. +
    + +    </center> +
    +
    +  The output:
    +
    + +    <div style="text-align: center;"> +
    + +     The PHP <span style="text-decoration: line-through;">software</span> script used for this <span style="text-decoration: line-through;">web-page</span> web-page is <span style="font-weight: bold; font-family: arial; color: red; font-size: 200%;">htmLawedTest.php</span>, from <span style="color:green; text-decoration: underline;">PHP Labware</span>. +
    + +    </div> +
    + +
    +

    +3.3.3  Tag balancing and proper nesting +

    (to top)
    +
    +  If $config["balance"] is set to 1, htmLawed (function hl_bal()) checks and corrects the input to have properly balanced tags and legal element content (i.e., any element nesting should be valid, and plain text may be present only in the content of elements that allow them).
    +
    +  Depending on the value of $config["keep_bad"] (see section 2.2 and section 3.3), illegal content may be removed or neutralized to plain text by converting < and > to entities:
    +
    0 - remove; this option is available only to maintain Kses-compatibility and should not be used otherwise (see section 2.6)
    1 - neutralize tags and keep element content
    2 - remove tags but keep element content
    3 and 4 - like 1 and 2, but keep element content only if text (pcdata) is valid in parent element as per specs
    5 and 6 -  like 3 and 4, but line-breaks, tabs and spaces are left
    +
    +  Example input (disallowing the p element):
    +
    + +    <*> Pseudo-tags <*> +
    + +    <xml>Non-HTML tag xml</xml> +
    + +    <p> +
    + +    Disallowed tag p +
    + +    </p> +
    + +    <ul>Bad<li>OK</li></ul> +
    +
    +  The output with $config["keep_bad"] = 1:
    +
    + +    &lt;*&gt; Pseudo-tags &lt;*&gt; +
    + +    &lt;xml&gt;Non-HTML tag xml&lt;/xml&gt; +
    + +    &lt;p&gt; +
    + +    Disallowed tag p +
    + +    &lt;/p&gt; +
    + +    <ul>Bad<li>OK</li></ul> +
    +
    +  The output with $config["keep_bad"] = 3:
    +
    + +    &lt;*&gt; Pseudo-tags &lt;*&gt; +
    + +    &lt;xml&gt;Non-HTML tag xml&lt;/xml&gt; +
    + +    &lt;p&gt; +
    + +    Disallowed tag p +
    + +    &lt;/p&gt; +
    + +    <ul><li>OK</li></ul> +
    +
    +  The output with $config["keep_bad"] = 6:
    +
    + +    &lt;*&gt; Pseudo-tags &lt;*&gt; +
    + +    Non-HTML tag xml +
    +
    + +    Disallowed tag p +
    +
    + +    <ul><li>OK</li></ul> +
    +
    +  An option like 1 is useful, e.g., when a writer previews his submission, whereas one like 3 is useful before content is finalized and made available to all.
    +
    Note: In the example above, unlike <*>, <xml> gets considered as a tag (even though there is no HTML element named xml). In general, text matching the regular expression pattern <(/?)([a-zA-Z][a-zA-Z1-6]*)([^>]*?)\s?> is considered a tag (phrase enclosed by the angled brackets < and >, and starting [with an optional slash preceding] with an alphanumeric word that starts with an alphabet...).
    +
    +  Nesting/content rules for each of the 86 elements in htmLawed's default set (see section 3.3) are defined in function hl_bal(). This means that if a non-standard element besides embed is being permitted through $config["elements"], the element's tag content will end up getting removed if $config["balance"] is set to 1.
    +
    +  Plain text and/or certain elements nested inside blockquote, form, map and noscript need to be in block-level elements. This point is often missed during manual writing of HTML code. htmLawed attempts to address this during balancing. E.g., if the parent container is set as form, the input B:<input type="text" value="b" />C:<input type="text" value="c" /> is converted to <div>B:<input type="text" value="b" />C:<input type="text" value="c" /></div>.
    + +
    +

    +3.3.4  Elements requiring child elements +

    (to top)
    +
    +  As per specs, the following elements require legal child elements nested inside them:
    +
    + +    blockquote, dir, dl, form, map, menu, noscript, ol, optgroup, rbc, rtc, ruby, select, table, tbody, tfoot, thead, tr, ul +
    +
    +  In some cases, the specs stipulate the number and/or the ordering of the child elements. A table can have 0 or 1 caption, tbody, tfoot, and thead, but they must be in this order: caption, thead, tfoot, tbody.
    +
    +  htmLawed currently does not check for conformance to these rules. Note that any non-compliance in this regard will not introduce security vulnerabilities, crash browser applications, or affect the rendering of web-pages.
    + +
    +

    +3.3.5  Beautify or compact HTML +

    (to top)
    +
    +  By default, htmLawed will neither beautify HTML code by formatting it with indentations, etc., nor will it make it compact by removing un-needed white-space.(It does always properly white-space tag content.)
    +
    +  As per the HTML standards, spaces, tabs and line-breaks in web-pages (except those inside pre elements) are all considered equivalent, and referred to as white-spaces. Browser applications are supposed to consider contiguous white-spaces as just a single space, and to disregard white-spaces trailing opening tags or preceding closing tags. This white-space normalization allows the use of text/code beautifully formatted with indentations and line-spacings for readability. Such pretty HTML can, however, increase the size of web-pages, or make the extraction or scraping of plain text cumbersome.
    +
    +  With the $config parameter tidy, htmLawed can be used to beautify or compact the input text. Input with just plain text and no HTML markup is also subject to this. Besides pre, the script and textarea elements, CDATA sections, and HTML comments are not subjected to the tidying process.
    +
    +  To compact, use $config["tidy"] = -1; single instances or runs of white-spaces are replaced with a single space, and white-spaces trailing and leading open and closing tags, respectively, are removed.
    +
    +  To beautify, $config["tidy"] is set as 1, or for customized tidying, as a string like 2s2n. The s or t character specifies the use of spaces or tabs for indentation. The first and third characters, any of the digits 0-9, specify the number of spaces or tabs per indentation, and any parental lead spacing (extra indenting of the whole block of input text). The r and n characters are used to specify line-break characters: n for \n (Unix/Mac OS X line-breaks), rn or nr for \r\n (Windows/DOS line-breaks), or r for \r.
    +
    +  The $config["tidy"] value of 1 is equivalent to 2s0n. Other $config["tidy"] values are read loosely: a value of 4 is equivalent to 4s0n; t2, to 1t2n; s, to 2s0n; 2TR, to 2t0r; T1, to 1t1n; nr3, to 3s0nr, and so on. Except in the indentations and line-spacings, runs of white-spaces are replaced with a single space during beautification.
    +
    +  Input formatting using $config["tidy"] is not recommended when input text has mixed markup (like HTML + PHP).
    + +
    +
    +

    +3.4  Attributes +

    (to top)
    +
    +  htmLawed will only permit attributes described in the HTML specs (including deprecated ones). It also permits some attributes for use with the embed element (the non-standard embed element is supported in htmLawed because of its widespread use), and the the xml:space attribute (valid only in XHTML 1.1). A list of such 111 attributes and the elements they are allowed in is in section 5.2.
    +
    +  When $config["deny_attribute"] is not set, or set to 0, or empty (""), all the 111 attributes are permitted. Otherwise, $config["deny_attribute"] can be set as a list of comma-separated names of the denied attributes. on* can be used to refer to the group of potentially dangerous, script-accepting attributes: onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreset, onselect and onsubmit.
    +
    +  Note that attributes specified in $config["deny_attribute"] are denied globally, for all elements. To deny attributes for only specific elements, $spec (see section 2.3) can be used. $spec can also be used to element-specifically permit an attribute otherwise denied through $config["deny_attribute"].
    +
    +  With $config["safe"] = 1 (section 3.6), the on* attributes are automatically disallowed.
    +
    Note: To deny all but a few attributes globally, a simpler way to specify $config["deny_attribute"] would be to use the notation * -attribute1 -attribute2 .... Thus, a value of * -title -href implies that except href and title (where allowed as per standards) all other attributes are to be removed. With this notation, the value for the parameter safe (section 3.6) will have no effect on deny_attribute.
    +
    +  htmLawed (function hl_tag()) also:
    +
    +  *  Lower-cases attribute names
    +  *  Removes duplicate attributes (last one stays)
    +  *  Gives attributes the form name="value" and single-spaces them, removing unnecessary white-spacing
    +  *  Provides required attributes (see section 3.4.1)
    +  *  Double-quotes values and escapes any " inside them
    +  *  Replaces the possibly dangerous soft-hyphen characters (hexadecimal code-point ad) in the values with spaces
    +  *  Allows custom function to additionally filter/modify attribute values (see section 3.4.9)
    + +

    +3.4.1  Auto-addition of XHTML-required attributes +

    (to top)
    +
    +  If indicated attributes for the following elements are found missing, htmLawed (function hl_tag()) will add them (with values same as attribute names unless indicated otherwise below):
    +
    +  *  area - alt (area)
    +  *  area, img - src, alt (image)
    +  *  bdo - dir (ltr)
    +  *  form - action
    +  *  map - name
    +  *  optgroup - label
    +  *  param - name
    +  *  script - type (text/javascript)
    +  *  textarea - rows (10), cols (50)
    +
    +  Additionally, with $config["xml:lang"] set to 1 or 2, if the lang but not the xml:lang attribute is declared, then the latter is added too, with a value copied from that of lang. This is for better standard-compliance. With $config["xml:lang"] set to 2, the lang attribute is removed (XHTML 1.1 specs).
    +
    +  Note that the name attribute for map, invalid in XHTML 1.1, is also transformed if required -- see section 3.4.6.
    + +
    +

    +3.4.2  Duplicate/invalid id values +

    (to top)
    +
    +  If $config["unique_ids"] is 1, htmLawed (function hl_tag()) removes id attributes with values that are not XHTML-compliant (must begin with a letter and can contain letters, digits, :, ., - and _) or duplicate. If $config["unique_ids"] is a word, any duplicate but otherwise valid value will be appropriately prefixed with the word to ensure its uniqueness. The word should begin with a letter and should contain only letters, numbers, :, ., _ and -.
    +
    +  Even if multiple inputs need to be filtered (through multiple calls to htmLawed), htmLawed ensures uniqueness of id values as it uses a global variable ($GLOBALS["hl_Ids"] array). Further, an admin can restrict the use of certain id values by presetting this variable before htmLawed is called into use. E.g.:
    +
    + +    $GLOBALS['hl_Ids'] = array('top'=>1, 'bottom'=>1, 'myform'=>1); // id values not allowed in input +
    + +    $processed = htmLawed($text); // filter input +
    + +
    +

    +3.4.3  URL schemes (protocols) and scripts in attribute values +

    (to top)
    +
    +  htmLawed edits attributes that take URLs as values if they are found to contain un-permitted schemes. E.g., if the afp scheme is not permitted, then <a href="afp://domain.org"> becomes <a href="denied:afp://domain.org">, and if Javascript is not permitted <a onclick="javascript:xss();"> becomes <a onclick="denied:javascript:xss();">.
    +
    +  By default htmLawed permits these schemes in URLs for the href attribute:
    +
    + +    aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet +
    +
    +  Also, only file, http and https are permitted in attributes whose names start with o (like onmouseover), and in these attributes that accept URLs:
    +
    + +    action, cite, classid, codebase, data, href, longdesc, model, pluginspage, pluginurl, src, style, usemap +
    +
    +  These default sets are used when $config["schemes"] is not set (see section 2.2). To over-ride the defaults, $config["schemes"] is defined as a string of semi-colon-separated sub-strings of type attribute: comma-separated schemes. E.g., href: mailto, http, https; onclick: javascript; src: http, https. For unspecified attributes, file, http and https are permitted. This can be changed by passing schemes for * in $config["schemes"]. E.g., href: mailto, http, https; *: https, https.
    +
    * can be put in the list of schemes to permit all protocols. E.g., style: *; img: http, https results in protocols not being checked in style attribute values. However, in such cases, any relative-to-absolute URL conversion, or vice versa, (section 3.4.4) is not done.
    +
    +  Thus, to allow Javascript, one can set $config["schemes"] as href: mailto, http, https; *: http, https, javascript, or href: mailto, http, https, javascript; *: http, https, javascript, or *: *, and so on.
    +
    +  As a side-note, one may find style: * useful as URLs in style attributes can be specified in a variety of ways, and the patterns that htmLawed uses to identify URLs may mistakenly identify non-URL text.
    +
    Note: If URL-accepting attributes other than those listed above are being allowed, then the scheme will not be checked unless the attribute name contains the string src (e.g., dynsrc) or starts with o (e.g., onbeforecopy).
    +
    +  With $config["safe"] = 1, all URLs are disallowed in the style attribute values.
    + +
    +

    +3.4.4  Absolute & relative URLs in attribute values +

    (to top)
    +
    +  htmLawed can make absolute URLs in attributes like href relative ($config["abs_url"] is -1), and vice versa ($config["abs_url"] is 1). URLs in scripts are not considered for this, and so are URLs like #section_6 (fragment), ?name=Tim#show (starting with query string), and ;var=1?name=Tim#show (starting with parameters). Further, this requires that $config["base_url"] be set properly, with the :// and a trailing slash (/), with no query string, etc. E.g., file:///D:/page/, https://abc.com/x/y/, or http://localhost/demo/ are okay, but file:///D:/page/?help=1, abc.com/x/y/ and http://localhost/demo/index.htm are not.
    +
    +  For making absolute URLs relative, only those URLs that have the $config["base_url"] string at the beginning are converted. E.g., with $config["base_url"] = "https://abc.com/x/y/", https://abc.com/x/y/a.gif and https://abc.com/x/y/z/b.gif become a.gif and z/b.gif respectively, while https://abc.com/x/c.gif is not changed.
    +
    +  When making relative URLs absolute, only values for scheme, network location (host-name) and path values in the base URL are inherited. See section 5.5 for more about the URL specification as per RFC 1808.
    + +
    +

    +3.4.5  Lower-cased, standard attribute values +

    (to top)
    +
    +  Optionally, for standard-compliance, htmLawed (function hl_tag()) lower-cases standard attribute values to give, e.g., input type="password" instead of input type="Password", if $config["lc_std_val"] is 1. Attribute values matching those listed below for any of the elements (plus those for the type attribute of button or input) are lower-cased:
    +
    + +    all, baseline, bottom, button, center, char, checkbox, circle, col, colgroup, cols, data, default, file, get, groups, hidden, image, justify, left, ltr, middle, none, object, password, poly, post, preserve, radio, rect, ref, reset, right, row, rowgroup, rows, rtl, submit, text, top +
    +
    + +    a, area, bdo, button, col, form, img, input, object, option, optgroup, param, script, select, table, td, tfoot, th, thead, tr, xml:space +
    +
    +  The following empty (minimized) attributes are always assigned lower-cased values (same as the names):
    +
    + +    checked, compact, declare, defer, disabled, ismap, multiple, nohref, noresize, noshade, nowrap, readonly, selected +
    + +
    +

    +3.4.6  Transformation of deprecated attributes +

    (to top)
    +
    +  If $config["no_deprecated_attr"] is 0, then deprecated attributes (see appendix in section 5.2) are removed and, in most cases, their values are transformed to CSS style properties and added to the style attributes (function hl_tag()). Except for bordercolor for table, tr and td, the scores of proprietary attributes that were never part of any cross-browser standard are not supported.
    +
    Note: The attribute target for a is allowed even though it is not in XHTML 1.0 specs. This is because of the attribute's wide-spread use and browser-support, and because the attribute is valid in XHTML 1.1 onwards.
    +
    +  *  align - for img with value of left or right, becomes, e.g., float: left; for div and table with value center, becomes margin: auto; all others become, e.g., text-align: right
    +
    +  *  bgcolor - E.g., bgcolor="#ffffff" becomes background-color: #ffffff
    +  *  border - E.g., height= "10" becomes height: 10px
    +  *  bordercolor - E.g., bordercolor=#999999 becomes border-color: #999999;
    +  *  compact - font-size: 85%
    +  *  clear - E.g., 'clear="all" becomes clear: both
    +
    +  *  height - E.g., height= "10" becomes height: 10px and height="*" becomes height: auto
    +
    +  *  hspace - E.g., hspace="10" becomes margin-left: 10px; margin-right: 10px
    +  *  language - language="VBScript" becomes type="text/vbscript"
    +  *  name - E.g., name="xx" becomes id="xx"
    +  *  noshade - border-style: none; border: 0; background-color: gray; color: gray
    +  *  nowrap - white-space: nowrap
    +  *  size - E.g., size="10" becomes height: 10px
    +  *  start - removed
    +  *  type - E.g., type="i" becomes list-style-type: lower-roman
    +  *  value - removed
    +  *  vspace - E.g., vspace="10" becomes margin-top: 10px; margin-bottom: 10px
    +  *  width - like height
    +
    +  Example input:
    +
    + +    <img src="j.gif" alt="image" name="dad's" /><img src="k.gif" alt="image" id="dad_off" name="dad" /> +
    + +    <br clear="left" /> +
    + +    <hr noshade size="1" /> +
    + +    <img name="img" src="i.gif" align="left" alt="image" hspace="10" vspace="10" width="10em" height="20" border="1" style="padding:5px;" /> +
    + +    <table width="50em" align="center" bgcolor="red"> +
    + +     <tr> +
    + +      <td width="20%"> +
    + +       <div align="center"> +
    + +        <h3 align="right">Section</h3> +
    + +        <p align="right">Para</p> +
    + +        <ol type="a" start="e"><li value="x">First item</li></ol> +
    + +       </div> +
    + +      </td> +
    + +      <td width="*"> +
    + +       <ol type="1"><li>First item</li></ol> +
    + +      </td> +
    + +     </tr> +
    + +    </table> +
    + +    <br clear="all" /> +
    +
    +  And the output with $config["no_deprecated_attr"] = 1:
    +
    + +    <img src="j.gif" alt="image" /><img src="k.gif" alt="image" id="dad_off" /> +
    + +    <br style="clear: left;" /> +
    + +    <hr style="border-style: none; border: 0; background-color: gray; color: gray; size: 1px;" /> +
    + +    <img src="i.gif" alt="image" width="10em" height="20" style="padding:5px; float: left; margin-left: 10px; margin-right: 10px; margin-top: 10px; margin-bottom: 10px; border: 1px;" id="img" /> +
    + +    <table width="50em" style="margin: auto; background-color: red;"> +
    + +     <tr> +
    + +      <td style="width: 20%;"> +
    + +       <div style="margin: auto;"> +
    + +        <h3 style="text-align: right;">Section</h3> +
    + +        <p style="text-align: right;">Para</p> +
    + +        <ol style="list-style-type: lower-latin;"><li>First item</li></ol> +
    + +       </div> +
    + +      </td> +
    + +      <td style="width: auto;"> +
    + +       <ol style="list-style-type: decimal;"><li>First item</li></ol> +
    + +      </td> +
    + +     </tr> +
    + +    </table> +
    + +    <br style="clear: both;" /> +
    +
    +  For lang, deprecated in XHTML 1.1, transformation is taken care of through $config["xml:lang"]; see section 3.4.1.
    +
    +  The attribute name is deprecated in form, iframe, and img, and is replaced with id if an id attribute doesn't exist and if the name value is appropriate for id. For such replacements for a and map, for which the name attribute is deprecated in XHTML 1.1, $config["no_deprecated_attr"] should be set to 2 (when set to 1, for these two elements, the name attribute is retained).
    + +
    +

    +3.4.7  Anti-spam & href +

    (to top)
    +
    +  htmLawed (function hl_tag()) can check the href attribute values (link addresses) as an anti-spam (email or link spam) measure.
    +
    +  If $config["anti_mail_spam"] is not 0, the @ of email addresses in href values like mailto:a@b.com is replaced with text specified by $config["anti_mail_spam"]. The text should be of a form that makes it clear to others that the address needs to be edited before a mail is sent; e.g., <remove_this_antispam>@ (makes the example address a<remove_this_antispam>@b.com).
    +
    +  For regular links, one can choose to have a rel attribute with nofollow in its value (which tells some search engines to not follow a link). This can discourage link spammers. Additionally, or as an alternative, one can choose to empty the href value altogether (disable the link).
    +
    +  For use of these options, $config["anti_link_spam"] should be set as an array with values regex1 and regex2, both or one of which can be empty (like array("", "regex2")) to indicate that that option is not to be used. Otherwise, regex1 or regex2 should be PHP- and PCRE-compatible regular expression patterns: href values will be matched against them and those matching the pattern will accordingly be treated.
    +
    +  Note that the regular expressions should have delimiters, and be well-formed and preferably fast. Absolute efficiency/accuracy is often not needed.
    +
    +  An example, to have a rel attribute with nofollow for all links, and to disable links that do not point to domains abc.com and xyz.org:
    +
    + +    $config["anti_link_spam"] = array('`.`', '`://\W*(?!(abc\.com|xyz\.org))`'); +
    + +
    +

    +3.4.8  Inline style properties +

    (to top)
    +
    +  htmLawed can check URL schemes and dynamic expressions (to guard against Javascript, etc., script-based insecurities) in inline CSS style property values in the style attributes. (CSS properties like background-image that accept URLs in their values are noted in section 5.3.) Dynamic CSS expressions that allow scripting in the IE browser, and can be a vulnerability, can be removed from property values by setting $config["css_expression"] to 1 (default setting).
    +
    Note: Because of the various ways of representing characters in attribute values (URL-escapement, entitification, etc.), htmLawed might alter the values of the style attribute values, and may even falsely identify dynamic CSS expressions and URL schemes in them. If this is an important issue, checking of URLs and dynamic expressions can be turned off ($config["schemes"] = "...style:*...", see section 3.4.3, and $config["css_expression"] = 0). Alternately, admins can use their own custom function for finer handling of style values through the hook_tag parameter (see section 3.4.9).
    +
    +  It is also possible to have htmLawed let through any style value by setting $config["style_pass"] to 1.
    +
    +  As such, it is better to set up a CSS file with class declarations, disallow the style attribute, set a $spec rule (see section 2.3) for class for the oneof or match parameter, and ask writers to make use of the class attribute.
    + +
    +

    +3.4.9  Hook function for tag content +

    (to top)
    +
    +  It is possible to utilize a custom hook function to alter the tag content htmLawed has finalized (i.e., after it has checked/corrected for required attributes, transformed attributes, lower-cased attribute names, etc.).
    +
    +  When $config parameter hook_tag is set to the name of a function, htmLawed (function hl_tag()) will pass on the element name, and the finalized attribute name-value pairs as array elements to the function. The function is expected to return the full opening tag string like <element_name attribute_1_name="attribute_1_value"...> (for empty elements like img and input, the element-closing slash / should also be included).
    +
    +  This is a powerful functionality that can be exploited for various objectives: consolidate-and-convert inline style attributes to class, convert embed elements to object, permit only one caption element in a table element, disallow embedding of certain types of media, inject HTML, use CSSTidy to sanitize style attribute values, etc.
    +
    +  As an example, the custom hook code below can be used to force a series of specifically ordered id attributes on all elements, and a specific param element inside all object elements:
    +
    + +    function my_tag_function($element, $attribute_array){ +
    + +      static $id = 0; +
    + +      // Remove any duplicate element +
    + +      if($element == 'param' && isset($attribute_array['allowscriptaccess'])){ +
    + +        return ''; +
    + +      } +
    +
    + +      $new_element = ''; +
    +
    + +      // Force a serialized ID number +
    + +      $attribute_array['id'] = 'my_'. $id; +
    + +      ++$id; +
    +
    + +      // Inject param for allowscriptaccess +
    + +      if($element == 'object'){ +
    + +        $new_element = '<param id='my_'. $id; allowscriptaccess="never" />'; +
    + +        ++$id; +
    + +      } +
    +
    + +      $string = ''; +
    + +      foreach($attribute_array as $k=>$v){ +
    + +        $string .= " {$k}=\"{$v}\""; +
    + +      } +
    + +      return "<{$element}{$string}". (isset($in_array($element, $empty_elements) ? ' /' : ''). '>'. $new_element; +
    + +    } +
    +
    +  The hook_tag parameter is different from the hook parameter (section 3.7).
    +
    +  Snippets of hook function code developed by others may be available on the htmLawed website.
    + +
    +
    +

    +3.5  Simple configuration directive for most valid XHTML +

    (to top)
    +
    +  If $config["valid_xhtml"] is set to 1, some relevant $config parameters (indicated by ~ in section 2.2) are auto-adjusted. This allows one to pass the $config argument with a simpler value. If a value for a parameter auto-set through valid_xhtml is still manually provided, then that value will over-ride the auto-set value.
    + +
    +

    +3.6  Simple configuration directive for most safe HTML +

    (to top)
    +
    Safe HTML refers to HTML that is restricted to reduce the vulnerability for scripting attacks (such as XSS) based on HTML code which otherwise may still be legal and compliant with the HTML standard specs. When elements such as script and object, and attributes such as onmouseover and style are allowed in the input text, an input writer can introduce malevolent HTML code. Note that what is considered safe depends on the nature of the web application and the trust-level accorded to its users.
    +
    +  htmLawed allows an admin to use $config["safe"] to auto-adjust multiple $config parameters (such as elements which declares the allowed element-set), which otherwise would have to be manually set. The relevant parameters are indicated by " in section 2.2). Thus, one can pass the $config argument with a simpler value.
    +
    +  With the value of 1, htmLawed considers CDATA sections and HTML comments as plain text, and prohibits the applet, embed, iframe, object and script elements, and the on* attributes like onclick. ( There are $config parameters like css_expression that are not affected by the value set for safe but whose default values still contribute towards a more safe output.) Further, URLs with schemes (see section 3.4.3) are neutralized so that, e.g., style="moz-binding:url(http://danger)" becomes style="moz-binding:url(denied:http://danger)" while style="moz-binding:url(ok)" remains intact.
    +
    +  Admins, however, may still want to completely deny the style attribute, e.g., with code like
    +
    + +    $processed = htmLawed($text, array('safe'=>1, 'deny_attribute'=>'style')); +
    +
    +  If a value for a parameter auto-set through safe is still manually provided, then that value can over-ride the auto-set value. E.g., with $config["safe"] = 1 and $config["elements"] = "*+script", script, but not applet, is allowed.
    +
    +  A page illustrating the efficacy of htmLawed's anti-XSS abilities with safe set to 1 against XSS vectors listed by RSnake may be available here.
    + +
    +

    +3.7  Using a hook function +

    (to top)
    +
    +  If $config["hook"] is not set to 0, then htmLawed will allow preliminarily processed input to be altered by a hook function named by $config["hook"] before starting the main work (but after handling of characters, entities, HTML comments and CDATA sections -- see code for function htmLawed()).
    +
    +  The hook function also allows one to alter the finalized values of $config and $spec.
    +
    +  Note that the hook parameter is different from the hook_tag parameter (section 3.4.9).
    +
    +  Snippets of hook function code developed by others may be available on the htmLawed website.
    + +
    +

    +3.8  Obtaining finalized parameter values +

    (to top)
    +
    +  htmLawed can assign the finalized $config and $spec values to a variable named by $config["show_setting"]. The variable, made global by htmLawed, is set as an array with three keys: config, with the $config value, spec, with the $spec value, and time, with a value that is the Unix time (the output of PHP's microtime() function) when the value was assigned. Admins should use a PHP-compliant variable name (e.g., one that does not begin with a numerical digit) that does not conflict with variable names in their non-htmLawed code.
    +
    +  The values, which are also post-hook function (if any), can be used to auto-generate information (on, e.g., the elements that are permitted) for input writers.
    + +
    +

    +3.9  Retaining non-HTML tags in input with mixed markup +

    (to top)
    +
    +  htmLawed does not remove certain characters that though invalid are nevertheless discouraged in HTML documents as per the specs (see section 5.1). This can be utilized to deal with input that contains mixed markup. Input that may have HTML markup as well as some other markup that is based on the <, > and & characters is considered to have mixed markup. The non-HTML markup can be rather proprietary (like markup for emoticons/smileys), or standard (like MathML or SVG). Or it can be programming code meant for execution/evaluation (such as embedded PHP code).
    +
    +  To deal with such mixed markup, the input text can be pre-processed to hide the non-HTML markup by specifically replacing the <, > and & characters with some of the HTML-discouraged characters (see section 3.1.2). Post-htmLawed processing, the replacements are reverted.
    +
    +  An example (mixed HTML and PHP code in input text):
    +
    + +    $text = preg_replace('`<\?php(.+?)\?>`sm', "\x83?php\\1?\x84", $text); +
    + +    $processed = htmLawed($text); +
    + +    $processed = preg_replace('`\x83\?php(.+?)\?\x84`sm', '<?php$1?>', $processed); +
    +
    +  This code will not work if $config["clean_ms_char"] is set to 1 (section 3.1), in which case one should instead deploy a hook function (section 3.7). (htmLawed internally uses certain control characters, code-points 1 to 7, and use of these characters as markers in the logic of hook functions may cause issues.)
    +
    +  Admins may also be able to use $config["and_mark"] to deal with such mixed markup; see section 3.2.
    + +
    +
    +

    +4  Other +

    (to top)
    +

    +4.1  Support +

    (to top)
    +
    +  A careful re-reading of this documentation will very likely answer your questions.
    +
    +  Software updates and forum-based community-support may be found at http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed. For general PHP issues (not htmLawed-specific), support may be found through internet searches and at http://php.net.
    + +
    +

    +4.2  Known issues +

    (to top)
    +
    +  See section 2.8.
    +
    +  Readers are advised to cross-check information given in this document.
    + +
    +

    +4.3  Change-log +

    (to top)
    +
    +  (The release date for the downloadable package of files containing documentation, demo script, test-cases, etc., besides the htmLawed.php file may be updated independently if the secondary files are revised.)
    +
    Version number - Release date. Notes
    +
    +  1.1.8.1 - 16 July 2009. Minor code-change to fix a PHP error notice
    +
    +  1.1.8 - 23 April 2009. Parameter deny_attribute now accepts the wild-card *, making it simpler to specify its value when all but a few attributes are being denied; fixed a bug in interpreting $spec
    +
    +  1.1.7 - 11-12 March 2009. Attributes globally denied through deny_attribute can be allowed element-specifically through $spec; $config["style_pass"] allowing letting through any style value introduced; altered logic to catch certain types of dynamic crafted CSS expressions
    +
    +  1.1.3-6 - 28-31 January - 4 February 2009. Altered logic to catch certain types of dynamic crafted CSS expressions
    +
    +  1.1.2 - 22 January 2009. Fixed bug in parsing of font attributes during tag transformation
    +
    +  1.1.1 - 27 September 2008. Better nesting correction when omitable closing tags are absent
    +
    +  1.1 - 29 June 2008. $config["hook_tag"] and $config["format"] introduced for custom tag/attribute check/modification/injection and output compaction/beautification; fixed a regex-in-$spec parsing bug
    +
    +  1.0.9 - 11 June 2008. Fixed bug in invalid HTML code-point entity check
    +
    +  1.0.8 - 15 May 2008. bordercolor attribute for table, td and tr
    +
    +  1.0.7 - 1 May 2008. Support for wmode attribute for embed; $config["show_setting"] introduced; improved $config["elements"] evaluation
    +
    +  1.0.6 - 20 April 2008. $config["and_mark"] introduced
    +
    +  1.0.5 - 12 March 2008. style URL schemes essentially disallowed when $config safe is on; improved regex for CSS expression search
    +
    +  1.0.4 - 10 March 2008. Improved corrections for blockquote, form, map and noscript
    +
    +  1.0.3 - 3 March 2008. Character entities for soft-hyphens are now replaced with spaces (instead of being removed); a bug allowing td directly inside table fixed; safe $config parameter added
    +
    +  1.0.2 - 13 February 2008. Improved implementation of $config["keep_bad"]
    +
    +  1.0.1 - 7 November 2007. Improved regex for identifying URLs, protocols and dynamic expressions (hl_tag() and hl_prot()); no error display with hl_regex()
    +
    +  1.0 - 2 November 2007. First release
    + +
    +

    +4.4  Testing +

    (to top)
    +
    +  To test htmLawed using a form interface, a demo web-page is provided with the htmLawed distribution (htmLawed.php and htmLawedTest.php should be in the same directory on the web-server). A file with test-cases is also provided.
    + +
    +

    +4.5  Upgrade, & old versions +

    (to top)
    +
    +  Upgrading is as simple as replacing the previous version of htmLawed.php (assuming it was not modified for customized features). As htmLawed output is almost always used in static documents, upgrading should not affect old, finalized content.
    +
    +  Old versions of htmLawed may be available online. E.g., for version 1.0, check http://www.bioinformatics.org/phplabware/downloads/htmLawed1.zip, for 1.1.1, htmLawed111.zip, and for 1.1.10, htmLawed1110.zip.
    + +
    +

    +4.6  Comparison with HTMLPurifier +

    (to top)
    +
    +  The HTMLPurifier PHP library by Edward Yang is a very good HTML filtering script that uses object oriented PHP code. Compared to htmLawed, it:
    +
    +  *  does not support PHP versions older than 5.0 (HTMLPurifier dropped PHP 4 support after version 2)
    +
    +  *  is 15-20 times bigger (scores of files totalling more than 750 kb)
    +
    +  *  consumes 10-15 times more RAM memory (just including the HTMLPurifier files without calling the filter requires a few MBs of memory)
    +
    +  *  is expectedly slower
    +
    +  *  does not allow admins to fully allow all valid HTML (because of incomplete HTML support, it always considers elements like script illegal)
    +
    +  *  lacks many of the extra features of htmLawed (like entity conversions and code compaction/beautification)
    +
    +  *  has poor documentation
    +
    +  However, HTMLPurifier has finer checks for character encodings and attribute values, and can log warnings and errors. Visit the HTMLPurifier website for updated information.
    + +
    +

    +4.7  Use through application plug-ins/modules +

    (to top)
    +
    +  Plug-ins/modules to implement htmLawed in applications such as Drupal and DokuWiki may have been developed. Please check the application websites and the forum on the htmLawed site.
    + +
    +

    +4.8  Use in non-PHP applications +

    (to top)
    +
    +  Non-PHP applications written in Python, Ruby, etc., may be able to use htmLawed through system calls to the PHP engine. Such code may have been documented on the internet. Also check the forum on the htmLawed site.
    + +
    +

    +4.9  Donate +

    (to top)
    +
    +  A donation in any currency and amount to appreciate or support this software can be sent by PayPal to this email address: drpatnaik at yahoo dot com.
    + +
    +

    +4.10  Acknowledgements +

    (to top)
    +
    +  Bryan Blakey, Ulf Harnhammer, Gareth Heyes, Lukasz Pilorz, Shelley Powers, Edward Yang, and many anonymous users.
    +
    +  Thank you!
    + +
    +
    +

    +5  Appendices +

    (to top)
    +

    +5.1  Characters discouraged in XHTML +

    (to top)
    +
    +  Characters represented by the following hexadecimal code-points are not invalid, even though some validators may issue messages stating otherwise.
    +
    7f to 84, 86 to 9f, fdd0 to fddf, 1fffe, 1ffff, 2fffe, 2ffff, 3fffe, 3ffff, 4fffe, 4ffff, 5fffe, 5ffff, 6fffe, 6ffff, 7fffe, 7ffff, 8fffe, 8ffff, 9fffe, 9ffff, afffe, affff, bfffe, bffff, cfffe, cffff, dfffe, dffff, efffe, effff, ffffe, fffff, 10fffe and 10ffff
    + +
    +

    +5.2  Valid attribute-element combinations +

    (to top)
    +
    +  Valid attribute-element combinations as per W3C specs.
    +
    +  *  includes deprecated attributes (marked ^), attributes for the non-standard embed element (marked *), and the proprietary bordercolor (marked ~)
    +  *  only non-frameset, HTML body elements
    +  *  name for a and map, and lang are invalid in XHTML 1.1
    +  *  target is valid for a in XHTML 1.1 and higher
    +  *  xml:space is only for XHTML 1.1
    +
    +  abbr - td, th
    +  accept - form, input
    +  accept-charset - form
    +  accesskey - a, area, button, input, label, legend, textarea
    +  action - form
    +  align - caption^, embed, applet, iframe, img^, input^, object^, legend^, table^, hr^, div^, h1^, h2^, h3^, h4^, h5^, h6^, p^, col, colgroup, tbody, td, tfoot, th, thead, tr
    +  alt - applet, area, img, input
    +  archive - applet, object
    +  axis - td, th
    +  bgcolor - embed, table^, tr^, td^, th^
    +  border - table, img^, object^
    +  bordercolor~ - table, td, tr
    +  cellpadding - table
    +  cellspacing - table
    +  char - col, colgroup, tbody, td, tfoot, th, thead, tr
    +  charoff - col, colgroup, tbody, td, tfoot, th, thead, tr
    +  charset - a, script
    +  checked - input
    +  cite - blockquote, q, del, ins
    +  classid - object
    +  clear - br^
    +  code - applet
    +  codebase - object, applet
    +  codetype - object
    +  color - font
    +  cols - textarea
    +  colspan - td, th
    +  compact - dir, dl^, menu, ol^, ul^
    +  coords - area, a
    +  data - object
    +  datetime - del, ins
    +  declare - object
    +  defer - script
    +  dir - bdo
    +  disabled - button, input, optgroup, option, select, textarea
    +  enctype - form
    +  face - font
    +  for - label
    +  frame - table
    +  frameborder - iframe
    +  headers - td, th
    +  height - embed, iframe, td^, th^, img, object, applet
    +  href - a, area
    +  hreflang - a
    +  hspace - applet, img^, object^
    +  ismap - img, input
    +  label - option, optgroup
    +  language - script^
    +  longdesc - img, iframe
    +  marginheight - iframe
    +  marginwidth - iframe
    +  maxlength - input
    +  method - form
    +  model* - embed
    +  multiple - select
    +  name - button, embed, textarea, applet^, select, form^, iframe^, img^, a^, input, object, map^, param
    +  nohref - area
    +  noshade - hr^
    +  nowrap - td^, th^
    +  object - applet
    +  onblur - a, area, button, input, label, select, textarea
    +  onchange - input, select, textarea
    +  onfocus - a, area, button, input, label, select, textarea
    +  onreset - form
    +  onselect - input, textarea
    +  onsubmit - form
    +  pluginspage* - embed
    +  pluginurl* - embed
    +  prompt - isindex
    +  readonly - textarea, input
    +  rel - a
    +  rev - a
    +  rows - textarea
    +  rowspan - td, th
    +  rules - table
    +  scope - td, th
    +  scrolling - iframe
    +  selected - option
    +  shape - area, a
    +  size - hr^, font, input, select
    +  span - col, colgroup
    +  src - embed, script, input, iframe, img
    +  standby - object
    +  start - ol^
    +  summary - table
    +  tabindex - a, area, button, input, object, select, textarea
    +  target - a^, area, form
    +  type - a, embed, object, param, script, input, li^, ol^, ul^, button
    +  usemap - img, input, object
    +  valign - col, colgroup, tbody, td, tfoot, th, thead, tr
    +  value - input, option, param, button, li^
    +  valuetype - param
    +  vspace - applet, img^, object^
    +  width - embed, hr^, iframe, img, object, table, td^, th^, applet, col, colgroup, pre^
    +  wmode - embed
    +  xml:space - pre, script, style
    +
    +  These are allowed in all but the shown elements:
    +
    +  class - param, script
    +  dir - applet, bdo, br, iframe, param, script
    +  id - script
    +  lang - applet, br, iframe, param, script
    +  onclick - applet, bdo, br, font, iframe, isindex, param, script
    +  ondblclick - applet, bdo, br, font, iframe, isindex, param, script
    +  onkeydown - applet, bdo, br, font, iframe, isindex, param, script
    +  onkeypress - applet, bdo, br, font, iframe, isindex, param, script
    +  onkeyup - applet, bdo, br, font, iframe, isindex, param, script
    +  onmousedown - applet, bdo, br, font, iframe, isindex, param, script
    +  onmousemove - applet, bdo, br, font, iframe, isindex, param, script
    +  onmouseout - applet, bdo, br, font, iframe, isindex, param, script
    +  onmouseover - applet, bdo, br, font, iframe, isindex, param, script
    +  onmouseup - applet, bdo, br, font, iframe, isindex, param, script
    +  style - param, script
    +  title - param, script
    +  xml:lang - applet, br, iframe, param, script
    + +
    +

    +5.3  CSS 2.1 properties accepting URLs +

    (to top)
    +
    +  background
    +  background-image
    +  content
    +  cue-after
    +  cue-before
    +  cursor
    +  list-style
    +  list-style-image
    +  play-during
    + +
    +

    +5.4  Microsoft Windows 1252 character replacements +

    (to top)
    +
    +  Key: d double, l left, q quote, r right, s. single
    +
    +  Code-point (decimal) - hexadecimal value - replacement entity - represented character
    +
    +  127 - 7f - (removed) - (not used)
    +  128 - 80 - &#8364; - euro
    +  129 - 81 - (removed) - (not used)
    +  130 - 82 - &#8218; - baseline s. q
    +  131 - 83 - &#402; - florin
    +  132 - 84 - &#8222; - baseline d q
    +  133 - 85 - &#8230; - ellipsis
    +  134 - 86 - &#8224; - dagger
    +  135 - 87 - &#8225; - d dagger
    +  136 - 88 - &#710; - circumflex accent
    +  137 - 89 - &#8240; - permile
    +  138 - 8a - &#352; - S Hacek
    +  139 - 8b - &#8249; - l s. guillemet
    +  140 - 8c - &#338; - OE ligature
    +  141 - 8d - (removed) - (not used)
    +  142 - 8e - &#381; - Z dieresis
    +  143 - 8f - (removed) - (not used)
    +  144 - 90 - (removed) - (not used)
    +  145 - 91 - &#8216; - l s. q
    +  146 - 92 - &#8217; - r s. q
    +  147 - 93 - &#8220; - l d q
    +  148 - 94 - &#8221; - r d q
    +  149 - 95 - &#8226; - bullet
    +  150 - 96 - &#8211; - en dash
    +  151 - 97 - &#8212; - em dash
    +  152 - 98 - &#732; - tilde accent
    +  153 - 99 - &#8482; - trademark
    +  154 - 9a - &#353; - s Hacek
    +  155 - 9b - &#8250; - r s. guillemet
    +  156 - 9c - &#339; - oe ligature
    +  157 - 9d - (removed) - (not used)
    +  158 - 9e - &#382; - z dieresis
    +  159 - 9f - &#376; - Y dieresis
    + +
    +

    +5.5  URL format +

    (to top)
    +
    +  An absolute URL has a protocol or scheme, a network location or hostname, and, optional path, parameters, query and fragment segments. Thus, an absolute URL has this generic structure:
    +
    + +    (scheme) : (//network location) /(path) ;(parameters) ?(query) #(fragment) +
    +
    +  The schemes can only contain letters, digits, +, . and -. Hostname is the portion after the // and up to the first / (if any; else, up to the end) when : is followed by a // (e.g., abc.com in ftp://abc.com/def); otherwise, it consists of everything after the : (e.g., def@abc.com in mailto:def@abc.com').
    +
    Relative URLs do not have explicit schemes and network locations; such values are inherited from a base URL.
    + +
    +

    +5.6  Brief on htmLawed code +

    (to top)
    +
    +  Much of the code's logic and reasoning can be understood from the documentation above.
    +
    +  The output of htmLawed is a text string containing the processed input. There is no custom error tracking.
    +
    Function arguments for htmLawed are:
    +
    +  *  $in - 1st argument; a text string; the input text to be processed. Any extraneous slashes added by PHP when magic quotes are enabled should be removed beforehand using PHP's stripslashes() function.
    +
    +  *  $config - 2nd argument; an associative array; optional (named $C in htmLawed code). The array has keys with names like balance and keep_bad, and the values, which can be boolean, string, or array, depending on the key, are read to accordingly set the configurable parameters (indicated by the keys). All configurable parameters receive some default value if the value to be used is not specified by the user through $config. Finalized $config is thus a filtered and possibly larger array.
    +
    +  *  $spec - 3rd argument; a text string; optional. The string has rules, written in an htmLawed-designated format, specifying element-specific attribute and attribute value restrictions. Function hl_spec() is used to convert the string to an associative-array for internal use. Finalized $spec is thus an array.
    +
    Finalized $config and $spec are made global variables while htmLawed is at work. Values of any pre-existing global variables with same names are noted, and their values are restored after htmLawed finishes processing the input (to capture the finalized values, the show_settings parameter of $config should be used). Depending on $config, another global variable hl_Ids, to track id attribute values for uniqueness, may be set. Unlike the other two variables, this one is not reset (or unset) post-processing.
    +
    +  Except for the main function htmLawed() and the functions kses() and kses_hook(), htmLawed's functions are name-spaced using the hl_ prefix. The functions and their roles are:
    +
    +  *  hl_attrval - checking attribute values against $spec
    +  *  hl_bal - tag balancing
    +  *  hl_cmtcd - handling CDATA sections and HTML comments
    +  *  hl_ent - entity handling
    +  *  hl_prot - checking a URL scheme/protocol
    +  *  hl_regex - checking syntax of a regular expression
    +  *  hl_spec - converting user-supplied $spec value to one used by htmLawed internally
    +  *  hl_tag - handling tags
    +  *  hl_tag2 - transforming tags
    +  *  hl_tidy - compact/beautify HTML
    +  *  hl_version - reporting htmLawed version
    +  *  htmLawed - main function
    +  *  kses - main function of kses
    +  *  kses_hook - hook function of kses
    +
    +  The last two are for compatibility with pre-existing code using the kses script. htmLawed's kses() basically passes on the filtering task to htmLawed() function after deciphering $config and $spec from the argument values supplied to it. kses_hook() is an empty function and is meant for being filled with custom code if the kses script users were using one.
    +
    htmLawed() finalizes $spec (with the help of hl_spec()) and $config, and globalizes them. Finalization of $config involves setting default values if an inappropriate or invalid one is supplied. This includes calling hl_regex() to check well-formedness of regular expression patterns if such expressions are user-supplied through $config. htmLawed() then removes invalid characters like nulls and x01 and appropriately handles entities using hl_ent(). HTML comments and CDATA sections are identified and treated as per $config with the help of hl_cmtcd(). When retained, the < and > characters identifying them, and the <, > and & characters inside them, are replaced with control characters (code-points 1 to 5) till any tag balancing is completed.
    +
    +  After this initial processing htmLawed() identifies tags using regex and processes them with the help of hl_tag() --  a large function that analyzes tag content, filtering it as per HTML standards, $config and $spec. Among other things, hl_tag() transforms deprecated elements using hl_tag2(), removes attributes from closing tags, checks attribute values as per $spec rules using hl_attrval(), and checks URL protocols using hl_prot(). htmLawed() performs tag balancing and nesting checks with a call to hl_bal(), and optionally compacts/beautifies the output with proper white-spacing with a call to hl_tidy(). The latter temporarily replaces white-space, and <, > and & characters inside pre, script and textarea elements, and HTML comments and CDATA sections with control characters (code-points 1 to 5, and 7).
    +
    +  htmLawed permits the use of custom code or hook functions at two stages. The first, called inside htmLawed(), allows the input text as well as the finalized $config and $spec values to be altered right after the initial processing (see section 3.7). The second is called by hl_tag() once the tag content is finalized (see section 3.4.9).
    +
    +  Being dictated by the external and stable HTML standard, htmLawed's objective is very clear-cut and less concerned with tweakability. The code is only minimally annotated with comments -- it is not meant to instruct; PHP developers familiar with the HTML specs will see the logic, and others can always refer to the htmLawed documentation. The compact structuring of the statements is meant to aid in quickly grasping the logic, at least when viewed with code syntax highlighted. +
    +
    +
    +


    HTM version of htmLawed_README.txt generated on 23 Apr, 2009 using rTxt2htm from PHP Labware +
    +
    + + \ No newline at end of file diff --git a/extlib/htmLawed/htmLawed_README.txt b/extlib/htmLawed/htmLawed_README.txt new file mode 100644 index 000000000..3ce4b9ac1 --- /dev/null +++ b/extlib/htmLawed/htmLawed_README.txt @@ -0,0 +1,1600 @@ +/* +htmLawed_README.txt, 16 July 2009 +htmLawed 1.1.8.1, 16 July 2009 +Copyright Santosh Patnaik +GPL v3 license +A PHP Labware internal utility - http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed +*/ + + +== Content ========================================================== + + +1 About htmLawed + 1.1 Example uses + 1.2 Features + 1.3 History + 1.4 License & copyright + 1.5 Terms used here +2 Usage + 2.1 Simple + 2.2 Configuring htmLawed using the '$config' parameter + 2.3 Extra HTML specifications using the '$spec' parameter + 2.4 Performance time & memory usage + 2.5 Some security risks to keep in mind + 2.6 Use without modifying old 'kses()' code + 2.7 Tolerance for ill-written HTML + 2.8 Limitations & work-arounds + 2.9 Examples +3 Details + 3.1 Invalid/dangerous characters + 3.2 Character references/entities + 3.3 HTML elements + 3.3.1 HTML comments and 'CDATA' sections + 3.3.2 Tag-transformation for better XHTML-Strict + 3.3.3 Tag balancing and proper nesting + 3.3.4 Elements requiring child elements + 3.3.5 Beautify or compact HTML + 3.4 Attributes + 3.4.1 Auto-addition of XHTML-required attributes + 3.4.2 Duplicate/invalid 'id' values + 3.4.3 URL schemes (protocols) and scripts in attribute values + 3.4.4 Absolute & relative URLs + 3.4.5 Lower-cased, standard attribute values + 3.4.6 Transformation of deprecated attributes + 3.4.7 Anti-spam & 'href' + 3.4.8 Inline style properties + 3.4.9 Hook function for tag content + 3.5 Simple configuration directive for most valid XHTML + 3.6 Simple configuration directive for most `safe` HTML + 3.7 Using a hook function + 3.8 Obtaining `finalized` parameter values + 3.9 Retaining non-HTML tags in input with mixed markup +4 Other + 4.1 Support + 4.2 Known issues + 4.3 Change-log + 4.4 Testing + 4.5 Upgrade, & old versions + 4.6 Comparison with 'HTMLPurifier' + 4.7 Use through application plug-ins/modules + 4.8 Use in non-PHP applications + 4.9 Donate + 4.10 Acknowledgements +5 Appendices + 5.1 Characters discouraged in HTML + 5.2 Valid attribute-element combinations + 5.3 CSS 2.1 properties accepting URLs + 5.4 Microsoft Windows 1252 character replacements + 5.5 URL format + 5.6 Brief on htmLawed code + + +== 1 About htmLawed ================================================ + + + htmLawed is a highly customizable single-file PHP script to make text secure, and standard- and admin policy-compliant for use in the body of HTML 4, XHTML 1 or 1.1, or generic XML documents. It is thus a configurable input (X)HTML filter, processor, purifier, sanitizer, beautifier, etc., and an alternative to the HTMLTidy:- http://tidy.sourceforge.net application. + + The `lawing in` of input text is needed to ensure that HTML code in the text is standard-compliant, does not introduce security vulnerabilities, and does not break the aesthetics, design or layout of web-pages. htmLawed tries to do this by, for example, making HTML well-formed with balanced and properly nested tags, neutralizing code that may be used for cross-site scripting ('XSS') attacks, and allowing only specified HTML elements/tags and attributes. + + +-- 1.1 Example uses ------------------------------------------------ + + + * Filtering of text submitted as comments on blogs to allow only certain HTML elements + + * Making RSS/Atom newsfeed item-content standard-compliant: often one uses an excerpt from an HTML document for the content, and with unbalanced tags, non-numerical entities, etc., such excerpts may not be XML-compliant + + * Text processing for stricter XML standard-compliance: e.g., to have lowercased 'x' in hexadecimal numeric entities becomes necessary if an XHTML document with MathML content needs to be served as 'application/xml' + + * Scraping text or data from web-pages + + * Pretty-printing HTML code + + +-- 1.2 Features ---------------------------------------------------o + + + Key: '*' security feature, '^' standard compliance, '~' requires setting right options, '`' different from 'Kses' + + * make input more *secure* and *standard-compliant* + * use for HTML 4, XHTML 1.0 or 1.1, or even generic *XML* documents ^~` + + * *beautify* or *compact* HTML ^~` + + * *restrict elements* ^~` + * proper closure of empty elements like 'img' ^` + * *transform deprecated elements* like 'u' ^~` + * HTML *comments* and 'CDATA' sections can be permitted ^~` + * elements like 'script', 'object' and 'form' can be permitted ~ + + * *restrict attributes*, including *element-specifically* ^~` + * remove *invalid attributes* ^` + * element and attribute names are *lower-cased* ^ + * provide *required attributes*, like 'alt' for 'image' ^` + * *transform deprecated attributes* ^~` + * attributes *declared only once* ^` + + * *restrict attribute values*, including *element-specifically* ^~` + * a value is declared for `empty` (`minimized`) attributes like 'checked' ^ + * check for potentially dangerous attribute values *~ + * ensure *unique* 'id' attribute values ^~` + * *double-quote* attribute values ^ + * lower-case *standard attribute values* like 'password' ^` + + * *attribute-specific URL protocol/scheme restriction* *~` + * disable *dynamic expressions* in 'style' values *~` + + * neutralize invalid named character entities ^` + * *convert* hexadecimal numeric entities to decimal ones, or vice versa ^~` + * convert named entities to numeric ones for generic XML use ^~` + + * remove *null* characters * + * neutralize potentially dangerous proprietary Netscape *Javascript entities* * + * replace potentially dangerous *soft-hyphen* character in attribute values with spaces * + + * remove common *invalid characters* not allowed in HTML or XML ^` + * replace *characters from Microsoft applications* like 'Word' that are discouraged in HTML or XML ^~` + * neutralize entities for characters invalid or discouraged in HTML or XML ^` + * appropriately neutralize '<', '&', '"', and '>' characters ^*` + + * understands improperly spaced tag content (like, spread over more than a line) and properly spaces them ` + * attempts to *balance tags* for well-formedness ^~` + * understands when *omitable closing tags* like '

    ' (allowed in HTML 4, transitional, e.g.) are missing ^~` + * attempts to permit only *validly nested tags* ^~` + * option to *remove or neutralize bad content* ^~` + * attempts to *rectify common errors of plain-text misplacement* (e.g., directly inside 'blockquote') ^~` + + * fast, *non-OOP* code of ~45 kb incurring peak basal memory usage of ~0.5 MB + * *compatible* with pre-existing code using 'Kses' (the filter used by 'WordPress') + + * optional *anti-spam* measures such as addition of 'rel="nofollow"' and link-disabling ~` + * optionally makes *relative URLs absolute*, and vice versa ~` + + * optionally mark '&' to identify the entities for '&', '<' and '>' introduced by htmLawed ~` + + * allows deployment of powerful *hook functions* to *inject* HTML, *consolidate* 'style' attributes to 'class', finely check attribute values, etc. ~` + + * *independent of character encoding* of input and does not affect it + + * *tolerance for ill-written HTML* to a certain degree + + +-- 1.3 History ----------------------------------------------------o + + + htmLawed was developed for use with 'LabWiki', a wiki software developed at PHP Labware, as a suitable software could not be found. Existing PHP software like 'Kses' and 'HTMLPurifier' were deemed inadequate, slow, resource-intensive, or dependent on external applications like 'HTML Tidy'. + + htmLawed started as a modification of Ulf Harnhammar's 'Kses' (version 0.2.2) software, and is compatible with code that uses 'Kses'; see section:- #2.6. + + +-- 1.4 License & copyright ----------------------------------------o + + + htmLawed is free and open-source software licensed under GPL license version 3:- http://www.gnu.org/licenses/gpl-3.0.txt, and copyrighted by Santosh Patnaik, MD, PhD. + + +-- 1.5 Terms used here --------------------------------------------o + + + * `administrator` - or admin; person setting up the code to pass input through htmLawed; also, `user` + * `attributes` - name-value pairs like 'href="http://x.com"' in opening tags + * `author` - `writer` + * `character` - atomic unit of text; internally represented by a numeric `code-point` as specified by the `encoding` or `charset` in use + * `entity` - markup like '>' and ' ' used to refer to a character + * `element` - HTML element like 'a' and 'img' + * `element content` - content between the opening and closing tags of an element, like 'click' of 'click' + * `HTML` - implies XHTML unless specified otherwise + * `input` - text string given to htmLawed to process + * `processing` - involves filtering, correction, etc., of input + * `safe` - absence or reduction of certain characters and HTML elements and attributes in the input that can otherwise potentially and circumstantially expose web-site users to security vulnerabilities like cross-site scripting attacks (XSS) + * `scheme` - URL protocol like 'http' and 'ftp' + * `specs` - standard specifications + * `style property` - terms like 'border' and 'height' for which declarations are made in values for the 'style' attribute of elements + * `tag` - markers like '' and '' delineating element content; the opening tag can contain attributes + * `tag content` - consists of tag markers '<' and '>', element names like 'div', and possibly attributes + * `user` - administrator + * `writer` - end-user like a blog commenter providing the input that is to be processed; also, `author` + + +== 2 Usage ========================================================oo + + + htmLawed should work with PHP 4.3 and higher. Either 'include()' the 'htmLawed.php' file or copy-paste the entire code. + + To easily *test* htmLawed using a form-based interface, use the provided demo:- htmLawedTest.php ('htmLawed.php' and 'htmLawedTest.php' should be in the same directory on the web-server). + + +-- 2.1 Simple ------------------------------------------------------ + + + The input text to be processed, '$text', is passed as an argument of type string; 'htmLawed()' returns the processed string: + + $processed = htmLawed($text); + + *Note*: If input is from a '$_GET' or '$_POST' value, and 'magic quotes' are enabled on the PHP setup, run 'stripslashes()' on the input before passing to htmLawed. + + By default, htmLawed will process the text allowing all valid HTML elements/tags, secure URL scheme/CSS style properties, etc. It will allow 'CDATA' sections and HTML comments, balance tags, and ensure proper nesting of elements. Such actions can be configured using two other optional arguments -- '$config' and '$spec': + + $processed = htmLawed($text, $config, $spec); + + These extra parameters are detailed below. Some examples are shown in section:- #2.9. + + *Note*: For maximum protection against 'XSS' and other scripting attacks (e.g., by disallowing Javascript code), consider using the 'safe' parameter; see section:- #3.6. + + +-- 2.2 Configuring htmLawed using the '$config' parameter ---------o + + + '$config' instructs htmLawed on how to tackle certain tasks. When '$config' is not specified, or not set as an array (e.g., '$config = 1'), htmLawed will take default actions. One or many of the task-action or value-specification pairs can be specified in '$config' as array key-value pairs. If a parameter is not specified, htmLawed will use the default value/action indicated further below. + + $config = array('comment'=>0, 'cdata'=>1); + $processed = htmLawed($text, $config); + + Or, + + $processed = htmLawed($text, array('comment'=>0, 'cdata'=>1)); + + Below are the possible value-specification combinations. In PHP code, values that are integers should not be quoted and should be used as numeric types (unless meant as string/text). + + Key: '*' default, '^' different default when htmLawed is used in the Kses-compatible mode (see section:- #2.6), '~' different default when 'valid_xhtml' is set to '1' (see section:- #3.5), '"' different default when 'safe' is set to '1' (see section:- #3.6) + + *abs_url* + Make URLs absolute or relative; '$config["base_url"]' needs to be set; see section:- #3.4.4 + + '-1' - make relative + '0' - no action * + '1' - make absolute + + *and_mark* + Mark '&' characters in the original input; see section:- #3.2 + + *anti_link_spam* + Anti-link-spam measure; see section:- #3.4.7 + + '0' - no measure taken * + 'array("regex1", "regex2")' - will ensure a 'rel' attribute with 'nofollow' in its value in case the 'href' attribute value matches the regular expression pattern 'regex1', and/or will remove 'href' if its value matches the regular expression pattern 'regex2'. E.g., 'array("/./", "/://\W*(?!(abc\.com|xyz\.org))/")'; see section:- #3.4.7 for more. + + *anti_mail_spam* + Anti-mail-spam measure; see section:- #3.4.7 + + '0' - no measure taken * + 'word' - '@' in mail address in 'href' attribute value is replaced with specified 'word' + + *balance* + Balance tags for well-formedness and proper nesting; see section:- #3.3.3 + + '0' - no + '1' - yes * + + *base_url* + Base URL value that needs to be set if '$config["abs_url"]' is not '0'; see section:- #3.4.4 + + *cdata* + Handling of 'CDATA' sections; see section:- #3.3.1 + + '0' - don't consider 'CDATA' sections as markup and proceed as if plain text ^" + '1' - remove + '2' - allow, but neutralize any '<', '>', and '&' inside by converting them to named entities + '3' - allow * + + *clean_ms_char* + Replace discouraged characters introduced by Microsoft Word, etc.; see section:- #3.1 + + '0' - no * + '1' - yes + '2' - yes, but replace special single & double quotes with ordinary ones + + *comment* + Handling of HTML comments; see section:- #3.3.1 + + '0' - don't consider comments as markup and proceed as if plain text ^" + '1' - remove + '2' - allow, but neutralize any '<', '>', and '&' inside by converting to named entities + '3' - allow * + + *css_expression* + Allow dynamic CSS expression by not removing the expression from CSS property values in 'style' attributes; see section:- #3.4.8 + + '0' - remove * + '1' - allow + + *deny_attribute* + Denied HTML attributes; see section:- #3.4 + + '0' - none * + 'string' - dictated by values in 'string' + 'on*' (like 'onfocus') attributes not allowed - " + + *elements* + Allowed HTML elements; see section:- #3.3 + + '* -center -dir -font -isindex -menu -s -strike -u' - ~ + 'applet, embed, iframe, object, script' not allowed - " + + *hexdec_entity* + Allow hexadecimal numeric entities and do not convert to the more widely accepted decimal ones, or convert decimal to hexadecimal ones; see section:- #3.2 + + '0' - no + '1' - yes * + '2' - convert decimal to hexadecimal ones + + *hook* + Name of an optional hook function to alter the input string, '$config' or '$spec' before htmLawed starts its main work; see section:- #3.7 + + '0' - no hook function * + 'name' - 'name' is name of the hook function ('kses_hook' ^) + + *hook_tag* + Name of an optional hook function to alter tag content finalized by htmLawed; see section:- #3.4.9 + + '0' - no hook function * + 'name' - 'name' is name of the hook function + + *keep_bad* + Neutralize bad tags by converting '<' and '>' to entities, or remove them; see section:- #3.3.3 + + '0' - remove ^ + '1' - neutralize both tags and element content + '2' - remove tags but neutralize element content + '3' and '4' - like '1' and '2' but remove if text ('pcdata') is invalid in parent element + '5' and '6' * - like '3' and '4' but line-breaks, tabs and spaces are left + + *lc_std_val* + For XHTML compliance, predefined, standard attribute values, like 'get' for the 'method' attribute of 'form', must be lowercased; see section:- #3.4.5 + + '0' - no + '1' - yes * + + *make_tag_strict* + Transform/remove these non-strict XHTML elements, even if they are allowed by the admin: 'applet' 'center' 'dir' 'embed' 'font' 'isindex' 'menu' 's' 'strike' 'u'; see section:- #3.3.2 + + '0' - no ^ + '1' - yes, but leave 'applet', 'embed' and 'isindex' elements that currently can't be transformed * + '2' - yes, removing 'applet', 'embed' and 'isindex' elements and their contents (nested elements remain) ~ + + *named_entity* + Allow non-universal named HTML entities, or convert to numeric ones; see section:- #3.2 + + '0' - convert + '1' - allow * + + *no_deprecated_attr* + Allow deprecated attributes or transform them; see section:- #3.4.6 + + '0' - allow ^ + '1' - transform, but 'name' attributes for 'a' and 'map' are retained * + '2' - transform + + *parent* + Name of the parent element, possibly imagined, that will hold the input; see section:- #3.3 + + *safe* + Magic parameter to make input the most secure against XSS without needing to specify other relevant '$config' parameters; see section:- #3.6 + + '0' - no * + '1' - will auto-adjust other relevant '$config' parameters (indicated by '"' in this list) + + *schemes* + Array of attribute-specific, comma-separated, lower-cased list of schemes (protocols) allowed in attributes accepting URLs; '*' covers all unspecified attributes; see section:- #3.4.3 + + 'href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; *:file, http, https' * + '*: ftp, gopher, http, https, mailto, news, nntp, telnet' ^ + 'href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https' " + + *show_setting* + Name of a PHP variable to assign the `finalized` '$config' and '$spec' values; see section:- #3.8 + + *style_pass* + Do not look at 'style' attribute values, letting them through without any alteration + + '0' - no * + '1' - htmLawed will let through any 'style' value; see section:- #3.4.8 + + *tidy* + Beautify or compact HTML code; see section:- #3.3.5 + + '-1' - compact + '0' - no * + '1' or 'string' - beautify (custom format specified by 'string') + + *unique_ids* + 'id' attribute value checks; see section:- #3.4.2 + + '0' - no ^ + '1' - remove duplicate and/or invalid ones * + 'word' - remove invalid ones and replace duplicate ones with new and unique ones based on the 'word'; the admin-specified 'word', like 'my_', should begin with a letter (a-z) and can contain letters, digits, '.', '_', '-', and ':'. + + *valid_xhtml* + Magic parameter to make input the most valid XHTML without needing to specify other relevant '$config' parameters; see section:- #3.5 + + '0' - no * + '1' - will auto-adjust other relevant '$config' parameters (indicated by '~' in this list) + + *xml:lang* + Auto-adding 'xml:lang' attribute; see section:- #3.4.1 + + '0' - no * + '1' - add if 'lang' attribute is present + '2' - add if 'lang' attribute is present, and remove 'lang' ~ + + +-- 2.3 Extra HTML specifications using the $spec parameter --------o + + + The '$spec' argument can be used to disallow an otherwise legal attribute for an element, or to restrict the attribute's values. This can also be helpful as a security measure (e.g., in certain versions of browsers, certain values can cause buffer overflows and denial of service attacks), or in enforcing admin policy compliance. '$spec' is specified as a string of text containing one or more `rules`, with multiple rules separated from each other by a semi-colon (';'). E.g., + + $spec = 'i=-*; td, tr=style, id, -*; a=id(match="/[a-z][a-z\d.:\-`"]*/i"/minval=2), href(maxlen=100/minlen=34); img=-width,-alt'; + $processed = htmLawed($text, $config, $spec); + + Or, + + $processed = htmLawed($text, $config, 'i=-*; td, tr=style, id, -*; a=id(match="/[a-z][a-z\d.:\-`"]*/i"/minval=2), href(maxlen=100/minlen=34); img=-width,-alt'); + + A rule begins with an HTML *element* name(s) (`rule-element`), for which the rule applies, followed by an equal ('=') sign. A rule-element may represent multiple elements if comma (,)-separated element names are used. E.g., 'th,td,tr='. + + Rest of the rule consists of comma-separated HTML *attribute names*. A minus ('-') character before an attribute means that the attribute is not permitted inside the rule-element. E.g., '-width'. To deny all attributes, '-*' can be used. + + Following shows examples of rule excerpts with rule-element 'a' and the attributes that are being permitted: + + * 'a=' - all + * 'a=id' - all + * 'a=href, title, -id, -onclick' - all except 'id' and 'onclick' + * 'a=*, id, -id' - all except 'id' + * 'a=-*' - none + * 'a=-*, href, title' - none except 'href' and 'title' + * 'a=-*, -id, href, title' - none except 'href' and 'title' + + Rules regarding *attribute values* are optionally specified inside round brackets after attribute names in slash ('/')-separated `parameter = value` pairs. E.g., 'title(maxlen=30/minlen=5)'. None, or one or more of the following parameters may be specified: + + * 'oneof' - one or more choices separated by '|' that the value should match; if only one choice is provided, then the value must match that choice + + * 'noneof' - one or more choices separated by '|' that the value should not match + + * 'maxlen' and 'minlen' - upper and lower limits for the number of characters in the attribute value; specified in numbers + + * 'maxval' and 'minval' - upper and lower limits for the numerical value specified in the attribute value; specified in numbers + + * 'match' and 'nomatch' - pattern that the attribute value should or should not match; specified as PHP/PCRE-compatible regular expressions with delimiters and possibly modifiers + + * 'default' - a value to force on the attribute if the value provided by the writer does not fit any of the specified parameters + + If 'default' is not set and the attribute value does not satisfy any of the specified parameters, then the attribute is removed. The 'default' value can also be used to force all attribute declarations to take the same value (by getting the values declared illegal by setting, e.g., 'maxlen' to '-1'). + + Examples with `input` '' are shown below. + + `Rule`: 'input=title(maxlen=60/minlen=6), value' + `Output`: '' + + `Rule`: 'input=title(), value(maxval=8/default=6)' + `Output`: '' + + `Rule`: 'input=title(nomatch=$w.d$i), value(match=$em$/default=6em)' + `Output`: '' + + `Rule`: 'input=title(oneof=height|depth/default=depth), value(noneof=5|6)' + `Output`: '' + + *Special characters*: The characters ';', ',', '/', '(', ')', '|', '~' and space have special meanings in the rules. Words in the rules that use such characters, or the characters themselves, should be `escaped` by enclosing in pairs of double-quotes ('"'). A back-tick ('`') can be used to escape a literal '"'. An example rule illustrating this is 'input=value(maxlen=30/match="/^\w/"/default="your `"ID`"")'. + + *Note*: To deny an attribute for all elements for which it is legal, '$config["deny_attribute"]' (see section:- #3.4) can be used instead of '$spec'. Also, attributes can be allowed element-specifically through '$spec' while being denied globally through '$config["deny_attribute"]'. The 'hook_tag' parameter (section:- #3.4.9) can also be used to implement the '$spec' functionality. + + +-- 2.4 Performance time & memory usage ----------------------------o + + + The time and memory used by htmLawed depends on its configuration and the size of the input, and the amount, nestedness and well-formedness of the HTML markup within it. In particular, tag balancing and beautification each can increase the processing time by about a quarter. + + The htmLawed demo:- htmLawedTest.php can be used to evaluate the performance and effects of different types of input and '$config'. + + +-- 2.5 Some security risks to keep in mind ------------------------o + + + When setting the parameters/arguments (like those to allow certain HTML elements) for use with htmLawed, one should bear in mind that the setting may let through potentially `dangerous` HTML code. (This may not be a problem if the authors are trusted.) + + For example, following increase security risks: + + * Allowing 'script', 'applet', 'embed', 'iframe' or 'object' elements, or certain of their attributes like 'allowscriptaccess' + + * Allowing HTML comments (some Internet Explorer versions are vulnerable with, e.g., '' + + * Allowing dynamic CSS expressions (a feature of the IE browser) + + `Unsafe` HTML can be removed by setting '$config' appropriately. E.g., '$config["elements"] = "* -script"' (section:- #3.3), '$config["safe"] = 1' (section:- #3.6), etc. + + +-- 2.6 Use without modifying old 'kses()' code --------------------o + + + The 'Kses' PHP script is used by many applications (like 'WordPress'). It is possible to have such applications use htmLawed instead, since it is compatible with code that calls the 'kses()' function declared in the 'Kses' file (usually named 'kses.php'). E.g., application code like this will continue to work after replacing 'Kses' with htmLawed: + + $comment_filtered = kses($comment_input, array('a'=>array(), 'b'=>array(), 'i'=>array())); + + For some of the '$config' parameters, htmLawed will use values other than the default ones. These are indicated by '^' in section:- #2.2. To force htmLawed to use other values, function 'kses()' in the htmLawed code should be edited -- a few configurable parameters/variables need to be changed. + + If the application uses a 'Kses' file that has the 'kses()' function declared, then, to have the application use htmLawed instead of 'Kses', simply rename 'htmLawed.php' (to 'kses.php', e.g.) and replace the 'Kses' file (or just replace the code in the 'Kses' file with the htmLawed code). If the 'kses()' function in the 'Kses' file had been renamed by the application developer (e.g., in 'WordPress', it is named 'wp_kses()'), then appropriately rename the 'kses()' function in the htmLawed code. + + If the 'Kses' file used by the application has been highly altered by the application developers, then one may need a different approach. E.g., with 'WordPress', it is best to copy the htmLawed code to 'wp_includes/kses.php', rename the newly added function 'kses()' to 'wp_kses()', and delete the code for the original 'wp_kses()' function. + + If the 'Kses' code has a non-empty hook function (e.g., 'wp_kses_hook()' in case of 'WordPress'), then the code for htmLawed's 'kses_hook()' function should be appropriately edited. However, the requirement of the hook function should be re-evaluated considering that htmLawed has extra capabilities. With 'WordPress', the hook function is an essential one. The following code is suggested for the htmLawed 'kses_hook()' in case of 'WordPress': + + function kses_hook($string, &$cf, &$spec){ + // kses compatibility + $allowed_html = $spec; + $allowed_protocols = array(); + foreach($cf['schemes'] as $v){ + foreach($v as $k2=>$v2){ + if(!in_array($k2, $allowed_protocols)){ + $allowed_protocols[] = $k2; + } + } + } + return wp_kses_hook($string, $allowed_html, $allowed_protocols); + // eof + } + + +-- 2.7 Tolerance for ill-written HTML -----------------------------o + + + htmLawed can work with ill-written HTML code in the input. However, HTML that is too ill-written may not be `read` as HTML, and be considered mere plain text instead. Following statements indicate the degree of `looseness` that htmLawed can work with, and can be provided in instructions to writers: + + * Tags must be flanked by '<' and '>' with no '>' inside -- any needed '>' should be put in as '>'. It is possible for tag content (element name and attributes) to be spread over many lines instead of being on one. A space may be present between the tag content and '>', like '
    ' and '', but not after the '<'. + + * Element and attribute names need not be lower-cased. + + * Attribute string of elements may be liberally spaced with tabs, line-breaks, etc. + + * Attribute values may not be double-quoted, or may be single-quoted. + + * Left-padding of numeric entities (like, ' ', '&x07ff;') with '0' is okay as long as the number of characters between between the '&' and the ';' does not exceed 8. All entities must end with ';' though. + + * Named character entities must be properly cased. E.g., '≪' or '&TILDE;' will not be let through without modification. + + * HTML comments should not be inside element tags (okay between tags), and should begin with ''. Characters like '<', '>', and '&' may be allowed inside depending on '$config', but any '-->' inside should be put in as '-->'. Any '--' inside will be automatically converted to '-', and a space will be added before the comment delimiter '-->'. + + * 'CDATA' sections should not be inside element tags, and can be in element content only if plain text is allowed for that element. They should begin with '<[CDATA[' and end with ']]>'. Characters like '<', '>', and '&' may be allowed inside depending on '$config', but any ']]>' inside should be put in as ']]>'. + + * For attribute values, character entities '<', '>' and '&' should be used instead of characters '<' and '>', and '&' (when '&' is not part of a character entity). This applies even for Javascript code in values of attributes like 'onclick'. + + * Characters '<', '>', '&' and '"' that are part of actual Javascript, etc., code in 'script' elements should be used as such and not be put in as entities like '>'. Otherwise, though the HTML will be valid, the code may fail to work. Further, if such characters have to be used, then they should be put inside 'CDATA' sections. + + * Simple instructions like "an opening tag cannot be present between two closing tags" and "nested elements should be closed in the reverse order of how they were opened" can help authors write balanced HTML. If tags are imbalanced, htmLawed will try to balance them, but in the process, depending on '$config["keep_bad"]', some code/text may be lost. + + * Input authors should be notified of admin-specified allowed elements, attributes, configuration values (like conversion of named entities to numeric ones), etc. + + * With '$config["unique_ids"]' not '0' and the 'id' attribute being permitted, writers should carefully avoid using duplicate or invalid 'id' values as even though htmLawed will correct/remove the values, the final output may not be the one desired. E.g., when '' is processed into +''. + + * Note that even if intended HTML is lost in a highly ill-written input, the processed output will be more secure and standard-compliant. + + * For URLs, unless '$config["scheme"]' is appropriately set, writers should avoid using escape characters or entities in schemes. E.g., 'http' (which many browsers will read as the harmless 'http') may be considered bad by htmLawed. + + * htmLawed will attempt to put plain text present directly inside 'blockquote', 'form', 'map' and 'noscript' elements (illegal as per the specs) inside auto-generated 'div' elements. + + +-- 2.8 Limitations & work-arounds ---------------------------------o + + + htmLawed's main objective is to make the input text `more` standard-compliant, secure for web-page readers, and free of HTML elements and attributes considered undesirable by the administrator. Some of its current limitations, regardless of this objective, are noted below along with work-arounds. + + It should be borne in mind that no browser application is 100% standard-compliant, and that some of the standard specs (like asking for normalization of white-spacing within 'textarea' elements) are clearly wrong. Regarding security, note that `unsafe` HTML code is not necessarily legally invalid. + + * htmLawed is meant for input that goes into the 'body' of HTML documents. HTML's head-level elements are not supported, nor are the frameset elements 'frameset', 'frame' and 'noframes'. + + * It cannot transform the non-standard 'embed' elements to the standard-compliant 'object' elements. Yet, it can allow 'embed' elements if permitted ('embed' is widely used and supported). Admins can certainly use the 'hook_tag' parameter (section:- #3.4.9) to deploy a custom embed-to-object converter function. + + * The only non-standard element that may be permitted is 'embed'; others like 'noembed' and 'nobr' cannot be permitted without modifying the htmLawed code. + + * It cannot handle input that has non-HTML code like 'SVG' and 'MathML'. One way around is to break the input into pieces and passing only those without non-HTML code to htmLawed. Another is described in section:- #3.9. A third way may be to some how take advantage of the '$config["and_mark"]' parameter (see section:- #3.2). + + * By default, htmLawed won't check many attribute values for standard compliance. E.g., 'width="20m"' with the dimension in non-standard 'm' is let through. Implementing universal and strict attribute value checks can make htmLawed slow and resource-intensive. Admins should look at the 'hook_tag' parameter (section:- #3.4.9) or '$spec' to enforce finer checks. + + * The attributes, deprecated (which can be transformed too) or not, that it supports are largely those that are in the specs. Only a few of the proprietary attributes are supported. + + * Except for contained URLs and dynamic expressions (also optional), htmLawed does not check CSS style property values. Admins should look at using the 'hook_tag' parameter (section:- #3.4.9) or '$spec' for finer checks. Perhaps the best option is to disallow 'style' but allow 'class' attributes with the right 'oneof' or 'match' values for 'class', and have the various class style properties in '.css' CSS stylesheet files. + + * htmLawed does not parse emoticons, decode `BBcode`, or `wikify`, auto-converting text to proper HTML. Similarly, it won't convert line-breaks to 'br' elements. Such functions are beyond its purview. Admins should use other code to pre- or post-process the input for such purposes. + + * htmLawed cannot be used to have links force-opened in new windows (by auto-adding appropriate 'target' and 'onclick' attributes to 'a'). Admins should look at Javascript-based DOM-modifying solutions for this. Admins may also be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9). + + * Nesting-based checks are not possible. E.g., one cannot disallow 'p' elements specifically inside 'td' while permitting it elsewhere. Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9). + + * Except for optionally converting absolute or relative URLs to the other type, htmLawed will not alter URLs (e.g., to change the value of query strings or to convert 'http' to 'https'. Having absolute URLs may be a standard-requirement, e.g., when HTML is embedded in email messages, whereas altering URLs for other purposes is beyond htmLawed's goals. Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9). + + * Pairs of opening and closing tags that do not enclose any content (like '') are not removed. This may be against the standard specs for certain elements (e.g., 'table'). However, presence of such standard-incompliant code will not break the display or layout of content. Admins can also use simple regex-based code to filter out such code. + + * htmLawed does not check for certain element orderings described in the standard specs (e.g., in a 'table', 'tbody' is allowed before 'tfoot'). Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9). + + * htmLawed does not check the number of nested elements. E.g., it will allow two 'caption' elements in a 'table' element, illegal as per the specs. Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9). + + * htmLawed might convert certain entities to actual characters and remove backslashes and CSS comment-markers ('/*') in 'style' attribute values in order to detect malicious HTML like crafted IE-specific dynamic expressions like 'expression...'. If this is too harsh, admins can allow CSS expressions through htmLawed core but then use a custom function through the 'hook_tag' parameter (section:- #3.4.9) to more specifically identify CSS expressions in the 'style' attribute values. Also, using '$config["style_pass"]', it is possible to have htmLawed pass 'style' attribute values without even looking at them (section:- #3.4.8). + + * htmLawed does not correct certain possible attribute-based security vulnerabilities (e.g., 'x'). These arise when browsers mis-identify markup in `escaped` text, defeating the very purpose of escaping text (a bad browser will read the given example as 'x'). + + * Because of poor Unicode support in PHP, htmLawed does not remove the `high value` HTML-invalid characters with multi-byte code-points. Such characters however are extremely unlikely to be in the input. (see section:- #3.1). + + * Like any script using PHP's PCRE regex functions, PHP setup-specific low PCRE limit values can cause htmLawed to at least partially fail with very long input texts. + + +-- 2.9 Examples ---------------------------------------------------o + + + *1.* A blog administrator wants to allow only 'a', 'em', 'strike', 'strong' and 'u' in comments, but needs 'strike' and 'u' transformed to 'span' for better XHTML 1-strict compliance, and, he wants the 'a' links to be to 'http' or 'https' resources: + + $processed = htmLawed($in, array('elements'=>'a, em, strike, strong, u', 'make_tag_strict'=>1, 'safe'=>1, 'schemes'=>'*:http, https'), 'a=href'); + + *2.* An author uses a custom-made web application to load content on his web-site. He is the only one using that application and the content he generates has all types of HTML, including scripts. The web application uses htmLawed primarily as a tool to correct errors that creep in while writing HTML and to take care of the occasional `bad` characters in copy-paste text introduced by Microsoft Office. The web application provides a preview before submitted input is added to the content. For the previewing process, htmLawed is set up as follows: + + $processed = htmLawed($in, array('css_expression'=>1, 'keep_bad'=>1, 'make_tag_strict'=>1, 'schemes'=>'*:*', 'valid_xhtml'=>1)); + + For the final submission process, 'keep_bad' is set to '6'. A value of '1' for the preview process allows the author to note and correct any HTML mistake without losing any of the typed text. + + *3.* A data-miner is scraping information in a specific table of similar web-pages and is collating the data rows, and uses htmLawed to reduce unnecessary markup and white-spaces: + + $processed = htmLawed($in, array('elements'=>'tr, td', 'tidy'=>-1), 'tr, td ='); + + +== 3 Details =====================================================oo + + +-- 3.1 Invalid/dangerous characters -------------------------------- + + + Valid characters (more correctly, their code-points) in HTML or XML are, hexadecimally, '9', 'a', 'd', '20' to 'd7ff', and 'e000' to '10ffff', except 'fffe' and 'ffff' (decimally, '9', '10', '13', '32' to '55295', and '57344' to '1114111', except '65534' and '65535'). htmLawed removes the invalid characters '0' to '8', 'b', 'c', and 'e' to '1f'. + + Because of PHP's poor native support for multi-byte characters, htmLawed cannot check for the remaining invalid code-points. However, for various reasons, it is very unlikely for any of those characters to be in the input. + + Characters that are discouraged (see section:- #5.1) but not invalid are not removed by htmLawed. + + It (function 'hl_tag()') also replaces the potentially dangerous (in some Mozilla [Firefox] and Opera browsers) soft-hyphen character (code-point, hexadecimally, 'ad', or decimally, '173') in attribute values with spaces. Where required, the characters '<', '>', '&', and '"' are converted to entities. + + With '$config["clean_ms_char"]' set as '1' or '2', many of the discouraged characters (decimal code-points '127' to '159' except '133') that many Microsoft applications incorrectly use (as per the 'Windows 1252' ['Cp-1252'] or a similar encoding system), and the character for decimal code-point '133', are converted to appropriate decimal numerical entities (or removed for a few cases)-- see appendix in section:- #5.4. This can help avoid some display issues arising from copying-pasting of content. + + With '$config["clean_ms_char"]' set as '2', characters for the hexadecimal code-points '82', '91', and '92' (for special single-quotes), and '84', '93', and '94' (for special double-quotes) are converted to ordinary single and double quotes respectively and not to entities. + + The character values are replaced with entities/characters and not character values referred to by the entities/characters to keep this task independent of the character-encoding of input text. + + The '$config["clean_ms_char"]' parameter need not be used if authors do not copy-paste Microsoft-created text or if the input text is not believed to use the 'Windows 1252' or a similar encoding. Further, the input form and the web-pages displaying it or its content should have the character encoding appropriately marked-up. + + +-- 3.2 Character references/entities ------------------------------o + + + Valid character entities take the form '&*;' where '*' is '#x' followed by a hexadecimal number (hexadecimal numeric entity; like ' ' for non-breaking space), or alphanumeric like 'gt' (external or named entity; like ' ' for non-breaking space), or '#' followed by a number (decimal numeric entity; like ' ' for non-breaking space). Character entities referring to the soft-hyphen character (the '­' or '\xad' character; hexadecimal code-point 'ad' [decimal '173']) in attribute values are always replaced with spaces; soft-hyphens in attribute values introduce vulnerabilities in some older versions of the Opera and Mozilla [Firefox] browsers. + + htmLawed (function 'hl_ent()'): + + * Neutralizes entities with multiple leading zeroes or missing semi-colons (potentially dangerous) + + * Lowercases the 'X' (for XML-compliance) and 'A-F' of hexadecimal numeric entities + + * Neutralizes entities referring to characters that are HTML-invalid (see section:- #3.1) + + * Neutralizes entities referring to characters that are HTML-discouraged (code-points, hexadecimally, '7f' to '84', '86' to '9f', and 'fdd0' to 'fddf', or decimally, '127' to '132', '134' to '159', and '64991' to '64976'). Entities referring to the remaining discouraged characters (see section:- #5.1 for a full list) are let through. + + * Neutralizes named entities that are not in the specs. + + * Optionally converts valid HTML-specific named entities except '>', '<', '"', and '&' to decimal numeric ones (hexadecimal if $config["hexdec_entity"] is '2') for generic XML-compliance. For this, '$config["named_entity"]' should be '1'. + + * Optionally converts hexadecimal numeric entities to the more widely supported decimal ones. For this, '$config["hexdec_entity"]' should be '0'. + + * Optionally converts decimal numeric entities to the hexadecimal ones. For this, '$config["hexdec_entity"]' should be '2'. + + `Neutralization` refers to the `entitification` of '&' to '&'. + + *Note*: htmLawed does not convert entities to the actual characters represented by them; one can pass the htmLawed output through PHP's 'html_entity_decode' function:- http://www.php.net/html_entity_decode for that. + + *Note*: If '$config["and_mark"]' is set, and set to a value other than '0', then the '&' characters in the original input are replaced with the control character for the hexadecimal code-point '6' ('\x06'; '&' characters introduced by htmLawed, e.g., after converting '<' to '<', are not affected). This allows one to distinguish, say, an '>' introduced by htmLawed and an '>' put in by the input writer, and can be helpful in further processing of the htmLawed-processed text (e.g., to identify the character sequence 'o(><)o' to generate an emoticon image). When this feature is active, admins should ensure that the htmLawed output is not directly used in web pages or XML documents as the presence of the '\x06' can break documents. Before use in such documents, and preferably before any storage, any remaining '\x06' should be changed back to '&', e.g., with: + + $final = str_replace("\x06", '&', $prelim); + + Also, see section:- #3.9. + + +-- 3.3 HTML elements ----------------------------------------------o + + + htmLawed can be configured to allow only certain HTML elements (tags) in the input. Disallowed elements (just tag-content, and not element-content), based on '$config["keep_bad"]', are either `neutralized` (converted to plain text by entitification of '<' and '>') or removed. + + E.g., with only 'em' permitted: + + Input: + + My website is My website is a.com. + + Output, with '$config["keep_bad"]' not '0': + + My website is <a href="">a.com</a>. + + See section:- #3.3.3 for differences between the various non-zero '$config["keep_bad"]' values. + + htmLawed by default permits these 86 elements: + + a, abbr, acronym, address, applet, area, b, bdo, big, blockquote, br, button, caption, center, cite, code, col, colgroup, dd, del, dfn, dir, div, dl, dt, em, embed, fieldset, font, form, h1, h2, h3, h4, h5, h6, hr, i, iframe, img, input, ins, isindex, kbd, label, legend, li, map, menu, noscript, object, ol, optgroup, option, p, param, pre, q, rb, rbc, rp, rt, rtc, ruby, s, samp, script, select, small, span, strike, strong, sub, sup, table, tbody, td, textarea, tfoot, th, thead, tr, tt, u, ul, var + + Except for 'embed' (included because of its wide-spread use) and the Ruby elements ('rb', 'rbc', 'rp', 'rt', 'rtc', 'ruby'; part of XHTML 1.1), these are all the elements in the HTML 4/XHTML 1 specs. Strict-specific specs. exclude 'center', 'dir', 'font', 'isindex', 'menu', 's', 'strike', and 'u'. + + With '$config["safe"] = 1', the default set will exclude 'applet', 'embed', 'iframe', 'object' and 'script'; see section:- #3.6. + + When '$config["elements"]', which specifies allowed elements, is `properly` defined, and neither empty nor set to '0' or '*', the default set is not used. To have elements added to or removed from the default set, a '+/-' notation is used. E.g., '*-script-object' implies that only 'script' and 'object' are disallowed, whereas '*+embed' means that 'noembed' is also allowed. Elements can also be specified as comma separated names. E.g., 'a, b, i' means only 'a', 'b' and 'i' are permitted. In this notation, '*', '+' and '-' have no significance and can actually cause a mis-reading. + + Some more examples of '$config["elements"]' values indicating permitted elements (note that empty spaces are liberally allowed for clarity): + + * 'a, blockquote, code, em, strong' -- only 'a', 'blockquote', 'code', 'em', and 'strong' + * '*-script' -- all excluding 'script' + * '* -center -dir -font -isindex -menu -s -strike -u' -- only XHTML-Strict elements + * '*+noembed-script' -- all including 'noembed' excluding 'script' + + Some mis-usages (and the resulting permitted elements) that can be avoided: + + * '-*' -- none; instead of htmLawed, one might just use, e.g., the 'htmlspecialchars()' PHP function + * '*, -script' -- all except 'script'; admin probably meant '*-script' + * '-*, a, em, strong' -- all; admin probably meant 'a, em, strong' + * '*' -- all; admin need not have set 'elements' + * '*-form+form' -- all; a '+' will always over-ride any '-' + * '*, noembed' -- only 'noembed'; admin probably meant '*+noembed' + * 'a, +b, i' -- only 'a' and 'i'; admin probably meant 'a, b, i' + + Basically, when using the '+/-' notation, commas (',') should not be used, and vice versa, and '*' should be used with the former but not the latter. + + *Note*: Even if an element that is not in the default set is allowed through '$config["elements"]', like 'noembed' in the last example, it will eventually be removed during tag balancing unless such balancing is turned off ('$config["balance"]' set to '0'). Currently, the only way around this, which actually is simple, is to edit the various arrays in the function 'hl_bal()' to accommodate the element and its nesting properties. + + *A possibly second way to specify allowed elements* is to set '$config["parent"]' to an element name that supposedly will hold the input, and to set '$config["balance"]' to '1'. During tag balancing (see section:- #3.3.3), all elements that cannot legally nest inside the parent element will be removed. The parent element is auto-reset to 'div' if '$config["parent"]' is empty, 'body', or an element not in htmLawed's default set of 86 elements. + + `Tag transformation` is possible for improving XHTML-Strict compliance -- most of the deprecated elements are removed or converted to valid XHTML-Strict ones; see section:- #3.3.2. + + +.. 3.3.1 Handling of comments and CDATA sections ................... + + + 'CDATA' sections have the format '"...]]>', and HTML comments, '"... -->'. Neither HTML comments nor 'CDATA' sections can reside inside tags. HTML comments can exist anywhere else, but 'CDATA' sections can exist only where plain text is allowed (e.g., immediately inside 'td' element content but not immediately inside 'tr' element content). + + htmLawed (function 'hl_cmtcd()') handles HTML comments or 'CDATA' sections depending on the values of '$config["comment"]' or '$config["cdata"]'. If '0', such markup is not looked for and the text is processed like plain text. If '1', it is removed completely. If '2', it is preserved but any '<', '>' and '&' inside are changed to entities. If '3', they are left as such. + + Note that for the last two cases, HTML comments and 'CDATA' sections will always be removed from tag content (function 'hl_tag()'). + + Examples: + + Input: + Home + Output ('$config["comment"] = 0, $config["cdata"] = 2'): + <-- home link -->Home + Output ('$config["comment"] = 1, $config["cdata"] = 2'): + Home + Output ('$config["comment"] = 2, $config["cdata"] = 2'): + Home + Output ('$config["comment"] = 2, $config["cdata"] = 1'): + Home + Output ('$config["comment"] = 3, $config["cdata"] = 3'): + Home + + For standard-compliance, comments are given the form '', and any '--' in the content is made '-'. + + When '$config["safe"] = 1', CDATA sections and comments are considered plain text unless '$config["comment"]' or '$config["cdata"]' is explicitly specified; see section:- #3.6. + + +.. 3.3.2 Tag-transformation for better XHTML-Strict ................o + + + If '$config["make_tag_strict"]' is set and not '0', following non-XHTML-Strict elements (and attributes), even if admin-permitted, are mutated as indicated (element content remains intact; function 'hl_tag2()'): + + * applet - (based on '$config["make_tag_strict"]', unchanged ('1') or removed ('2')) + * center - 'div style="text-align: center;"' + * dir - 'ul' + * embed - (based on '$config["make_tag_strict"]', unchanged ('1') or removed ('2')) + * font (face, size, color) - 'span style="font-family: ; font-size: ; color: ;"' (size transformation reference:- http://style.cleverchimp.com/font_size_intervals/altintervals.html) + * isindex - (based on '$config["make_tag_strict"]', unchanged ('1') or removed ('2')) + * menu - 'ul' + * s - 'span style="text-decoration: line-through;"' + * strike - 'span style="text-decoration: line-through;"' + * u - 'span style="text-decoration: underline;"' + + For an element with a pre-existing 'style' attribute value, the extra style properties are appended. + + Example input: + +
    + The PHP software script used for this web-page web-page is htmLawedTest.php, from PHP Labware. +
    + + The output: + +
    + The PHP software script used for this web-page web-page is htmLawedTest.php, from PHP Labware. +
    + + +-- 3.3.3 Tag balancing and proper nesting -------------------------o + + + If '$config["balance"]' is set to '1', htmLawed (function 'hl_bal()') checks and corrects the input to have properly balanced tags and legal element content (i.e., any element nesting should be valid, and plain text may be present only in the content of elements that allow them). + + Depending on the value of '$config["keep_bad"]' (see section:- #2.2 and section:- #3.3), illegal content may be removed or neutralized to plain text by converting < and > to entities: + + '0' - remove; this option is available only to maintain Kses-compatibility and should not be used otherwise (see section:- #2.6) + '1' - neutralize tags and keep element content + '2' - remove tags but keep element content + '3' and '4' - like '1' and '2', but keep element content only if text ('pcdata') is valid in parent element as per specs + '5' and '6' - like '3' and '4', but line-breaks, tabs and spaces are left + + Example input (disallowing the 'p' element): + + <*> Pseudo-tags <*> + Non-HTML tag xml +

    + Disallowed tag p +

    +
      Bad
    • OK
    + + The output with '$config["keep_bad"] = 1': + + <*> Pseudo-tags <*> + <xml>Non-HTML tag xml</xml> + <p> + Disallowed tag p + </p> +
      Bad
    • OK
    + + The output with '$config["keep_bad"] = 3': + + <*> Pseudo-tags <*> + <xml>Non-HTML tag xml</xml> + <p> + Disallowed tag p + </p> +
    • OK
    + + The output with '$config["keep_bad"] = 6': + + <*> Pseudo-tags <*> + Non-HTML tag xml + + Disallowed tag p + +
    • OK
    + + An option like '1' is useful, e.g., when a writer previews his submission, whereas one like '3' is useful before content is finalized and made available to all. + + *Note:* In the example above, unlike '<*>', '' gets considered as a tag (even though there is no HTML element named 'xml'). In general, text matching the regular expression pattern '<(/?)([a-zA-Z][a-zA-Z1-6]*)([^>]*?)\s?>' is considered a tag (phrase enclosed by the angled brackets '<' and '>', and starting [with an optional slash preceding] with an alphanumeric word that starts with an alphabet...). + + Nesting/content rules for each of the 86 elements in htmLawed's default set (see section:- #3.3) are defined in function 'hl_bal()'. This means that if a non-standard element besides 'embed' is being permitted through '$config["elements"]', the element's tag content will end up getting removed if '$config["balance"]' is set to '1'. + + Plain text and/or certain elements nested inside 'blockquote', 'form', 'map' and 'noscript' need to be in block-level elements. This point is often missed during manual writing of HTML code. htmLawed attempts to address this during balancing. E.g., if the parent container is set as 'form', the input 'B:C:' is converted to '
    B:C:
    '. + + +-- 3.3.4 Elements requiring child elements ------------------------o + + + As per specs, the following elements require legal child elements nested inside them: + + blockquote, dir, dl, form, map, menu, noscript, ol, optgroup, rbc, rtc, ruby, select, table, tbody, tfoot, thead, tr, ul + + In some cases, the specs stipulate the number and/or the ordering of the child elements. A 'table' can have 0 or 1 'caption', 'tbody', 'tfoot', and 'thead', but they must be in this order: 'caption', 'thead', 'tfoot', 'tbody'. + + htmLawed currently does not check for conformance to these rules. Note that any non-compliance in this regard will not introduce security vulnerabilities, crash browser applications, or affect the rendering of web-pages. + + +-- 3.3.5 Beautify or compact HTML ---------------------------------o + + + By default, htmLawed will neither `beautify` HTML code by formatting it with indentations, etc., nor will it make it compact by removing un-needed white-space.(It does always properly white-space tag content.) + + As per the HTML standards, spaces, tabs and line-breaks in web-pages (except those inside 'pre' elements) are all considered equivalent, and referred to as `white-spaces`. Browser applications are supposed to consider contiguous white-spaces as just a single space, and to disregard white-spaces trailing opening tags or preceding closing tags. This white-space `normalization` allows the use of text/code beautifully formatted with indentations and line-spacings for readability. Such `pretty` HTML can, however, increase the size of web-pages, or make the extraction or scraping of plain text cumbersome. + + With the '$config' parameter 'tidy', htmLawed can be used to beautify or compact the input text. Input with just plain text and no HTML markup is also subject to this. Besides 'pre', the 'script' and 'textarea' elements, CDATA sections, and HTML comments are not subjected to the tidying process. + + To `compact`, use '$config["tidy"] = -1'; single instances or runs of white-spaces are replaced with a single space, and white-spaces trailing and leading open and closing tags, respectively, are removed. + + To `beautify`, '$config["tidy"]' is set as '1', or for customized tidying, as a string like '2s2n'. The 's' or 't' character specifies the use of spaces or tabs for indentation. The first and third characters, any of the digits 0-9, specify the number of spaces or tabs per indentation, and any parental lead spacing (extra indenting of the whole block of input text). The 'r' and 'n' characters are used to specify line-break characters: 'n' for '\n' (Unix/Mac OS X line-breaks), 'rn' or 'nr' for '\r\n' (Windows/DOS line-breaks), or 'r' for '\r'. + + The '$config["tidy"]' value of '1' is equivalent to '2s0n'. Other '$config["tidy"]' values are read loosely: a value of '4' is equivalent to '4s0n'; 't2', to '1t2n'; 's', to '2s0n'; '2TR', to '2t0r'; 'T1', to '1t1n'; 'nr3', to '3s0nr', and so on. Except in the indentations and line-spacings, runs of white-spaces are replaced with a single space during beautification. + + Input formatting using '$config["tidy"]' is not recommended when input text has mixed markup (like HTML + PHP). + + +-- 3.4 Attributes ------------------------------------------------oo + + + htmLawed will only permit attributes described in the HTML specs (including deprecated ones). It also permits some attributes for use with the 'embed' element (the non-standard 'embed' element is supported in htmLawed because of its widespread use), and the the 'xml:space' attribute (valid only in XHTML 1.1). A list of such 111 attributes and the elements they are allowed in is in section:- #5.2. + + When '$config["deny_attribute"]' is not set, or set to '0', or empty ('""'), all the 111 attributes are permitted. Otherwise, '$config["deny_attribute"]' can be set as a list of comma-separated names of the denied attributes. 'on*' can be used to refer to the group of potentially dangerous, script-accepting attributes: 'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onreset', 'onselect' and 'onsubmit'. + + Note that attributes specified in '$config["deny_attribute"]' are denied globally, for all elements. To deny attributes for only specific elements, '$spec' (see section:- #2.3) can be used. '$spec' can also be used to element-specifically permit an attribute otherwise denied through '$config["deny_attribute"]'. + + With '$config["safe"] = 1' (section:- #3.6), the 'on*' attributes are automatically disallowed. + + *Note*: To deny all but a few attributes globally, a simpler way to specify '$config["deny_attribute"]' would be to use the notation '* -attribute1 -attribute2 ...'. Thus, a value of '* -title -href' implies that except 'href' and 'title' (where allowed as per standards) all other attributes are to be removed. With this notation, the value for the parameter 'safe' (section:- #3.6) will have no effect on 'deny_attribute'. + + htmLawed (function 'hl_tag()') also: + + * Lower-cases attribute names + * Removes duplicate attributes (last one stays) + * Gives attributes the form 'name="value"' and single-spaces them, removing unnecessary white-spacing + * Provides `required` attributes (see section:- #3.4.1) + * Double-quotes values and escapes any '"' inside them + * Replaces the possibly dangerous soft-hyphen characters (hexadecimal code-point 'ad') in the values with spaces + * Allows custom function to additionally filter/modify attribute values (see section:- #3.4.9) + + +.. 3.4.1 Auto-addition of XHTML-required attributes ................ + + + If indicated attributes for the following elements are found missing, htmLawed (function 'hl_tag()') will add them (with values same as attribute names unless indicated otherwise below): + + * area - alt ('area') + * area, img - src, alt ('image') + * bdo - dir ('ltr') + * form - action + * map - name + * optgroup - label + * param - name + * script - type ('text/javascript') + * textarea - rows ('10'), cols ('50') + + Additionally, with '$config["xml:lang"]' set to '1' or '2', if the 'lang' but not the 'xml:lang' attribute is declared, then the latter is added too, with a value copied from that of 'lang'. This is for better standard-compliance. With '$config["xml:lang"]' set to '2', the 'lang' attribute is removed (XHTML 1.1 specs). + + Note that the 'name' attribute for 'map', invalid in XHTML 1.1, is also transformed if required -- see section:- #3.4.6. + + +.. 3.4.2 Duplicate/invalid 'id' values ............................o + + + If '$config["unique_ids"]' is '1', htmLawed (function 'hl_tag()') removes 'id' attributes with values that are not XHTML-compliant (must begin with a letter and can contain letters, digits, ':', '.', '-' and '_') or duplicate. If '$config["unique_ids"]' is a word, any duplicate but otherwise valid value will be appropriately prefixed with the word to ensure its uniqueness. The word should begin with a letter and should contain only letters, numbers, ':', '.', '_' and '-'. + + Even if multiple inputs need to be filtered (through multiple calls to htmLawed), htmLawed ensures uniqueness of 'id' values as it uses a global variable ('$GLOBALS["hl_Ids"]' array). Further, an admin can restrict the use of certain 'id' values by presetting this variable before htmLawed is called into use. E.g.: + + $GLOBALS['hl_Ids'] = array('top'=>1, 'bottom'=>1, 'myform'=>1); // id values not allowed in input + $processed = htmLawed($text); // filter input + + +.. 3.4.3 URL schemes (protocols) and scripts in attribute values ............o + + + htmLawed edits attributes that take URLs as values if they are found to contain un-permitted schemes. E.g., if the 'afp' scheme is not permitted, then '' becomes '', and if Javascript is not permitted '' becomes ''. + + By default htmLawed permits these schemes in URLs for the 'href' attribute: + + aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet + + Also, only 'file', 'http' and 'https' are permitted in attributes whose names start with 'o' (like 'onmouseover'), and in these attributes that accept URLs: + + action, cite, classid, codebase, data, href, longdesc, model, pluginspage, pluginurl, src, style, usemap + + These default sets are used when '$config["schemes"]' is not set (see section:- #2.2). To over-ride the defaults, '$config["schemes"]' is defined as a string of semi-colon-separated sub-strings of type 'attribute: comma-separated schemes'. E.g., 'href: mailto, http, https; onclick: javascript; src: http, https'. For unspecified attributes, 'file', 'http' and 'https' are permitted. This can be changed by passing schemes for '*' in '$config["schemes"]'. E.g., 'href: mailto, http, https; *: https, https'. + + '*' can be put in the list of schemes to permit all protocols. E.g., 'style: *; img: http, https' results in protocols not being checked in 'style' attribute values. However, in such cases, any relative-to-absolute URL conversion, or vice versa, (section:- #3.4.4) is not done. + + Thus, `to allow Javascript`, one can set '$config["schemes"]' as 'href: mailto, http, https; *: http, https, javascript', or 'href: mailto, http, https, javascript; *: http, https, javascript', or '*: *', and so on. + + As a side-note, one may find 'style: *' useful as URLs in 'style' attributes can be specified in a variety of ways, and the patterns that htmLawed uses to identify URLs may mistakenly identify non-URL text. + + *Note*: If URL-accepting attributes other than those listed above are being allowed, then the scheme will not be checked unless the attribute name contains the string 'src' (e.g., 'dynsrc') or starts with 'o' (e.g., 'onbeforecopy'). + + With '$config["safe"] = 1', all URLs are disallowed in the 'style' attribute values. + + +.. 3.4.4 Absolute & relative URLs in attribute values .............o + + + htmLawed can make absolute URLs in attributes like 'href' relative ('$config["abs_url"]' is '-1'), and vice versa ('$config["abs_url"]' is '1'). URLs in scripts are not considered for this, and so are URLs like '#section_6' (fragment), '?name=Tim#show' (starting with query string), and ';var=1?name=Tim#show' (starting with parameters). Further, this requires that '$config["base_url"]' be set properly, with the '://' and a trailing slash ('/'), with no query string, etc. E.g., 'file:///D:/page/', 'https://abc.com/x/y/', or 'http://localhost/demo/' are okay, but 'file:///D:/page/?help=1', 'abc.com/x/y/' and 'http://localhost/demo/index.htm' are not. + + For making absolute URLs relative, only those URLs that have the '$config["base_url"]' string at the beginning are converted. E.g., with '$config["base_url"] = "https://abc.com/x/y/"', 'https://abc.com/x/y/a.gif' and 'https://abc.com/x/y/z/b.gif' become 'a.gif' and 'z/b.gif' respectively, while 'https://abc.com/x/c.gif' is not changed. + + When making relative URLs absolute, only values for scheme, network location (host-name) and path values in the base URL are inherited. See section:- #5.5 for more about the URL specification as per RFC 1808:- http://www.ietf.org/rfc/rfc1808.txt. + + +.. 3.4.5 Lower-cased, standard attribute values ....................o + + + Optionally, for standard-compliance, htmLawed (function 'hl_tag()') lower-cases standard attribute values to give, e.g., 'input type="password"' instead of 'input type="Password"', if '$config["lc_std_val"]' is '1'. Attribute values matching those listed below for any of the elements (plus those for the 'type' attribute of 'button' or 'input') are lower-cased: + + all, baseline, bottom, button, center, char, checkbox, circle, col, colgroup, cols, data, default, file, get, groups, hidden, image, justify, left, ltr, middle, none, object, password, poly, post, preserve, radio, rect, ref, reset, right, row, rowgroup, rows, rtl, submit, text, top + + a, area, bdo, button, col, form, img, input, object, option, optgroup, param, script, select, table, td, tfoot, th, thead, tr, xml:space + + The following `empty` (`minimized`) attributes are always assigned lower-cased values (same as the names): + + checked, compact, declare, defer, disabled, ismap, multiple, nohref, noresize, noshade, nowrap, readonly, selected + + +.. 3.4.6 Transformation of deprecated attributes ..................o + + + If '$config["no_deprecated_attr"]' is '0', then deprecated attributes (see appendix in section:- #5.2) are removed and, in most cases, their values are transformed to CSS style properties and added to the 'style' attributes (function 'hl_tag()'). Except for 'bordercolor' for 'table', 'tr' and 'td', the scores of proprietary attributes that were never part of any cross-browser standard are not supported. + + *Note*: The attribute 'target' for 'a' is allowed even though it is not in XHTML 1.0 specs. This is because of the attribute's wide-spread use and browser-support, and because the attribute is valid in XHTML 1.1 onwards. + + * align - for 'img' with value of 'left' or 'right', becomes, e.g., 'float: left'; for 'div' and 'table' with value 'center', becomes 'margin: auto'; all others become, e.g., 'text-align: right' + + * bgcolor - E.g., 'bgcolor="#ffffff"' becomes 'background-color: #ffffff' + * border - E.g., 'height= "10"' becomes 'height: 10px' + * bordercolor - E.g., 'bordercolor=#999999' becomes 'border-color: #999999;' + * compact - 'font-size: 85%' + * clear - E.g., 'clear="all" becomes 'clear: both' + + * height - E.g., 'height= "10"' becomes 'height: 10px' and 'height="*"' becomes 'height: auto' + + * hspace - E.g., 'hspace="10"' becomes 'margin-left: 10px; margin-right: 10px' + * language - 'language="VBScript"' becomes 'type="text/vbscript"' + * name - E.g., 'name="xx"' becomes 'id="xx"' + * noshade - 'border-style: none; border: 0; background-color: gray; color: gray' + * nowrap - 'white-space: nowrap' + * size - E.g., 'size="10"' becomes 'height: 10px' + * start - removed + * type - E.g., 'type="i"' becomes 'list-style-type: lower-roman' + * value - removed + * vspace - E.g., 'vspace="10"' becomes 'margin-top: 10px; margin-bottom: 10px' + * width - like 'height' + + Example input: + + imageimage +
    +
    + image + + + + + +
    +
    +

    Section

    +

    Para

    +
    1. First item
    +
    +
    +
    1. First item
    +
    +
    + + And the output with '$config["no_deprecated_attr"] = 1': + + imageimage +
    +
    + image + + + + + +
    +
    +

    Section

    +

    Para

    +
    1. First item
    +
    +
    +
    1. First item
    +
    +
    + + For 'lang', deprecated in XHTML 1.1, transformation is taken care of through '$config["xml:lang"]'; see section:- #3.4.1. + + The attribute 'name' is deprecated in 'form', 'iframe', and 'img', and is replaced with 'id' if an 'id' attribute doesn't exist and if the 'name' value is appropriate for 'id'. For such replacements for 'a' and 'map', for which the 'name' attribute is deprecated in XHTML 1.1, '$config["no_deprecated_attr"]' should be set to '2' (when set to '1', for these two elements, the 'name' attribute is retained). + + +-- 3.4.7 Anti-spam & 'href' ---------------------------------------o + + + htmLawed (function 'hl_tag()') can check the 'href' attribute values (link addresses) as an anti-spam (email or link spam) measure. + + If '$config["anti_mail_spam"]' is not '0', the '@' of email addresses in 'href' values like 'mailto:a@b.com' is replaced with text specified by '$config["anti_mail_spam"]'. The text should be of a form that makes it clear to others that the address needs to be edited before a mail is sent; e.g., '@' (makes the example address 'a@b.com'). + + For regular links, one can choose to have a 'rel' attribute with 'nofollow' in its value (which tells some search engines to not follow a link). This can discourage link spammers. Additionally, or as an alternative, one can choose to empty the 'href' value altogether (disable the link). + + For use of these options, '$config["anti_link_spam"]' should be set as an array with values 'regex1' and 'regex2', both or one of which can be empty (like 'array("", "regex2")') to indicate that that option is not to be used. Otherwise, 'regex1' or 'regex2' should be PHP- and PCRE-compatible regular expression patterns: 'href' values will be matched against them and those matching the pattern will accordingly be treated. + + Note that the regular expressions should have `delimiters`, and be well-formed and preferably fast. Absolute efficiency/accuracy is often not needed. + + An example, to have a 'rel' attribute with 'nofollow' for all links, and to disable links that do not point to domains 'abc.com' and 'xyz.org': + + $config["anti_link_spam"] = array('`.`', '`://\W*(?!(abc\.com|xyz\.org))`'); + + +-- 3.4.8 Inline style properties ----------------------------------o + + + htmLawed can check URL schemes and dynamic expressions (to guard against Javascript, etc., script-based insecurities) in inline CSS style property values in the 'style' attributes. (CSS properties like 'background-image' that accept URLs in their values are noted in section:- #5.3.) Dynamic CSS expressions that allow scripting in the IE browser, and can be a vulnerability, can be removed from property values by setting '$config["css_expression"]' to '1' (default setting). + + *Note*: Because of the various ways of representing characters in attribute values (URL-escapement, entitification, etc.), htmLawed might alter the values of the 'style' attribute values, and may even falsely identify dynamic CSS expressions and URL schemes in them. If this is an important issue, checking of URLs and dynamic expressions can be turned off ('$config["schemes"] = "...style:*..."', see section:- #3.4.3, and '$config["css_expression"] = 0'). Alternately, admins can use their own custom function for finer handling of 'style' values through the 'hook_tag' parameter (see section:- #3.4.9). + + It is also possible to have htmLawed let through any 'style' value by setting '$config["style_pass"]' to '1'. + + As such, it is better to set up a CSS file with class declarations, disallow the 'style' attribute, set a '$spec' rule (see section:- #2.3) for 'class' for the 'oneof' or 'match' parameter, and ask writers to make use of the 'class' attribute. + + +-- 3.4.9 Hook function for tag content ----------------------------o + + + It is possible to utilize a custom hook function to alter the tag content htmLawed has finalized (i.e., after it has checked/corrected for required attributes, transformed attributes, lower-cased attribute names, etc.). + + When '$config' parameter 'hook_tag' is set to the name of a function, htmLawed (function 'hl_tag()') will pass on the element name, and the `finalized` attribute name-value pairs as array elements to the function. The function is expected to return the full opening tag string like '' (for empty elements like 'img' and 'input', the element-closing slash '/' should also be included). + + This is a *powerful functionality* that can be exploited for various objectives: consolidate-and-convert inline 'style' attributes to 'class', convert 'embed' elements to 'object', permit only one 'caption' element in a 'table' element, disallow embedding of certain types of media, *inject HTML*, use CSSTidy:- http://csstidy.sourceforge.net to sanitize 'style' attribute values, etc. + + As an example, the custom hook code below can be used to force a series of specifically ordered 'id' attributes on all elements, and a specific 'param' element inside all 'object' elements: + + function my_tag_function($element, $attribute_array){ + static $id = 0; + // Remove any duplicate element + if($element == 'param' && isset($attribute_array['allowscriptaccess'])){ + return ''; + } + + $new_element = ''; + + // Force a serialized ID number + $attribute_array['id'] = 'my_'. $id; + ++$id; + + // Inject param for allowscriptaccess + if($element == 'object'){ + $new_element = ''; + ++$id; + } + + $string = ''; + foreach($attribute_array as $k=>$v){ + $string .= " {$k}=\"{$v}\""; + } + return "<{$element}{$string}". (isset($in_array($element, $empty_elements) ? ' /' : ''). '>'. $new_element; + } + + The 'hook_tag' parameter is different from the 'hook' parameter (section:- #3.7). + + Snippets of hook function code developed by others may be available on the htmLawed:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed website. + + +-- 3.5 Simple configuration directive for most valid XHTML -------oo + + + If '$config["valid_xhtml"]' is set to '1', some relevant '$config' parameters (indicated by '~' in section:- #2.2) are auto-adjusted. This allows one to pass the '$config' argument with a simpler value. If a value for a parameter auto-set through 'valid_xhtml' is still manually provided, then that value will over-ride the auto-set value. + + +-- 3.6 Simple configuration directive for most `safe` HTML --------o + + + `Safe` HTML refers to HTML that is restricted to reduce the vulnerability for scripting attacks (such as XSS) based on HTML code which otherwise may still be legal and compliant with the HTML standard specs. When elements such as 'script' and 'object', and attributes such as 'onmouseover' and 'style' are allowed in the input text, an input writer can introduce malevolent HTML code. Note that what is considered 'safe' depends on the nature of the web application and the trust-level accorded to its users. + + htmLawed allows an admin to use '$config["safe"]' to auto-adjust multiple '$config' parameters (such as 'elements' which declares the allowed element-set), which otherwise would have to be manually set. The relevant parameters are indicated by '"' in section:- #2.2). Thus, one can pass the '$config' argument with a simpler value. + + With the value of '1', htmLawed considers 'CDATA' sections and HTML comments as plain text, and prohibits the 'applet', 'embed', 'iframe', 'object' and 'script' elements, and the 'on*' attributes like 'onclick'. ( There are '$config' parameters like 'css_expression' that are not affected by the value set for 'safe' but whose default values still contribute towards a more `safe` output.) Further, URLs with schemes (see section:- #3.4.3) are neutralized so that, e.g., 'style="moz-binding:url(http://danger)"' becomes 'style="moz-binding:url(denied:http://danger)"' while 'style="moz-binding:url(ok)"' remains intact. + + Admins, however, may still want to completely deny the 'style' attribute, e.g., with code like + + $processed = htmLawed($text, array('safe'=>1, 'deny_attribute'=>'style')); + + If a value for a parameter auto-set through 'safe' is still manually provided, then that value can over-ride the auto-set value. E.g., with '$config["safe"] = 1' and '$config["elements"] = "*+script"', 'script', but not 'applet', is allowed. + + A page illustrating the efficacy of htmLawed's anti-XSS abilities with 'safe' set to '1' against XSS vectors listed by RSnake:- http://ha.ckers.org/xss.html may be available here:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/rsnake/RSnakeXSSTest.htm. + + +-- 3.7 Using a hook function --------------------------------------o + + + If '$config["hook"]' is not set to '0', then htmLawed will allow preliminarily processed input to be altered by a hook function named by '$config["hook"]' before starting the main work (but after handling of characters, entities, HTML comments and 'CDATA' sections -- see code for function 'htmLawed()'). + + The hook function also allows one to alter the `finalized` values of '$config' and '$spec'. + + Note that the 'hook' parameter is different from the 'hook_tag' parameter (section:- #3.4.9). + + Snippets of hook function code developed by others may be available on the htmLawed:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed website. + + +-- 3.8 Obtaining `finalized` parameter values ---------------------o + + + htmLawed can assign the `finalized` '$config' and '$spec' values to a variable named by '$config["show_setting"]'. The variable, made global by htmLawed, is set as an array with three keys: 'config', with the '$config' value, 'spec', with the '$spec' value, and 'time', with a value that is the Unix time (the output of PHP's 'microtime()' function) when the value was assigned. Admins should use a PHP-compliant variable name (e.g., one that does not begin with a numerical digit) that does not conflict with variable names in their non-htmLawed code. + + The values, which are also post-hook function (if any), can be used to auto-generate information (on, e.g., the elements that are permitted) for input writers. + + +-- 3.9 Retaining non-HTML tags in input with mixed markup ---------o + + + htmLawed does not remove certain characters that though invalid are nevertheless discouraged in HTML documents as per the specs (see section:- #5.1). This can be utilized to deal with input that contains mixed markup. Input that may have HTML markup as well as some other markup that is based on the '<', '>' and '&' characters is considered to have mixed markup. The non-HTML markup can be rather proprietary (like markup for emoticons/smileys), or standard (like MathML or SVG). Or it can be programming code meant for execution/evaluation (such as embedded PHP code). + + To deal with such mixed markup, the input text can be pre-processed to hide the non-HTML markup by specifically replacing the '<', '>' and '&' characters with some of the HTML-discouraged characters (see section:- #3.1.2). Post-htmLawed processing, the replacements are reverted. + + An example (mixed HTML and PHP code in input text): + + $text = preg_replace('`<\?php(.+?)\?>`sm', "\x83?php\\1?\x84", $text); + $processed = htmLawed($text); + $processed = preg_replace('`\x83\?php(.+?)\?\x84`sm', '', $processed); + + This code will not work if '$config["clean_ms_char"]' is set to '1' (section:- #3.1), in which case one should instead deploy a hook function (section:- #3.7). (htmLawed internally uses certain control characters, code-points '1' to '7', and use of these characters as markers in the logic of hook functions may cause issues.) + + Admins may also be able to use '$config["and_mark"]' to deal with such mixed markup; see section:- #3.2. + + +== 4 Other =======================================================oo + + +-- 4.1 Support ----------------------------------------------------- + + + A careful re-reading of this documentation will very likely answer your questions. + + Software updates and forum-based community-support may be found at http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed. For general PHP issues (not htmLawed-specific), support may be found through internet searches and at http://php.net. + + +-- 4.2 Known issues -----------------------------------------------o + + + See section:- #2.8. + + Readers are advised to cross-check information given in this document. + + +-- 4.3 Change-log -------------------------------------------------o + + + (The release date for the downloadable package of files containing documentation, demo script, test-cases, etc., besides the 'htmLawed.php' file may be updated independently if the secondary files are revised.) + + `Version number - Release date. Notes` + + 1.1.8.1 - 16 July 2009. Minor code-change to fix a PHP error notice + + 1.1.8 - 23 April 2009. Parameter 'deny_attribute' now accepts the wild-card '*', making it simpler to specify its value when all but a few attributes are being denied; fixed a bug in interpreting '$spec' + + 1.1.7 - 11-12 March 2009. Attributes globally denied through 'deny_attribute' can be allowed element-specifically through '$spec'; '$config["style_pass"]' allowing letting through any 'style' value introduced; altered logic to catch certain types of dynamic crafted CSS expressions + + 1.1.3-6 - 28-31 January - 4 February 2009. Altered logic to catch certain types of dynamic crafted CSS expressions + + 1.1.2 - 22 January 2009. Fixed bug in parsing of 'font' attributes during tag transformation + + 1.1.1 - 27 September 2008. Better nesting correction when omitable closing tags are absent + + 1.1 - 29 June 2008. '$config["hook_tag"]' and '$config["format"]' introduced for custom tag/attribute check/modification/injection and output compaction/beautification; fixed a regex-in-$spec parsing bug + + 1.0.9 - 11 June 2008. Fixed bug in invalid HTML code-point entity check + + 1.0.8 - 15 May 2008. 'bordercolor' attribute for 'table', 'td' and 'tr' + + 1.0.7 - 1 May 2008. Support for 'wmode' attribute for 'embed'; '$config["show_setting"]' introduced; improved '$config["elements"]' evaluation + + 1.0.6 - 20 April 2008. '$config["and_mark"]' introduced + + 1.0.5 - 12 March 2008. 'style' URL schemes essentially disallowed when $config 'safe' is on; improved regex for CSS expression search + + 1.0.4 - 10 March 2008. Improved corrections for 'blockquote', 'form', 'map' and 'noscript' + + 1.0.3 - 3 March 2008. Character entities for soft-hyphens are now replaced with spaces (instead of being removed); a bug allowing 'td' directly inside 'table' fixed; 'safe' '$config' parameter added + + 1.0.2 - 13 February 2008. Improved implementation of '$config["keep_bad"]' + + 1.0.1 - 7 November 2007. Improved regex for identifying URLs, protocols and dynamic expressions ('hl_tag()' and 'hl_prot()'); no error display with 'hl_regex()' + + 1.0 - 2 November 2007. First release + + +-- 4.4 Testing ----------------------------------------------------o + + + To test htmLawed using a form interface, a demo:- htmLawedTest.php web-page is provided with the htmLawed distribution ('htmLawed.php' and 'htmLawedTest.php' should be in the same directory on the web-server). A file with test-cases:- htmLawed_TESTCASE.txt is also provided. + + +-- 4.5 Upgrade, & old versions ------------------------------------o + + + Upgrading is as simple as replacing the previous version of 'htmLawed.php' (assuming it was not modified for customized features). As htmLawed output is almost always used in static documents, upgrading should not affect old, finalized content. + + Old versions of htmLawed may be available online. E.g., for version 1.0, check http://www.bioinformatics.org/phplabware/downloads/htmLawed1.zip, for 1.1.1, htmLawed111.zip, and for 1.1.10, htmLawed1110.zip. + + +-- 4.6 Comparison with 'HTMLPurifier' -----------------------------o + + + The HTMLPurifier PHP library by Edward Yang is a very good HTML filtering script that uses object oriented PHP code. Compared to htmLawed, it: + + * does not support PHP versions older than 5.0 (HTMLPurifier dropped PHP 4 support after version 2) + + * is 15-20 times bigger (scores of files totalling more than 750 kb) + + * consumes 10-15 times more RAM memory (just including the HTMLPurifier files without calling the filter requires a few MBs of memory) + + * is expectedly slower + + * does not allow admins to fully allow all valid HTML (because of incomplete HTML support, it always considers elements like 'script' illegal) + + * lacks many of the extra features of htmLawed (like entity conversions and code compaction/beautification) + + * has poor documentation + + However, HTMLPurifier has finer checks for character encodings and attribute values, and can log warnings and errors. Visit the HTMLPurifier website:- http://htmlpurifier.org for updated information. + + +-- 4.7 Use through application plug-ins/modules -------------------o + + + Plug-ins/modules to implement htmLawed in applications such as Drupal and DokuWiki may have been developed. Please check the application websites and the forum on the htmLawed site:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed. + + +-- 4.8 Use in non-PHP applications --------------------------------o + + + Non-PHP applications written in Python, Ruby, etc., may be able to use htmLawed through system calls to the PHP engine. Such code may have been documented on the internet. Also check the forum on the htmLawed site:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed. + + +-- 4.9 Donate -----------------------------------------------------o + + + A donation in any currency and amount to appreciate or support this software can be sent by PayPal:- http://paypal.com to this email address: drpatnaik at yahoo dot com. + + +-- 4.10 Acknowledgements ------------------------------------------o + + + Bryan Blakey, Ulf Harnhammer, Gareth Heyes, Lukasz Pilorz, Shelley Powers, Edward Yang, and many anonymous users. + + Thank you! + + +== 5 Appendices ==================================================oo + + +-- 5.1 Characters discouraged in XHTML ----------------------------- + + + Characters represented by the following hexadecimal code-points are `not` invalid, even though some validators may issue messages stating otherwise. + + '7f' to '84', '86' to '9f', 'fdd0' to 'fddf', '1fffe', '1ffff', '2fffe', '2ffff', '3fffe', '3ffff', '4fffe', '4ffff', '5fffe', '5ffff', '6fffe', '6ffff', '7fffe', '7ffff', '8fffe', '8ffff', '9fffe', '9ffff', 'afffe', 'affff', 'bfffe', 'bffff', 'cfffe', 'cffff', 'dfffe', 'dffff', 'efffe', 'effff', 'ffffe', 'fffff', '10fffe' and '10ffff' + + +-- 5.2 Valid attribute-element combinations -----------------------o + + + Valid attribute-element combinations as per W3C specs. + + * includes deprecated attributes (marked '^'), attributes for the non-standard 'embed' element (marked '*'), and the proprietary 'bordercolor' (marked '~') + * only non-frameset, HTML body elements + * 'name' for 'a' and 'map', and 'lang' are invalid in XHTML 1.1 + * 'target' is valid for 'a' in XHTML 1.1 and higher + * 'xml:space' is only for XHTML 1.1 + + abbr - td, th + accept - form, input + accept-charset - form + accesskey - a, area, button, input, label, legend, textarea + action - form + align - caption^, embed, applet, iframe, img^, input^, object^, legend^, table^, hr^, div^, h1^, h2^, h3^, h4^, h5^, h6^, p^, col, colgroup, tbody, td, tfoot, th, thead, tr + alt - applet, area, img, input + archive - applet, object + axis - td, th + bgcolor - embed, table^, tr^, td^, th^ + border - table, img^, object^ + bordercolor~ - table, td, tr + cellpadding - table + cellspacing - table + char - col, colgroup, tbody, td, tfoot, th, thead, tr + charoff - col, colgroup, tbody, td, tfoot, th, thead, tr + charset - a, script + checked - input + cite - blockquote, q, del, ins + classid - object + clear - br^ + code - applet + codebase - object, applet + codetype - object + color - font + cols - textarea + colspan - td, th + compact - dir, dl^, menu, ol^, ul^ + coords - area, a + data - object + datetime - del, ins + declare - object + defer - script + dir - bdo + disabled - button, input, optgroup, option, select, textarea + enctype - form + face - font + for - label + frame - table + frameborder - iframe + headers - td, th + height - embed, iframe, td^, th^, img, object, applet + href - a, area + hreflang - a + hspace - applet, img^, object^ + ismap - img, input + label - option, optgroup + language - script^ + longdesc - img, iframe + marginheight - iframe + marginwidth - iframe + maxlength - input + method - form + model* - embed + multiple - select + name - button, embed, textarea, applet^, select, form^, iframe^, img^, a^, input, object, map^, param + nohref - area + noshade - hr^ + nowrap - td^, th^ + object - applet + onblur - a, area, button, input, label, select, textarea + onchange - input, select, textarea + onfocus - a, area, button, input, label, select, textarea + onreset - form + onselect - input, textarea + onsubmit - form + pluginspage* - embed + pluginurl* - embed + prompt - isindex + readonly - textarea, input + rel - a + rev - a + rows - textarea + rowspan - td, th + rules - table + scope - td, th + scrolling - iframe + selected - option + shape - area, a + size - hr^, font, input, select + span - col, colgroup + src - embed, script, input, iframe, img + standby - object + start - ol^ + summary - table + tabindex - a, area, button, input, object, select, textarea + target - a^, area, form + type - a, embed, object, param, script, input, li^, ol^, ul^, button + usemap - img, input, object + valign - col, colgroup, tbody, td, tfoot, th, thead, tr + value - input, option, param, button, li^ + valuetype - param + vspace - applet, img^, object^ + width - embed, hr^, iframe, img, object, table, td^, th^, applet, col, colgroup, pre^ + wmode - embed + xml:space - pre, script, style + + These are allowed in all but the shown elements: + + class - param, script + dir - applet, bdo, br, iframe, param, script + id - script + lang - applet, br, iframe, param, script + onclick - applet, bdo, br, font, iframe, isindex, param, script + ondblclick - applet, bdo, br, font, iframe, isindex, param, script + onkeydown - applet, bdo, br, font, iframe, isindex, param, script + onkeypress - applet, bdo, br, font, iframe, isindex, param, script + onkeyup - applet, bdo, br, font, iframe, isindex, param, script + onmousedown - applet, bdo, br, font, iframe, isindex, param, script + onmousemove - applet, bdo, br, font, iframe, isindex, param, script + onmouseout - applet, bdo, br, font, iframe, isindex, param, script + onmouseover - applet, bdo, br, font, iframe, isindex, param, script + onmouseup - applet, bdo, br, font, iframe, isindex, param, script + style - param, script + title - param, script + xml:lang - applet, br, iframe, param, script + + +-- 5.3 CSS 2.1 properties accepting URLs ------------------------o + + + background + background-image + content + cue-after + cue-before + cursor + list-style + list-style-image + play-during + + +-- 5.4 Microsoft Windows 1252 character replacements --------------o + + + Key: 'd' double, 'l' left, 'q' quote, 'r' right, 's.' single + + Code-point (decimal) - hexadecimal value - replacement entity - represented character + + 127 - 7f - (removed) - (not used) + 128 - 80 - € - euro + 129 - 81 - (removed) - (not used) + 130 - 82 - ‚ - baseline s. q + 131 - 83 - ƒ - florin + 132 - 84 - „ - baseline d q + 133 - 85 - … - ellipsis + 134 - 86 - † - dagger + 135 - 87 - ‡ - d dagger + 136 - 88 - ˆ - circumflex accent + 137 - 89 - ‰ - permile + 138 - 8a - Š - S Hacek + 139 - 8b - ‹ - l s. guillemet + 140 - 8c - Œ - OE ligature + 141 - 8d - (removed) - (not used) + 142 - 8e - Ž - Z dieresis + 143 - 8f - (removed) - (not used) + 144 - 90 - (removed) - (not used) + 145 - 91 - ‘ - l s. q + 146 - 92 - ’ - r s. q + 147 - 93 - “ - l d q + 148 - 94 - ” - r d q + 149 - 95 - • - bullet + 150 - 96 - – - en dash + 151 - 97 - — - em dash + 152 - 98 - ˜ - tilde accent + 153 - 99 - ™ - trademark + 154 - 9a - š - s Hacek + 155 - 9b - › - r s. guillemet + 156 - 9c - œ - oe ligature + 157 - 9d - (removed) - (not used) + 158 - 9e - ž - z dieresis + 159 - 9f - Ÿ - Y dieresis + + +-- 5.5 URL format -------------------------------------------------o + + + An `absolute` URL has a 'protocol' or 'scheme', a 'network location' or 'hostname', and, optional 'path', 'parameters', 'query' and 'fragment' segments. Thus, an absolute URL has this generic structure: + + (scheme) : (//network location) /(path) ;(parameters) ?(query) #(fragment) + + The schemes can only contain letters, digits, '+', '.' and '-'. Hostname is the portion after the '//' and up to the first '/' (if any; else, up to the end) when ':' is followed by a '//' (e.g., 'abc.com' in 'ftp://abc.com/def'); otherwise, it consists of everything after the ':' (e.g., 'def@abc.com' in mailto:def@abc.com'). + + `Relative` URLs do not have explicit schemes and network locations; such values are inherited from a `base` URL. + + +-- 5.6 Brief on htmLawed code -------------------------------------o + + + Much of the code's logic and reasoning can be understood from the documentation above. + + The *output* of htmLawed is a text string containing the processed input. There is no custom error tracking. + + *Function arguments* for htmLawed are: + + * '$in' - 1st argument; a text string; the *input text* to be processed. Any extraneous slashes added by PHP when `magic quotes` are enabled should be removed beforehand using PHP's 'stripslashes()' function. + + * '$config' - 2nd argument; an associative array; optional (named '$C' in htmLawed code). The array has keys with names like 'balance' and 'keep_bad', and the values, which can be boolean, string, or array, depending on the key, are read to accordingly set the *configurable parameters* (indicated by the keys). All configurable parameters receive some default value if the value to be used is not specified by the user through '$config'. `Finalized` '$config' is thus a filtered and possibly larger array. + + * '$spec' - 3rd argument; a text string; optional. The string has rules, written in an htmLawed-designated format, *specifying* element-specific attribute and attribute value restrictions. Function 'hl_spec()' is used to convert the string to an associative-array for internal use. `Finalized` '$spec' is thus an array. + + `Finalized` '$config' and '$spec' are made *global variables* while htmLawed is at work. Values of any pre-existing global variables with same names are noted, and their values are restored after htmLawed finishes processing the input (to capture the `finalized` values, the 'show_settings' parameter of '$config' should be used). Depending on '$config', another global variable 'hl_Ids', to track 'id' attribute values for uniqueness, may be set. Unlike the other two variables, this one is not reset (or unset) post-processing. + + Except for the main function 'htmLawed()' and the functions 'kses()' and 'kses_hook()', htmLawed's functions are *name-spaced* using the 'hl_' prefix. The *functions* and their roles are: + + * 'hl_attrval' - checking attribute values against $spec + * 'hl_bal' - tag balancing + * 'hl_cmtcd' - handling CDATA sections and HTML comments + * 'hl_ent' - entity handling + * 'hl_prot' - checking a URL scheme/protocol + * 'hl_regex' - checking syntax of a regular expression + * 'hl_spec' - converting user-supplied $spec value to one used by htmLawed internally + * 'hl_tag' - handling tags + * 'hl_tag2' - transforming tags + * 'hl_tidy' - compact/beautify HTML + * 'hl_version' - reporting htmLawed version + * 'htmLawed' - main function + * 'kses' - main function of 'kses' + * 'kses_hook' - hook function of 'kses' + + The last two are for compatibility with pre-existing code using the 'kses' script. htmLawed's 'kses()' basically passes on the filtering task to 'htmLawed()' function after deciphering '$config' and '$spec' from the argument values supplied to it. 'kses_hook()' is an empty function and is meant for being filled with custom code if the 'kses' script users were using one. + + 'htmLawed()' finalizes '$spec' (with the help of 'hl_spec()') and '$config', and globalizes them. Finalization of '$config' involves setting default values if an inappropriate or invalid one is supplied. This includes calling 'hl_regex()' to check well-formedness of regular expression patterns if such expressions are user-supplied through '$config'. 'htmLawed()' then removes invalid characters like nulls and 'x01' and appropriately handles entities using 'hl_ent()'. HTML comments and CDATA sections are identified and treated as per '$config' with the help of 'hl_cmtcd()'. When retained, the '<' and '>' characters identifying them, and the '<', '>' and '&' characters inside them, are replaced with control characters (code-points '1' to '5') till any tag balancing is completed. + + After this `initial processing` 'htmLawed()' identifies tags using regex and processes them with the help of 'hl_tag()' -- a large function that analyzes tag content, filtering it as per HTML standards, '$config' and '$spec'. Among other things, 'hl_tag()' transforms deprecated elements using 'hl_tag2()', removes attributes from closing tags, checks attribute values as per '$spec' rules using 'hl_attrval()', and checks URL protocols using 'hl_prot()'. 'htmLawed()' performs tag balancing and nesting checks with a call to 'hl_bal()', and optionally compacts/beautifies the output with proper white-spacing with a call to 'hl_tidy()'. The latter temporarily replaces white-space, and '<', '>' and '&' characters inside 'pre', 'script' and 'textarea' elements, and HTML comments and CDATA sections with control characters (code-points '1' to '5', and '7'). + + htmLawed permits the use of custom code or *hook functions* at two stages. The first, called inside 'htmLawed()', allows the input text as well as the finalized $config and $spec values to be altered right after the initial processing (see section:- #3.7). The second is called by 'hl_tag()' once the tag content is finalized (see section:- #3.4.9). + + Being dictated by the external and stable HTML standard, htmLawed's objective is very clear-cut and less concerned with tweakability. The code is only minimally annotated with comments -- it is not meant to instruct; PHP developers familiar with the HTML specs will see the logic, and others can always refer to the htmLawed documentation. The compact structuring of the statements is meant to aid in quickly grasping the logic, at least when viewed with code syntax highlighted. + +___________________________________________________________________oo + + +@@description: htmLawed PHP software is a free, open-source, customizable HTML input purifier and filter +@@encoding: utf-8 +@@keywords: htmLawed, HTM, HTML, HTML Tidy, converter, filter, formatter, purifier, sanitizer, XSS, input, PHP, software, code, script, security, cross-site scripting, hack, sanitize, remove, standards, tags, attributes, elements +@@language: en +@@title: htmLawed documentation \ No newline at end of file diff --git a/extlib/htmLawed/htmLawed_TESTCASE.txt b/extlib/htmLawed/htmLawed_TESTCASE.txt new file mode 100644 index 000000000..366465ce3 --- /dev/null +++ b/extlib/htmLawed/htmLawed_TESTCASE.txt @@ -0,0 +1,370 @@ +/* +htmLawed_TESTCASE.txt, 23 April 2009 +htmLawed 1.1.8.1, 16 July 2009 +Copyright Santosh Patnaik +GPL v3 license +A PHP Labware internal utility - http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed +*/ + +This file has UTF-8-encoded text with both correct and incorrect/malformed HTML/XHTML code snippets to test htmLawed (test cases/samples). The entire text may also be used as a unit. + +************************************************ +when viewing this file in a web browser, set the +character encoding to Unicode/UTF-8 +************************************************ + +--------------------- start -------------------- + +Try different $config and $spec values. Some text even when filtered in will not be displayed in a rendered web-page
    + +
    Attributes
    + +Xml:lang:
    , ,
    +Standard, predefined value, or empty attribute: , ,
    +Required: , image
    +Quote & space variation: a, a, a
    +Invalid: a
    +Duplicated: a
    +Deprecated: a,

    +Casing:
    +Admin-restricted?: + +
    Attribute values
    + +Duplicate ID value:, ,
    +(try 'my_' for prefix)
    +Double-quotes in value:, ,
    +(try filter for CSS expression)
    +CSS expression:

    +Other: ,
    +(try 'maxlen', 'maxval', etc., for 'input' in '$spec') + +
    Blockquotes
    + +
    abc

    +
    abc
    def

    +
    abc
    def

    +
    abc
    def
    ghi

    +abc
    def
    ghi
    +(try with blockquote parent) + +
    CDATA sections
    + +Special characters inside: ]]>, 3.5, & 4 > 4 ]]>
    +Normal: , CDATA follows:
    +Malformed: , < ![CDATA check ]]>, , < ![CDATA check ] ]>
    +Invalid: >CDATA in tag content,
    text not allowed
    + +
    Complex-1: deprecated elements
    + +
    +The PHP software script used for this web-page webpage is htmLawedTest.php, from PHP Labware. +
    + +
    Complex-2: deprecated attributes
    + +aa +
    +
    +image + + + + + +
    +
    +

    Section

    +

    Para

    +
    1. First item
    +
    +
    +
    1. First item
    +
    +
    + +
    Complex-3: embed, object, area
    + +
    + +
    + + +

    navigate the site: 1 | 3 | 4

    + +
    + +
    Complex-4: nested and other tables
    + +
    Cell
    Cell
    Cell
    Cell Cell Cell
    Cell
    Cell Cell Cell

    +PCDATA wrong: Well
    Hello

    +Missing tr:
    Well

    + +
    Complex-5: pseudo, disallowed or non-HTML tags
    + +(Try different 'keep_bad' values) +<*> Pseudotags <*> +Non-HTML tag xml +

    +Disallowed tag p +

    +
      Bad
    • OK
    + +
    Elements
    + +Unbalanced: check
    +Non-XHTML:

    +Malformed: < a href="">, , , , < /a>, < a href="">, a, a,
    +Invalid: a
    +Empty: a, a, atext
    +Content invalid: 12
    +Content invalid?:

    (try setting 'form' as parent) +Casing: + +
    Entities
    + +Special: & 3 < 2 & 5>4 and j >i >a & ia
    +Padding: B B f f  
    +Malformed: & #x27;, &x27;, ' &TILDE;, &tilde
    +Invalid: , �, , �, ￿, &bad;
    +Discouraged characters: , „, ﷠, 􏿾
    +Context: '>', <?
    +Casing: ', ', &TILDE;, ˜ +
    +(also check named-to-numeric and hexdec-to-decimal, and vice versa, conversions) + +
    Format
    + +Valid but ill-formatted: text +text + text text
    p r e
    + text text

    +text none text +text none t e x t +
    text none t e x t + +text none t e x t + +
    +
    p r e  
    +
    +				pre
    +		
    +
    +
    Cell
    Cell
    Cell
    CellCellCell
    Cell
    CellCellCell
    +(try to compact or beautify) + +
    Forms
    + +(note nesting of 'form', missing required attributes, etc.)
    +
    + +
    pl
    + h + +

    +


    +
    B:C:

    +(try each of these lines separately)
    +
    what
    +what +(try with container as div and as form)
    +c a b + +
    HTML comments (also CDATA)
    + +Special characters inside: , , , c
    +Normal: , , comment:,
    text not allowed

    +Malformed: , < ![CDATA check ]]>, < ![CDATA check ] ]>
    +Invalid: >comment in tag content, + +
    Ins-Del
    + +(depending on context, these elements can be of either block or inline type)
    +

    block


    +

    d


    +

    d

    d

    d
    + +
    Lists
    + +Invalid character data:
    • (item
    • )

    +Definition list:
    a
    bad
    first one
    b
    second

    +Definition list, close-tags omitted:
    a
    bad
    first one
    b
    second

    +Definition lists, nested:
    +
    T1
    +
    D1
    +
    T2
    +
    D2
    t1
    d1
    t2
    d2
    +
    T3
    +
    D3
    +
    T4
    +
    D4
    t1
    d1
    +

    +Definition lists, nested, close-tags omitted:
    +
    T1 +
    D1
    +
    T2
    +
    D2
    t1
    d1
    t2
    d2
    +
    T3 +
    D3 +
    T4 +
    D4
    t1
    d1
    +

    +Nested:
      +
    • l1
    • +
    • l2
      1. lo1
      2. lo2
    • +
    • l3
    • +
    • l4
      1. lo3
      2. lo4
        1. lo5
    • +

    +Nested, close-tags omitted:
      +
    • l1
    • +
    • l2
      1. lo1
      2. lo2
      +
    • l3 +
    • l4
      1. lo3
      2. lo4
        1. lo5
      +

    +Complex: +
    1. +
      +
    + +
    Non-English text-1
    + +Inscrieţi-vă acum la a Zecea Conferinţă Internaţională
    +გთხოვთ ახლავე გაიაროთ რეგისტრაცია
    +večjezično računalništvo
    +Зарегистрируйтесь сейчас +на Десятую Международную Конференцию по
    +(this file should have utf-8 encoding; some characters may not be displayed because of missing fonts, etc.) + +
    Non-English text-2: entities
    + +用统一码
    +გთხოვთ
    +Inscreva-se agora para a Décima Conferência Internacional Sobre O Unicode, realizada entre os dias 10 e 12 de março de 1997 em Mainz +na Alemanha. + +
    Ruby
    + +(need compatible browser)
    + + + + + + + + + さい + とう + のぶ + + + + W3C Associate Chairman + +
    + + WWW + (World Wide Web) +
    + + A + (aaa) + + +
    Tables
    + +Omitted closing tags: ++ + +
    h1c1h1c2 +
    r1c1r1c2 +
    r2c1r2c2 +

    +Nested, omitted closing tags: ++ + +
    h1c1h1c2 +
    r1c1r1c2 ++ + +
    h1c1h1c2 +
    r1c1r1c2 +
    r2c1r2c2 +
    +
    r2c1r2c2 +

    + +
    URLs
    + +Relative and absolute: , , , , , ,
    +(try base URL value of 'http://a.com/b/')
    +CSS URLs:
    ,
    ,
    ,
    ,

    +Anti-spam: (try regex for 'http://a.com', etc.) , , , , , ,
    + +
    XSS
    + +'';!--"=&{()}
    +
    +
    +
    +
    +

    +

    +

    +
    +
    +

    +test
    +Bad IE7: x
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: xxx
    +Bad IE7: x
    +Bad IE7: x
    +Bad IE7: x
    +Bad IE7: x
    +Bad IE7: exp/*x
    +Bad IE7: hi
    +Bad IE7: hi
    +Bad IE7: test
    +Bad IE7: hi
    +Bad IE7: hi
    + +
    Other
    + +3 < 4
    +3 > 4
    + > 3
    \ No newline at end of file diff --git a/lib/attachmentlist.php b/lib/attachmentlist.php index f6a1b59d0..41d03f8e2 100644 --- a/lib/attachmentlist.php +++ b/lib/attachmentlist.php @@ -340,7 +340,12 @@ class Attachment extends AttachmentListItem case 'video': case 'link': if (!empty($this->oembed->html)) { - $this->out->raw($this->oembed->html); + require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php'; + $config = array( + 'safe'=>1, + 'elements'=>'*+object+embed'); + $this->out->raw(htmLawed($this->oembed->html,$config)); + //$this->out->raw($this->oembed->html); } break; -- cgit v1.2.3-54-g00ecf From a5f78449b1d1f6a517727388cfbd350914d66b6e Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 27 Jul 2009 13:51:40 -0400 Subject: better check for existing DB connection runs SET NAMES UTF8 less --- classes/Memcached_DataObject.php | 69 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/classes/Memcached_DataObject.php b/classes/Memcached_DataObject.php index f7cbb9d5b..ea070ec84 100644 --- a/classes/Memcached_DataObject.php +++ b/classes/Memcached_DataObject.php @@ -241,10 +241,19 @@ class Memcached_DataObject extends DB_DataObject function _connect() { global $_DB_DATAOBJECT; - $exists = !empty($this->_database_dsn_md5) && - isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]); + + $sum = $this->_getDbDsnMD5(); + + if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) && + !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) { + $exists = true; + } else { + $exists = false; + } + $result = parent::_connect(); - if (!$exists) { + + if ($result && !$exists) { $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]; if (common_config('db', 'type') == 'mysql' && common_config('db', 'utf8')) { @@ -258,7 +267,61 @@ class Memcached_DataObject extends DB_DataObject } } } + return $result; } + // XXX: largely cadged from DB_DataObject + + function _getDbDsnMD5() + { + if ($this->_database_dsn_md5) { + return $this->_database_dsn_md5; + } + + $dsn = $this->_getDbDsn(); + + if (is_string($dsn)) { + $sum = md5($dsn); + } else { + /// support array based dsn's + $sum = md5(serialize($dsn)); + } + + return $sum; + } + + function _getDbDsn() + { + global $_DB_DATAOBJECT; + + if (empty($_DB_DATAOBJECT['CONFIG'])) { + DB_DataObject::_loadConfig(); + } + + $options = &$_DB_DATAOBJECT['CONFIG']; + + // if the databse dsn dis defined in the object.. + + $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null; + + if (!$dsn) { + + if (!$this->_database) { + $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null; + } + + if ($this->_database && !empty($options["database_{$this->_database}"])) { + $dsn = $options["database_{$this->_database}"]; + } else if (!empty($options['database'])) { + $dsn = $options['database']; + } + } + + if (!$dsn) { + throw new Exception("No database name / dsn found anywhere"); + } + + return $dsn; + } } -- cgit v1.2.3-54-g00ecf From 7835393c25e26ea31b8ee3ca4f956ff9d209c6cf Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 27 Jul 2009 15:07:39 -0400 Subject: change front page to link to max member groups --- actions/public.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actions/public.php b/actions/public.php index ef9ef0d1a..d0317ac70 100644 --- a/actions/public.php +++ b/actions/public.php @@ -229,7 +229,7 @@ class PublicAction extends Action // $top->show(); $pop = new PopularNoticeSection($this); $pop->show(); - $gbp = new GroupsByPostsSection($this); + $gbp = new GroupsByMembersSection($this); $gbp->show(); $feat = new FeaturedUsersSection($this); $feat->show(); -- cgit v1.2.3-54-g00ecf From 92c12898e780ed3685c93bd85cae5772f1547c5e Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 27 Jul 2009 15:07:39 -0400 Subject: change front page to link to max member groups --- actions/public.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actions/public.php b/actions/public.php index ef9ef0d1a..d0317ac70 100644 --- a/actions/public.php +++ b/actions/public.php @@ -229,7 +229,7 @@ class PublicAction extends Action // $top->show(); $pop = new PopularNoticeSection($this); $pop->show(); - $gbp = new GroupsByPostsSection($this); + $gbp = new GroupsByMembersSection($this); $gbp->show(); $feat = new FeaturedUsersSection($this); $feat->show(); -- cgit v1.2.3-54-g00ecf From 2cbee8213ae9973c929d8d130cdc54d031e0ccd6 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 27 Jul 2009 13:51:40 -0400 Subject: better check for existing DB connection runs SET NAMES UTF8 less --- classes/Memcached_DataObject.php | 69 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/classes/Memcached_DataObject.php b/classes/Memcached_DataObject.php index f7cbb9d5b..ea070ec84 100644 --- a/classes/Memcached_DataObject.php +++ b/classes/Memcached_DataObject.php @@ -241,10 +241,19 @@ class Memcached_DataObject extends DB_DataObject function _connect() { global $_DB_DATAOBJECT; - $exists = !empty($this->_database_dsn_md5) && - isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]); + + $sum = $this->_getDbDsnMD5(); + + if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$sum]) && + !PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$sum])) { + $exists = true; + } else { + $exists = false; + } + $result = parent::_connect(); - if (!$exists) { + + if ($result && !$exists) { $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]; if (common_config('db', 'type') == 'mysql' && common_config('db', 'utf8')) { @@ -258,7 +267,61 @@ class Memcached_DataObject extends DB_DataObject } } } + return $result; } + // XXX: largely cadged from DB_DataObject + + function _getDbDsnMD5() + { + if ($this->_database_dsn_md5) { + return $this->_database_dsn_md5; + } + + $dsn = $this->_getDbDsn(); + + if (is_string($dsn)) { + $sum = md5($dsn); + } else { + /// support array based dsn's + $sum = md5(serialize($dsn)); + } + + return $sum; + } + + function _getDbDsn() + { + global $_DB_DATAOBJECT; + + if (empty($_DB_DATAOBJECT['CONFIG'])) { + DB_DataObject::_loadConfig(); + } + + $options = &$_DB_DATAOBJECT['CONFIG']; + + // if the databse dsn dis defined in the object.. + + $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null; + + if (!$dsn) { + + if (!$this->_database) { + $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null; + } + + if ($this->_database && !empty($options["database_{$this->_database}"])) { + $dsn = $options["database_{$this->_database}"]; + } else if (!empty($options['database'])) { + $dsn = $options['database']; + } + } + + if (!$dsn) { + throw new Exception("No database name / dsn found anywhere"); + } + + return $dsn; + } } -- cgit v1.2.3-54-g00ecf From e804b2a500959289e233cd6ca80979c40400d9a0 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Mon, 27 Jul 2009 16:02:03 -0400 Subject: trim the subject line of invite emails Thanks semjaza http://laconi.ca/trac/ticket/1746 --- actions/invite.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actions/invite.php b/actions/invite.php index bdea4807d..26c951ed2 100644 --- a/actions/invite.php +++ b/actions/invite.php @@ -216,7 +216,7 @@ class InviteAction extends CurrentUserDesignAction $recipients = array($email); $headers['From'] = mail_notify_from(); - $headers['To'] = $email; + $headers['To'] = trim($email); $headers['Subject'] = sprintf(_('%1$s has invited you to join them on %2$s'), $bestname, $sitename); $body = sprintf(_("%1\$s has invited you to join them on %2\$s (%3\$s).\n\n". -- cgit v1.2.3-54-g00ecf From 87bc612778932748d5b638af4c45493435c404d4 Mon Sep 17 00:00:00 2001 From: Eric Helgeson Date: Mon, 27 Jul 2009 18:29:11 -0500 Subject: pgsql's install had windows newlines. ran db/laconica_pg.sql Thanks grim26 --- db/laconica_pg.sql | 1058 ++++++++++++++++++++++++++-------------------------- 1 file changed, 529 insertions(+), 529 deletions(-) diff --git a/db/laconica_pg.sql b/db/laconica_pg.sql index 31210fd1e..24581bad0 100644 --- a/db/laconica_pg.sql +++ b/db/laconica_pg.sql @@ -1,529 +1,529 @@ -/* local and remote users have profiles */ - -create sequence profile_seq; -create table profile ( - id bigint default nextval('profile_seq') primary key /* comment 'unique identifier' */, - nickname varchar(64) not null /* comment 'nickname or username' */, - fullname varchar(255) /* comment 'display name' */, - profileurl varchar(255) /* comment 'URL, cached so we dont regenerate' */, - homepage varchar(255) /* comment 'identifying URL' */, - bio varchar(140) /* comment 'descriptive biography' */, - location varchar(255) /* comment 'physical location' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - textsearch tsvector -); -create index profile_nickname_idx on profile using btree(nickname); - -create table avatar ( - profile_id integer not null /* comment 'foreign key to profile table' */ references profile (id) , - original integer default 0 /* comment 'uploaded by user or generated?' */, - width integer not null /* comment 'image width' */, - height integer not null /* comment 'image height' */, - mediatype varchar(32) not null /* comment 'file type' */, - filename varchar(255) null /* comment 'local filename, if local' */, - url varchar(255) unique /* comment 'avatar location' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key(profile_id, width, height) -); -create index avatar_profile_id_idx on avatar using btree(profile_id); - -create sequence sms_carrier_seq; -create table sms_carrier ( - id bigint default nextval('sms_carrier_seq') primary key /* comment 'primary key for SMS carrier' */, - name varchar(64) unique /* comment 'name of the carrier' */, - email_pattern varchar(255) not null /* comment 'sprintf pattern for making an email address from a phone number' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified ' */ -); - -create sequence design_seq; -create table design ( - id bigint default nextval('design_seq') /* comment 'design ID'*/, - backgroundcolor integer /* comment 'main background color'*/ , - contentcolor integer /*comment 'content area background color'*/ , - sidebarcolor integer /*comment 'sidebar background color'*/ , - textcolor integer /*comment 'text color'*/ , - linkcolor integer /*comment 'link color'*/, - backgroundimage varchar(255) /*comment 'background image, if any'*/, - disposition int default 1 /*comment 'bit 1 = hide background image, bit 2 = display background image, bit 4 = tile background image'*/, - primary key (id) -); - -/* local users */ - -create table "user" ( - id integer primary key /* comment 'foreign key to profile table' */ references profile (id) , - nickname varchar(64) unique /* comment 'nickname or username, duped in profile' */, - password varchar(255) /* comment 'salted password, can be null for OpenID users' */, - email varchar(255) unique /* comment 'email address for password recovery etc.' */, - incomingemail varchar(255) unique /* comment 'email address for post-by-email' */, - emailnotifysub integer default 1 /* comment 'Notify by email of subscriptions' */, - emailnotifyfav integer default 1 /* comment 'Notify by email of favorites' */, - emailnotifynudge integer default 1 /* comment 'Notify by email of nudges' */, - emailnotifymsg integer default 1 /* comment 'Notify by email of direct messages' */, - emailnotifyattn integer default 1 /* command 'Notify by email of @-replies' */, - emailmicroid integer default 1 /* comment 'whether to publish email microid' */, - language varchar(50) /* comment 'preferred language' */, - timezone varchar(50) /* comment 'timezone' */, - emailpost integer default 1 /* comment 'Post by email' */, - jabber varchar(255) unique /* comment 'jabber ID for notices' */, - jabbernotify integer default 0 /* comment 'whether to send notices to jabber' */, - jabberreplies integer default 0 /* comment 'whether to send notices to jabber on replies' */, - jabbermicroid integer default 1 /* comment 'whether to publish xmpp microid' */, - updatefrompresence integer default 0 /* comment 'whether to record updates from Jabber presence notices' */, - sms varchar(64) unique /* comment 'sms phone number' */, - carrier integer /* comment 'foreign key to sms_carrier' */ references sms_carrier (id) , - smsnotify integer default 0 /* comment 'whether to send notices to SMS' */, - smsreplies integer default 0 /* comment 'whether to send notices to SMS on replies' */, - smsemail varchar(255) /* comment 'built from sms and carrier' */, - uri varchar(255) unique /* comment 'universally unique identifier, usually a tag URI' */, - autosubscribe integer default 0 /* comment 'automatically subscribe to users who subscribe to us' */, - urlshorteningservice varchar(50) default 'ur1.ca' /* comment 'service to use for auto-shortening URLs' */, - inboxed integer default 0 /* comment 'has an inbox been created for this user?' */, - design_id integer /* comment 'id of a design' */references design(id), - viewdesigns integer default 1 /* comment 'whether to view user-provided designs'*/, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ - -); -create index user_smsemail_idx on "user" using btree(smsemail); - -/* remote people */ - -create table remote_profile ( - id integer primary key /* comment 'foreign key to profile table' */ references profile (id) , - uri varchar(255) unique /* comment 'universally unique identifier, usually a tag URI' */, - postnoticeurl varchar(255) /* comment 'URL we use for posting notices' */, - updateprofileurl varchar(255) /* comment 'URL we use for updates to this profile' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ -); - -create table subscription ( - subscriber integer not null /* comment 'profile listening' */, - subscribed integer not null /* comment 'profile being listened to' */, - jabber integer default 1 /* comment 'deliver jabber messages' */, - sms integer default 1 /* comment 'deliver sms messages' */, - token varchar(255) /* comment 'authorization token' */, - secret varchar(255) /* comment 'token secret' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key (subscriber, subscribed) -); -create index subscription_subscriber_idx on subscription using btree(subscriber); -create index subscription_subscribed_idx on subscription using btree(subscribed); - -create sequence notice_seq; -create table notice ( - - id bigint default nextval('notice_seq') primary key /* comment 'unique identifier' */, - profile_id integer not null /* comment 'who made the update' */ references profile (id) , - uri varchar(255) unique /* comment 'universally unique identifier, usually a tag URI' */, - content varchar(140) /* comment 'update content' */, - rendered text /* comment 'HTML version of the content' */, - url varchar(255) /* comment 'URL of any attachment (image, video, bookmark, whatever)' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - reply_to integer /* comment 'notice replied to (usually a guess)' */ references notice (id) , - is_local integer default 0 /* comment 'notice was generated by a user' */, - source varchar(32) /* comment 'source of comment, like "web", "im", or "clientname"' */, - conversation integer /*id of root notice in this conversation' */ references notice (id) - - -/* FULLTEXT(content) */ -); -create index notice_profile_id_idx on notice using btree(profile_id); -create index notice_created_idx on notice using btree(created); - -create table notice_source ( - code varchar(32) primary key not null /* comment 'source code' */, - name varchar(255) not null /* comment 'name of the source' */, - url varchar(255) not null /* comment 'url to link to' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ -); - -create table reply ( - - notice_id integer not null /* comment 'notice that is the reply' */ references notice (id) , - profile_id integer not null /* comment 'profile replied to' */ references profile (id) , - modified timestamp /* comment 'date this record was modified' */, - replied_id integer /* comment 'notice replied to (not used, see notice.reply_to)' */, - - primary key (notice_id, profile_id) - -); -create index reply_notice_id_idx on reply using btree(notice_id); -create index reply_profile_id_idx on reply using btree(profile_id); -create index reply_replied_id_idx on reply using btree(replied_id); - -create table fave ( - - notice_id integer not null /* comment 'notice that is the favorite' */ references notice (id), - user_id integer not null /* comment 'user who likes this notice' */ references "user" (id) , - modified timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was modified' */, - primary key (notice_id, user_id) - -); -create index fave_notice_id_idx on fave using btree(notice_id); -create index fave_user_id_idx on fave using btree(user_id); -create index fave_modified_idx on fave using btree(modified); - -/* tables for OAuth */ - -create table consumer ( - consumer_key varchar(255) primary key /* comment 'unique identifier, root URL' */, - seed char(32) not null /* comment 'seed for new tokens by this consumer' */, - - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ -); - -create table token ( - consumer_key varchar(255) not null /* comment 'unique identifier, root URL' */ references consumer (consumer_key), - tok char(32) not null /* comment 'identifying value' */, - secret char(32) not null /* comment 'secret value' */, - type integer not null default 0 /* comment 'request or access' */, - state integer default 0 /* comment 'for requests 0 = initial, 1 = authorized, 2 = used' */, - - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key (consumer_key, tok) -); - -create table nonce ( - consumer_key varchar(255) not null /* comment 'unique identifier, root URL' */, - tok char(32) /* comment 'buggy old value, ignored' */, - nonce char(32) null /* comment 'buggy old value, ignored */, - ts integer not null /* comment 'timestamp sent' values are epoch, and only used internally */, - - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key (consumer_key, ts, nonce) -); - -/* One-to-many relationship of user to openid_url */ - -create table user_openid ( - canonical varchar(255) primary key /* comment 'Canonical true URL' */, - display varchar(255) not null unique /* comment 'URL for viewing, may be different from canonical' */, - user_id integer not null /* comment 'user owning this URL' */ references "user" (id) , - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ - -); -create index user_openid_user_id_idx on user_openid using btree(user_id); - -/* These are used by JanRain OpenID library */ - -create table oid_associations ( - server_url varchar(2047), - handle varchar(255), - secret bytea, - issued integer, - lifetime integer, - assoc_type varchar(64), - primary key (server_url, handle) -); - -create table oid_nonces ( - server_url varchar(2047), - "timestamp" integer, - salt character(40), - unique (server_url, "timestamp", salt) -); - -create table confirm_address ( - code varchar(32) not null primary key /* comment 'good random code' */, - user_id integer not null /* comment 'user who requested confirmation' */ references "user" (id), - address varchar(255) not null /* comment 'address (email, Jabber, SMS, etc.)' */, - address_extra varchar(255) not null default '' /* comment 'carrier ID, for SMS' */, - address_type varchar(8) not null /* comment 'address type ("email", "jabber", "sms")' */, - claimed timestamp /* comment 'date this was claimed for queueing' */, - sent timestamp /* comment 'date this was sent for queueing' */, - modified timestamp /* comment 'date this record was modified' */ -); - -create table remember_me ( - code varchar(32) not null primary key /* comment 'good random code' */, - user_id integer not null /* comment 'user who is logged in' */ references "user" (id), - modified timestamp /* comment 'date this record was modified' */ -); - -create table queue_item ( - - notice_id integer not null /* comment 'notice queued' */ references notice (id) , - transport varchar(8) not null /* comment 'queue for what? "email", "jabber", "sms", "irc", ...' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - claimed timestamp /* comment 'date this item was claimed' */, - - primary key (notice_id, transport) - -); -create index queue_item_created_idx on queue_item using btree(created); - -/* Hash tags */ -create table notice_tag ( - tag varchar( 64 ) not null /* comment 'hash tag associated with this notice' */, - notice_id integer not null /* comment 'notice tagged' */ references notice (id) , - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - - primary key (tag, notice_id) -); -create index notice_tag_created_idx on notice_tag using btree(created); - -/* Synching with foreign services */ - -create table foreign_service ( - id int not null primary key /* comment 'numeric key for service' */, - name varchar(32) not null unique /* comment 'name of the service' */, - description varchar(255) /* comment 'description' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ -); - -create table foreign_user ( - id int not null unique /* comment 'unique numeric key on foreign service' */, - service int not null /* comment 'foreign key to service' */ references foreign_service(id) , - uri varchar(255) not null unique /* comment 'identifying URI' */, - nickname varchar(255) /* comment 'nickname on foreign service' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key (id, service) -); - -create table foreign_link ( - user_id int /* comment 'link to user on this system, if exists' */ references "user" (id), - foreign_id int /* comment 'link' */ references foreign_user (id), - service int not null /* comment 'foreign key to service' */ references foreign_service (id), - credentials varchar(255) /* comment 'authc credentials, typically a password' */, - noticesync int not null default 1 /* comment 'notice synchronisation, bit 1 = sync outgoing, bit 2 = sync incoming, bit 3 = filter local replies' */, - friendsync int not null default 2 /* comment 'friend synchronisation, bit 1 = sync outgoing, bit 2 = sync incoming */, - profilesync int not null default 1 /* comment 'profile synchronization, bit 1 = sync outgoing, bit 2 = sync incoming' */, - last_noticesync timestamp default null /* comment 'last time notices were imported' */, - last_friendsync timestamp default null /* comment 'last time friends were imported' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key (user_id,foreign_id,service) -); -create index foreign_user_user_id_idx on foreign_link using btree(user_id); - -create table foreign_subscription ( - service int not null /* comment 'service where relationship happens' */ references foreign_service(id) , - subscriber int not null /* comment 'subscriber on foreign service' */ , - subscribed int not null /* comment 'subscribed user' */ , - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - - primary key (service, subscriber, subscribed) -); -create index foreign_subscription_subscriber_idx on foreign_subscription using btree(subscriber); -create index foreign_subscription_subscribed_idx on foreign_subscription using btree(subscribed); - -create table invitation ( - code varchar(32) not null primary key /* comment 'random code for an invitation' */, - user_id int not null /* comment 'who sent the invitation' */ references "user" (id), - address varchar(255) not null /* comment 'invitation sent to' */, - address_type varchar(8) not null /* comment 'address type ("email", "jabber", "sms") '*/, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */ - -); -create index invitation_address_idx on invitation using btree(address,address_type); -create index invitation_user_id_idx on invitation using btree(user_id); - -create sequence message_seq; -create table message ( - - id bigint default nextval('message_seq') primary key /* comment 'unique identifier' */, - uri varchar(255) unique /* comment 'universally unique identifier' */, - from_profile integer not null /* comment 'who the message is from' */ references profile (id), - to_profile integer not null /* comment 'who the message is to' */ references profile (id), - content varchar(140) /* comment 'message content' */, - rendered text /* comment 'HTML version of the content' */, - url varchar(255) /* comment 'URL of any attachment (image, video, bookmark, whatever)' */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - source varchar(32) /* comment 'source of comment, like "web", "im", or "clientname"' */ - -); -create index message_from_idx on message using btree(from_profile); -create index message_to_idx on message using btree(to_profile); -create index message_created_idx on message using btree(created); - -create table notice_inbox ( - - user_id integer not null /* comment 'user receiving the message' */ references "user" (id), - notice_id integer not null /* comment 'notice received' */ references notice (id), - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date the notice was created' */, - source integer default 1 /* comment 'reason it is in the inbox: 1=subscription' */, - - primary key (user_id, notice_id) -); -create index notice_inbox_notice_id_idx on notice_inbox using btree(notice_id); - -create table profile_tag ( - tagger integer not null /* comment 'user making the tag' */ references "user" (id), - tagged integer not null /* comment 'profile tagged' */ references profile (id), - tag varchar(64) not null /* comment 'hash tag associated with this notice' */, - modified timestamp /* comment 'date the tag was added' */, - - primary key (tagger, tagged, tag) -); -create index profile_tag_modified_idx on profile_tag using btree(modified); -create index profile_tag_tagger_tag_idx on profile_tag using btree(tagger,tag); - -create table profile_block ( - - blocker integer not null /* comment 'user making the block' */ references "user" (id), - blocked integer not null /* comment 'profile that is blocked' */ references profile (id), - modified timestamp /* comment 'date of blocking' */, - - primary key (blocker, blocked) - -); - -create sequence user_group_seq; -create table user_group ( - - id bigint default nextval('user_group_seq') primary key /* comment 'unique identifier' */, - - nickname varchar(64) unique /* comment 'nickname for addressing' */, - fullname varchar(255) /* comment 'display name' */, - homepage varchar(255) /* comment 'URL, cached so we dont regenerate' */, - description varchar(140) /* comment 'descriptive biography' */, - location varchar(255) /* comment 'related physical location, if any' */, - - original_logo varchar(255) /* comment 'original size logo' */, - homepage_logo varchar(255) /* comment 'homepage (profile) size logo' */, - stream_logo varchar(255) /* comment 'stream-sized logo' */, - mini_logo varchar(255) /* comment 'mini logo' */, - design_id integer /*comment 'id of a design' */ references design(id), - - - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */ - -); -create index user_group_nickname_idx on user_group using btree(nickname); - -create table group_member ( - - group_id integer not null /* comment 'foreign key to user_group' */ references user_group (id), - profile_id integer not null /* comment 'foreign key to profile table' */ references profile (id), - is_admin integer default 0 /* comment 'is this user an admin?' */, - - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - modified timestamp /* comment 'date this record was modified' */, - - primary key (group_id, profile_id) -); - -create table related_group ( - - group_id integer not null /* comment 'foreign key to user_group' */ references user_group (id) , - related_group_id integer not null /* comment 'foreign key to user_group' */ references user_group (id), - - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, - - primary key (group_id, related_group_id) - -); - -create table group_inbox ( - group_id integer not null /* comment 'group receiving the message' references user_group (id) */, - notice_id integer not null /* comment 'notice received' references notice (id) */, - created timestamp not null default CURRENT_TIMESTAMP /* comment 'date the notice was created' */, - primary key (group_id, notice_id) -); -create index group_inbox_created_idx on group_inbox using btree(created); - - -/*attachments and URLs stuff */ -create sequence file_seq; -create table file ( - id bigint default nextval('file_seq') primary key /* comment 'unique identifier' */, - url varchar(255) unique, - mimetype varchar(50), - size integer, - title varchar(255), - date integer, - protected integer, - filename text /* comment 'if a local file, name of the file' */, - modified timestamp default CURRENT_TIMESTAMP /* comment 'date this record was modified'*/ -); - -create sequence file_oembed_seq; -create table file_oembed ( - file_id bigint default nextval('file_oembed_seq') primary key /* comment 'unique identifier' */, - version varchar(20), - type varchar(20), - provider varchar(50), - provider_url varchar(255), - width integer, - height integer, - html text, - title varchar(255), - author_name varchar(50), - author_url varchar(255), - url varchar(255) -); - -create sequence file_redirection_seq; -create table file_redirection ( - url varchar(255) primary key, - file_id bigint, - redirections integer, - httpcode integer -); - -create sequence file_thumbnail_seq; -create table file_thumbnail ( - file_id bigint primary key, - url varchar(255) unique, - width integer, - height integer -); - -create sequence file_to_post_seq; -create table file_to_post ( - file_id bigint, - post_id bigint, - - primary key (file_id, post_id) -); - -create table group_block ( - group_id integer not null /* comment 'group profile is blocked from' */ references user_group (id), - blocked integer not null /* comment 'profile that is blocked' */references profile (id), - blocker integer not null /* comment 'user making the block'*/ references "user" (id), - modified timestamp /* comment 'date of blocking'*/ , - - primary key (group_id, blocked) -); - -create table group_alias ( - - alias varchar(64) /* comment 'additional nickname for the group'*/ , - group_id integer not null /* comment 'group profile is blocked from'*/ references user_group (id), - modified timestamp /* comment 'date alias was created'*/, - primary key (alias) - -); -create index group_alias_group_id_idx on group_alias (group_id); - - -/* Textsearch stuff */ - -create index textsearch_idx on profile using gist(textsearch); -create index noticecontent_idx on notice using gist(to_tsvector('english',content)); -create trigger textsearchupdate before insert or update on profile for each row -execute procedure tsvector_update_trigger(textsearch, 'pg_catalog.english', nickname, fullname, location, bio, homepage); - +/* local and remote users have profiles */ + +create sequence profile_seq; +create table profile ( + id bigint default nextval('profile_seq') primary key /* comment 'unique identifier' */, + nickname varchar(64) not null /* comment 'nickname or username' */, + fullname varchar(255) /* comment 'display name' */, + profileurl varchar(255) /* comment 'URL, cached so we dont regenerate' */, + homepage varchar(255) /* comment 'identifying URL' */, + bio varchar(140) /* comment 'descriptive biography' */, + location varchar(255) /* comment 'physical location' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + textsearch tsvector +); +create index profile_nickname_idx on profile using btree(nickname); + +create table avatar ( + profile_id integer not null /* comment 'foreign key to profile table' */ references profile (id) , + original integer default 0 /* comment 'uploaded by user or generated?' */, + width integer not null /* comment 'image width' */, + height integer not null /* comment 'image height' */, + mediatype varchar(32) not null /* comment 'file type' */, + filename varchar(255) null /* comment 'local filename, if local' */, + url varchar(255) unique /* comment 'avatar location' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key(profile_id, width, height) +); +create index avatar_profile_id_idx on avatar using btree(profile_id); + +create sequence sms_carrier_seq; +create table sms_carrier ( + id bigint default nextval('sms_carrier_seq') primary key /* comment 'primary key for SMS carrier' */, + name varchar(64) unique /* comment 'name of the carrier' */, + email_pattern varchar(255) not null /* comment 'sprintf pattern for making an email address from a phone number' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified ' */ +); + +create sequence design_seq; +create table design ( + id bigint default nextval('design_seq') /* comment 'design ID'*/, + backgroundcolor integer /* comment 'main background color'*/ , + contentcolor integer /*comment 'content area background color'*/ , + sidebarcolor integer /*comment 'sidebar background color'*/ , + textcolor integer /*comment 'text color'*/ , + linkcolor integer /*comment 'link color'*/, + backgroundimage varchar(255) /*comment 'background image, if any'*/, + disposition int default 1 /*comment 'bit 1 = hide background image, bit 2 = display background image, bit 4 = tile background image'*/, + primary key (id) +); + +/* local users */ + +create table "user" ( + id integer primary key /* comment 'foreign key to profile table' */ references profile (id) , + nickname varchar(64) unique /* comment 'nickname or username, duped in profile' */, + password varchar(255) /* comment 'salted password, can be null for OpenID users' */, + email varchar(255) unique /* comment 'email address for password recovery etc.' */, + incomingemail varchar(255) unique /* comment 'email address for post-by-email' */, + emailnotifysub integer default 1 /* comment 'Notify by email of subscriptions' */, + emailnotifyfav integer default 1 /* comment 'Notify by email of favorites' */, + emailnotifynudge integer default 1 /* comment 'Notify by email of nudges' */, + emailnotifymsg integer default 1 /* comment 'Notify by email of direct messages' */, + emailnotifyattn integer default 1 /* command 'Notify by email of @-replies' */, + emailmicroid integer default 1 /* comment 'whether to publish email microid' */, + language varchar(50) /* comment 'preferred language' */, + timezone varchar(50) /* comment 'timezone' */, + emailpost integer default 1 /* comment 'Post by email' */, + jabber varchar(255) unique /* comment 'jabber ID for notices' */, + jabbernotify integer default 0 /* comment 'whether to send notices to jabber' */, + jabberreplies integer default 0 /* comment 'whether to send notices to jabber on replies' */, + jabbermicroid integer default 1 /* comment 'whether to publish xmpp microid' */, + updatefrompresence integer default 0 /* comment 'whether to record updates from Jabber presence notices' */, + sms varchar(64) unique /* comment 'sms phone number' */, + carrier integer /* comment 'foreign key to sms_carrier' */ references sms_carrier (id) , + smsnotify integer default 0 /* comment 'whether to send notices to SMS' */, + smsreplies integer default 0 /* comment 'whether to send notices to SMS on replies' */, + smsemail varchar(255) /* comment 'built from sms and carrier' */, + uri varchar(255) unique /* comment 'universally unique identifier, usually a tag URI' */, + autosubscribe integer default 0 /* comment 'automatically subscribe to users who subscribe to us' */, + urlshorteningservice varchar(50) default 'ur1.ca' /* comment 'service to use for auto-shortening URLs' */, + inboxed integer default 0 /* comment 'has an inbox been created for this user?' */, + design_id integer /* comment 'id of a design' */references design(id), + viewdesigns integer default 1 /* comment 'whether to view user-provided designs'*/, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ + +); +create index user_smsemail_idx on "user" using btree(smsemail); + +/* remote people */ + +create table remote_profile ( + id integer primary key /* comment 'foreign key to profile table' */ references profile (id) , + uri varchar(255) unique /* comment 'universally unique identifier, usually a tag URI' */, + postnoticeurl varchar(255) /* comment 'URL we use for posting notices' */, + updateprofileurl varchar(255) /* comment 'URL we use for updates to this profile' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ +); + +create table subscription ( + subscriber integer not null /* comment 'profile listening' */, + subscribed integer not null /* comment 'profile being listened to' */, + jabber integer default 1 /* comment 'deliver jabber messages' */, + sms integer default 1 /* comment 'deliver sms messages' */, + token varchar(255) /* comment 'authorization token' */, + secret varchar(255) /* comment 'token secret' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key (subscriber, subscribed) +); +create index subscription_subscriber_idx on subscription using btree(subscriber); +create index subscription_subscribed_idx on subscription using btree(subscribed); + +create sequence notice_seq; +create table notice ( + + id bigint default nextval('notice_seq') primary key /* comment 'unique identifier' */, + profile_id integer not null /* comment 'who made the update' */ references profile (id) , + uri varchar(255) unique /* comment 'universally unique identifier, usually a tag URI' */, + content varchar(140) /* comment 'update content' */, + rendered text /* comment 'HTML version of the content' */, + url varchar(255) /* comment 'URL of any attachment (image, video, bookmark, whatever)' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + reply_to integer /* comment 'notice replied to (usually a guess)' */ references notice (id) , + is_local integer default 0 /* comment 'notice was generated by a user' */, + source varchar(32) /* comment 'source of comment, like "web", "im", or "clientname"' */, + conversation integer /*id of root notice in this conversation' */ references notice (id) + + +/* FULLTEXT(content) */ +); +create index notice_profile_id_idx on notice using btree(profile_id); +create index notice_created_idx on notice using btree(created); + +create table notice_source ( + code varchar(32) primary key not null /* comment 'source code' */, + name varchar(255) not null /* comment 'name of the source' */, + url varchar(255) not null /* comment 'url to link to' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ +); + +create table reply ( + + notice_id integer not null /* comment 'notice that is the reply' */ references notice (id) , + profile_id integer not null /* comment 'profile replied to' */ references profile (id) , + modified timestamp /* comment 'date this record was modified' */, + replied_id integer /* comment 'notice replied to (not used, see notice.reply_to)' */, + + primary key (notice_id, profile_id) + +); +create index reply_notice_id_idx on reply using btree(notice_id); +create index reply_profile_id_idx on reply using btree(profile_id); +create index reply_replied_id_idx on reply using btree(replied_id); + +create table fave ( + + notice_id integer not null /* comment 'notice that is the favorite' */ references notice (id), + user_id integer not null /* comment 'user who likes this notice' */ references "user" (id) , + modified timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was modified' */, + primary key (notice_id, user_id) + +); +create index fave_notice_id_idx on fave using btree(notice_id); +create index fave_user_id_idx on fave using btree(user_id); +create index fave_modified_idx on fave using btree(modified); + +/* tables for OAuth */ + +create table consumer ( + consumer_key varchar(255) primary key /* comment 'unique identifier, root URL' */, + seed char(32) not null /* comment 'seed for new tokens by this consumer' */, + + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ +); + +create table token ( + consumer_key varchar(255) not null /* comment 'unique identifier, root URL' */ references consumer (consumer_key), + tok char(32) not null /* comment 'identifying value' */, + secret char(32) not null /* comment 'secret value' */, + type integer not null default 0 /* comment 'request or access' */, + state integer default 0 /* comment 'for requests 0 = initial, 1 = authorized, 2 = used' */, + + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key (consumer_key, tok) +); + +create table nonce ( + consumer_key varchar(255) not null /* comment 'unique identifier, root URL' */, + tok char(32) /* comment 'buggy old value, ignored' */, + nonce char(32) null /* comment 'buggy old value, ignored */, + ts integer not null /* comment 'timestamp sent' values are epoch, and only used internally */, + + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key (consumer_key, ts, nonce) +); + +/* One-to-many relationship of user to openid_url */ + +create table user_openid ( + canonical varchar(255) primary key /* comment 'Canonical true URL' */, + display varchar(255) not null unique /* comment 'URL for viewing, may be different from canonical' */, + user_id integer not null /* comment 'user owning this URL' */ references "user" (id) , + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ + +); +create index user_openid_user_id_idx on user_openid using btree(user_id); + +/* These are used by JanRain OpenID library */ + +create table oid_associations ( + server_url varchar(2047), + handle varchar(255), + secret bytea, + issued integer, + lifetime integer, + assoc_type varchar(64), + primary key (server_url, handle) +); + +create table oid_nonces ( + server_url varchar(2047), + "timestamp" integer, + salt character(40), + unique (server_url, "timestamp", salt) +); + +create table confirm_address ( + code varchar(32) not null primary key /* comment 'good random code' */, + user_id integer not null /* comment 'user who requested confirmation' */ references "user" (id), + address varchar(255) not null /* comment 'address (email, Jabber, SMS, etc.)' */, + address_extra varchar(255) not null default '' /* comment 'carrier ID, for SMS' */, + address_type varchar(8) not null /* comment 'address type ("email", "jabber", "sms")' */, + claimed timestamp /* comment 'date this was claimed for queueing' */, + sent timestamp /* comment 'date this was sent for queueing' */, + modified timestamp /* comment 'date this record was modified' */ +); + +create table remember_me ( + code varchar(32) not null primary key /* comment 'good random code' */, + user_id integer not null /* comment 'user who is logged in' */ references "user" (id), + modified timestamp /* comment 'date this record was modified' */ +); + +create table queue_item ( + + notice_id integer not null /* comment 'notice queued' */ references notice (id) , + transport varchar(8) not null /* comment 'queue for what? "email", "jabber", "sms", "irc", ...' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + claimed timestamp /* comment 'date this item was claimed' */, + + primary key (notice_id, transport) + +); +create index queue_item_created_idx on queue_item using btree(created); + +/* Hash tags */ +create table notice_tag ( + tag varchar( 64 ) not null /* comment 'hash tag associated with this notice' */, + notice_id integer not null /* comment 'notice tagged' */ references notice (id) , + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + + primary key (tag, notice_id) +); +create index notice_tag_created_idx on notice_tag using btree(created); + +/* Synching with foreign services */ + +create table foreign_service ( + id int not null primary key /* comment 'numeric key for service' */, + name varchar(32) not null unique /* comment 'name of the service' */, + description varchar(255) /* comment 'description' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ +); + +create table foreign_user ( + id int not null unique /* comment 'unique numeric key on foreign service' */, + service int not null /* comment 'foreign key to service' */ references foreign_service(id) , + uri varchar(255) not null unique /* comment 'identifying URI' */, + nickname varchar(255) /* comment 'nickname on foreign service' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key (id, service) +); + +create table foreign_link ( + user_id int /* comment 'link to user on this system, if exists' */ references "user" (id), + foreign_id int /* comment 'link' */ references foreign_user (id), + service int not null /* comment 'foreign key to service' */ references foreign_service (id), + credentials varchar(255) /* comment 'authc credentials, typically a password' */, + noticesync int not null default 1 /* comment 'notice synchronisation, bit 1 = sync outgoing, bit 2 = sync incoming, bit 3 = filter local replies' */, + friendsync int not null default 2 /* comment 'friend synchronisation, bit 1 = sync outgoing, bit 2 = sync incoming */, + profilesync int not null default 1 /* comment 'profile synchronization, bit 1 = sync outgoing, bit 2 = sync incoming' */, + last_noticesync timestamp default null /* comment 'last time notices were imported' */, + last_friendsync timestamp default null /* comment 'last time friends were imported' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key (user_id,foreign_id,service) +); +create index foreign_user_user_id_idx on foreign_link using btree(user_id); + +create table foreign_subscription ( + service int not null /* comment 'service where relationship happens' */ references foreign_service(id) , + subscriber int not null /* comment 'subscriber on foreign service' */ , + subscribed int not null /* comment 'subscribed user' */ , + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + + primary key (service, subscriber, subscribed) +); +create index foreign_subscription_subscriber_idx on foreign_subscription using btree(subscriber); +create index foreign_subscription_subscribed_idx on foreign_subscription using btree(subscribed); + +create table invitation ( + code varchar(32) not null primary key /* comment 'random code for an invitation' */, + user_id int not null /* comment 'who sent the invitation' */ references "user" (id), + address varchar(255) not null /* comment 'invitation sent to' */, + address_type varchar(8) not null /* comment 'address type ("email", "jabber", "sms") '*/, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */ + +); +create index invitation_address_idx on invitation using btree(address,address_type); +create index invitation_user_id_idx on invitation using btree(user_id); + +create sequence message_seq; +create table message ( + + id bigint default nextval('message_seq') primary key /* comment 'unique identifier' */, + uri varchar(255) unique /* comment 'universally unique identifier' */, + from_profile integer not null /* comment 'who the message is from' */ references profile (id), + to_profile integer not null /* comment 'who the message is to' */ references profile (id), + content varchar(140) /* comment 'message content' */, + rendered text /* comment 'HTML version of the content' */, + url varchar(255) /* comment 'URL of any attachment (image, video, bookmark, whatever)' */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + source varchar(32) /* comment 'source of comment, like "web", "im", or "clientname"' */ + +); +create index message_from_idx on message using btree(from_profile); +create index message_to_idx on message using btree(to_profile); +create index message_created_idx on message using btree(created); + +create table notice_inbox ( + + user_id integer not null /* comment 'user receiving the message' */ references "user" (id), + notice_id integer not null /* comment 'notice received' */ references notice (id), + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date the notice was created' */, + source integer default 1 /* comment 'reason it is in the inbox: 1=subscription' */, + + primary key (user_id, notice_id) +); +create index notice_inbox_notice_id_idx on notice_inbox using btree(notice_id); + +create table profile_tag ( + tagger integer not null /* comment 'user making the tag' */ references "user" (id), + tagged integer not null /* comment 'profile tagged' */ references profile (id), + tag varchar(64) not null /* comment 'hash tag associated with this notice' */, + modified timestamp /* comment 'date the tag was added' */, + + primary key (tagger, tagged, tag) +); +create index profile_tag_modified_idx on profile_tag using btree(modified); +create index profile_tag_tagger_tag_idx on profile_tag using btree(tagger,tag); + +create table profile_block ( + + blocker integer not null /* comment 'user making the block' */ references "user" (id), + blocked integer not null /* comment 'profile that is blocked' */ references profile (id), + modified timestamp /* comment 'date of blocking' */, + + primary key (blocker, blocked) + +); + +create sequence user_group_seq; +create table user_group ( + + id bigint default nextval('user_group_seq') primary key /* comment 'unique identifier' */, + + nickname varchar(64) unique /* comment 'nickname for addressing' */, + fullname varchar(255) /* comment 'display name' */, + homepage varchar(255) /* comment 'URL, cached so we dont regenerate' */, + description varchar(140) /* comment 'descriptive biography' */, + location varchar(255) /* comment 'related physical location, if any' */, + + original_logo varchar(255) /* comment 'original size logo' */, + homepage_logo varchar(255) /* comment 'homepage (profile) size logo' */, + stream_logo varchar(255) /* comment 'stream-sized logo' */, + mini_logo varchar(255) /* comment 'mini logo' */, + design_id integer /*comment 'id of a design' */ references design(id), + + + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */ + +); +create index user_group_nickname_idx on user_group using btree(nickname); + +create table group_member ( + + group_id integer not null /* comment 'foreign key to user_group' */ references user_group (id), + profile_id integer not null /* comment 'foreign key to profile table' */ references profile (id), + is_admin integer default 0 /* comment 'is this user an admin?' */, + + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + modified timestamp /* comment 'date this record was modified' */, + + primary key (group_id, profile_id) +); + +create table related_group ( + + group_id integer not null /* comment 'foreign key to user_group' */ references user_group (id) , + related_group_id integer not null /* comment 'foreign key to user_group' */ references user_group (id), + + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date this record was created' */, + + primary key (group_id, related_group_id) + +); + +create table group_inbox ( + group_id integer not null /* comment 'group receiving the message' references user_group (id) */, + notice_id integer not null /* comment 'notice received' references notice (id) */, + created timestamp not null default CURRENT_TIMESTAMP /* comment 'date the notice was created' */, + primary key (group_id, notice_id) +); +create index group_inbox_created_idx on group_inbox using btree(created); + + +/*attachments and URLs stuff */ +create sequence file_seq; +create table file ( + id bigint default nextval('file_seq') primary key /* comment 'unique identifier' */, + url varchar(255) unique, + mimetype varchar(50), + size integer, + title varchar(255), + date integer, + protected integer, + filename text /* comment 'if a local file, name of the file' */, + modified timestamp default CURRENT_TIMESTAMP /* comment 'date this record was modified'*/ +); + +create sequence file_oembed_seq; +create table file_oembed ( + file_id bigint default nextval('file_oembed_seq') primary key /* comment 'unique identifier' */, + version varchar(20), + type varchar(20), + provider varchar(50), + provider_url varchar(255), + width integer, + height integer, + html text, + title varchar(255), + author_name varchar(50), + author_url varchar(255), + url varchar(255) +); + +create sequence file_redirection_seq; +create table file_redirection ( + url varchar(255) primary key, + file_id bigint, + redirections integer, + httpcode integer +); + +create sequence file_thumbnail_seq; +create table file_thumbnail ( + file_id bigint primary key, + url varchar(255) unique, + width integer, + height integer +); + +create sequence file_to_post_seq; +create table file_to_post ( + file_id bigint, + post_id bigint, + + primary key (file_id, post_id) +); + +create table group_block ( + group_id integer not null /* comment 'group profile is blocked from' */ references user_group (id), + blocked integer not null /* comment 'profile that is blocked' */references profile (id), + blocker integer not null /* comment 'user making the block'*/ references "user" (id), + modified timestamp /* comment 'date of blocking'*/ , + + primary key (group_id, blocked) +); + +create table group_alias ( + + alias varchar(64) /* comment 'additional nickname for the group'*/ , + group_id integer not null /* comment 'group profile is blocked from'*/ references user_group (id), + modified timestamp /* comment 'date alias was created'*/, + primary key (alias) + +); +create index group_alias_group_id_idx on group_alias (group_id); + + +/* Textsearch stuff */ + +create index textsearch_idx on profile using gist(textsearch); +create index noticecontent_idx on notice using gist(to_tsvector('english',content)); +create trigger textsearchupdate before insert or update on profile for each row +execute procedure tsvector_update_trigger(textsearch, 'pg_catalog.english', nickname, fullname, location, bio, homepage); + -- cgit v1.2.3-54-g00ecf From 421ee4297ef5055bdd190fe2bd62cdc22b41c82b Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Fri, 17 Jul 2009 22:59:58 -0400 Subject: Fix RDFS namespace declaration. Thanks tobyink --- lib/rssaction.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/rssaction.php b/lib/rssaction.php index ffa1f9e99..7686d0646 100644 --- a/lib/rssaction.php +++ b/lib/rssaction.php @@ -320,6 +320,8 @@ class Rss10Action extends Action 'http://rdfs.org/sioc/ns#', 'xmlns:sioct' => 'http://rdfs.org/sioc/types#', + 'xmlns:rdfs' => + 'http://www.w3.org/2000/01/rdf-schema#', 'xmlns:laconica' => 'http://laconi.ca/ont/', 'xmlns' => 'http://purl.org/rss/1.0/')); -- cgit v1.2.3-54-g00ecf From c85b6155eb004fe556de255482c04b87046c90b3 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Tue, 28 Jul 2009 17:14:11 +0000 Subject: Minor UI fix for IE6 notice-options --- theme/base/css/ie6.css | 3 +++ 1 file changed, 3 insertions(+) diff --git a/theme/base/css/ie6.css b/theme/base/css/ie6.css index eca240faa..edc49478f 100644 --- a/theme/base/css/ie6.css +++ b/theme/base/css/ie6.css @@ -35,3 +35,6 @@ width:20%; width:50%; margin-left:30px; } +.notice-options a { +width:16px; +} \ No newline at end of file -- cgit v1.2.3-54-g00ecf From 72117294d7675434fc14303ad84711d43be003b9 Mon Sep 17 00:00:00 2001 From: Eric Helgeson Date: Tue, 28 Jul 2009 20:17:20 -0500 Subject: Splitting br3nda's merge 97db6e17b3f76e9a6acf87ddbad47ba54e9b1a3b Add session table to pg.sql --- db/laconica_pg.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/db/laconica_pg.sql b/db/laconica_pg.sql index 24581bad0..ad34720a2 100644 --- a/db/laconica_pg.sql +++ b/db/laconica_pg.sql @@ -519,6 +519,16 @@ create table group_alias ( ); create index group_alias_group_id_idx on group_alias (group_id); +create table session ( + + id varchar(32) primary key /* comment 'session ID'*/, + session_data text /* comment 'session data'*/, + created timestamp not null DEFAULT CURRENT_TIMESTAMP /* comment 'date this record was created'*/, + modified integer DEFAULT extract(epoch from CURRENT_TIMESTAMP) /* comment 'date this record was modified'*/ +); + +create index session_modified_idx on session (modified); + /* Textsearch stuff */ -- cgit v1.2.3-54-g00ecf From 5aa303320b4e57f5296eccba5bba7134cc12503f Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Tue, 28 Jul 2009 22:22:07 -0400 Subject: Handle UTF-8 encoded text in emails. Thanks to jaakko for pointing this out! http://identi.ca/notice/7169471 --- scripts/maildaemon.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/maildaemon.php b/scripts/maildaemon.php index a4003b6b2..9b3628b86 100755 --- a/scripts/maildaemon.php +++ b/scripts/maildaemon.php @@ -301,7 +301,7 @@ class MailerDaemon $this->extract_part($parsed,$msg,$attachments); - return array($from, $to, $msg, $attachments); + return array($from, $to, utf8_encode($msg), $attachments); } function extract_part($parsed,&$msg,&$attachments){ -- cgit v1.2.3-54-g00ecf From f3352254b792b201b1acaa93c9f58530c671ad11 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Tue, 28 Jul 2009 22:47:32 -0400 Subject: Avoid potentially double encoding already utf-8 encoded messages --- scripts/maildaemon.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/maildaemon.php b/scripts/maildaemon.php index 9b3628b86..3ef4d0638 100755 --- a/scripts/maildaemon.php +++ b/scripts/maildaemon.php @@ -301,7 +301,7 @@ class MailerDaemon $this->extract_part($parsed,$msg,$attachments); - return array($from, $to, utf8_encode($msg), $attachments); + return array($from, $to, $msg, $attachments); } function extract_part($parsed,&$msg,&$attachments){ @@ -317,6 +317,9 @@ class MailerDaemon } else if ($parsed->ctype_primary == 'text' && $parsed->ctype_secondary=='plain') { $msg = $parsed->body; + if(strtolower($parsed->ctype_parameters['charset']) != "utf-8"){ + $msg = utf8_encode($msg); + } }else if(!empty($parsed->body)){ if(common_config('attachments', 'uploads')){ //only save attachments if uploads are enabled -- cgit v1.2.3-54-g00ecf From 18573632b463c8ecf865b8a6f6a1887fa91e5ca7 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Wed, 29 Jul 2009 11:45:32 -0400 Subject: New algorithm for reply_to saving I changed the reply-to algorithm so that we only say a notice is in reply to another notice if a) we receive that information from the Web or API or b) it's in a "low bandwidth" (XMPP, SMS) channel, and begins with "@nickname" or "T NICKNAME". The goal is to avoid false-positives and make conversation trees more accurate and useful. --- classes/Notice.php | 158 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 116 insertions(+), 42 deletions(-) diff --git a/classes/Notice.php b/classes/Notice.php index c2770edbe..ebd5e1efd 100644 --- a/classes/Notice.php +++ b/classes/Notice.php @@ -102,15 +102,14 @@ class Notice extends Memcached_DataObject if (!$count) { return true; } - + //turn each into their canonical tag //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag $hashtags = array(); for($i=0; $iis_local = $is_local; } - $notice->query('BEGIN'); - - $notice->reply_to = $reply_to; if (!empty($created)) { $notice->created = $created; } else { $notice->created = common_sql_now(); } + $notice->content = $final; $notice->rendered = common_render_content($final, $notice); $notice->source = $source; $notice->uri = $uri; - if (!empty($reply_to)) { - $reply_notice = Notice::staticGet('id', $reply_to); - if (!empty($reply_notice)) { - $notice->reply_to = $reply_to; - $notice->conversation = $reply_notice->conversation; - } + $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final); + + if (!empty($notice->reply_to)) { + $reply = Notice::staticGet('id', $notice->reply_to); + $notice->conversation = $reply->conversation; } if (Event::handle('StartNoticeSave', array(&$notice))) { + // XXX: some of these functions write to the DB + + $notice->query('BEGIN'); + $id = $notice->insert(); if (!$id) { @@ -213,18 +213,33 @@ class Notice extends Memcached_DataObject return _('Problem saving notice.'); } - # Update the URI after the notice is in the database - if (!$uri) { - $orig = clone($notice); + // Update ID-dependent columns: URI, conversation + + $orig = clone($notice); + + $changed = false; + + if (empty($uri)) { $notice->uri = common_notice_uri($notice); + $changed = true; + } + + // If it's not part of a conversation, it's + // the beginning of a new conversation. + if (empty($notice->conversation)) { + $notice->conversation = $notice->id; + $changed = true; + } + + if ($changed) { if (!$notice->update($orig)) { common_log_db_error($notice, 'UPDATE', __FILE__); return _('Problem saving notice.'); } } - # XXX: do we need to change this for remote users? + // XXX: do we need to change this for remote users? $notice->saveReplies(); $notice->saveTags(); @@ -232,8 +247,13 @@ class Notice extends Memcached_DataObject $notice->addToInboxes(); $notice->saveUrls(); + + // FIXME: why do we have to re-render the content? + // Remove this if it's not necessary. + $orig2 = clone($notice); - $notice->rendered = common_render_content($final, $notice); + + $notice->rendered = common_render_content($final, $notice); if (!$notice->update($orig2)) { common_log_db_error($notice, 'UPDATE', __FILE__); return _('Problem saving notice.'); @@ -290,9 +310,9 @@ class Notice extends Memcached_DataObject $notice->profile_id = $profile_id; $notice->content = $content; if (common_config('db','type') == 'pgsql') - $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit')); + $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit')); else - $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit')); + $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit')); $cnt = $notice->count(); return ($cnt == 0); @@ -906,14 +926,14 @@ class Notice extends Memcached_DataObject { $user = new User(); - if(common_config('db','quote_identifiers')) - $user_table = '"user"'; - else $user_table = 'user'; + if(common_config('db','quote_identifiers')) + $user_table = '"user"'; + else $user_table = 'user'; $qry = 'SELECT id ' . - 'FROM '. $user_table .' JOIN subscription '. - 'ON '. $user_table .'.id = subscription.subscriber ' . + 'FROM '. $user_table .' JOIN subscription '. + 'ON '. $user_table .'.id = subscription.subscriber ' . 'WHERE subscription.subscribed = %d '; $user->query(sprintf($qry, $this->profile_id)); @@ -1031,16 +1051,6 @@ class Notice extends Memcached_DataObject if (!$recipient) { continue; } - if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self - $reply_for = $recipient; - $recipient_notice = $reply_for->getCurrentNotice(); - if ($recipient_notice) { - $orig = clone($this); - $this->reply_to = $recipient_notice->id; - $this->conversation = $recipient_notice->conversation; - $this->update($orig); - } - } // Don't save replies from blocked profile to local user $recipient_user = User::staticGet('id', $recipient->id); if ($recipient_user && $recipient_user->hasBlocked($sender)) { @@ -1087,14 +1097,6 @@ class Notice extends Memcached_DataObject } } - // If it's not a reply, make it the root of a new conversation - - if (empty($this->conversation)) { - $orig = clone($this); - $this->conversation = $this->id; - $this->update($orig); - } - foreach (array_keys($replied) as $recipient) { $user = User::staticGet('id', $recipient); if ($user) { @@ -1266,4 +1268,76 @@ class Notice extends Memcached_DataObject return $ids; } + + /** + * Determine which notice, if any, a new notice is in reply to. + * + * For conversation tracking, we try to see where this notice fits + * in the tree. Rough algorithm is: + * + * if (reply_to is set and valid) { + * return reply_to; + * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) { + * return ID of last notice by initial @name in content; + * } + * + * Note that all @nickname instances will still be used to save "reply" records, + * so the notice shows up in the mentioned users' "replies" tab. + * + * @param integer $reply_to ID passed in by Web or API + * @param integer $profile_id ID of author + * @param string $source Source tag, like 'web' or 'gwibber' + * @param string $content Final notice content + * + * @return integer ID of replied-to notice, or null for not a reply. + */ + + static function getReplyTo($reply_to, $profile_id, $source, $content) + { + static $lb = array('xmpp', 'mail', 'sms', 'omb'); + + // If $reply_to is specified, we check that it exists, and then + // return it if it does + + if (!empty($reply_to)) { + $reply_notice = Notice::staticGet('id', $reply_to); + if (!empty($reply_notice)) { + return $reply_to; + } + } + + // If it's not a "low bandwidth" source (one where you can't set + // a reply_to argument), we return. This is mostly web and API + // clients. + + if (!in_array($source, $lb)) { + return null; + } + + // Is there an initial @ or T? + + if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) || + preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) { + $nickname = common_canonical_nickname($match[1]); + } else { + return null; + } + + // Figure out who that is. + + $sender = Profile::staticGet('id', $profile_id); + $recipient = common_relative_profile($sender, $nickname, common_sql_now()); + + if (empty($recipient)) { + return null; + } + + // Get their last notice + + $last = $recipient->getCurrentNotice(); + + if (!empty($last)) { + return $last->id; + } + } } -- cgit v1.2.3-54-g00ecf From 6b48fd8f86cd4e6ee7309104bdb4e5b44b9b60c6 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 29 Jul 2009 15:33:09 -0400 Subject: move oEmbed router connection after plugins, so other endpoints (such as main/facebooklogin) from plugins don't get accidentally intercepted --- lib/router.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/router.php b/lib/router.php index 8e4836497..e10d484f4 100644 --- a/lib/router.php +++ b/lib/router.php @@ -129,11 +129,6 @@ class Router $m->connect('index.php?action=' . $action, array('action' => $action)); } - $m->connect('main/:method', - array('action' => 'api', - 'method' => 'oembed(.xml|.json)?', - 'apiaction' => 'oembed')); - // settings foreach (array('profile', 'avatar', 'password', 'openid', 'im', @@ -480,6 +475,11 @@ class Router Event::handle('RouterInitialized', array($m)); + $m->connect('main/:method', + array('action' => 'api', + 'method' => 'oembed(.xml|.json)?', + 'apiaction' => 'oembed')); + return $m; } -- cgit v1.2.3-54-g00ecf From 3350770cc7d4636fa1c0942ed01d5f26a5faa66a Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Tue, 28 Jul 2009 06:19:02 +0100 Subject: Use

    Cannot write directory:

    On your server, try this command: chmod a+w

    - Date: Tue, 28 Jul 2009 06:21:18 +0100 Subject: Pass $fancy to *_db_installer. --- install.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/install.php b/install.php index 334671599..c222afa7b 100644 --- a/install.php +++ b/install.php @@ -219,9 +219,9 @@ function handlePost() } switch($dbtype) { - case 'mysql': mysql_db_installer($host, $database, $username, $password, $sitename); + case 'mysql': mysql_db_installer($host, $database, $username, $password, $sitename, $fancy); break; - case 'pgsql': pgsql_db_installer($host, $database, $username, $password, $sitename); + case 'pgsql': pgsql_db_installer($host, $database, $username, $password, $sitename, $fancy); break; default: } @@ -232,7 +232,7 @@ function handlePost() Date: Thu, 30 Jul 2009 00:20:13 +0000 Subject: Add new Foreign_link col to store OAuth access token --- classes/Foreign_link.php | 1 + classes/laconica.ini | 1 + db/laconica.sql | 3 ++- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/classes/Foreign_link.php b/classes/Foreign_link.php index c0b356ece..a3a159eb5 100644 --- a/classes/Foreign_link.php +++ b/classes/Foreign_link.php @@ -14,6 +14,7 @@ class Foreign_link extends Memcached_DataObject public $foreign_id; // bigint(8) primary_key not_null unsigned public $service; // int(4) primary_key not_null public $credentials; // varchar(255) + public $token; // varchar(255) public $noticesync; // tinyint(1) not_null default_1 public $friendsync; // tinyint(1) not_null default_2 public $profilesync; // tinyint(1) not_null default_1 diff --git a/classes/laconica.ini b/classes/laconica.ini index 766bed75d..85d5f528d 100644 --- a/classes/laconica.ini +++ b/classes/laconica.ini @@ -127,6 +127,7 @@ user_id = 129 foreign_id = 129 service = 129 credentials = 2 +token = 2 noticesync = 145 friendsync = 145 profilesync = 145 diff --git a/db/laconica.sql b/db/laconica.sql index 2c04f680a..8b1152cbd 100644 --- a/db/laconica.sql +++ b/db/laconica.sql @@ -291,7 +291,8 @@ create table foreign_link ( user_id int comment 'link to user on this system, if exists' references user (id), foreign_id bigint unsigned comment 'link to user on foreign service, if exists' references foreign_user(id), service int not null comment 'foreign key to service' references foreign_service(id), - credentials varchar(255) comment 'authc credentials, typically a password', + credentials varchar(255) comment 'auth credentials, typically a password or token secret', + token varchar(255) comment 'access token', noticesync tinyint not null default 1 comment 'notice synchronization, bit 1 = sync outgoing, bit 2 = sync incoming, bit 3 = filter local replies', friendsync tinyint not null default 2 comment 'friend synchronization, bit 1 = sync outgoing, bit 2 = sync incoming', profilesync tinyint not null default 1 comment 'profile synchronization, bit 1 = sync outgoing, bit 2 = sync incoming', -- cgit v1.2.3-54-g00ecf From 63e8f15448ac2cfb5217ddd96bb95821b6f106c5 Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Thu, 30 Jul 2009 00:12:18 +0100 Subject: /check-fancy now works when installed in root dir. --- index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.php b/index.php index 69c0bc1b2..a73983b59 100644 --- a/index.php +++ b/index.php @@ -108,7 +108,7 @@ function checkMirror($action_obj) function main() { // quick check for fancy URL auto-detection support in installer. - if (isset($_SERVER['REDIRECT_URL']) && ((dirname($_SERVER['REQUEST_URI']) . '/check-fancy') === $_SERVER['REDIRECT_URL'])) { + if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/","",(dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) { die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs."); } global $user, $action; -- cgit v1.2.3-54-g00ecf From cd9748ad563ac8a0cf6f00f9aa3cf825647d394f Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Thu, 30 Jul 2009 19:34:32 +0000 Subject: Attempt to reduce the number of calls to FB to speed things up --- plugins/FBConnect/FBConnectPlugin.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/plugins/FBConnect/FBConnectPlugin.php b/plugins/FBConnect/FBConnectPlugin.php index 2e32ad198..6788793b2 100644 --- a/plugins/FBConnect/FBConnectPlugin.php +++ b/plugins/FBConnect/FBConnectPlugin.php @@ -122,9 +122,7 @@ class FBConnectPlugin extends Plugin FB_RequireFeatures( ["XFBML"], function() { - FB.init("%s", "../xd_receiver.html", - {"doNotUseCachedConnectState":true }); - + FB.init("%s", "../xd_receiver.html"); } ); } @@ -222,7 +220,7 @@ class FBConnectPlugin extends Plugin try { $facebook = getFacebook(); - $fbuid = $facebook->api_client->users_getLoggedInUser(); + $fbuid = $facebook->get_loggedin_user(); } catch (Exception $e) { common_log(LOG_WARNING, -- cgit v1.2.3-54-g00ecf From 15848a815efa00d89c0daa7abf340ec899059f8f Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Thu, 30 Jul 2009 15:37:35 -0400 Subject: Fix the router entries for the oEmbed endpoint so they don't accidentally catch too much --- lib/router.php | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/router.php b/lib/router.php index e10d484f4..19839b997 100644 --- a/lib/router.php +++ b/lib/router.php @@ -113,6 +113,16 @@ class Router $m->connect('main/tagother/:id', array('action' => 'tagother')); + $m->connect('main/oembed.xml', + array('action' => 'api', + 'method' => 'oembed.xml', + 'apiaction' => 'oembed')); + + $m->connect('main/oembed.json', + array('action' => 'api', + 'method' => 'oembed.json', + 'apiaction' => 'oembed')); + // these take a code foreach (array('register', 'confirmaddress', 'recoverpassword') as $c) { @@ -475,11 +485,6 @@ class Router Event::handle('RouterInitialized', array($m)); - $m->connect('main/:method', - array('action' => 'api', - 'method' => 'oembed(.xml|.json)?', - 'apiaction' => 'oembed')); - return $m; } -- cgit v1.2.3-54-g00ecf From ae81d361374641ce5cd73b353fae613711e145fe Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Thu, 30 Jul 2009 16:24:04 -0400 Subject: Site-wide design configuration I added some code so that the site-wide design can be set, using the configuration interface. I also moved the configuration option from $config['site']['design']['background'] to just $config['design']['background'], but the old syntax will still work. --- README | 17 ++++++-- classes/Design.php | 92 +++++++++++++++++++++++++++++++++-------- config.php.sample | 16 +++---- lib/action.php | 28 +++++++++++++ lib/common.php | 20 +++++---- lib/currentuserdesignaction.php | 37 ++++------------- lib/groupdesignaction.php | 30 +++----------- lib/ownerdesignaction.php | 31 ++++---------- 8 files changed, 160 insertions(+), 111 deletions(-) diff --git a/README b/README index 0bf1319c6..ef5a13934 100644 --- a/README +++ b/README @@ -964,9 +964,6 @@ sslserver: use an alternate server name for SSL URLs, like shorturllength: Length of URL at which URLs in a message exceeding 140 characters will be sent to the user's chosen shortening service. -design: a default design (colors and background) for the site. - Sub-items are: backgroundcolor, contentcolor, sidebarcolor, - textcolor, linkcolor, backgroundimage, disposition. dupelimit: minimum time allowed for one person to say the same thing twice. Default 60s. Anything lower is considered a user or UI error. @@ -1432,6 +1429,20 @@ notify third-party servers of updates. notify: an array of URLs for ping endpoints. Default is the empty array (no notification). +design +------ + +Default design (colors and background) for the site. Actual appearance +depends on the theme. Null values mean to use the theme defaults. + +backgroundcolor: Hex color of the site background. +contentcolor: Hex color of the content area background. +sidebarcolor: Hex color of the sidebar background. +textcolor: Hex color of all non-link text. +linkcolor: Hex color of all links. +backgroundimage: Image to use for the background. +disposition: Flags for whether or not to tile the background image. + Plugins ======= diff --git a/classes/Design.php b/classes/Design.php index 0927fcda7..43544f1c9 100644 --- a/classes/Design.php +++ b/classes/Design.php @@ -55,26 +55,38 @@ class Design extends Memcached_DataObject function showCSS($out) { - try { + $css = ''; - $bgcolor = new WebColor($this->backgroundcolor); - $ccolor = new WebColor($this->contentcolor); - $sbcolor = new WebColor($this->sidebarcolor); - $tcolor = new WebColor($this->textcolor); - $lcolor = new WebColor($this->linkcolor); + $bgcolor = Design::toWebColor($this->backgroundcolor); - } catch (WebColorException $e) { - // This shouldn't happen - common_log(LOG_ERR, "Unable to create color for design $id.", - __FILE__); + if (!empty($bgcolor)) { + $css .= 'body { background-color: #' . $bgcolor->hexValue() . ' }' . "\n"; + } + + $ccolor = Design::toWebColor($this->contentcolor); + + if (!empty($ccolor)) { + $css .= '#content, #site_nav_local_views .current a { background-color: #'; + $css .= $ccolor->hexValue() . '} '."\n"; + } + + $sbcolor = Design::toWebColor($this->sidebarcolor); + + if (!empty($sbcolor)) { + $css .= '#aside_primary { background-color: #'. $sbcolor->hexValue() . ' }' . "\n"; + } + + $tcolor = Design::toWebColor($this->textcolor); + + if (!empty($tcolor)) { + $css .= 'html body { color: #'. $tcolor->hexValue() . ' }'. "\n"; } - $css = 'body { background-color: #' . $bgcolor->hexValue() . ' }' . "\n"; - $css .= '#content, #site_nav_local_views .current a { background-color: #'; - $css .= $ccolor->hexValue() . '} '."\n"; - $css .= '#aside_primary { background-color: #'. $sbcolor->hexValue() . ' }' . "\n"; - $css .= 'html body { color: #'. $tcolor->hexValue() . ' }'. "\n"; - $css .= 'a { color: #' . $lcolor->hexValue() . ' }' . "\n"; + $lcolor = Design::toWebColor($this->linkcolor); + + if (!empty($lcolor)) { + $css .= 'a { color: #' . $lcolor->hexValue() . ' }' . "\n"; + } if (!empty($this->backgroundimage) && $this->disposition & BACKGROUND_ON) { @@ -88,8 +100,25 @@ class Design extends Memcached_DataObject '); ' . $repeat . ' background-attachment:fixed; }' . "\n"; } - $out->element('style', array('type' => 'text/css'), $css); + if (0 != mb_strlen($css)) { + $out->element('style', array('type' => 'text/css'), $css); + } + } + + static function toWebColor($color) + { + if (is_null($color)) { + return null; + } + try { + return new WebColor($color); + } catch (WebColorException $e) { + // This shouldn't happen + common_log(LOG_ERR, "Unable to create color for design $id.", + __FILE__); + return null; + } } static function filename($id, $extension, $extra=null) @@ -152,4 +181,33 @@ class Design extends Memcached_DataObject } } + /** + * Return a design object based on the configured site design. + * + * @return Design a singleton design object for the site. + */ + + static function siteDesign() + { + static $siteDesign = null; + + if (empty($siteDesign)) { + + $siteDesign = new Design(); + + $attrs = array('backgroundcolor', + 'contentcolor', + 'sidebarcolor', + 'textcolor', + 'linkcolor', + 'backgroundimage', + 'disposition'); + + foreach ($attrs as $attr) { + $siteDesign->$attr = common_config('design', $attr); + } + } + + return $siteDesign; + } } diff --git a/config.php.sample b/config.php.sample index 36e62f70f..c27645ff8 100644 --- a/config.php.sample +++ b/config.php.sample @@ -18,14 +18,14 @@ $config['site']['server'] = 'localhost'; $config['site']['path'] = 'laconica'; // $config['site']['fancy'] = false; // $config['site']['theme'] = 'default'; -// Sets the site's default design values (match it with the values in the theme) -// $config['site']['design']['backgroundcolor'] = '#F0F2F5'; -// $config['site']['design']['contentcolor'] = '#FFFFFF'; -// $config['site']['design']['sidebarcolor'] = '#CEE1E9'; -// $config['site']['design']['textcolor'] = '#000000'; -// $config['site']['design']['linkcolor'] = '#002E6E'; -// $config['site']['design']['backgroundimage'] = null; -// $config['site']['design']['disposition'] = 1; +// Sets the site's default design values +// $config['design']['backgroundcolor'] = '#F0F2F5'; +// $config['design']['contentcolor'] = '#FFFFFF'; +// $config['design']['sidebarcolor'] = '#CEE1E9'; +// $config['design']['textcolor'] = '#000000'; +// $config['design']['linkcolor'] = '#002E6E'; +// $config['design']['backgroundimage'] = null; +// $config['design']['disposition'] = 1; // To enable the built-in mobile style sheet, defaults to false. // $config['site']['mobile'] = true; // For contact email, defaults to $_SERVER["SERVER_ADMIN"] diff --git a/lib/action.php b/lib/action.php index 95ee10c64..a5244371a 100644 --- a/lib/action.php +++ b/lib/action.php @@ -191,6 +191,7 @@ class Action extends HTMLOutputter // lawsuit function showStylesheets() { if (Event::handle('StartShowStyles', array($this))) { + if (Event::handle('StartShowLaconicaStyles', array($this))) { $this->element('link', array('rel' => 'stylesheet', 'type' => 'text/css', @@ -209,6 +210,7 @@ class Action extends HTMLOutputter // lawsuit 'media' => 'print')); Event::handle('EndShowLaconicaStyles', array($this)); } + if (Event::handle('StartShowUAStyles', array($this))) { $this->comment('[if IE]>viewdesigns) { + $design = $this->getDesign(); + + if (!empty($design)) { + $design->showCSS($this); + } + } + + Event::handle('EndShowDesign', array($this)); + } Event::handle('EndShowStyles', array($this)); } } @@ -1074,4 +1091,15 @@ class Action extends HTMLOutputter // lawsuit { return null; } + + /** + * A design for this action + * + * @return Design a design object to use + */ + + function getDesign() + { + return Design::siteDesign(); + } } diff --git a/lib/common.php b/lib/common.php index 9d7954fa9..b3d301862 100644 --- a/lib/common.php +++ b/lib/common.php @@ -94,14 +94,6 @@ $config = array('name' => 'Just another Laconica microblog', 'server' => $_server, 'theme' => 'default', - 'design' => - array('backgroundcolor' => '#CEE1E9', - 'contentcolor' => '#FFFFFF', - 'sidebarcolor' => '#C8D1D5', - 'textcolor' => '#000000', - 'linkcolor' => '#002E6E', - 'backgroundimage' => null, - 'disposition' => 1), 'path' => $_path, 'logfile' => null, 'logo' => null, @@ -261,6 +253,14 @@ $config = 'sessions' => array('handle' => false, // whether to handle sessions ourselves 'debug' => false), // debugging output for sessions + 'design' => + array('backgroundcolor' => null, // null -> 'use theme default' + 'contentcolor' => null, + 'sidebarcolor' => null, + 'textcolor' => null, + 'linkcolor' => null, + 'backgroundimage' => null, + 'disposition' => null), ); $config['db'] = &PEAR::getStaticProperty('DB_DataObject','options'); @@ -277,6 +277,10 @@ $config['db'] = 'quote_identifiers' => false, 'type' => 'mysql' ); +// Backward compatibility + +$config['site']['design'] =& $config['design']; + if (function_exists('date_default_timezone_set')) { /* Work internally in UTC */ date_default_timezone_set('UTC'); diff --git a/lib/currentuserdesignaction.php b/lib/currentuserdesignaction.php index 4c7e15a8b..52516b624 100644 --- a/lib/currentuserdesignaction.php +++ b/lib/currentuserdesignaction.php @@ -47,33 +47,10 @@ if (!defined('LACONICA')) { class CurrentUserDesignAction extends Action { - - /** - * Show the user's design stylesheet - * - * @return nothing - */ - - function showStylesheets() - { - parent::showStylesheets(); - - $user = common_current_user(); - - if (empty($user) || $user->viewdesigns) { - $design = $this->getDesign(); - - if (!empty($design)) { - $design->showCSS($this); - } - } - } - /** * A design for this action * - * if the user attribute has been set, returns that user's - * design. + * Returns the design preferences for the current user. * * @return Design a design object to use */ @@ -82,11 +59,15 @@ class CurrentUserDesignAction extends Action { $cur = common_current_user(); - if (empty($cur)) { - return null; + if (!empty($cur)) { + + $design = $cur->getDesign(); + + if (!empty($design)) { + return $design; + } } - return $cur->getDesign(); + return parent::getDesign(); } - } diff --git a/lib/groupdesignaction.php b/lib/groupdesignaction.php index 58777c283..c7cdff1fe 100644 --- a/lib/groupdesignaction.php +++ b/lib/groupdesignaction.php @@ -49,26 +49,6 @@ class GroupDesignAction extends Action { /** The group in question */ var $group = null; - /** - * Show the groups's design stylesheet - * - * @return nothing - */ - function showStylesheets() - { - parent::showStylesheets(); - - $user = common_current_user(); - - if (empty($user) || $user->viewdesigns) { - $design = $this->getDesign(); - - if (!empty($design)) { - $design->showCSS($this); - } - } - } - /** * A design for this action * @@ -80,10 +60,12 @@ class GroupDesignAction extends Action { function getDesign() { - if (empty($this->group)) { - return null; + if (!empty($this->group)) { + $design = $this->group->getDesign(); + if (!empty($design)) { + return $design; + } } - - return $this->group->getDesign(); + return parent::getDesign(); } } diff --git a/lib/ownerdesignaction.php b/lib/ownerdesignaction.php index 785b8a93d..b42df926d 100644 --- a/lib/ownerdesignaction.php +++ b/lib/ownerdesignaction.php @@ -52,26 +52,6 @@ class OwnerDesignAction extends Action { var $user = null; - /** - * Show the owner's design stylesheet - * - * @return nothing - */ - function showStylesheets() - { - parent::showStylesheets(); - - $user = common_current_user(); - - if (empty($user) || $user->viewdesigns) { - $design = $this->getDesign(); - - if (!empty($design)) { - $design->showCSS($this); - } - } - } - /** * A design for this action * @@ -83,10 +63,15 @@ class OwnerDesignAction extends Action { function getDesign() { - if (empty($this->user)) { - return null; + if (!empty($this->user)) { + + $design = $this->user->getDesign(); + + if (!empty($design)) { + return $design; + } } - return $this->user->getDesign(); + return parent::getDesign(); } } -- cgit v1.2.3-54-g00ecf From 8371aea9c1320f8902465dea8cdf1d45a789a971 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Thu, 30 Jul 2009 16:38:50 -0400 Subject: remove debugging code about processing a new URL --- classes/File.php | 1 - 1 file changed, 1 deletion(-) diff --git a/classes/File.php b/classes/File.php index 0c4fbf7e6..7f1e7881f 100644 --- a/classes/File.php +++ b/classes/File.php @@ -93,7 +93,6 @@ class File extends Memcached_DataObject if (empty($file)) { $file_redir = File_redirection::staticGet('url', $given_url); if (empty($file_redir)) { - common_debug("processNew() '$given_url' not a known redirect.\n"); $redir_data = File_redirection::where($given_url); $redir_url = $redir_data['url']; if ($redir_url === $given_url) { -- cgit v1.2.3-54-g00ecf From 80ad02610a428bef62b18e284e15ca847a435cde Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Thu, 30 Jul 2009 20:44:51 +0000 Subject: Removed default values from s. JavaScript will now get the colours from the theme. This approach removes data that was previously available in HTML. It was only necessary if the user wanted to know the site's default values. --- js/userdesign.go.js | 31 ++++++++++++++++++++++++++++++- lib/designsettings.php | 10 +++++----- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/js/userdesign.go.js b/js/userdesign.go.js index dda86294e..70dd9c7de 100644 --- a/js/userdesign.go.js +++ b/js/userdesign.go.js @@ -7,6 +7,35 @@ * @link http://laconi.ca/ */ $(document).ready(function() { + function InitColors(i, E) { + switch (parseInt(E.id.slice(-1))) { + case 1: default: + $(E).val(rgb2hex($('body').css('background-color'))); + break; + case 2: + $(E).val(rgb2hex($('#content').css('background-color'))); + break; + case 3: + $(E).val(rgb2hex($('#aside_primary').css('background-color'))); + break; + case 4: + $(E).val(rgb2hex($('html body').css('color'))); + break; + case 5: + $(E).val(rgb2hex($('a').css('color'))); + break; + } + } + + function rgb2hex(rgb) { + rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); + function hex(x) { + hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); + return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; + } + return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); + } + function UpdateColors(S) { C = $(S).val(); switch (parseInt(S.id.slice(-1))) { @@ -55,7 +84,7 @@ $(document).ready(function() { f = $.farbtastic('#color-picker', SynchColors); swatches = $('#settings_design_color .swatch'); - + swatches.each(InitColors); swatches .each(SynchColors) .blur(function() { diff --git a/lib/designsettings.php b/lib/designsettings.php index fbffdb208..1b0e62166 100644 --- a/lib/designsettings.php +++ b/lib/designsettings.php @@ -182,7 +182,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $bgcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $ccolor = new WebColor($design->contentcolor); @@ -195,7 +195,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $ccolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $sbcolor = new WebColor($design->sidebarcolor); @@ -208,7 +208,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $sbcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $tcolor = new WebColor($design->textcolor); @@ -221,7 +221,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $tcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $lcolor = new WebColor($design->linkcolor); @@ -234,7 +234,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $lcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); } catch (WebColorException $e) { -- cgit v1.2.3-54-g00ecf From 3af5774769bd1a8193b4061c0b94ed867272c485 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Thu, 30 Jul 2009 16:55:09 -0400 Subject: throw an exception rather than die() --- classes/File.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/classes/File.php b/classes/File.php index 7f1e7881f..959301eda 100644 --- a/classes/File.php +++ b/classes/File.php @@ -113,7 +113,9 @@ class File extends Memcached_DataObject if (empty($x)) { $x = File::staticGet($file_id); - if (empty($x)) die('Impossible!'); + if (empty($x)) { + throw new ServerException("Robin thinks something is impossible."); + } } File_to_post::processNew($file_id, $notice_id); -- cgit v1.2.3-54-g00ecf From 854d24b05a052bffe21f112b705d58c9abf126a9 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Thu, 30 Jul 2009 17:05:35 -0400 Subject: Site-wide design configuration I added some code so that the site-wide design can be set, using the configuration interface. I also moved the configuration option from $config['site']['design']['background'] to just $config['design']['background'], but the old syntax will still work. Conflicts: config.php.sample --- README | 17 ++++++-- classes/Design.php | 92 +++++++++++++++++++++++++++++++++-------- config.php.sample | 8 ++++ lib/action.php | 28 +++++++++++++ lib/common.php | 20 +++++---- lib/currentuserdesignaction.php | 37 ++++------------- lib/groupdesignaction.php | 30 +++----------- lib/ownerdesignaction.php | 31 ++++---------- 8 files changed, 160 insertions(+), 103 deletions(-) diff --git a/README b/README index 0214e4931..41c015d29 100644 --- a/README +++ b/README @@ -961,9 +961,6 @@ sslserver: use an alternate server name for SSL URLs, like shorturllength: Length of URL at which URLs in a message exceeding 140 characters will be sent to the user's chosen shortening service. -design: a default design (colors and background) for the site. - Sub-items are: backgroundcolor, contentcolor, sidebarcolor, - textcolor, linkcolor, backgroundimage, disposition. dupelimit: minimum time allowed for one person to say the same thing twice. Default 60s. Anything lower is considered a user or UI error. @@ -1429,6 +1426,20 @@ notify third-party servers of updates. notify: an array of URLs for ping endpoints. Default is the empty array (no notification). +design +------ + +Default design (colors and background) for the site. Actual appearance +depends on the theme. Null values mean to use the theme defaults. + +backgroundcolor: Hex color of the site background. +contentcolor: Hex color of the content area background. +sidebarcolor: Hex color of the sidebar background. +textcolor: Hex color of all non-link text. +linkcolor: Hex color of all links. +backgroundimage: Image to use for the background. +disposition: Flags for whether or not to tile the background image. + Plugins ======= diff --git a/classes/Design.php b/classes/Design.php index 0927fcda7..43544f1c9 100644 --- a/classes/Design.php +++ b/classes/Design.php @@ -55,26 +55,38 @@ class Design extends Memcached_DataObject function showCSS($out) { - try { + $css = ''; - $bgcolor = new WebColor($this->backgroundcolor); - $ccolor = new WebColor($this->contentcolor); - $sbcolor = new WebColor($this->sidebarcolor); - $tcolor = new WebColor($this->textcolor); - $lcolor = new WebColor($this->linkcolor); + $bgcolor = Design::toWebColor($this->backgroundcolor); - } catch (WebColorException $e) { - // This shouldn't happen - common_log(LOG_ERR, "Unable to create color for design $id.", - __FILE__); + if (!empty($bgcolor)) { + $css .= 'body { background-color: #' . $bgcolor->hexValue() . ' }' . "\n"; + } + + $ccolor = Design::toWebColor($this->contentcolor); + + if (!empty($ccolor)) { + $css .= '#content, #site_nav_local_views .current a { background-color: #'; + $css .= $ccolor->hexValue() . '} '."\n"; + } + + $sbcolor = Design::toWebColor($this->sidebarcolor); + + if (!empty($sbcolor)) { + $css .= '#aside_primary { background-color: #'. $sbcolor->hexValue() . ' }' . "\n"; + } + + $tcolor = Design::toWebColor($this->textcolor); + + if (!empty($tcolor)) { + $css .= 'html body { color: #'. $tcolor->hexValue() . ' }'. "\n"; } - $css = 'body { background-color: #' . $bgcolor->hexValue() . ' }' . "\n"; - $css .= '#content, #site_nav_local_views .current a { background-color: #'; - $css .= $ccolor->hexValue() . '} '."\n"; - $css .= '#aside_primary { background-color: #'. $sbcolor->hexValue() . ' }' . "\n"; - $css .= 'html body { color: #'. $tcolor->hexValue() . ' }'. "\n"; - $css .= 'a { color: #' . $lcolor->hexValue() . ' }' . "\n"; + $lcolor = Design::toWebColor($this->linkcolor); + + if (!empty($lcolor)) { + $css .= 'a { color: #' . $lcolor->hexValue() . ' }' . "\n"; + } if (!empty($this->backgroundimage) && $this->disposition & BACKGROUND_ON) { @@ -88,8 +100,25 @@ class Design extends Memcached_DataObject '); ' . $repeat . ' background-attachment:fixed; }' . "\n"; } - $out->element('style', array('type' => 'text/css'), $css); + if (0 != mb_strlen($css)) { + $out->element('style', array('type' => 'text/css'), $css); + } + } + + static function toWebColor($color) + { + if (is_null($color)) { + return null; + } + try { + return new WebColor($color); + } catch (WebColorException $e) { + // This shouldn't happen + common_log(LOG_ERR, "Unable to create color for design $id.", + __FILE__); + return null; + } } static function filename($id, $extension, $extra=null) @@ -152,4 +181,33 @@ class Design extends Memcached_DataObject } } + /** + * Return a design object based on the configured site design. + * + * @return Design a singleton design object for the site. + */ + + static function siteDesign() + { + static $siteDesign = null; + + if (empty($siteDesign)) { + + $siteDesign = new Design(); + + $attrs = array('backgroundcolor', + 'contentcolor', + 'sidebarcolor', + 'textcolor', + 'linkcolor', + 'backgroundimage', + 'disposition'); + + foreach ($attrs as $attr) { + $siteDesign->$attr = common_config('design', $attr); + } + } + + return $siteDesign; + } } diff --git a/config.php.sample b/config.php.sample index 57aa6a6c8..c27645ff8 100644 --- a/config.php.sample +++ b/config.php.sample @@ -18,6 +18,14 @@ $config['site']['server'] = 'localhost'; $config['site']['path'] = 'laconica'; // $config['site']['fancy'] = false; // $config['site']['theme'] = 'default'; +// Sets the site's default design values +// $config['design']['backgroundcolor'] = '#F0F2F5'; +// $config['design']['contentcolor'] = '#FFFFFF'; +// $config['design']['sidebarcolor'] = '#CEE1E9'; +// $config['design']['textcolor'] = '#000000'; +// $config['design']['linkcolor'] = '#002E6E'; +// $config['design']['backgroundimage'] = null; +// $config['design']['disposition'] = 1; // To enable the built-in mobile style sheet, defaults to false. // $config['site']['mobile'] = true; // For contact email, defaults to $_SERVER["SERVER_ADMIN"] diff --git a/lib/action.php b/lib/action.php index 95ee10c64..a5244371a 100644 --- a/lib/action.php +++ b/lib/action.php @@ -191,6 +191,7 @@ class Action extends HTMLOutputter // lawsuit function showStylesheets() { if (Event::handle('StartShowStyles', array($this))) { + if (Event::handle('StartShowLaconicaStyles', array($this))) { $this->element('link', array('rel' => 'stylesheet', 'type' => 'text/css', @@ -209,6 +210,7 @@ class Action extends HTMLOutputter // lawsuit 'media' => 'print')); Event::handle('EndShowLaconicaStyles', array($this)); } + if (Event::handle('StartShowUAStyles', array($this))) { $this->comment('[if IE]>viewdesigns) { + $design = $this->getDesign(); + + if (!empty($design)) { + $design->showCSS($this); + } + } + + Event::handle('EndShowDesign', array($this)); + } Event::handle('EndShowStyles', array($this)); } } @@ -1074,4 +1091,15 @@ class Action extends HTMLOutputter // lawsuit { return null; } + + /** + * A design for this action + * + * @return Design a design object to use + */ + + function getDesign() + { + return Design::siteDesign(); + } } diff --git a/lib/common.php b/lib/common.php index c47702779..507a2a281 100644 --- a/lib/common.php +++ b/lib/common.php @@ -94,14 +94,6 @@ $config = array('name' => 'Just another Laconica microblog', 'server' => $_server, 'theme' => 'default', - 'design' => - array('backgroundcolor' => '#CEE1E9', - 'contentcolor' => '#FFFFFF', - 'sidebarcolor' => '#C8D1D5', - 'textcolor' => '#000000', - 'linkcolor' => '#002E6E', - 'backgroundimage' => null, - 'disposition' => 1), 'path' => $_path, 'logfile' => null, 'logo' => null, @@ -261,6 +253,14 @@ $config = 'sessions' => array('handle' => false, // whether to handle sessions ourselves 'debug' => false), // debugging output for sessions + 'design' => + array('backgroundcolor' => null, // null -> 'use theme default' + 'contentcolor' => null, + 'sidebarcolor' => null, + 'textcolor' => null, + 'linkcolor' => null, + 'backgroundimage' => null, + 'disposition' => null), ); $config['db'] = &PEAR::getStaticProperty('DB_DataObject','options'); @@ -277,6 +277,10 @@ $config['db'] = 'quote_identifiers' => false, 'type' => 'mysql' ); +// Backward compatibility + +$config['site']['design'] =& $config['design']; + if (function_exists('date_default_timezone_set')) { /* Work internally in UTC */ date_default_timezone_set('UTC'); diff --git a/lib/currentuserdesignaction.php b/lib/currentuserdesignaction.php index 4c7e15a8b..52516b624 100644 --- a/lib/currentuserdesignaction.php +++ b/lib/currentuserdesignaction.php @@ -47,33 +47,10 @@ if (!defined('LACONICA')) { class CurrentUserDesignAction extends Action { - - /** - * Show the user's design stylesheet - * - * @return nothing - */ - - function showStylesheets() - { - parent::showStylesheets(); - - $user = common_current_user(); - - if (empty($user) || $user->viewdesigns) { - $design = $this->getDesign(); - - if (!empty($design)) { - $design->showCSS($this); - } - } - } - /** * A design for this action * - * if the user attribute has been set, returns that user's - * design. + * Returns the design preferences for the current user. * * @return Design a design object to use */ @@ -82,11 +59,15 @@ class CurrentUserDesignAction extends Action { $cur = common_current_user(); - if (empty($cur)) { - return null; + if (!empty($cur)) { + + $design = $cur->getDesign(); + + if (!empty($design)) { + return $design; + } } - return $cur->getDesign(); + return parent::getDesign(); } - } diff --git a/lib/groupdesignaction.php b/lib/groupdesignaction.php index 58777c283..c7cdff1fe 100644 --- a/lib/groupdesignaction.php +++ b/lib/groupdesignaction.php @@ -49,26 +49,6 @@ class GroupDesignAction extends Action { /** The group in question */ var $group = null; - /** - * Show the groups's design stylesheet - * - * @return nothing - */ - function showStylesheets() - { - parent::showStylesheets(); - - $user = common_current_user(); - - if (empty($user) || $user->viewdesigns) { - $design = $this->getDesign(); - - if (!empty($design)) { - $design->showCSS($this); - } - } - } - /** * A design for this action * @@ -80,10 +60,12 @@ class GroupDesignAction extends Action { function getDesign() { - if (empty($this->group)) { - return null; + if (!empty($this->group)) { + $design = $this->group->getDesign(); + if (!empty($design)) { + return $design; + } } - - return $this->group->getDesign(); + return parent::getDesign(); } } diff --git a/lib/ownerdesignaction.php b/lib/ownerdesignaction.php index 785b8a93d..b42df926d 100644 --- a/lib/ownerdesignaction.php +++ b/lib/ownerdesignaction.php @@ -52,26 +52,6 @@ class OwnerDesignAction extends Action { var $user = null; - /** - * Show the owner's design stylesheet - * - * @return nothing - */ - function showStylesheets() - { - parent::showStylesheets(); - - $user = common_current_user(); - - if (empty($user) || $user->viewdesigns) { - $design = $this->getDesign(); - - if (!empty($design)) { - $design->showCSS($this); - } - } - } - /** * A design for this action * @@ -83,10 +63,15 @@ class OwnerDesignAction extends Action { function getDesign() { - if (empty($this->user)) { - return null; + if (!empty($this->user)) { + + $design = $this->user->getDesign(); + + if (!empty($design)) { + return $design; + } } - return $this->user->getDesign(); + return parent::getDesign(); } } -- cgit v1.2.3-54-g00ecf From d5cc1357fdc90c70b0a71a04f9448abf558c3f94 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Thu, 30 Jul 2009 17:06:03 -0400 Subject: don't ignore config.php.sample --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index f4c2bba5f..5394f5eac 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,4 @@ config-*.php good-config.php lac08.log php.log -config.php.* + -- cgit v1.2.3-54-g00ecf From 77c5f9481c5cf1cc548c73c71bd4723001d912f5 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Thu, 30 Jul 2009 20:44:51 +0000 Subject: Removed default values from s. JavaScript will now get the colours from the theme. This approach removes data that was previously available in HTML. It was only necessary if the user wanted to know the site's default values. --- js/userdesign.go.js | 31 ++++++++++++++++++++++++++++++- lib/designsettings.php | 10 +++++----- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/js/userdesign.go.js b/js/userdesign.go.js index dda86294e..70dd9c7de 100644 --- a/js/userdesign.go.js +++ b/js/userdesign.go.js @@ -7,6 +7,35 @@ * @link http://laconi.ca/ */ $(document).ready(function() { + function InitColors(i, E) { + switch (parseInt(E.id.slice(-1))) { + case 1: default: + $(E).val(rgb2hex($('body').css('background-color'))); + break; + case 2: + $(E).val(rgb2hex($('#content').css('background-color'))); + break; + case 3: + $(E).val(rgb2hex($('#aside_primary').css('background-color'))); + break; + case 4: + $(E).val(rgb2hex($('html body').css('color'))); + break; + case 5: + $(E).val(rgb2hex($('a').css('color'))); + break; + } + } + + function rgb2hex(rgb) { + rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); + function hex(x) { + hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); + return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; + } + return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); + } + function UpdateColors(S) { C = $(S).val(); switch (parseInt(S.id.slice(-1))) { @@ -55,7 +84,7 @@ $(document).ready(function() { f = $.farbtastic('#color-picker', SynchColors); swatches = $('#settings_design_color .swatch'); - + swatches.each(InitColors); swatches .each(SynchColors) .blur(function() { diff --git a/lib/designsettings.php b/lib/designsettings.php index fbffdb208..1b0e62166 100644 --- a/lib/designsettings.php +++ b/lib/designsettings.php @@ -182,7 +182,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $bgcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $ccolor = new WebColor($design->contentcolor); @@ -195,7 +195,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $ccolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $sbcolor = new WebColor($design->sidebarcolor); @@ -208,7 +208,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $sbcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $tcolor = new WebColor($design->textcolor); @@ -221,7 +221,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $tcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); $lcolor = new WebColor($design->linkcolor); @@ -234,7 +234,7 @@ class DesignSettingsAction extends AccountSettingsAction 'class' => 'swatch', 'maxlength' => '7', 'size' => '7', - 'value' => '#' . $lcolor->hexValue())); + 'value' => '')); $this->elementEnd('li'); } catch (WebColorException $e) { -- cgit v1.2.3-54-g00ecf From ec103b90e39c20bfdc2f5663e35eae8b1df212e9 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Thu, 30 Jul 2009 22:15:24 -0400 Subject: Implemented the "show" method of the laconica groups api --- actions/api.php | 1 + actions/twitapigroups.php | 26 ++++++++++++++++++++++++++ lib/twitterapi.php | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) diff --git a/actions/api.php b/actions/api.php index 8b92889f8..99ab262ad 100644 --- a/actions/api.php +++ b/actions/api.php @@ -130,6 +130,7 @@ class ApiAction extends Action 'laconica/wadl', 'tags/timeline', 'oembed/oembed', + 'groups/show', 'groups/timeline'); static $bareauth = array('statuses/user_timeline', diff --git a/actions/twitapigroups.php b/actions/twitapigroups.php index 71a0776f4..f899bc369 100644 --- a/actions/twitapigroups.php +++ b/actions/twitapigroups.php @@ -51,6 +51,32 @@ require_once INSTALLDIR.'/lib/twitterapi.php'; class TwitapigroupsAction extends TwitterapiAction { + function show($args, $apidata) + { + parent::handle($args); + + common_debug("in groups api action"); + + $this->auth_user = $apidata['user']; + $group = $this->get_group($apidata['api_arg'], $apidata); + + if (empty($group)) { + $this->clientError('Not Found', 404, $apidata['content-type']); + return; + } + + switch($apidata['content-type']) { + case 'xml': + $this->show_single_xml_group($group); + break; + case 'json': + $this->show_single_json_group($group); + break; + default: + $this->clientError(_('API method not found!'), $code = 404); + } + } + function timeline($args, $apidata) { parent::handle($args); diff --git a/lib/twitterapi.php b/lib/twitterapi.php index b2602e77c..2f969f2ba 100644 --- a/lib/twitterapi.php +++ b/lib/twitterapi.php @@ -213,6 +213,25 @@ class TwitterapiAction extends Action return $twitter_status; } + function twitter_group_array($group) + { + $twitter_group=array(); + $twitter_group['id']=$group->id; + $twitter_group['nickname']=$group->nickname; + $twitter_group['fullname']=$group->fullname; + $twitter_group['url']=$group->url; + $twitter_group['original_logo']=$group->original_logo; + $twitter_group['homepage_logo']=$group->homepage_logo; + $twitter_group['stream_logo']=$group->stream_logo; + $twitter_group['mini_logo']=$group->mini_logo; + $twitter_group['homepage']=$group->homepage; + $twitter_group['description']=$group->description; + $twitter_group['location']=$group->location; + $twitter_group['created']=$this->date_twitter($group->created); + $twitter_group['modified']=$this->date_twitter($group->modified); + return $twitter_group; + } + function twitter_rss_entry_array($notice) { $profile = $notice->getProfile(); @@ -413,6 +432,15 @@ class TwitterapiAction extends Action $this->elementEnd('status'); } + function show_twitter_xml_group($twitter_group) + { + $this->elementStart('group'); + foreach($twitter_group as $element => $value) { + $this->element($element, null, $value); + } + $this->elementEnd('group'); + } + function show_twitter_xml_user($twitter_user, $role='user') { $this->elementStart($role); @@ -639,6 +667,22 @@ class TwitterapiAction extends Action $this->end_document('json'); } + function show_single_json_group($group) + { + $this->init_document('json'); + $twitter_group = $this->twitter_group_array($group); + $this->show_json_objects($twitter_group); + $this->end_document('json'); + } + + function show_single_xml_group($group) + { + $this->init_document('xml'); + $twitter_group = $this->twitter_group_array($group); + $this->show_twitter_xml_group($twitter_group); + $this->end_document('xml'); + } + // Anyone know what date format this is? // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach function date_twitter($dt) -- cgit v1.2.3-54-g00ecf From 45ad4cfe7253d1cd2da219378fd714644c906f53 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Thu, 30 Jul 2009 22:43:07 -0400 Subject: Added a url field to hold the permalink. I believe this field is very useful for api consumers. --- lib/twitterapi.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/twitterapi.php b/lib/twitterapi.php index 2f969f2ba..e6af33e82 100644 --- a/lib/twitterapi.php +++ b/lib/twitterapi.php @@ -217,9 +217,10 @@ class TwitterapiAction extends Action { $twitter_group=array(); $twitter_group['id']=$group->id; + $twitter_group['url']=$group->permalink(); $twitter_group['nickname']=$group->nickname; $twitter_group['fullname']=$group->fullname; - $twitter_group['url']=$group->url; + $twitter_group['homepage_url']=$group->homepage_url; $twitter_group['original_logo']=$group->original_logo; $twitter_group['homepage_logo']=$group->homepage_logo; $twitter_group['stream_logo']=$group->stream_logo; -- cgit v1.2.3-54-g00ecf From 5f3af3e121a7ff06f5961bb4158e0b777ce5b5c1 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Fri, 31 Jul 2009 19:31:23 +0000 Subject: Added credit to rgb2hex() author --- js/userdesign.go.js | 1 + 1 file changed, 1 insertion(+) diff --git a/js/userdesign.go.js b/js/userdesign.go.js index 70dd9c7de..4416dc8ae 100644 --- a/js/userdesign.go.js +++ b/js/userdesign.go.js @@ -27,6 +27,7 @@ $(document).ready(function() { } } + /* rgb2hex written by R0bb13 */ function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { -- cgit v1.2.3-54-g00ecf From 6f4b2f0ac2f235332c850b050d9e4563fc71f89d Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Sat, 1 Aug 2009 08:20:44 +0000 Subject: Twitter OAuth server dance working --- actions/twitterauthorization.php | 136 +++++++++++++++++++++++++++++++++++++++ actions/twittersettings.php | 111 ++++++++++++++------------------ lib/common.php | 3 + lib/router.php | 4 ++ lib/twitteroauthclient.php | 109 +++++++++++++++++++++++++++++++ 5 files changed, 302 insertions(+), 61 deletions(-) create mode 100644 actions/twitterauthorization.php create mode 100644 lib/twitteroauthclient.php diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php new file mode 100644 index 000000000..f19cd7f65 --- /dev/null +++ b/actions/twitterauthorization.php @@ -0,0 +1,136 @@ +. + * + * @category TwitterauthorizationAction + * @package Laconica + * @author Zach Copely + * @copyright 2009 Control Yourself, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} + +class TwitterauthorizationAction extends Action +{ + + function prepare($args) + { + parent::prepare($args); + + $this->oauth_token = $this->arg('oauth_token'); + + return true; + } + + function handle($args) + { + parent::handle($args); + + if (!common_logged_in()) { + $this->clientError(_('Not logged in.'), 403); + } + + $user = common_current_user(); + $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); + + // If there's already a foreign link record, it means we already + // have an access token, and this is unecessary. So go back. + + if (isset($flink)) { + common_redirect(common_local_url('twittersettings')); + } + + // $this->oauth_token is only populated once Twitter authorizes our + // request token. If it's empty we're at the beginning of the auth + // process + + if (empty($this->oauth_token)) { + + // Get a new request token and authorize it + + $client = new TwitterOAuthClient(); + $req_tok = $client->getRequestToken(); + + // Sock the request token away in the session temporarily + + $_SESSION['twitter_request_token'] = $req_tok->key; + $_SESSION['twitter_request_token_secret'] = $req_tok->key; + + $auth_link = $client->getAuthorizeLink($req_tok); + common_redirect($auth_link); + + } else { + + // Check to make sure Twitter sent us the same request token we sent + + if ($_SESSION['twitter_request_token'] != $this->oauth_token) { + $this->serverError(_('Couldn\'t link your Twitter account.')); + } + + $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], + $_SESSION['twitter_request_token_secret']); + + // Exchange the request token for an access token + + $atok = $client->getAccessToken(); + + // Save the access token and Twitter user info + + $client = new TwitterOAuthClient($atok->key, $atok->secret); + + $twitter_user = $client->verify_credentials(); + + $user = common_current_user(); + + $flink = new Foreign_link(); + + $flink->user_id = $user->id; + $flink->foreign_id = $twitter_user->id; + $flink->service = TWITTER_SERVICE; + $flink->token = $atok->key; + $flink->credentials = $atok->secret; + $flink->created = common_sql_now(); + + $flink->set_flags(true, false, false, false); + + $flink_id = $flink->insert(); + + if (empty($flink_id)) { + common_log_db_error($flink, 'INSERT', __FILE__); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } + + save_twitter_user($twitter_user->id, $twitter_user->screen_name); + + // clean up the the mess we made in the session + + unset($_SESSION['twitter_request_token']); + unset($_SESSION['twitter_request_token_secret']); + + common_redirect(common_local_url('twittersettings')); + } + } + +} + diff --git a/actions/twittersettings.php b/actions/twittersettings.php index 2b742788e..acc9fb935 100644 --- a/actions/twittersettings.php +++ b/actions/twittersettings.php @@ -69,9 +69,8 @@ class TwittersettingsAction extends ConnectSettingsAction function getInstructions() { - return _('Add your Twitter account to automatically send '. - ' your notices to Twitter, ' . - 'and subscribe to Twitter friends already here.'); + return _('Connect your Twitter account to share your updates ' . + 'with your Twitter friends and vice-versa.'); } /** @@ -93,7 +92,7 @@ class TwittersettingsAction extends ConnectSettingsAction $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); - if ($flink) { + if (!empty($flink)) { $fuser = $flink->getForeignUser(); } @@ -102,73 +101,61 @@ class TwittersettingsAction extends ConnectSettingsAction 'class' => 'form_settings', 'action' => common_local_url('twittersettings'))); - $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); - $this->element('legend', null, _('Twitter Account')); + $this->hidden('token', common_session_token()); - if ($fuser) { + + + if (empty($fuser)) { + + $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); $this->elementStart('ul', 'form_data'); - $this->elementStart('li', array('id' => 'settings_twitter_remove')); - $this->element('span', 'twitter_user', $fuser->nickname); - $this->element('a', array('href' => $fuser->uri), $fuser->uri); - $this->element('p', 'form_note', - _('Current verified Twitter account.')); - $this->hidden('flink_foreign_id', $flink->foreign_id); - $this->elementEnd('li'); + $this->elementStart('li', array('id' => 'settings_twitter_login_button')); + $this->element('a', array('href' => common_local_url('twitterauthorization')), + 'Connect my Twitter account'); + $this->elementEnd('li'); $this->elementEnd('ul'); - $this->submit('remove', _('Remove')); + $this->elementEnd('fieldset'); + } else { + + $this->elementStart('fieldset', + array('id' => 'settings_twitter_preferences')); + $this->element('legend', null, _('Preferences')); + $this->elementStart('ul', 'form_data'); - $this->elementStart('li', array('id' => 'settings_twitter_login')); - $this->input('twitter_username', _('Twitter user name'), - ($this->arg('twitter_username')) ? - $this->arg('twitter_username') : - $profile->nickname, - _('No spaces, please.')); // hey, it's what Twitter says + $this->elementStart('li'); + $this->checkbox('noticesend', + _('Automatically send my notices to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND) : + true); $this->elementEnd('li'); $this->elementStart('li'); - $this->password('twitter_password', _('Twitter password')); - $this->elementend('li'); - $this->elementEnd('ul'); - } - $this->elementEnd('fieldset'); + $this->checkbox('replysync', + _('Send local "@" replies to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : + true); + $this->elementEnd('li'); + $this->elementStart('li'); + $this->checkbox('friendsync', + _('Subscribe to my Twitter friends here.'), + ($flink) ? + ($flink->friendsync & FOREIGN_FRIEND_RECV) : + false); + $this->elementEnd('li'); - $this->elementStart('fieldset', - array('id' => 'settings_twitter_preferences')); - $this->element('legend', null, _('Preferences')); - - $this->elementStart('ul', 'form_data'); - $this->elementStart('li'); - $this->checkbox('noticesend', - _('Automatically send my notices to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND) : - true); - $this->elementEnd('li'); - $this->elementStart('li'); - $this->checkbox('replysync', - _('Send local "@" replies to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : - true); - $this->elementEnd('li'); - $this->elementStart('li'); - $this->checkbox('friendsync', - _('Subscribe to my Twitter friends here.'), - ($flink) ? - ($flink->friendsync & FOREIGN_FRIEND_RECV) : - false); - $this->elementEnd('li'); - - if (common_config('twitterbridge','enabled')) { + if (common_config('twitterbridge','enabled')) { $this->elementStart('li'); $this->checkbox('noticerecv', - _('Import my Friends Timeline.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_RECV) : - false); + _('Import my Friends Timeline.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_RECV) : + false); $this->elementEnd('li'); - } else { + // preserve setting even if bidrection bridge toggled off + if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) { $this->hidden('noticerecv', true, 'noticerecv'); } @@ -181,11 +168,13 @@ class TwittersettingsAction extends ConnectSettingsAction } else { $this->submit('add', _('Add')); } + $this->elementEnd('fieldset'); + } - $this->showTwitterSubscriptions(); + $this->showTwitterSubscriptions(); - $this->elementEnd('form'); + $this->elementEnd('form'); } /** diff --git a/lib/common.php b/lib/common.php index 9d7954fa9..f9ac66f4f 100644 --- a/lib/common.php +++ b/lib/common.php @@ -196,6 +196,9 @@ $config = 'integration' => array('source' => 'Laconica', # source attribute for Twitter 'taguri' => $_server.',2009'), # base for tag URIs + 'twitter' => + array('consumer_key' => null, + 'consumer_secret' => null), 'memcached' => array('enabled' => false, 'server' => 'localhost', diff --git a/lib/router.php b/lib/router.php index e10d484f4..582dfae6d 100644 --- a/lib/router.php +++ b/lib/router.php @@ -88,6 +88,10 @@ class Router $m->connect('doc/:title', array('action' => 'doc')); + // Twitter + + $m->connect('twitter/authorization', array('action' => 'twitterauthorization')); + // facebook $m->connect('facebook', array('action' => 'facebookhome')); diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php new file mode 100644 index 000000000..616fbc213 --- /dev/null +++ b/lib/twitteroauthclient.php @@ -0,0 +1,109 @@ +sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); + $consumer_key = common_config('twitter', 'consumer_key'); + $consumer_secret = common_config('twitter', 'consumer_secret'); + $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); + $this->token = null; + + if (isset($oauth_token) && isset($oauth_token_secret)) { + $this->token = new OAuthToken($oauth_token, $oauth_token_secret); + } + } + + function getRequestToken() + { + $response = $this->oAuthGet(TwitterOAuthClient::$requestTokenURL); + parse_str($response); + $token = new OAuthToken($oauth_token, $oauth_token_secret); + return $token; + } + + function getAuthorizeLink($request_token) + { + // Not sure Twitter actually looks at oauth_callback + + return TwitterOAuthClient::$authorizeURL . + '?oauth_token=' . $request_token->key . '&oauth_callback=' . + urlencode(common_local_url('twitterauthorization')); + } + + function getAccessToken() + { + $response = $this->oAuthPost(TwitterOAuthClient::$accessTokenURL); + parse_str($response); + $token = new OAuthToken($oauth_token, $oauth_token_secret); + return $token; + } + + function verify_credentials() + { + $url = 'https://twitter.com/account/verify_credentials.json'; + $response = $this->oAuthGet($url); + $twitter_user = json_decode($response); + return $twitter_user; + } + + function oAuthGet($url) + { + $request = OAuthRequest::from_consumer_and_token($this->consumer, + $this->token, 'GET', $url, null); + $request->sign_request($this->sha1_method, + $this->consumer, $this->token); + + return $this->httpRequest($request->to_url()); + } + + function oAuthPost($url, $params = null) + { + $request = OAuthRequest::from_consumer_and_token($this->consumer, + $this->token, 'POST', $url, $params); + $request->sign_request($this->sha1_method, + $this->consumer, $this->token); + + return $this->httpRequest($request->get_normalized_http_url(), + $request->to_postdata()); + } + + function httpRequest($url, $params = null) + { + $options = array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FAILONERROR => true, + CURLOPT_HEADER => false, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_USERAGENT => 'Laconica', + CURLOPT_CONNECTTIMEOUT => 120, + CURLOPT_TIMEOUT => 120, + CURLOPT_HTTPAUTH => CURLAUTH_ANY, + CURLOPT_SSL_VERIFYPEER => false, + + // Twitter is strict about accepting invalid "Expect" headers + + CURLOPT_HTTPHEADER => array('Expect:') + ); + + if (isset($params)) { + $options[CURLOPT_POST] = true; + $options[CURLOPT_POSTFIELDS] = $params; + } + + $ch = curl_init($url); + curl_setopt_array($ch, $options); + $response = curl_exec($ch); + curl_close($ch); + + return $response; + } + +} -- cgit v1.2.3-54-g00ecf From b2d2b19d3a8fae84e1bc6532661c71ac180eceec Mon Sep 17 00:00:00 2001 From: Jeffery To Date: Sun, 2 Aug 2009 19:36:09 +0800 Subject: Fixed PHP Notice "Use of undefined constant session_name - assumed 'session_name'" --- lib/util.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/util.php b/lib/util.php index d784bb793..db794181c 100644 --- a/lib/util.php +++ b/lib/util.php @@ -140,7 +140,7 @@ function common_have_session() function common_ensure_session() { $c = null; - if (array_key_exists(session_name, $_COOKIE)) { + if (array_key_exists(session_name(), $_COOKIE)) { $c = $_COOKIE[session_name()]; } if (!common_have_session()) { -- cgit v1.2.3-54-g00ecf From 6c1bd6759127968908a0d7f179447a7a6f653d17 Mon Sep 17 00:00:00 2001 From: Jeffery To Date: Sun, 2 Aug 2009 19:38:03 +0800 Subject: Fixed PHP Notice "Undefined index: enclosures" (and a possible one for 'tags') --- lib/twitterapi.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/twitterapi.php b/lib/twitterapi.php index e6af33e82..4115d9dcb 100644 --- a/lib/twitterapi.php +++ b/lib/twitterapi.php @@ -479,12 +479,12 @@ class TwitterapiAction extends Action $this->element('link', null, $entry['link']); # RSS only supports 1 enclosure per item - if($entry['enclosures']){ + if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){ $enclosure = $entry['enclosures'][0]; $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null); } - if($entry['tags']){ + if(array_key_exists('tags', $entry)){ foreach($entry['tags'] as $tag){ $this->element('category', null,$tag); } -- cgit v1.2.3-54-g00ecf From fe57e2e06b3ae5e7eb9001a0ffe80d9a7d20a5be Mon Sep 17 00:00:00 2001 From: Jeffery To Date: Sun, 2 Aug 2009 19:47:36 +0800 Subject: Fixed PHP Notice "Undefined variable: suplink" --- actions/twitapigroups.php | 5 ++--- actions/twitapitags.php | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/actions/twitapigroups.php b/actions/twitapigroups.php index f899bc369..82604ebff 100644 --- a/actions/twitapigroups.php +++ b/actions/twitapigroups.php @@ -114,8 +114,7 @@ require_once INSTALLDIR.'/lib/twitterapi.php'; $this->show_xml_timeline($notice); break; case 'rss': - $this->show_rss_timeline($notice, $title, $link, - $subtitle, $suplink); + $this->show_rss_timeline($notice, $title, $link, $subtitle); break; case 'atom': if (isset($apidata['api_arg'])) { @@ -127,7 +126,7 @@ require_once INSTALLDIR.'/lib/twitterapi.php'; 'api/laconica/groups/timeline.atom'; } $this->show_atom_timeline($notice, $title, $id, $link, - $subtitle, $suplink, $selfuri); + $subtitle, null, $selfuri); break; case 'json': $this->show_json_timeline($notice); diff --git a/actions/twitapitags.php b/actions/twitapitags.php index 5c8527530..e19e1b1ed 100644 --- a/actions/twitapitags.php +++ b/actions/twitapitags.php @@ -88,8 +88,7 @@ require_once INSTALLDIR.'/lib/twitterapi.php'; $this->show_xml_timeline($notice); break; case 'rss': - $this->show_rss_timeline($notice, $title, $link, - $subtitle, $suplink); + $this->show_rss_timeline($notice, $title, $link, $subtitle); break; case 'atom': if (isset($apidata['api_arg'])) { @@ -101,7 +100,7 @@ require_once INSTALLDIR.'/lib/twitterapi.php'; 'api/laconica/tags/timeline.atom'; } $this->show_atom_timeline($notice, $title, $id, $link, - $subtitle, $suplink, $selfuri); + $subtitle, null, $selfuri); break; case 'json': $this->show_json_timeline($notice); -- cgit v1.2.3-54-g00ecf From 20c536fdd461c8f39dd6a03751b534a996a94078 Mon Sep 17 00:00:00 2001 From: Jeffery To Date: Sun, 2 Aug 2009 19:52:27 +0800 Subject: Fixed PHP Notice "Undefined variable: cnt" --- actions/conversation.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actions/conversation.php b/actions/conversation.php index c8755ba6e..6b5d8d54d 100644 --- a/actions/conversation.php +++ b/actions/conversation.php @@ -167,6 +167,8 @@ class ConversationTree extends NoticeList function _buildTree() { + $cnt = 0; + $this->tree = array(); $this->table = array(); -- cgit v1.2.3-54-g00ecf From e670e4306bf3e0e7e90523bcbfa2eb8060f4ed67 Mon Sep 17 00:00:00 2001 From: Jeffery To Date: Sun, 2 Aug 2009 20:10:31 +0800 Subject: Fixed PHP Notices: Undefined index: HTTP_X_FORWARDED_FOR Undefined index: HTTP_CLIENT_IP Undefined variable: proxy Also fixed the return value order to match calls to common_client_ip() in actions/api.php and lib/rssaction.php --- lib/util.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/util.php b/lib/util.php index db794181c..c8e318efe 100644 --- a/lib/util.php +++ b/lib/util.php @@ -1410,20 +1410,21 @@ function common_client_ip() return null; } - if ($_SERVER['HTTP_X_FORWARDED_FOR']) { - if ($_SERVER['HTTP_CLIENT_IP']) { + if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) { + if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) { $proxy = $_SERVER['HTTP_CLIENT_IP']; } else { $proxy = $_SERVER['REMOTE_ADDR']; } $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { - if ($_SERVER['HTTP_CLIENT_IP']) { + $proxy = null; + if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) { $ip = $_SERVER['HTTP_CLIENT_IP']; } else { $ip = $_SERVER['REMOTE_ADDR']; } } - return array($ip, $proxy); + return array($proxy, $ip); } -- cgit v1.2.3-54-g00ecf From 34e8b25ceef890c0d1e41b75696b19e8b53db960 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sun, 2 Aug 2009 10:34:23 -0400 Subject: GC sessions one by one to make sure memcached gets cleared --- classes/Session.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/classes/Session.php b/classes/Session.php index ac80279c5..a92ce405b 100644 --- a/classes/Session.php +++ b/classes/Session.php @@ -110,9 +110,18 @@ class Session extends Memcached_DataObject $session = new Session(); $session->whereAdd('modified < "'.$epoch.'"'); - $result = $session->delete(DB_DATAOBJECT_WHEREADD_ONLY); - self::logdeb("garbage collection result = $result"); + $session->find(); + + while ($session->fetch()) { + $other = new Session(); + $other->id = $session->id; + self::logdeb("Collecting session $other->id"); + $result = $other->delete(); + self::logdeb("garbage collection result = $result"); + } + + $session->free(); } static function setSaveHandler() -- cgit v1.2.3-54-g00ecf From 2934099fbd17281ed00055af654aa5b813d535a2 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sun, 2 Aug 2009 10:34:40 -0400 Subject: A script to GC sessions correctly --- scripts/sessiongc.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 scripts/sessiongc.php diff --git a/scripts/sessiongc.php b/scripts/sessiongc.php new file mode 100644 index 000000000..314b641eb --- /dev/null +++ b/scripts/sessiongc.php @@ -0,0 +1,36 @@ +#!/usr/bin/env php +. + */ + +define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); + +$helptext = << Date: Sun, 2 Aug 2009 10:34:23 -0400 Subject: GC sessions one by one to make sure memcached gets cleared --- classes/Session.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/classes/Session.php b/classes/Session.php index ac80279c5..a92ce405b 100644 --- a/classes/Session.php +++ b/classes/Session.php @@ -110,9 +110,18 @@ class Session extends Memcached_DataObject $session = new Session(); $session->whereAdd('modified < "'.$epoch.'"'); - $result = $session->delete(DB_DATAOBJECT_WHEREADD_ONLY); - self::logdeb("garbage collection result = $result"); + $session->find(); + + while ($session->fetch()) { + $other = new Session(); + $other->id = $session->id; + self::logdeb("Collecting session $other->id"); + $result = $other->delete(); + self::logdeb("garbage collection result = $result"); + } + + $session->free(); } static function setSaveHandler() -- cgit v1.2.3-54-g00ecf From f342db586d2d95035c53581bebba66eb7e7f7eec Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sun, 2 Aug 2009 10:34:40 -0400 Subject: A script to GC sessions correctly --- scripts/sessiongc.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 scripts/sessiongc.php diff --git a/scripts/sessiongc.php b/scripts/sessiongc.php new file mode 100644 index 000000000..314b641eb --- /dev/null +++ b/scripts/sessiongc.php @@ -0,0 +1,36 @@ +#!/usr/bin/env php +. + */ + +define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); + +$helptext = << Date: Sun, 2 Aug 2009 11:18:41 -0400 Subject: don't delete during select --- classes/Session.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/classes/Session.php b/classes/Session.php index a92ce405b..5ec509f5f 100644 --- a/classes/Session.php +++ b/classes/Session.php @@ -108,20 +108,24 @@ class Session extends Memcached_DataObject $epoch = common_sql_date(time() - $maxlifetime); + $ids = array(); + $session = new Session(); $session->whereAdd('modified < "'.$epoch.'"'); + $session->selectAdd(); + $session->selectAdd('id'); $session->find(); while ($session->fetch()) { - $other = new Session(); - $other->id = $session->id; - self::logdeb("Collecting session $other->id"); - $result = $other->delete(); - self::logdeb("garbage collection result = $result"); + $ids[] = $session->id; } $session->free(); + + foreach ($ids as $id) { + self::destroy($id); + } } static function setSaveHandler() -- cgit v1.2.3-54-g00ecf From b27af3247d4e0a13a1cd8b29e3938e8d81fa3d22 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sun, 2 Aug 2009 11:18:41 -0400 Subject: don't delete during select --- classes/Session.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/classes/Session.php b/classes/Session.php index a92ce405b..5ec509f5f 100644 --- a/classes/Session.php +++ b/classes/Session.php @@ -108,20 +108,24 @@ class Session extends Memcached_DataObject $epoch = common_sql_date(time() - $maxlifetime); + $ids = array(); + $session = new Session(); $session->whereAdd('modified < "'.$epoch.'"'); + $session->selectAdd(); + $session->selectAdd('id'); $session->find(); while ($session->fetch()) { - $other = new Session(); - $other->id = $session->id; - self::logdeb("Collecting session $other->id"); - $result = $other->delete(); - self::logdeb("garbage collection result = $result"); + $ids[] = $session->id; } $session->free(); + + foreach ($ids as $id) { + self::destroy($id); + } } static function setSaveHandler() -- cgit v1.2.3-54-g00ecf From 92ef468fcc5adf6e9445b3b80b87fdc8e55896dd Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Mon, 3 Aug 2009 11:47:58 -0400 Subject: Use the same favorite notification function in the API as everywhere else http://laconi.ca/trac/ticket/873 --- actions/twitapifavorites.php | 26 ++------------------------ 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/actions/twitapifavorites.php b/actions/twitapifavorites.php index 8256668f3..6f9361065 100644 --- a/actions/twitapifavorites.php +++ b/actions/twitapifavorites.php @@ -207,32 +207,10 @@ class TwitapifavoritesAction extends TwitterapiAction $other = User::staticGet('id', $notice->profile_id); if ($other && $other->id != $user->id) { if ($other->email && $other->emailnotifyfav) { - $this->notify_mail($other, $user, $notice); + mail_notify_fave($other, $user, $notice); } # XXX: notify by IM # XXX: notify by SMS } } - - function notify_mail($other, $user, $notice) - { - $profile = $user->getProfile(); - $bestname = $profile->getBestName(); - $subject = sprintf(_('%s added your notice as a favorite'), $bestname); - $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . - "In case you forgot, you can see the text of your notice here:\n\n" . - "%3\$s\n\n" . - "You can see the list of %1\$s's favorites here:\n\n" . - "%4\$s\n\n" . - "Faithfully yours,\n" . - "%5\$s\n"), - $bestname, - common_exact_date($notice->created), - common_local_url('shownotice', array('notice' => $notice->id)), - common_local_url('showfavorites', array('nickname' => $user->nickname)), - common_config('site', 'name')); - - mail_to_user($other, $subject, $body); - } - -} \ No newline at end of file +} -- cgit v1.2.3-54-g00ecf From d0b85d3ad2cb8244a62489742706ad95b78ef4eb Mon Sep 17 00:00:00 2001 From: Brenda Wallace Date: Tue, 4 Aug 2009 08:43:13 +1200 Subject: Upgrade script --- db/074to080_pg.sql | 108 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 db/074to080_pg.sql diff --git a/db/074to080_pg.sql b/db/074to080_pg.sql new file mode 100644 index 000000000..0a7171ae5 --- /dev/null +++ b/db/074to080_pg.sql @@ -0,0 +1,108 @@ +BEGIN; +create sequence design_seq; +create table design ( + id bigint default nextval('design_seq') /* comment 'design ID'*/, + backgroundcolor integer /* comment 'main background color'*/ , + contentcolor integer /*comment 'content area background color'*/ , + sidebarcolor integer /*comment 'sidebar background color'*/ , + textcolor integer /*comment 'text color'*/ , + linkcolor integer /*comment 'link color'*/, + backgroundimage varchar(255) /*comment 'background image, if any'*/, + disposition int default 1 /*comment 'bit 1 = hide background image, bit 2 = display background image, bit 4 = tile background image'*/, + primary key (id) +); +alter table "user" + add column design_id integer references design(id); +alter table "user" + add column viewdesigns integer default 1; + +alter table notice add column + conversation integer references notice (id); + +create index notice_conversation_idx on notice(conversation); + +alter table foreign_user + alter column id TYPE bigint; + +alter table foreign_user alter column id set not null; + +alter table foreign_link + alter column foreign_id TYPE bigint; + +alter table user_group + add column design_id integer; + +/*attachments and URLs stuff */ +create sequence file_seq; +create table file ( + id bigint default nextval('file_seq') primary key /* comment 'unique identifier' */, + url varchar(255) unique, + mimetype varchar(50), + size integer, + title varchar(255), + date integer, + protected integer, + filename text /* comment 'if a local file, name of the file' */, + modified timestamp default CURRENT_TIMESTAMP /* comment 'date this record was modified'*/ +); + +create sequence file_oembed_seq; +create table file_oembed ( + file_id bigint default nextval('file_oembed_seq') primary key /* comment 'unique identifier' */, + version varchar(20), + type varchar(20), + provider varchar(50), + provider_url varchar(255), + width integer, + height integer, + html text, + title varchar(255), + author_name varchar(50), + author_url varchar(255), + url varchar(255) +); + +create sequence file_redirection_seq; +create table file_redirection ( + url varchar(255) primary key, + file_id bigint, + redirections integer, + httpcode integer +); + +create sequence file_thumbnail_seq; +create table file_thumbnail ( + file_id bigint primary key, + url varchar(255) unique, + width integer, + height integer +); +create sequence file_to_post_seq; +create table file_to_post ( + file_id bigint, + post_id bigint, + + primary key (file_id, post_id) +); + + +create table group_block ( + group_id integer not null /* comment 'group profile is blocked from' */ references user_group (id), + blocked integer not null /* comment 'profile that is blocked' */references profile (id), + blocker integer not null /* comment 'user making the block'*/ references "user" (id), + modified timestamp /* comment 'date of blocking'*/ , + + primary key (group_id, blocked) +); + +create table group_alias ( + + alias varchar(64) /* comment 'additional nickname for the group'*/ , + group_id integer not null /* comment 'group profile is blocked from'*/ references user_group (id), + modified timestamp /* comment 'date alias was created'*/, + primary key (alias) + +); +create index group_alias_group_id_idx on group_alias (group_id); + +COMMIT; \ No newline at end of file -- cgit v1.2.3-54-g00ecf From ff6e976d0315c57fc5b7e31845e9a3bad4f095bc Mon Sep 17 00:00:00 2001 From: Eric Helgeson Date: Mon, 3 Aug 2009 16:39:10 -0500 Subject: Added the 0.2 recaptcha plugin. Should work in all browsers. Please test. --- plugins/recaptcha/LICENSE | 22 +++ plugins/recaptcha/README | 23 +++ plugins/recaptcha/recaptcha.php | 106 ++++++++++++++ plugins/recaptcha/recaptchalib.php | 277 +++++++++++++++++++++++++++++++++++++ 4 files changed, 428 insertions(+) create mode 100644 plugins/recaptcha/LICENSE create mode 100644 plugins/recaptcha/README create mode 100644 plugins/recaptcha/recaptcha.php create mode 100644 plugins/recaptcha/recaptchalib.php diff --git a/plugins/recaptcha/LICENSE b/plugins/recaptcha/LICENSE new file mode 100644 index 000000000..b612f71f0 --- /dev/null +++ b/plugins/recaptcha/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net +AUTHORS: + Mike Crawford + Ben Maurer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/plugins/recaptcha/README b/plugins/recaptcha/README new file mode 100644 index 000000000..3100f697e --- /dev/null +++ b/plugins/recaptcha/README @@ -0,0 +1,23 @@ +Laconica reCAPTCHA plugin 0.2 8/3/09 +==================================== +Adds a captcha to your registration page to reduce automated spam bots registering. + +Use: +1. Get an API key from http://recaptcha.net + +2. In config.php add: +include_once('plugins/recaptcha.php'); +$captcha = new recaptcha(publickey, privatekey, showErrors); + +Changelog +========= +0.1 initial release +0.2 Work around for webkit browsers + +reCAPTCHA README +================ + +The reCAPTCHA PHP Lirary helps you use the reCAPTCHA API. Documentation +for this library can be found at + + http://recaptcha.net/plugins/php diff --git a/plugins/recaptcha/recaptcha.php b/plugins/recaptcha/recaptcha.php new file mode 100644 index 000000000..5ef8352d1 --- /dev/null +++ b/plugins/recaptcha/recaptcha.php @@ -0,0 +1,106 @@ +. + * + * @category Plugin + * @package Laconica + * @author Eric Helgeson + * @copyright 2009 + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} + +define('RECAPTCHA', '0.2'); + +class recaptcha extends Plugin +{ + var $private_key; + var $public_key; + var $display_errors; + var $failed; + var $ssl; + + function __construct($public_key, $private_key, $display_errors=false) + { + parent::__construct(); + require_once(INSTALLDIR.'/plugins/recaptcha/recaptchalib.php'); + $this->public_key = $public_key; + $this->private_key = $private_key; + $this->display_errors = $display_errors; + } + + function checkssl(){ + if(common_config('site', 'ssl') === 'sometimes' || common_config('site', 'ssl') === 'always') { + return true; + } + return false; + } + + function onStartShowHTML($action) + { + //XXX: Horrible hack to make Safari, FF2, and Chrome work with + //reChapcha. reChapcha beaks xhtml strict + header('Content-Type: text/html'); + + $action->extraHeaders(); + + $action->startXML('html', + '-//W3C//DTD XHTML 1.0 Strict//EN', + 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + + $action->raw(''); + return false; + } + + function onEndRegistrationFormData($action) + { + $action->elementStart('li'); + $action->raw(''); + if($this->checkssl() === true){ + $action->raw(recaptcha_get_html($this->public_key), null, true); + } else { + $action->raw(recaptcha_get_html($this->public_key)); + } + $action->elementEnd('li'); + return true; + } + + function onStartRegistrationTry($action) + { + $resp = recaptcha_check_answer ($this->private_key, + $_SERVER["REMOTE_ADDR"], + $action->trimmed('recaptcha_challenge_field'), + $action->trimmed('recaptcha_response_field')); + + if (!$resp->is_valid) + { + if($this->display_errors) + { + $action->showForm ("(reCAPTCHA said: " . $resp->error . ")"); + } + $action->showForm("Captcha does not match!"); + return false; + } + } +} diff --git a/plugins/recaptcha/recaptchalib.php b/plugins/recaptcha/recaptchalib.php new file mode 100644 index 000000000..897c50981 --- /dev/null +++ b/plugins/recaptcha/recaptchalib.php @@ -0,0 +1,277 @@ + $value ) + $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; + + // Cut the last '&' + $req=substr($req,0,strlen($req)-1); + return $req; +} + + + +/** + * Submits an HTTP POST to a reCAPTCHA server + * @param string $host + * @param string $path + * @param array $data + * @param int port + * @return array response + */ +function _recaptcha_http_post($host, $path, $data, $port = 80) { + + $req = _recaptcha_qsencode ($data); + + $http_request = "POST $path HTTP/1.0\r\n"; + $http_request .= "Host: $host\r\n"; + $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; + $http_request .= "Content-Length: " . strlen($req) . "\r\n"; + $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; + $http_request .= "\r\n"; + $http_request .= $req; + + $response = ''; + if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { + die ('Could not open socket'); + } + + fwrite($fs, $http_request); + + while ( !feof($fs) ) + $response .= fgets($fs, 1160); // One TCP-IP packet + fclose($fs); + $response = explode("\r\n\r\n", $response, 2); + + return $response; +} + + + +/** + * Gets the challenge HTML (javascript and non-javascript version). + * This is called from the browser, and the resulting reCAPTCHA HTML widget + * is embedded within the HTML form it was called from. + * @param string $pubkey A public key for reCAPTCHA + * @param string $error The error given by reCAPTCHA (optional, default is null) + * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) + + * @return string - The HTML to be embedded in the user's form. + */ +function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) +{ + if ($pubkey == null || $pubkey == '') { + die ("To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey"); + } + + if ($use_ssl) { + $server = RECAPTCHA_API_SECURE_SERVER; + } else { + $server = RECAPTCHA_API_SERVER; + } + + $errorpart = ""; + if ($error) { + $errorpart = "&error=" . $error; + } + return ' + + '; +} + + + + +/** + * A ReCaptchaResponse is returned from recaptcha_check_answer() + */ +class ReCaptchaResponse { + var $is_valid; + var $error; +} + + +/** + * Calls an HTTP POST function to verify if the user's guess was correct + * @param string $privkey + * @param string $remoteip + * @param string $challenge + * @param string $response + * @param array $extra_params an array of extra variables to post to the server + * @return ReCaptchaResponse + */ +function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) +{ + if ($privkey == null || $privkey == '') { + die ("To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey"); + } + + if ($remoteip == null || $remoteip == '') { + die ("For security reasons, you must pass the remote ip to reCAPTCHA"); + } + + + + //discard spam submissions + if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { + $recaptcha_response = new ReCaptchaResponse(); + $recaptcha_response->is_valid = false; + $recaptcha_response->error = 'incorrect-captcha-sol'; + return $recaptcha_response; + } + + $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/verify", + array ( + 'privatekey' => $privkey, + 'remoteip' => $remoteip, + 'challenge' => $challenge, + 'response' => $response + ) + $extra_params + ); + + $answers = explode ("\n", $response [1]); + $recaptcha_response = new ReCaptchaResponse(); + + if (trim ($answers [0]) == 'true') { + $recaptcha_response->is_valid = true; + } + else { + $recaptcha_response->is_valid = false; + $recaptcha_response->error = $answers [1]; + } + return $recaptcha_response; + +} + +/** + * gets a URL where the user can sign up for reCAPTCHA. If your application + * has a configuration page where you enter a key, you should provide a link + * using this function. + * @param string $domain The domain where the page is hosted + * @param string $appname The name of your application + */ +function recaptcha_get_signup_url ($domain = null, $appname = null) { + return "http://recaptcha.net/api/getkey?" . _recaptcha_qsencode (array ('domain' => $domain, 'app' => $appname)); +} + +function _recaptcha_aes_pad($val) { + $block_size = 16; + $numpad = $block_size - (strlen ($val) % $block_size); + return str_pad($val, strlen ($val) + $numpad, chr($numpad)); +} + +/* Mailhide related code */ + +function _recaptcha_aes_encrypt($val,$ky) { + if (! function_exists ("mcrypt_encrypt")) { + die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); + } + $mode=MCRYPT_MODE_CBC; + $enc=MCRYPT_RIJNDAEL_128; + $val=_recaptcha_aes_pad($val); + return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); +} + + +function _recaptcha_mailhide_urlbase64 ($x) { + return strtr(base64_encode ($x), '+/', '-_'); +} + +/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ +function recaptcha_mailhide_url($pubkey, $privkey, $email) { + if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { + die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . + "you can do so at http://mailhide.recaptcha.net/apikey"); + } + + + $ky = pack('H*', $privkey); + $cryptmail = _recaptcha_aes_encrypt ($email, $ky); + + return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); +} + +/** + * gets the parts of the email to expose to the user. + * eg, given johndoe@example,com return ["john", "example.com"]. + * the email is then displayed as john...@example.com + */ +function _recaptcha_mailhide_email_parts ($email) { + $arr = preg_split("/@/", $email ); + + if (strlen ($arr[0]) <= 4) { + $arr[0] = substr ($arr[0], 0, 1); + } else if (strlen ($arr[0]) <= 6) { + $arr[0] = substr ($arr[0], 0, 3); + } else { + $arr[0] = substr ($arr[0], 0, 4); + } + return $arr; +} + +/** + * Gets html to display an email address given a public an private key. + * to get a key, go to: + * + * http://mailhide.recaptcha.net/apikey + */ +function recaptcha_mailhide_html($pubkey, $privkey, $email) { + $emailparts = _recaptcha_mailhide_email_parts ($email); + $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); + + return htmlentities($emailparts[0]) . "...@" . htmlentities ($emailparts [1]); + +} + + +?> -- cgit v1.2.3-54-g00ecf From 981fa1b33a8073bd0d53d8bee7dfccd171685e61 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Mon, 3 Aug 2009 22:46:01 +0000 Subject: Make the TwitterQueuehandler post to Twitter using OAuth --- actions/twitterauthorization.php | 48 +++++++++++----- lib/mail.php | 19 ++++--- lib/twitter.php | 117 +++++++++++++++------------------------ lib/twitteroauthclient.php | 39 +++++++++---- 4 files changed, 116 insertions(+), 107 deletions(-) diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index f19cd7f65..519427dac 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -67,39 +67,57 @@ class TwitterauthorizationAction extends Action if (empty($this->oauth_token)) { - // Get a new request token and authorize it + try { - $client = new TwitterOAuthClient(); - $req_tok = $client->getRequestToken(); + // Get a new request token and authorize it - // Sock the request token away in the session temporarily + $client = new TwitterOAuthClient(); + $req_tok = $client->getRequestToken(); - $_SESSION['twitter_request_token'] = $req_tok->key; - $_SESSION['twitter_request_token_secret'] = $req_tok->key; + // Sock the request token away in the session temporarily + + $_SESSION['twitter_request_token'] = $req_tok->key; + $_SESSION['twitter_request_token_secret'] = $req_tok->key; + + $auth_link = $client->getAuthorizeLink($req_tok); + + } catch (TwitterOAuthClientException $e) { + $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', + $e->getCode(), $e->getMessage()); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } - $auth_link = $client->getAuthorizeLink($req_tok); common_redirect($auth_link); } else { - // Check to make sure Twitter sent us the same request token we sent + // Check to make sure Twitter returned the same request + // token we sent them if ($_SESSION['twitter_request_token'] != $this->oauth_token) { $this->serverError(_('Couldn\'t link your Twitter account.')); } - $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], - $_SESSION['twitter_request_token_secret']); + try { - // Exchange the request token for an access token + $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], + $_SESSION['twitter_request_token_secret']); - $atok = $client->getAccessToken(); + // Exchange the request token for an access token - // Save the access token and Twitter user info + $atok = $client->getAccessToken(); - $client = new TwitterOAuthClient($atok->key, $atok->secret); + // Save the access token and Twitter user info - $twitter_user = $client->verify_credentials(); + $client = new TwitterOAuthClient($atok->key, $atok->secret); + + $twitter_user = $client->verify_credentials(); + + } catch (OAuthClientException $e) { + $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', + $e->getCode(), $e->getMessage()); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } $user = common_current_user(); diff --git a/lib/mail.php b/lib/mail.php index 0050ad810..16c1b0f30 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -645,13 +645,14 @@ function mail_twitter_bridge_removed($user) $subject = sprintf(_('Your Twitter bridge has been disabled.')); - $body = sprintf(_("Hi, %1\$s. We're sorry to inform you that your " . - 'link to Twitter has been disabled. Your Twitter credentials ' . - 'have either changed (did you recently change your Twitter ' . - 'password?) or you have otherwise revoked our access to your ' . - "Twitter account.\n\n" . - 'You can re-enable your Twitter bridge by visiting your ' . - "Twitter settings page:\n\n\t%2\$s\n\n" . + $site_name = common_config('site', 'name'); + + $body = sprintf(_('Hi, %1$s. We\'re sorry to inform you that your ' . + 'link to Twitter has been disabled. We no longer seem to have ' . + 'permission to update your Twitter status. (Did you revoke ' . + '%3$s\'s access?)' . "\n\n" . + 'You can re-enable your Twitter bridge by visiting your ' . + "Twitter settings page:\n\n\t%2\$s\n\n" . "Regards,\n%3\$s\n"), $profile->getBestName(), common_local_url('twittersettings'), @@ -679,11 +680,11 @@ function mail_facebook_app_removed($user) $site_name = common_config('site', 'name'); $subject = sprintf( - _('Your %1\$s Facebook application access has been disabled.', + _('Your %1$s Facebook application access has been disabled.', $site_name)); $body = sprintf(_("Hi, %1\$s. We're sorry to inform you that we are " . - 'unable to update your Facebook status from %2\$s, and have disabled ' . + 'unable to update your Facebook status from %2$s, and have disabled ' . 'the Facebook application for your account. This may be because ' . 'you have removed the Facebook application\'s authorization, or ' . 'have deleted your Facebook account. You can re-enable the ' . diff --git a/lib/twitter.php b/lib/twitter.php index 47af32e61..2369ac267 100644 --- a/lib/twitter.php +++ b/lib/twitter.php @@ -360,104 +360,72 @@ function is_twitter_bound($notice, $flink) { function broadcast_twitter($notice) { - $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); if (is_twitter_bound($notice, $flink)) { - $fuser = $flink->getForeignUser(); - $twitter_user = $fuser->nickname; - $twitter_password = $flink->credentials; - $uri = 'http://www.twitter.com/statuses/update.json'; + $user = $flink->getUser(); // XXX: Hack to get around PHP cURL's use of @ being a a meta character $statustxt = preg_replace('/^@/', ' @', $notice->content); - $options = array( - CURLOPT_USERPWD => "$twitter_user:$twitter_password", - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => - array( - 'status' => $statustxt, - 'source' => common_config('integration', 'source') - ), - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FAILONERROR => true, - CURLOPT_HEADER => false, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_USERAGENT => "Laconica", - CURLOPT_CONNECTTIMEOUT => 120, // XXX: How long should this be? - CURLOPT_TIMEOUT => 120, - - # Twitter is strict about accepting invalid "Expect" headers - CURLOPT_HTTPHEADER => array('Expect:') - ); - - $ch = curl_init($uri); - curl_setopt_array($ch, $options); - $data = curl_exec($ch); - $errmsg = curl_error($ch); - $errno = curl_errno($ch); + $client = new TwitterOAuthClient($flink->token, $flink->credentials); - if (!empty($errmsg)) { - common_debug("cURL error ($errno): $errmsg - " . - "trying to send notice for $twitter_user.", - __FILE__); + $status = null; - $user = $flink->getUser(); + try { + $status = $client->statuses_update($statustxt); + } catch (OAuthClientCurlException $e) { - if ($errmsg == 'The requested URL returned error: 401') { - common_debug(sprintf('User %s (user id: %s) ' . - 'has bad Twitter credentials!', - $user->nickname, $user->id)); + if ($e->getMessage() == 'The requested URL returned error: 401') { - // Bad credentials we need to delete the foreign_link - // to Twitter and inform the user. + $errmsg = sprintf('User %1$s (user id: %2$s) has an invalid ' . + 'Twitter OAuth access token.', + $user->nickname, $user->id); + common_log(LOG_WARNING, $errmsg); - remove_twitter_link($flink); + // Bad auth token! We need to delete the foreign_link + // to Twitter and inform the user. - return true; + remove_twitter_link($flink); + return true; - } else { + } else { - // Some other error happened, so we should try to - // send again later + // Some other error happened, so we should probably + // try to send again later. - return false; - } + $errmsg = sprintf('cURL error trying to send notice to Twitter ' . + 'for user %1$s (user id: %2$s) - ' . + 'code: %3$s message: $4$s.', + $user->nickname, $user->id, + $e->getCode(), $e->getMessage()); + common_log(LOG_WARNING, $errmsg); + return false; } + } - curl_close($ch); - - if (empty($data)) { - common_debug("No data returned by Twitter's " . - "API trying to send update for $twitter_user", - __FILE__); + if (empty($status)) { - // XXX: Not sure this represents a failure to send, but it - // probably does + // This could represent a failure posting, + // or the Twitter API might just be behaving flakey. - return false; + $errmsg = sprint('No data returned by Twitter API when ' . + 'trying to send update for %1$s (user id %2$s).', + $user->nickname, $user->id); + common_log(LOG_WARNING, $errmsg); - } else { - - // Twitter should return a status - $status = json_decode($data); + return false; + } - if (empty($status)) { - common_debug("Unexpected data returned by Twitter " . - " API trying to send update for $twitter_user", - __FILE__); + // Notice crossed the great divide - // XXX: Again, this could represent a failure posting - // or the Twitter API might just be behaving flakey. - // We're treating it as a failure to post. + $msg = sprintf('Twitter bridge posted notice %s to Twitter.', + $notice->id); + common_log(LOG_INFO, $msg); - return false; - } - } } return true; @@ -480,17 +448,20 @@ function remove_twitter_link($flink) // Notify the user that her Twitter bridge is down + if (isset($user->email)) { + $result = mail_twitter_bridge_removed($user); if (!$result) { $msg = 'Unable to send email to notify ' . - "$user->nickname (user id: $user->id) " . - 'that their Twitter bridge link was ' . + "$user->nickname (user id: $user->id) " . + 'that their Twitter bridge link was ' . 'removed!'; common_log(LOG_WARNING, $msg); } + } } diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index 616fbc213..63ffe1c7c 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -2,6 +2,8 @@ require_once('OAuth.php'); +class OAuthClientCurlException extends Exception { } + class TwitterOAuthClient { public static $requestTokenURL = 'https://twitter.com/oauth/request_token'; @@ -54,6 +56,16 @@ class TwitterOAuthClient return $twitter_user; } + function statuses_update($status, $in_reply_to_status_id = null) + { + $url = 'https://twitter.com/statuses/update.json'; + $params = array('status' => $status, + 'in_reply_to_status_id' => $in_reply_to_status_id); + $response = $this->oAuthPost($url, $params); + $status = json_decode($response); + return $status; + } + function oAuthGet($url) { $request = OAuthRequest::from_consumer_and_token($this->consumer, @@ -91,19 +103,26 @@ class TwitterOAuthClient // Twitter is strict about accepting invalid "Expect" headers CURLOPT_HTTPHEADER => array('Expect:') - ); + ); - if (isset($params)) { - $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = $params; - } + if (isset($params)) { + $options[CURLOPT_POST] = true; + $options[CURLOPT_POSTFIELDS] = $params; + } + + $ch = curl_init($url); + curl_setopt_array($ch, $options); + $response = curl_exec($ch); + + if ($response === false) { + $msg = curl_error($ch); + $code = curl_errno($ch); + throw new OAuthClientCurlException($msg, $code); + } - $ch = curl_init($url); - curl_setopt_array($ch, $options); - $response = curl_exec($ch); - curl_close($ch); + curl_close($ch); - return $response; + return $response; } } -- cgit v1.2.3-54-g00ecf From 1f9d1772c091e1f09cc741e3e21cfe5ba7fa3560 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 00:02:07 +0000 Subject: Allow removal of Twitter account. Deleted dead code. --- actions/twittersettings.php | 344 +++++++------------------------------------- 1 file changed, 52 insertions(+), 292 deletions(-) diff --git a/actions/twittersettings.php b/actions/twittersettings.php index acc9fb935..7fffa0af0 100644 --- a/actions/twittersettings.php +++ b/actions/twittersettings.php @@ -34,8 +34,6 @@ if (!defined('LACONICA')) { require_once INSTALLDIR.'/lib/connectsettingsaction.php'; require_once INSTALLDIR.'/lib/twitter.php'; -define('SUBSCRIPTIONS', 80); - /** * Settings for Twitter integration * @@ -70,7 +68,7 @@ class TwittersettingsAction extends ConnectSettingsAction function getInstructions() { return _('Connect your Twitter account to share your updates ' . - 'with your Twitter friends and vice-versa.'); + 'with your Twitter friends and vice-versa.'); } /** @@ -104,179 +102,83 @@ class TwittersettingsAction extends ConnectSettingsAction $this->hidden('token', common_session_token()); + $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); if (empty($fuser)) { - - $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); $this->elementStart('ul', 'form_data'); $this->elementStart('li', array('id' => 'settings_twitter_login_button')); $this->element('a', array('href' => common_local_url('twitterauthorization')), - 'Connect my Twitter account'); - $this->elementEnd('li'); + 'Connect my Twitter account'); + $this->elementEnd('li'); $this->elementEnd('ul'); - $this->elementEnd('fieldset'); + $this->elementEnd('fieldset'); } else { + $this->element('legend', null, _('Twitter account')); + $this->elementStart('p', array('id' => 'form_confirmed')); + $this->element('a', array('href' => $fuser->uri), $fuser->nickname); + $this->elementEnd('p'); + $this->element('p', 'form_note', + _('Connected Twitter account')); - $this->elementStart('fieldset', - array('id' => 'settings_twitter_preferences')); - $this->element('legend', null, _('Preferences')); + $this->submit('remove', _('Remove')); + + $this->elementEnd('fieldset'); + $this->elementStart('fieldset', array('id' => 'settings_twitter_preferences')); + + $this->element('legend', null, _('Preferences')); $this->elementStart('ul', 'form_data'); $this->elementStart('li'); $this->checkbox('noticesend', - _('Automatically send my notices to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND) : - true); + _('Automatically send my notices to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND) : + true); $this->elementEnd('li'); $this->elementStart('li'); $this->checkbox('replysync', - _('Send local "@" replies to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : - true); + _('Send local "@" replies to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : + true); $this->elementEnd('li'); $this->elementStart('li'); $this->checkbox('friendsync', - _('Subscribe to my Twitter friends here.'), - ($flink) ? - ($flink->friendsync & FOREIGN_FRIEND_RECV) : - false); + _('Subscribe to my Twitter friends here.'), + ($flink) ? + ($flink->friendsync & FOREIGN_FRIEND_RECV) : + false); $this->elementEnd('li'); if (common_config('twitterbridge','enabled')) { - $this->elementStart('li'); - $this->checkbox('noticerecv', - _('Import my Friends Timeline.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_RECV) : - false); - $this->elementEnd('li'); - - // preserve setting even if bidrection bridge toggled off - - if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) { - $this->hidden('noticerecv', true, 'noticerecv'); - } - } - - $this->elementEnd('ul'); - - if ($flink) { - $this->submit('save', _('Save')); - } else { - $this->submit('add', _('Add')); - } - - $this->elementEnd('fieldset'); - } - - $this->showTwitterSubscriptions(); - - $this->elementEnd('form'); - } - - /** - * Gets some of the user's Twitter friends - * - * Gets the number of Twitter friends that are on this - * instance of Laconica. - * - * @return array array of User objects - */ - - function subscribedTwitterUsers() - { - - $current_user = common_current_user(); - - $qry = 'SELECT "user".* ' . - 'FROM subscription ' . - 'JOIN "user" ON subscription.subscribed = "user".id ' . - 'JOIN foreign_link ON foreign_link.user_id = "user".id ' . - 'WHERE subscriber = %d ' . - 'ORDER BY "user".nickname'; - - $user = new User(); - - $user->query(sprintf($qry, $current_user->id)); - - $users = array(); - - while ($user->fetch()) { - - // Don't include the user's own self-subscription - if ($user->id != $current_user->id) { - $users[] = clone($user); - } - } - - return $users; - } - - /** - * Show user's Twitter friends - * - * Gets the number of Twitter friends that are on this - * instance of Laconica, and shows their mini-avatars. - * - * @return void - */ - - function showTwitterSubscriptions() - { - - $friends = $this->subscribedTwitterUsers(); - - $friends_count = count($friends); - - if ($friends_count > 0) { - $this->elementStart('div', array('id' => 'entity_subscriptions', - 'class' => 'section')); - $this->element('h2', null, _('Twitter Friends')); - $this->elementStart('ul', 'entities users xoxo'); - - for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) { + $this->elementStart('li'); + $this->checkbox('noticerecv', + _('Import my Friends Timeline.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_RECV) : + false); + $this->elementEnd('li'); - $other = Profile::staticGet($friends[$i]->id); + // preserve setting even if bidrection bridge toggled off - if (!$other) { - common_log_db_error($subs, 'SELECT', __FILE__); - continue; + if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) { + $this->hidden('noticerecv', true, 'noticerecv'); } - - $this->elementStart('li', 'vcard'); - $this->elementStart('a', array('title' => ($other->fullname) ? - $other->fullname : - $other->nickname, - 'href' => $other->profileurl, - 'class' => 'url')); - - $avatar = $other->getAvatar(AVATAR_MINI_SIZE); - - $avatar_url = ($avatar) ? - $avatar->displayUrl() : - Avatar::defaultImage(AVATAR_MINI_SIZE); - - $this->element('img', array('src' => $avatar_url, - 'width' => AVATAR_MINI_SIZE, - 'height' => AVATAR_MINI_SIZE, - 'class' => 'avatar photo', - 'alt' => ($other->fullname) ? - $other->fullname : - $other->nickname)); - - $this->element('span', 'fn nickname', $other->nickname); - $this->elementEnd('a'); - $this->elementEnd('li'); - } $this->elementEnd('ul'); - $this->elementEnd('div'); + if ($flink) { + $this->submit('save', _('Save')); + } else { + $this->submit('add', _('Add')); + } + + $this->elementEnd('fieldset'); } + + $this->elementEnd('form'); } /** @@ -292,7 +194,6 @@ class TwittersettingsAction extends ConnectSettingsAction function handlePost() { - // CSRF protection $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { @@ -303,8 +204,6 @@ class TwittersettingsAction extends ConnectSettingsAction if ($this->arg('save')) { $this->savePreferences(); - } else if ($this->arg('add')) { - $this->addTwitterAccount(); } else if ($this->arg('remove')) { $this->removeTwitterAccount(); } else { @@ -312,82 +211,6 @@ class TwittersettingsAction extends ConnectSettingsAction } } - /** - * Associate a Twitter account with the user's account - * - * Validates post input; verifies it against Twitter; and if - * successful stores in the database. - * - * @return void - */ - - function addTwitterAccount() - { - $screen_name = $this->trimmed('twitter_username'); - $password = $this->trimmed('twitter_password'); - $noticesend = $this->boolean('noticesend'); - $noticerecv = $this->boolean('noticerecv'); - $replysync = $this->boolean('replysync'); - $friendsync = $this->boolean('friendsync'); - - if (!Validate::string($screen_name, - array('min_length' => 1, - 'max_length' => 15, - 'format' => VALIDATE_NUM.VALIDATE_ALPHA.'_'))) { - $this->showForm(_('Username must have only numbers, '. - 'upper- and lowercase letters, '. - 'and underscore (_). 15 chars max.')); - return; - } - - if (!$this->verifyCredentials($screen_name, $password)) { - $this->showForm(_('Could not verify your Twitter credentials!')); - return; - } - - $twit_user = twitter_user_info($screen_name, $password); - - if (!$twit_user) { - $this->showForm(sprintf(_('Unable to retrieve account information '. - 'For "%s" from Twitter.'), - $screen_name)); - return; - } - - if (!save_twitter_user($twit_user->id, $screen_name)) { - $this->showForm(_('Unable to save your Twitter settings!')); - return; - } - - $user = common_current_user(); - - $flink = new Foreign_link(); - - $flink->user_id = $user->id; - $flink->foreign_id = $twit_user->id; - $flink->service = TWITTER_SERVICE; - $flink->credentials = $password; - $flink->created = common_sql_now(); - - $flink->set_flags($noticesend, $noticerecv, $replysync, $friendsync); - - $flink_id = $flink->insert(); - - if (!$flink_id) { - common_log_db_error($flink, 'INSERT', __FILE__); - $this->showForm(_('Unable to save your Twitter settings!')); - return; - } - - if ($friendsync) { - save_twitter_friends($user, $twit_user->id, $screen_name, $password); - $flink->last_friendsync = common_sql_now(); - $flink->update(); - } - - $this->showForm(_('Twitter settings saved.'), true); - } - /** * Disassociate an existing Twitter account from this account * @@ -397,20 +220,11 @@ class TwittersettingsAction extends ConnectSettingsAction function removeTwitterAccount() { $user = common_current_user(); - - $flink = Foreign_link::getByUserID($user->id, 1); - - $flink_foreign_id = $this->arg('flink_foreign_id'); - - // Maybe an old tab open...? - if ($flink->foreign_id != $flink_foreign_id) { - $this->showForm(_('That is not your Twitter account.')); - return; - } + $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); $result = $flink->delete(); - if (!$result) { + if (empty($result)) { common_log_db_error($flink, 'DELETE', __FILE__); $this->serverError(_('Couldn\'t remove Twitter user.')); return; @@ -433,32 +247,16 @@ class TwittersettingsAction extends ConnectSettingsAction $replysync = $this->boolean('replysync'); $user = common_current_user(); + $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); - $flink = Foreign_link::getByUserID($user->id, 1); - - if (!$flink) { + if (empty($flink)) { common_log_db_error($flink, 'SELECT', __FILE__); $this->showForm(_('Couldn\'t save Twitter preferences.')); return; } - $twitter_id = $flink->foreign_id; - $password = $flink->credentials; - - $fuser = $flink->getForeignUser(); - - if (!$fuser) { - common_log_db_error($fuser, 'SELECT', __FILE__); - $this->showForm(_('Couldn\'t save Twitter preferences.')); - return; - } - - $screen_name = $fuser->nickname; - $original = clone($flink); - $flink->set_flags($noticesend, $noticerecv, $replysync, $friendsync); - $result = $flink->update($original); if ($result === false) { @@ -467,45 +265,7 @@ class TwittersettingsAction extends ConnectSettingsAction return; } - if ($friendsync) { - save_twitter_friends($user, $flink->foreign_id, $screen_name, $password); - } - $this->showForm(_('Twitter preferences saved.'), true); } - /** - * Verifies a username and password against Twitter's API - * - * @param string $screen_name Twitter user name - * @param string $password Twitter password - * - * @return boolean success flag - */ - - function verifyCredentials($screen_name, $password) - { - $uri = 'http://twitter.com/account/verify_credentials.json'; - - $data = get_twitter_data($uri, $screen_name, $password); - - if (!$data) { - return false; - } - - $user = json_decode($data); - - if (!$user) { - return false; - } - - $twitter_id = $user->id; - - if ($twitter_id) { - return $twitter_id; - } - - return false; - } - } -- cgit v1.2.3-54-g00ecf From 4e9db95bcfe7818f4f937f3e29f31ea64cd73330 Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Thu, 30 Jul 2009 20:38:34 +0100 Subject: Use -
  • >
  • +
  • >
  • Date: Thu, 30 Jul 2009 19:19:12 +0100 Subject: Enable 404-based rewrites for lighttpd installations in / --- index.php | 18 ++++++++++++++++++ lighttpd.conf.example | 2 ++ 2 files changed, 20 insertions(+) create mode 100644 lighttpd.conf.example diff --git a/index.php b/index.php index a73983b59..c6776b11b 100644 --- a/index.php +++ b/index.php @@ -107,6 +107,24 @@ function checkMirror($action_obj) function main() { + // fake HTTP redirects using lighttpd's 404 redirects + if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) { + $_lighty_url = $base_url.$_SERVER['REQUEST_URI']; + $_lighty_url = @parse_url($_lighty_url); + + if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') { + $_SERVER['QUERY_STRING'] = 'p='.substr($_lighty_url['path'], 1); + if ($_lighty_url['query']) + $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query']; + parse_str($_lighty_url['query'], $_lighty_query); + foreach ($_lighty_query as $key => $val) { + $_GET[$key] = $_REQUEST[$key] = $val; + } + $_GET['p'] = $_REQUEST['p'] = substr($_lighty_url['path'], 1); + } + } + $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']); + // quick check for fancy URL auto-detection support in installer. if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/","",(dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) { die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs."); diff --git a/lighttpd.conf.example b/lighttpd.conf.example new file mode 100644 index 000000000..b8baafc9e --- /dev/null +++ b/lighttpd.conf.example @@ -0,0 +1,2 @@ +# Add this line to lighttpd.conf to enable pseudo-rewrites using 404s +server.error-handler-404 = "/index.php" -- cgit v1.2.3-54-g00ecf From 961d2a812f4f463d48385fe78412a116fbfe71f3 Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Thu, 30 Jul 2009 20:55:33 +0100 Subject: lighttpd rewrites now possible in other directories. --- index.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/index.php b/index.php index c6776b11b..5f13064da 100644 --- a/index.php +++ b/index.php @@ -113,14 +113,15 @@ function main() $_lighty_url = @parse_url($_lighty_url); if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') { - $_SERVER['QUERY_STRING'] = 'p='.substr($_lighty_url['path'], 1); + $_lighty_path = preg_replace('/^'.preg_quote(common_config('site','path')).'\//', '', substr($_lighty_url['path'], 1)); + $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path; if ($_lighty_url['query']) $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query']; parse_str($_lighty_url['query'], $_lighty_query); foreach ($_lighty_query as $key => $val) { $_GET[$key] = $_REQUEST[$key] = $val; } - $_GET['p'] = $_REQUEST['p'] = substr($_lighty_url['path'], 1); + $_GET['p'] = $_REQUEST['p'] = $_lighty_path; } } $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']); -- cgit v1.2.3-54-g00ecf From 20b254077925d3bc2642a6ff623432b3fb5bdd07 Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Tue, 4 Aug 2009 01:22:40 +0100 Subject: Only warn when chars remaining < 0, not <= 0. --- js/util.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/util.js b/js/util.js index f3ed918cf..fd30336b9 100644 --- a/js/util.js +++ b/js/util.js @@ -25,7 +25,7 @@ $(document).ready(function(){ var counter = $("#notice_text-count"); counter.text(remaining); - if (remaining <= 0) { + if (remaining < 0) { $("#form_notice").addClass("warning"); } else { $("#form_notice").removeClass("warning"); -- cgit v1.2.3-54-g00ecf From f94ee5597d09dd46c0580ce043907ea960ace358 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 00:46:18 +0000 Subject: Moved some stuff to a base class --- actions/twitterauthorization.php | 2 +- lib/oauthclient.php | 111 +++++++++++++++++++++++++++++++++++++++ lib/twitteroauthclient.php | 98 +++------------------------------- 3 files changed, 118 insertions(+), 93 deletions(-) create mode 100644 lib/oauthclient.php diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index 519427dac..2390034cd 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -80,7 +80,7 @@ class TwitterauthorizationAction extends Action $_SESSION['twitter_request_token_secret'] = $req_tok->key; $auth_link = $client->getAuthorizeLink($req_tok); - + } catch (TwitterOAuthClientException $e) { $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', $e->getCode(), $e->getMessage()); diff --git a/lib/oauthclient.php b/lib/oauthclient.php new file mode 100644 index 000000000..11de991c8 --- /dev/null +++ b/lib/oauthclient.php @@ -0,0 +1,111 @@ +sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); + $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); + $this->token = null; + + if (isset($oauth_token) && isset($oauth_token_secret)) { + $this->token = new OAuthToken($oauth_token, $oauth_token_secret); + } + } + + function getRequestToken() + { + $response = $this->oAuthGet(TwitterOAuthClient::$requestTokenURL); + parse_str($response); + $token = new OAuthToken($oauth_token, $oauth_token_secret); + return $token; + } + + function getAuthorizeLink($request_token, $oauth_callback = null) + { + $url = TwitterOAuthClient::$authorizeURL . '?oauth_token=' . + $request_token->key; + + if (isset($oauth_callback)) { + $url .= '&oauth_callback=' . urlencode($oauth_callback); + } + + return $url; + } + + function getAccessToken() + { + $response = $this->oAuthPost(TwitterOAuthClient::$accessTokenURL); + parse_str($response); + $token = new OAuthToken($oauth_token, $oauth_token_secret); + return $token; + } + + function oAuthGet($url) + { + $request = OAuthRequest::from_consumer_and_token($this->consumer, + $this->token, 'GET', $url, null); + $request->sign_request($this->sha1_method, + $this->consumer, $this->token); + + return $this->httpRequest($request->to_url()); + } + + function oAuthPost($url, $params = null) + { + $request = OAuthRequest::from_consumer_and_token($this->consumer, + $this->token, 'POST', $url, $params); + $request->sign_request($this->sha1_method, + $this->consumer, $this->token); + + return $this->httpRequest($request->get_normalized_http_url(), + $request->to_postdata()); + } + + function httpRequest($url, $params = null) + { + $options = array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FAILONERROR => true, + CURLOPT_HEADER => false, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_USERAGENT => 'Laconica', + CURLOPT_CONNECTTIMEOUT => 120, + CURLOPT_TIMEOUT => 120, + CURLOPT_HTTPAUTH => CURLAUTH_ANY, + CURLOPT_SSL_VERIFYPEER => false, + + // Twitter is strict about accepting invalid "Expect" headers + + CURLOPT_HTTPHEADER => array('Expect:') + ); + + if (isset($params)) { + $options[CURLOPT_POST] = true; + $options[CURLOPT_POSTFIELDS] = $params; + } + + $ch = curl_init($url); + curl_setopt_array($ch, $options); + $response = curl_exec($ch); + + if ($response === false) { + $msg = curl_error($ch); + $code = curl_errno($ch); + throw new OAuthClientCurlException($msg, $code); + } + + curl_close($ch); + + return $response; + } + +} diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index 63ffe1c7c..e1190f167 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -1,10 +1,6 @@ sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); $consumer_key = common_config('twitter', 'consumer_key'); $consumer_secret = common_config('twitter', 'consumer_secret'); - $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); - $this->token = null; - if (isset($oauth_token) && isset($oauth_token_secret)) { - $this->token = new OAuthToken($oauth_token, $oauth_token_secret); - } + parent::__construct($consumer_key, $consumer_secret, + $oauth_token, $oauth_token_secret); } - function getRequestToken() - { - $response = $this->oAuthGet(TwitterOAuthClient::$requestTokenURL); - parse_str($response); - $token = new OAuthToken($oauth_token, $oauth_token_secret); - return $token; - } - - function getAuthorizeLink($request_token) - { - // Not sure Twitter actually looks at oauth_callback - - return TwitterOAuthClient::$authorizeURL . - '?oauth_token=' . $request_token->key . '&oauth_callback=' . - urlencode(common_local_url('twitterauthorization')); - } + function getAuthorizeLink($request_token) { + return parent::getAuthorizeLink($request_token, + common_local_url('twitterauthorization')); - function getAccessToken() - { - $response = $this->oAuthPost(TwitterOAuthClient::$accessTokenURL); - parse_str($response); - $token = new OAuthToken($oauth_token, $oauth_token_secret); - return $token; } function verify_credentials() @@ -66,63 +39,4 @@ class TwitterOAuthClient return $status; } - function oAuthGet($url) - { - $request = OAuthRequest::from_consumer_and_token($this->consumer, - $this->token, 'GET', $url, null); - $request->sign_request($this->sha1_method, - $this->consumer, $this->token); - - return $this->httpRequest($request->to_url()); - } - - function oAuthPost($url, $params = null) - { - $request = OAuthRequest::from_consumer_and_token($this->consumer, - $this->token, 'POST', $url, $params); - $request->sign_request($this->sha1_method, - $this->consumer, $this->token); - - return $this->httpRequest($request->get_normalized_http_url(), - $request->to_postdata()); - } - - function httpRequest($url, $params = null) - { - $options = array( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FAILONERROR => true, - CURLOPT_HEADER => false, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_USERAGENT => 'Laconica', - CURLOPT_CONNECTTIMEOUT => 120, - CURLOPT_TIMEOUT => 120, - CURLOPT_HTTPAUTH => CURLAUTH_ANY, - CURLOPT_SSL_VERIFYPEER => false, - - // Twitter is strict about accepting invalid "Expect" headers - - CURLOPT_HTTPHEADER => array('Expect:') - ); - - if (isset($params)) { - $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = $params; - } - - $ch = curl_init($url); - curl_setopt_array($ch, $options); - $response = curl_exec($ch); - - if ($response === false) { - $msg = curl_error($ch); - $code = curl_errno($ch); - throw new OAuthClientCurlException($msg, $code); - } - - curl_close($ch); - - return $response; - } - } -- cgit v1.2.3-54-g00ecf From 2b00990d27b55644ff133355628f948ddca6df70 Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Tue, 4 Aug 2009 01:58:45 +0100 Subject: Prepend replyto string to message, don't destroy user input! --- js/util.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/util.js b/js/util.js index fd30336b9..d4db8b72a 100644 --- a/js/util.js +++ b/js/util.js @@ -257,7 +257,7 @@ function NoticeReplySet(nick,id) { if (nick.match(rgx_username)) { replyto = "@" + nick + " "; if ($("#notice_data-text").length) { - $("#notice_data-text").val(replyto); + $("#notice_data-text").val(replyto + $("#notice_data-text").val()); $("#form_notice input#notice_in-reply-to").val(id); $("#notice_data-text").focus(); return false; -- cgit v1.2.3-54-g00ecf From fe9fc152861a0131582c4aa512870d2d01bccb57 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 02:21:18 +0000 Subject: Make TwitterStatusFetcher daemon work with OAuth --- lib/twitteroauthclient.php | 19 +++++++++++++++++++ scripts/twitterstatusfetcher.php | 32 +++++++++++++++----------------- 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index e1190f167..aabda8d6a 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -39,4 +39,23 @@ class TwitterOAuthClient extends OAuthClient return $status; } + function statuses_friends_timeline($since_id = null, $max_id = null, + $cnt = null, $page = null) { + + $url = 'http://twitter.com/statuses/friends_timeline.json'; + $params = array('since_id' => $since_id, + 'max_id' => $max_id, + 'count' => $cnt, + 'page' => $page); + $qry = http_build_query($params); + + if (!empty($qry)) { + $url .= "?$qry"; + } + + $response = $this->oAuthGet($url); + $statuses = json_decode($response); + return $statuses; + } + } diff --git a/scripts/twitterstatusfetcher.php b/scripts/twitterstatusfetcher.php index e1745cfc0..d9f035fa6 100755 --- a/scripts/twitterstatusfetcher.php +++ b/scripts/twitterstatusfetcher.php @@ -191,7 +191,7 @@ class TwitterStatusFetcher extends Daemon { $flink = new Foreign_link(); - $flink->service = 1; // Twitter + $flink->service = TWITTER_SERVICE; $flink->orderBy('last_noticesync'); @@ -241,35 +241,33 @@ class TwitterStatusFetcher extends Daemon function getTimeline($flink) { - if (empty($flink)) { + if (empty($flink)) { common_log(LOG_WARNING, "Can't retrieve Foreign_link for foreign ID $fid"); return; } - $fuser = $flink->getForeignUser(); - - if (empty($fuser)) { - common_log(LOG_WARNING, "Unmatched user for ID " . - $flink->user_id); - return; - } - if (defined('SCRIPT_DEBUG')) { common_debug('Trying to get timeline for Twitter user ' . - "$fuser->nickname ($flink->foreign_id)."); + $flink->foreign_id); } // XXX: Biggest remaining issue - How do we know at which status // to start importing? How many statuses? Right now I'm going // with the default last 20. - $url = 'http://twitter.com/statuses/friends_timeline.json'; + $client = new TwitterOAuthClient($flink->token, $flink->credentials); - $timeline_json = get_twitter_data($url, $fuser->nickname, - $flink->credentials); + $timeline = null; - $timeline = json_decode($timeline_json); + try { + $timeline = $client->statuses_friends_timeline(); + } catch (OAuthClientCurlException $e) { + common_log(LOG_WARNING, + 'OAuth client unable to get friends timeline for user ' . + $flink->user_id . ' - code: ' . + $e->getCode() . 'msg: ' . $e->getMessage()); + } if (empty($timeline)) { common_log(LOG_WARNING, "Empty timeline."); @@ -303,7 +301,7 @@ class TwitterStatusFetcher extends Daemon $id = $this->ensureProfile($status->user); $profile = Profile::staticGet($id); - if (!$profile) { + if (empty($profile)) { common_log(LOG_ERR, 'Problem saving notice. No associated Profile.'); return null; @@ -318,7 +316,7 @@ class TwitterStatusFetcher extends Daemon // check to see if we've already imported the status - if (!$notice) { + if (empty($notice)) { $notice = new Notice(); -- cgit v1.2.3-54-g00ecf From 39c420b51fb57f98780d583efaaaebd79de12db9 Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Tue, 4 Aug 2009 09:22:37 +0100 Subject: Set focus to end of field. --- js/util.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/js/util.js b/js/util.js index d4db8b72a..0409dc601 100644 --- a/js/util.js +++ b/js/util.js @@ -256,10 +256,19 @@ function NoticeReplySet(nick,id) { rgx_username = /^[0-9a-zA-Z\-_.]*$/; if (nick.match(rgx_username)) { replyto = "@" + nick + " "; - if ($("#notice_data-text").length) { - $("#notice_data-text").val(replyto + $("#notice_data-text").val()); + var text = $("#notice_data-text"); + if (text.length) { + text.val(replyto + text.val()); $("#form_notice input#notice_in-reply-to").val(id); - $("#notice_data-text").focus(); + if (text.get(0).setSelectionRange) { + var len = text.val().length; + text.get(0).setSelectionRange(len,len); + text.get(0).focus(); + } else if (text.get(0).createTextRange) { + var range = text.createTextRange(); + range.collapse(false); + range.select(); + } return false; } } -- cgit v1.2.3-54-g00ecf From 0155d02cecae565e0709a7bd0c8d1b62dd80d9bc Mon Sep 17 00:00:00 2001 From: Jeffery To Date: Tue, 4 Aug 2009 18:45:11 +0800 Subject: Fixed PHP Notice "Undefined property: Profile::$value" --- lib/profilesection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/profilesection.php b/lib/profilesection.php index 9ff243fb5..d463a07b0 100644 --- a/lib/profilesection.php +++ b/lib/profilesection.php @@ -97,7 +97,7 @@ class ProfileSection extends Section $this->out->elementEnd('a'); $this->out->elementEnd('span'); $this->out->elementEnd('td'); - if ($profile->value) { + if (isset($profile->value)) { $this->out->element('td', 'value', $profile->value); } -- cgit v1.2.3-54-g00ecf From ffa1d662a759a729151f2444bdf759749d59045e Mon Sep 17 00:00:00 2001 From: Tom Adams Date: Tue, 4 Aug 2009 16:15:36 +0100 Subject: Didn't test that JS in IE. Revert a little. --- js/util.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/js/util.js b/js/util.js index 0409dc601..9d6e52b2d 100644 --- a/js/util.js +++ b/js/util.js @@ -264,10 +264,6 @@ function NoticeReplySet(nick,id) { var len = text.val().length; text.get(0).setSelectionRange(len,len); text.get(0).focus(); - } else if (text.get(0).createTextRange) { - var range = text.createTextRange(); - range.collapse(false); - range.select(); } return false; } -- cgit v1.2.3-54-g00ecf From 3a6e7d68fce1ef66f959071299dbe86aa91f495a Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Tue, 4 Aug 2009 15:54:02 +0000 Subject: Ticket 1758 Multiple replies in web interface on "profile" page appends own username --- js/util.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/util.js b/js/util.js index 9d6e52b2d..ef147bef4 100644 --- a/js/util.js +++ b/js/util.js @@ -244,7 +244,7 @@ function NoticeReply() { $('#content .notice').each(function() { var notice = $(this)[0]; $($('.notice_reply', notice)[0]).click(function() { - var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname'); + var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid'); NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text()); return false; }); -- cgit v1.2.3-54-g00ecf From cb2f668ff6a0d0208732837dca1f2cb7a16e814f Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Tue, 4 Aug 2009 16:24:23 +0000 Subject: Removed not overly significant style from div.entry-content. It helps with attachment views as well (Ticket 1761) --- theme/default/css/display.css | 3 --- theme/identica/css/display.css | 3 --- 2 files changed, 6 deletions(-) diff --git a/theme/default/css/display.css b/theme/default/css/display.css index b7c86ae07..921a6b27b 100644 --- a/theme/default/css/display.css +++ b/theme/default/css/display.css @@ -235,9 +235,6 @@ opacity:0.4; .notices li:hover div.notice-options { opacity:1; } -div.entry-content { -color:#333333; -} div.notice-options a, div.notice-options input { font-family:sans-serif; diff --git a/theme/identica/css/display.css b/theme/identica/css/display.css index 6a8820495..8af5644b6 100644 --- a/theme/identica/css/display.css +++ b/theme/identica/css/display.css @@ -235,9 +235,6 @@ opacity:0.4; .notices li:hover div.notice-options { opacity:1; } -div.entry-content { -color:#333333; -} div.notice-options a, div.notice-options input { font-family:sans-serif; -- cgit v1.2.3-54-g00ecf From 557e214ce968079362b73f36f2f2bd1bcbec61a7 Mon Sep 17 00:00:00 2001 From: Sarven Capadisli Date: Tue, 4 Aug 2009 12:26:29 -0400 Subject: Refactored rgb2hex --- js/userdesign.go.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/js/userdesign.go.js b/js/userdesign.go.js index 4416dc8ae..c53569bea 100644 --- a/js/userdesign.go.js +++ b/js/userdesign.go.js @@ -30,11 +30,11 @@ $(document).ready(function() { /* rgb2hex written by R0bb13 */ function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); - function hex(x) { - hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); - return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; - } - return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); + return '#' + dec2hex(rgb[1]) + dec2hex(rgb[2]) + dec2hex(rgb[3]); + } + function dec2hex(x) { + hexDigits = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); + return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } function UpdateColors(S) { -- cgit v1.2.3-54-g00ecf From 0685b85d8dd7ab9629b0acbfbd7b4aae20c14103 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 17:19:05 +0000 Subject: Use ssl for fetching frinds_timeline from Twitter since it requires auth and is a protected resource --- lib/twitteroauthclient.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index aabda8d6a..c5f114fb0 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -42,7 +42,7 @@ class TwitterOAuthClient extends OAuthClient function statuses_friends_timeline($since_id = null, $max_id = null, $cnt = null, $page = null) { - $url = 'http://twitter.com/statuses/friends_timeline.json'; + $url = 'https://twitter.com/statuses/friends_timeline.json'; $params = array('since_id' => $since_id, 'max_id' => $max_id, 'count' => $cnt, -- cgit v1.2.3-54-g00ecf From 5576917662b47ef27bf7ba3e551411c3d3b5e26c Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 17:20:28 +0000 Subject: Use empty() for checking whether DB_DataObject returned something --- scripts/twitterstatusfetcher.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/twitterstatusfetcher.php b/scripts/twitterstatusfetcher.php index d9f035fa6..dd139417c 100755 --- a/scripts/twitterstatusfetcher.php +++ b/scripts/twitterstatusfetcher.php @@ -356,7 +356,7 @@ class TwitterStatusFetcher extends Daemon $profileurl = 'http://twitter.com/' . $user->screen_name; $profile = Profile::staticGet('profileurl', $profileurl); - if ($profile) { + if (!empty($profile) { if (defined('SCRIPT_DEBUG')) { common_debug("Profile for $profile->nickname found."); } @@ -394,7 +394,7 @@ class TwitterStatusFetcher extends Daemon // check for remote profile $remote_pro = Remote_profile::staticGet('uri', $profileurl); - if (!$remote_pro) { + if (empty($remote_pro)) { $remote_pro = new Remote_profile(); -- cgit v1.2.3-54-g00ecf From 43eb19910f541a3b2a083f3cd02954e30e34aa35 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 20:49:18 +0000 Subject: Post to Facebook user's stream if notice has an attachment, otherwise post notice as a status update --- lib/facebookutil.php | 232 +++++++++++++++++++++++---------------------------- 1 file changed, 106 insertions(+), 126 deletions(-) diff --git a/lib/facebookutil.php b/lib/facebookutil.php index b7688f04f..e31a71f5e 100644 --- a/lib/facebookutil.php +++ b/lib/facebookutil.php @@ -36,7 +36,7 @@ function getFacebook() $facebook = new Facebook($apikey, $secret); } - if (!$facebook) { + if (empty($facebook)) { common_log(LOG_ERR, 'Could not make new Facebook client obj!', __FILE__); } @@ -44,71 +44,37 @@ function getFacebook() return $facebook; } -function updateProfileBox($facebook, $flink, $notice) { - $fbaction = new FacebookAction($output='php://output', $indent=true, $facebook, $flink); - $fbaction->updateProfileBox($notice); -} - function isFacebookBound($notice, $flink) { if (empty($flink)) { return false; } + // Avoid a loop + + if ($notice->source == 'Facebook') { + common_log(LOG_INFO, "Skipping notice $notice->id because its " . + 'source is Facebook.'); + return false; + } + // If the user does not want to broadcast to Facebook, move along + if (!($flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) { common_log(LOG_INFO, "Skipping notice $notice->id " . 'because user has FOREIGN_NOTICE_SEND bit off.'); return false; } - $success = false; + // If it's not a reply, or if the user WANTS to send @-replies, + // then, yeah, it can go to Facebook. - // If it's not a reply, or if the user WANTS to send @-replies... if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) || ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) { - - $success = true; - - // The two condition below are deal breakers: - - // Avoid a loop - if ($notice->source == 'Facebook') { - common_log(LOG_INFO, "Skipping notice $notice->id because its " . - 'source is Facebook.'); - $success = false; - } - - $facebook = getFacebook(); - $fbuid = $flink->foreign_id; - - try { - - // Check to see if the user has given the FB app status update perms - $result = $facebook->api_client-> - users_hasAppPermission('publish_stream', $fbuid); - - if ($result != 1) { - $result = $facebook->api_client-> - users_hasAppPermission('status_update', $fbuid); - } - if ($result != 1) { - $user = $flink->getUser(); - $msg = "Not sending notice $notice->id to Facebook " . - "because user $user->nickname hasn't given the " . - 'Facebook app \'status_update\' or \'publish_stream\' permission.'; - common_debug($msg); - $success = false; - } - - } catch(FacebookRestClientException $e){ - common_log(LOG_ERR, $e->getMessage()); - $success = false; - } - + return true; } - return $success; + return false; } @@ -119,88 +85,65 @@ function facebookBroadcastNotice($notice) if (isFacebookBound($notice, $flink)) { + // Okay, we're good to go, update the FB status + $status = null; $fbuid = $flink->foreign_id; - $user = $flink->getUser(); - - // Get the status 'verb' (prefix) the user has set + $attachments = $notice->attachments(); try { - $prefix = $facebook->api_client-> - data_getUserPreference(FACEBOOK_NOTICE_PREFIX, $fbuid); + + // Get the status 'verb' (prefix) the user has set + + // XXX: Does this call count against our per user FB request limit? + // If so we should consider storing verb elsewhere or not storing + + $prefix = $facebook->api_client->data_getUserPreference(FACEBOOK_NOTICE_PREFIX, + $fbuid); $status = "$prefix $notice->content"; - } catch(FacebookRestClientException $e) { - common_log(LOG_WARNING, $e->getMessage()); - common_log(LOG_WARNING, - 'Unable to get the status verb setting from Facebook ' . - "for $user->nickname (user id: $user->id)."); - } + $can_publish = $facebook->api_client->users_hasAppPermission('publish_stream', + $fbuid); - // Okay, we're good to go, update the FB status + $can_update = $facebook->api_client->users_hasAppPermission('status_update', + $fbuid); - try { - $result = $facebook->api_client-> - users_hasAppPermission('publish_stream', $fbuid); - if($result == 1){ - // authorized to use the stream api, so use it - $fbattachment = null; - $attachments = $notice->attachments(); - if($attachments){ - $fbattachment=array(); - $fbattachment['media']=array(); - //facebook only supports one attachment per item - $attachment = $attachments[0]; - $fbmedia=array(); - if(strncmp($attachment->mimetype,'image/',strlen('image/'))==0){ - $fbmedia['type']='image'; - $fbmedia['src']=$attachment->url; - $fbmedia['href']=$attachment->url; - $fbattachment['media'][]=$fbmedia; -/* Video doesn't seem to work. The notice never makes it to facebook, and no error is reported. - }else if(strncmp($attachment->mimetype,'video/',strlen('image/'))==0 || $attachment->mimetype="application/ogg"){ - $fbmedia['type']='video'; - $fbmedia['video_src']=$attachment->url; - // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29 - // says that preview_img is required... but we have no value to put in it - // $fbmedia['preview_img']=$attachment->url; - if($attachment->title){ - $fbmedia['video_title']=$attachment->title; - } - $fbmedia['video_type']=$attachment->mimetype; - $fbattachment['media'][]=$fbmedia; -*/ - }else if($attachment->mimetype=='audio/mpeg'){ - $fbmedia['type']='mp3'; - $fbmedia['src']=$attachment->url; - $fbattachment['media'][]=$fbmedia; - }else if($attachment->mimetype=='application/x-shockwave-flash'){ - $fbmedia['type']='flash'; - // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29 - // says that imgsrc is required... but we have no value to put in it - // $fbmedia['imgsrc']=''; - $fbmedia['swfsrc']=$attachment->url; - $fbattachment['media'][]=$fbmedia; - }else{ - $fbattachment['name']=($attachment->title?$attachment->title:$attachment->url); - $fbattachment['href']=$attachment->url; - } - } - $facebook->api_client->stream_publish($status, $fbattachment, null, null, $fbuid); - }else{ + if (!empty($attachments) && $can_publish == 1) { + $fbattachment = format_attachments($attachments); + $facebook->api_client->stream_publish($status, $fbattachment, + null, null, $fbuid); + common_log(LOG_INFO, + "Posted notice $notice->id w/attachment " . + "to Facebook user's stream (fbuid = $fbuid)."); + } elseif ($can_update == 1 || $can_publish == 1) { $facebook->api_client->users_setStatus($status, $fbuid, false, true); + common_log(LOG_INFO, + "Posted notice $notice->id to Facebook " . + "as a status update (fbuid = $fbuid)."); + } else { + $msg = "Not sending notice $notice->id to Facebook " . + "because user $user->nickname hasn't given the " . + 'Facebook app \'status_update\' or \'publish_stream\' permission.'; + common_log(LOG_WARNING, $msg); + } + + // Finally, attempt to update the user's profile box + + if ($can_publish == 1 || $can_update == 1) { + updateProfileBox($facebook, $flink, $notice); } - } catch(FacebookRestClientException $e) { + + } catch (FacebookRestClientException $e) { $code = $e->getCode(); - common_log(LOG_ERR, 'Facebook returned error code ' . - $code . ': ' . $e->getMessage()); - common_log(LOG_ERR, - 'Unable to update Facebook status for ' . - "$user->nickname (user id: $user->id)!"); + common_log(LOG_WARNING, 'Facebook returned error code ' . + $code . ': ' . $e->getMessage()); + common_log(LOG_WARNING, + 'Unable to update Facebook status for ' . + "$user->nickname (user id: $user->id)!"); if ($code == 200 || $code == 250) { @@ -209,25 +152,62 @@ function facebookBroadcastNotice($notice) // see: http://wiki.developers.facebook.com/index.php/Users.setStatus#Example_Return_XML remove_facebook_app($flink); + + } else { + + // Try sending again later. + + return false; } } + } - // Now try to update the profile box + return true; - try { - updateProfileBox($facebook, $flink, $notice); - } catch(FacebookRestClientException $e) { - common_log(LOG_ERR, 'Facebook returned error code ' . - $e->getCode() . ': ' . $e->getMessage()); - common_log(LOG_WARNING, - 'Unable to update Facebook profile box for ' . - "$user->nickname (user id: $user->id)."); - } +} +function updateProfileBox($facebook, $flink, $notice) { + $fbaction = new FacebookAction($output = 'php://output', + $indent = true, $facebook, $flink); + $fbaction->updateProfileBox($notice); +} + +function format_attachments($attachments) +{ + $fbattachment = array(); + $fbattachment['media'] = array(); + + // Facebook only supports one attachment per item + + $attachment = $attachments[0]; + $fbmedia = array(); + + if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) { + $fbmedia['type'] = 'image'; + $fbmedia['src'] = $attachment->url; + $fbmedia['href'] = $attachment->url; + $fbattachment['media'][] = $fbmedia; + } else if ($attachment->mimetype == 'audio/mpeg') { + $fbmedia['type'] = 'mp3'; + $fbmedia['src'] = $attachment->url; + $fbattachment['media'][] = $fbmedia; + }else if ($attachment->mimetype == 'application/x-shockwave-flash') { + $fbmedia['type'] = 'flash'; + + // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29 + // says that imgsrc is required... but we have no value to put in it + // $fbmedia['imgsrc']=''; + + $fbmedia['swfsrc'] = $attachment->url; + $fbattachment['media'][] = $fbmedia; + }else{ + $fbattachment['name'] = ($attachment->title ? + $attachment->title : $attachment->url); + $fbattachment['href'] = $attachment->url; } - return true; + return $fbattachment; } function remove_facebook_app($flink) -- cgit v1.2.3-54-g00ecf From cd71f9cc51f77b6b8e3b11c34cb7523f36339cea Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Wed, 5 Aug 2009 00:16:12 +0000 Subject: Better (hopefully) database connection management for child processes --- scripts/twitterstatusfetcher.php | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/scripts/twitterstatusfetcher.php b/scripts/twitterstatusfetcher.php index dd139417c..67f52a3cc 100755 --- a/scripts/twitterstatusfetcher.php +++ b/scripts/twitterstatusfetcher.php @@ -99,13 +99,6 @@ class TwitterStatusFetcher extends Daemon foreach ($flinks as $f) { - // We have to disconnect from the DB before forking so - // each sub-process will open its own connection and - // avoid stomping on the others - - $conn = &$f->getDatabaseConnection(); - $conn->disconnect(); - $pid = pcntl_fork(); if ($pid == -1) { @@ -125,7 +118,24 @@ class TwitterStatusFetcher extends Daemon } else { // Child + + // Each child ps needs its own DB connection + + // Note: DataObject::getDatabaseConnection() creates + // a new connection if there isn't one already + + global $_DB_DATAOBJECT; + $conn = &$f->getDatabaseConnection(); + $this->getTimeline($f); + + $conn->disconnect(); + + // XXX: Couldn't find a less brutal way to blow + // away a cached connection + + unset($_DB_DATAOBJECT['CONNECTIONS']); + exit(); } @@ -189,7 +199,10 @@ class TwitterStatusFetcher extends Daemon function refreshFlinks() { + global $_DB_DATAOBJECT; + $flink = new Foreign_link(); + $conn = &$flink->getDatabaseConnection(); $flink->service = TWITTER_SERVICE; @@ -215,6 +228,9 @@ class TwitterStatusFetcher extends Daemon $flink->free(); unset($flink); + $conn->disconnect(); + unset($_DB_DATAOBJECT['CONNECTIONS']); + return $flinks; } @@ -299,6 +315,7 @@ class TwitterStatusFetcher extends Daemon function saveStatus($status, $flink) { $id = $this->ensureProfile($status->user); + $profile = Profile::staticGet($id); if (empty($profile)) { @@ -356,7 +373,7 @@ class TwitterStatusFetcher extends Daemon $profileurl = 'http://twitter.com/' . $user->screen_name; $profile = Profile::staticGet('profileurl', $profileurl); - if (!empty($profile) { + if (!empty($profile)) { if (defined('SCRIPT_DEBUG')) { common_debug("Profile for $profile->nickname found."); } -- cgit v1.2.3-54-g00ecf From 36e5d2b45f9ec240c0cecbb78afcce92e2962a49 Mon Sep 17 00:00:00 2001 From: Eric Helgeson Date: Tue, 4 Aug 2009 22:11:20 -0500 Subject: Added correct null check. Created noisey errors on fresh install. $id is not defined, should be $this->id --- classes/Design.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/classes/Design.php b/classes/Design.php index 43544f1c9..b53096aa2 100644 --- a/classes/Design.php +++ b/classes/Design.php @@ -107,7 +107,7 @@ class Design extends Memcached_DataObject static function toWebColor($color) { - if (is_null($color)) { + if ($color == null) { return null; } @@ -115,7 +115,7 @@ class Design extends Memcached_DataObject return new WebColor($color); } catch (WebColorException $e) { // This shouldn't happen - common_log(LOG_ERR, "Unable to create color for design $id.", + common_log(LOG_ERR, "Unable to create color for design $this->id.", __FILE__); return null; } -- cgit v1.2.3-54-g00ecf From 535e3bae79006dd54f6d5c4918133a05c03c43ed Mon Sep 17 00:00:00 2001 From: Adrian Lang Date: Wed, 5 Aug 2009 15:58:18 +0200 Subject: Fix reference to undefined variable in Design::toWebColor. --- classes/Design.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Design.php b/classes/Design.php index 43544f1c9..5d8364be5 100644 --- a/classes/Design.php +++ b/classes/Design.php @@ -115,7 +115,7 @@ class Design extends Memcached_DataObject return new WebColor($color); } catch (WebColorException $e) { // This shouldn't happen - common_log(LOG_ERR, "Unable to create color for design $id.", + common_log(LOG_ERR, 'Unable to create color for design '.$this->id, __FILE__); return null; } -- cgit v1.2.3-54-g00ecf From 9b3adf789a7df54294fdafb44dc48a425490e787 Mon Sep 17 00:00:00 2001 From: Adrian Lang Date: Wed, 5 Aug 2009 16:05:29 +0200 Subject: Argh, first commit for ages and such a stupid error. Sorry. --- classes/Design.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Design.php b/classes/Design.php index 5d8364be5..dc1712aff 100644 --- a/classes/Design.php +++ b/classes/Design.php @@ -115,7 +115,7 @@ class Design extends Memcached_DataObject return new WebColor($color); } catch (WebColorException $e) { // This shouldn't happen - common_log(LOG_ERR, 'Unable to create color for design '.$this->id, + common_log(LOG_ERR, "Unable to create web color for $color", __FILE__); return null; } -- cgit v1.2.3-54-g00ecf From 44b2b6424714f82dc199fbe9780843638122e3ad Mon Sep 17 00:00:00 2001 From: Adrian Lang Date: Wed, 5 Aug 2009 16:05:29 +0200 Subject: Argh, first commit for ages and such a stupid error. Sorry. --- classes/Design.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Design.php b/classes/Design.php index b53096aa2..9354bfcda 100644 --- a/classes/Design.php +++ b/classes/Design.php @@ -115,7 +115,7 @@ class Design extends Memcached_DataObject return new WebColor($color); } catch (WebColorException $e) { // This shouldn't happen - common_log(LOG_ERR, "Unable to create color for design $this->id.", + common_log(LOG_ERR, "Unable to create web color for $color", __FILE__); return null; } -- cgit v1.2.3-54-g00ecf From c19df2dbc29fd6392a249ff5e4ea7634deb3f273 Mon Sep 17 00:00:00 2001 From: anontwit Date: Wed, 5 Aug 2009 10:50:27 -0700 Subject: updated IM docs with new commands --- doc-src/im | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/doc-src/im b/doc-src/im index da07f9fe7..a02670a6d 100644 --- a/doc-src/im +++ b/doc-src/im @@ -32,4 +32,15 @@ currently-implemented commands: you subscribe to. * **off**: Turn off notifications. You'll no longer receive Jabber notifications. - +* **stop**: Same as 'off' +* **quit**: Same as 'off' +* **help**: Show this help. List available Jabber/XMPP commands +* **follow <nickname>**: Subscribe to <nickname> +* **sub <nickname>**: Same as follow +* **leave <nickname>**: Subscribe to <nickname> +* **unsub <nickname>**: Same as leave +* **d <nickname> <text>**: Send direct message to <nickname> with message body <text> +* **get <nickname>**: Get last notice from <nickname> +* **get <nickname>**: Same as 'get' +* **whois <nickname>**: Get Profile info on <nickname> +* **fav <nickname>**: Add user's last notice as a favorite \ No newline at end of file -- cgit v1.2.3-54-g00ecf From c3a522623c3a0628c33407ee01b16e189c44bba5 Mon Sep 17 00:00:00 2001 From: anontwit Date: Wed, 5 Aug 2009 10:58:30 -0700 Subject: fixed double 'get' type --- doc-src/im | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc-src/im b/doc-src/im index a02670a6d..c722a4e2c 100644 --- a/doc-src/im +++ b/doc-src/im @@ -41,6 +41,6 @@ currently-implemented commands: * **unsub <nickname>**: Same as leave * **d <nickname> <text>**: Send direct message to <nickname> with message body <text> * **get <nickname>**: Get last notice from <nickname> -* **get <nickname>**: Same as 'get' +* **last <nickname>**: Same as 'get' * **whois <nickname>**: Get Profile info on <nickname> * **fav <nickname>**: Add user's last notice as a favorite \ No newline at end of file -- cgit v1.2.3-54-g00ecf From e797001be4cd982ed778bda16744ab4007eb31c8 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Wed, 5 Aug 2009 16:02:47 -0400 Subject: add livetweeter to notice source --- db/notice_source.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/notice_source.sql b/db/notice_source.sql index 983ea9150..71fa89344 100644 --- a/db/notice_source.sql +++ b/db/notice_source.sql @@ -22,6 +22,7 @@ VALUES ('IdentiFox','IdentiFox','http://www.bitbucket.org/uncryptic/identifox/', now()), ('identitwitch','IdentiTwitch','http://richfish.org/identitwitch/', now()), ('LaTwit','LaTwit','http://latwit.mac65.com/', now()), + ('livetweeter', 'livetweeter', 'http://addons.songbirdnest.com/addon/1204', now()), ('maisha', 'Maisha', 'http://maisha.grango.org/', now()), ('mbpidgin','mbpidgin','http://code.google.com/p/microblog-purple/', now()), ('Mobidentica', 'Mobidentica', 'http://www.substanceofcode.com/software/mobidentica/', now()), -- cgit v1.2.3-54-g00ecf From 7a61b0737d00adbdaaea7e82fa3a1702286332aa Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Wed, 5 Aug 2009 16:06:15 -0400 Subject: update version to 0.8.1pre1 --- lib/common.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common.php b/lib/common.php index b3d301862..8cd3ae2fc 100644 --- a/lib/common.php +++ b/lib/common.php @@ -19,7 +19,7 @@ if (!defined('LACONICA')) { exit(1); } -define('LACONICA_VERSION', '0.8.1dev'); +define('LACONICA_VERSION', '0.8.1pre1'); define('AVATAR_PROFILE_SIZE', 96); define('AVATAR_STREAM_SIZE', 48); -- cgit v1.2.3-54-g00ecf From 83ff1cecd39e197e108ecdaba7139b59d22dbee0 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 16:26:19 -0400 Subject: Use NICKNAME_FMT everywhere consistently --- actions/finishopenidlogin.php | 4 ++-- actions/profilesettings.php | 2 +- actions/updateprofile.php | 2 +- actions/userauthorization.php | 2 +- plugins/FBConnect/FBConnectAuth.php | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/actions/finishopenidlogin.php b/actions/finishopenidlogin.php index ff0b35218..ba1e933e3 100644 --- a/actions/finishopenidlogin.php +++ b/actions/finishopenidlogin.php @@ -217,7 +217,7 @@ class FinishopenidloginAction extends Action if (!Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.')); return; } @@ -389,7 +389,7 @@ class FinishopenidloginAction extends Action { if (!Validate::string($str, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { return false; } if (!User::allowed_nickname($str)) { diff --git a/actions/profilesettings.php b/actions/profilesettings.php index fb847680b..d8fb2c9bb 100644 --- a/actions/profilesettings.php +++ b/actions/profilesettings.php @@ -189,7 +189,7 @@ class ProfilesettingsAction extends AccountSettingsAction // Some validation if (!Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.')); return; } else if (!User::allowed_nickname($nickname)) { diff --git a/actions/updateprofile.php b/actions/updateprofile.php index d8b62fb09..f6cb277aa 100644 --- a/actions/updateprofile.php +++ b/actions/updateprofile.php @@ -79,7 +79,7 @@ class UpdateprofileAction extends Action $nickname = $req->get_parameter('omb_listenee_nickname'); if ($nickname && !Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { $this->clientError(_('Nickname must have only lowercase letters and numbers and no spaces.')); return false; } diff --git a/actions/userauthorization.php b/actions/userauthorization.php index 8dc2c808d..00903ae01 100644 --- a/actions/userauthorization.php +++ b/actions/userauthorization.php @@ -481,7 +481,7 @@ class UserauthorizationAction extends Action $nickname = $_GET['omb_listenee_nickname']; if (!Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { throw new OAuthException('Nickname must have only letters and numbers and no spaces.'); } $profile = $_GET['omb_listenee_profile']; diff --git a/plugins/FBConnect/FBConnectAuth.php b/plugins/FBConnect/FBConnectAuth.php index 3cf9fefc1..a3e2cdadc 100644 --- a/plugins/FBConnect/FBConnectAuth.php +++ b/plugins/FBConnect/FBConnectAuth.php @@ -238,7 +238,7 @@ class FBConnectauthAction extends Action if (!Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.')); return; } @@ -418,7 +418,7 @@ class FBConnectauthAction extends Action { if (!Validate::string($str, array('min_length' => 1, 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + 'format' => NICKNAME_FMT))) { return false; } if (!User::allowed_nickname($str)) { -- cgit v1.2.3-54-g00ecf From d77982b9b47b8b17051000cfcf3db1a8945d6279 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 17:09:19 -0400 Subject: added Infinite Scroll plugin --- plugins/InfiniteScroll/InfiniteScrollPlugin.php | 66 ++++++ plugins/InfiniteScroll/ajax-loader.gif | Bin 0 -> 10819 bytes plugins/InfiniteScroll/jquery.infinitescroll.js | 251 +++++++++++++++++++++ .../InfiniteScroll/jquery.infinitescroll.min.js | 8 + plugins/InfiniteScroll/readme.txt | 6 + 5 files changed, 331 insertions(+) create mode 100644 plugins/InfiniteScroll/InfiniteScrollPlugin.php create mode 100644 plugins/InfiniteScroll/ajax-loader.gif create mode 100644 plugins/InfiniteScroll/jquery.infinitescroll.js create mode 100644 plugins/InfiniteScroll/jquery.infinitescroll.min.js create mode 100644 plugins/InfiniteScroll/readme.txt diff --git a/plugins/InfiniteScroll/InfiniteScrollPlugin.php b/plugins/InfiniteScroll/InfiniteScrollPlugin.php new file mode 100644 index 000000000..6738dc760 --- /dev/null +++ b/plugins/InfiniteScroll/InfiniteScrollPlugin.php @@ -0,0 +1,66 @@ +. + * + * @category Plugin + * @package Laconica + * @author Craig Andrews + * @copyright 2009 Craig Andrews http://candrews.integralblue.com + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} + +class InfiniteScrollPlugin extends Plugin +{ + function __construct() + { + parent::__construct(); + } + + function onEndShowScripts($action) + { + $action->element('script', + array('type' => 'text/javascript', + 'src' => common_path('plugins/InfiniteScroll/jquery.infinitescroll.min.js')), + ''); + + $loading_image = common_path('plugins/InfiniteScroll/ajax-loader.gif'); + $js_string = << +jQuery(document).ready(function($){ + $('notices_primary').infinitescroll({ + nextSelector : "li.nav_next a", + loadingImg : "$loading_image", + text : "Loading the next set of posts...", + donetext : "Congratulations, you\'ve reached the end of the Internet.", + navSelector : "div.pagination", + contentSelector : "#notices_primary", + itemSelector : "ol.notices" + }); +}); + +EOT; + $action->raw($js_string); + } +} diff --git a/plugins/InfiniteScroll/ajax-loader.gif b/plugins/InfiniteScroll/ajax-loader.gif new file mode 100644 index 000000000..a576ecd5e Binary files /dev/null and b/plugins/InfiniteScroll/ajax-loader.gif differ diff --git a/plugins/InfiniteScroll/jquery.infinitescroll.js b/plugins/InfiniteScroll/jquery.infinitescroll.js new file mode 100644 index 000000000..670686b0e --- /dev/null +++ b/plugins/InfiniteScroll/jquery.infinitescroll.js @@ -0,0 +1,251 @@ + +/*! +// Infinite Scroll jQuery plugin +// copyright Paul Irish, licensed GPL & MIT +// version 1.2.090804 + +// home and docs: http://www.infinite-scroll.com +*/ + +// todo: add preloading option. + +;(function($){ + + $.fn.infinitescroll = function(options,callback){ + + // console log wrapper. + function debug(){ + if (opts.debug) { window.console && console.log.call(console,arguments)} + } + + // grab each selector option and see if any fail. + function areSelectorsValid(opts){ + for (var key in opts){ + if (key.indexOf && key.indexOf('Selector') && $(opts[key]).length === 0){ + debug('Your ' + key + ' found no elements.'); + return false; + } + return true; + } + } + + + // find the number to increment in the path. + function determinePath(path){ + + path.match(relurl) ? path.match(relurl)[2] : path; + + // there is a 2 in the url surrounded by slashes, e.g. /page/2/ + if ( path.match(/^(.*?)\b2\b(.*?$)/) ){ + path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1); + } else + // if there is any 2 in the url at all. + if (path.match(/^(.*?)2(.*?$)/)){ + debug('Trying backup next selector parse technique. Treacherous waters here, matey.'); + path = path.match(/^(.*?)2(.*?$)/).slice(1); + } else { + debug('Sorry, we couldn\'t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.'); + props.isInvalidPage = true; //prevent it from running on this page. + } + + return path; + } + + + // 'document' means the full document usually, but sometimes the content of the overflow'd div in local mode + function getDocumentHeight(){ + // weird doubletouch of scrollheight because http://soulpass.com/2006/07/24/ie-and-scrollheight/ + return opts.localMode ? ($(props.container)[0].scrollHeight && $(props.container)[0].scrollHeight) + // needs to be document's height. (not props.container's) html's height is wrong in IE. + : $(document).height() + } + + + + function isNearBottom(opts,props){ + + // distance remaining in the scroll + // computed as: document height - distance already scroll - viewport height - buffer + var pixelsFromWindowBottomToBottom = getDocumentHeight() - + (opts.localMode ? $(props.container).scrollTop() : + // have to do this bs because safari doesnt report a scrollTop on the html element + ($(props.container).scrollTop() || $(props.container.ownerDocument.body).scrollTop())) - + $(opts.localMode ? props.container : window).height(); + + debug('math:',pixelsFromWindowBottomToBottom, props.pixelsFromNavToBottom); + + // if distance remaining in the scroll (including buffer) is less than the orignal nav to bottom.... + return (pixelsFromWindowBottomToBottom - opts.bufferPx < props.pixelsFromNavToBottom); + } + + function showDoneMsg(){ + props.loadingMsg + .find('img').hide() + .parent() + .find('div').html(opts.donetext).animate({opacity: 1},2000).fadeOut('normal'); + + // user provided callback when done + opts.errorCallback(); + } + + function infscrSetup(path,opts,props,callback){ + + if (props.isDuringAjax || props.isInvalidPage || props.isDone) return; + + if ( !isNearBottom(opts,props) ) return; + + // we dont want to fire the ajax multiple times + props.isDuringAjax = true; + + // show the loading message and hide the previous/next links + props.loadingMsg.appendTo( opts.contentSelector ).show(); + $( opts.navSelector ).hide(); + + // increment the URL bit. e.g. /page/3/ + props.currPage++; + + debug('heading into ajax',path); + + // if we're dealing with a table we can't use DIVs + var box = $(opts.contentSelector).is('table') ? $('') : $('
    '); + + box + .attr('id','infscr-page-'+props.currPage) + .addClass('infscr-pages') + .appendTo( opts.contentSelector ) + .load( path.join( props.currPage ) + ' ' + opts.itemSelector,null,function(){ + + // if we've hit the last page... + if (props.isDone){ + showDoneMsg(); + return false; + + } else { + + // if it didn't return anything + if (box.children().length == 0){ + // fake an ajaxError so we can quit. + $.event.trigger( "ajaxError", [{status:404}] ); + } + + // fadeout currently makes the 'd text ugly in IE6 + props.loadingMsg.fadeOut('normal' ); + + // smooth scroll to ease in the new content + if (opts.animate){ + var scrollTo = $(window).scrollTop() + $('#infscr-loading').height() + opts.extraScrollPx + 'px'; + $('html,body').animate({scrollTop: scrollTo}, 800,function(){ props.isDuringAjax = false; }); + } + + // pass in the new DOM element as context for the callback + callback.call( box[0] ); + + if (!opts.animate) props.isDuringAjax = false; // once the call is done, we can allow it again. + } + }); // end of load() + + + } // end of infscrSetup() + + + + + // lets get started. + + var opts = $.extend({}, $.infinitescroll.defaults, options); + var props = $.infinitescroll; // shorthand + callback = callback || function(){}; + + if (!areSelectorsValid(opts)){ return false; } + + // we doing this on an overflow:auto div? + props.container = opts.localMode ? this : document.documentElement; + + // contentSelector we'll use for our .load() + opts.contentSelector = opts.contentSelector || this; + + + // get the relative URL - everything past the domain name. + var relurl = /(.*?\/\/).*?(\/.*)/; + var path = $(opts.nextSelector).attr('href'); + + + if (!path) { debug('Navigation selector not found'); return; } + + // set the path to be a relative URL from root. + path = determinePath(path); + + + // reset scrollTop in case of page refresh: + if (opts.localMode) $(props.container)[0].scrollTop = 0; + + // distance from nav links to bottom + // computed as: height of the document + top offset of container - top offset of nav link + props.pixelsFromNavToBottom = getDocumentHeight() + + $(props.container).offset().top - + $(opts.navSelector).offset().top; + + // define loading msg + props.loadingMsg = $('
    Loading...
    '+opts.loadingText+'
    '); + // preload the image + (new Image()).src = opts.loadingImg; + + + + // set up our bindings + $(document).ajaxError(function(e,xhr,opt){ + debug('Page not found. Self-destructing...'); + + // die if we're out of pages. + if (xhr.status == 404){ + showDoneMsg(); + props.isDone = true; + $(opts.localMode ? this : window).unbind('scroll.infscr'); + } + }); + + // bind scroll handler to element (if its a local scroll) or window + $(opts.localMode ? this : window) + .bind('scroll.infscr', function(){ infscrSetup(path,opts,props,callback); } ) + .trigger('scroll.infscr'); // trigger the event, in case it's a short page + + + return this; + + } // end of $.fn.infinitescroll() + + + + // options and read-only properties object + + $.infinitescroll = { + defaults : { + debug : false, + preload : false, + nextSelector : "div.navigation a:first", + loadingImg : "http://www.infinite-scroll.com/loading.gif", + loadingText : "Loading the next set of posts...", + donetext : "Congratulations, you've reached the end of the internet.", + navSelector : "div.navigation", + contentSelector : null, // not really a selector. :) it's whatever the method was called on.. + extraScrollPx : 150, + itemSelector : "div.post", + animate : false, + localMode : false, + bufferPx : 40, + errorCallback : function(){} + }, + loadingImg : undefined, + loadingMsg : undefined, + container : undefined, + currPage : 1, + currDOMChunk : null, // defined in setup()'s load() + isDuringAjax : false, + isInvalidPage : false, + isDone : false // for when it goes all the way through the archive. + }; + + + +})(jQuery); diff --git a/plugins/InfiniteScroll/jquery.infinitescroll.min.js b/plugins/InfiniteScroll/jquery.infinitescroll.min.js new file mode 100644 index 000000000..04c75c456 --- /dev/null +++ b/plugins/InfiniteScroll/jquery.infinitescroll.min.js @@ -0,0 +1,8 @@ +/* +// Infinite Scroll jQuery plugin +// copyright Paul Irish, licensed GPL & MIT +// version 1.2.090804 + +// home and docs: http://www.infinite-scroll.com +*/ +(function(A){A.fn.infinitescroll=function(N,L){function E(){if(B.debug){window.console&&console.log.call(console,arguments)}}function G(P){for(var O in P){if(O.indexOf&&O.indexOf("Selector")&&A(P[O]).length===0){E("Your "+O+" found no elements.");return false}return true}}function K(O){O.match(C)?O.match(C)[2]:O;if(O.match(/^(.*?)\b2\b(.*?$)/)){O=O.match(/^(.*?)\b2\b(.*?$)/).slice(1)}else{if(O.match(/^(.*?)2(.*?$)/)){E("Trying backup next selector parse technique. Treacherous waters here, matey.");O=O.match(/^(.*?)2(.*?$)/).slice(1)}else{E("Sorry, we couldn't parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.");H.isInvalidPage=true}}return O}function I(){return B.localMode?(A(H.container)[0].scrollHeight&&A(H.container)[0].scrollHeight):A(document).height()}function F(Q,P){var O=I()-(Q.localMode?A(P.container).scrollTop():(A(P.container).scrollTop()||A(P.container.ownerDocument.body).scrollTop()))-A(Q.localMode?P.container:window).height();E("math:",O,P.pixelsFromNavToBottom);return(O-Q.bufferPx"):A("
    ");P.attr("id","infscr-page-"+O.currPage).addClass("infscr-pages").appendTo(Q.contentSelector).load(R.join(O.currPage)+" "+Q.itemSelector,null,function(){if(O.isDone){J();return false}else{if(P.children().length==0){A.event.trigger("ajaxError",[{status:404}])}O.loadingMsg.fadeOut("normal");if(Q.animate){var T=A(window).scrollTop()+A("#infscr-loading").height()+Q.extraScrollPx+"px";A("html,body").animate({scrollTop:T},800,function(){O.isDuringAjax=false})}S.call(P[0]);if(!Q.animate){O.isDuringAjax=false}}})}var B=A.extend({},A.infinitescroll.defaults,N);var H=A.infinitescroll;L=L||function(){};if(!G(B)){return false}H.container=B.localMode?this:document.documentElement;B.contentSelector=B.contentSelector||this;var C=/(.*?\/\/).*?(\/.*)/;var M=A(B.nextSelector).attr("href");if(!M){E("Navigation selector not found");return }M=K(M);if(B.localMode){A(H.container)[0].scrollTop=0}H.pixelsFromNavToBottom=I()+A(H.container).offset().top-A(B.navSelector).offset().top;H.loadingMsg=A('
    Loading...
    '+B.loadingText+"
    ");(new Image()).src=B.loadingImg;A(document).ajaxError(function(P,Q,O){E("Page not found. Self-destructing...");if(Q.status==404){J();H.isDone=true;A(B.localMode?this:window).unbind("scroll.infscr")}});A(B.localMode?this:window).bind("scroll.infscr",function(){D(M,B,H,L)}).trigger("scroll.infscr");return this};A.infinitescroll={defaults:{debug:false,preload:false,nextSelector:"div.navigation a:first",loadingImg:"http://www.infinite-scroll.com/loading.gif",loadingText:"Loading the next set of posts...",donetext:"Congratulations, you've reached the end of the internet.",navSelector:"div.navigation",contentSelector:null,extraScrollPx:150,itemSelector:"div.post",animate:false,localMode:false,bufferPx:40,errorCallback:function(){}},loadingImg:undefined,loadingMsg:undefined,container:undefined,currPage:1,currDOMChunk:null,isDuringAjax:false,isInvalidPage:false,isDone:false}})(jQuery); \ No newline at end of file diff --git a/plugins/InfiniteScroll/readme.txt b/plugins/InfiniteScroll/readme.txt new file mode 100644 index 000000000..3ce3b7fd2 --- /dev/null +++ b/plugins/InfiniteScroll/readme.txt @@ -0,0 +1,6 @@ +Infinite Scroll adds the following functionality to your Laconica installation: When a user scrolls towards the bottom of the page, the next page of notices is automatically retrieved and appended. This means they never need to click "Next Page", which dramatically increases stickiness. + +Installation +============ +Add "addPlugin('InfiniteScroll');" to the bottom of your config.php +That's it! -- cgit v1.2.3-54-g00ecf From 95ba22c5d7ffb28fa5c44a398edca86cc0f637f5 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 18:27:27 -0400 Subject: Switch DOCTYPE's to the XHTML 5 DOCTYPE --- install.php | 4 +--- lib/htmloutputter.php | 4 +--- plugins/FBConnect/FBC_XDReceiver.php | 4 +--- plugins/FBConnect/FBConnectPlugin.php | 4 +--- plugins/recaptcha/recaptcha.php | 4 +--- tpl/index.php | 6 ++---- 6 files changed, 7 insertions(+), 19 deletions(-) diff --git a/install.php b/install.php index 227f99789..ea2135651 100644 --- a/install.php +++ b/install.php @@ -383,9 +383,7 @@ function runDbScript($filename, $conn, $type='mysql') ?> xml version="1.0" encoding="UTF-8" "; ?> - + Install Laconica diff --git a/lib/htmloutputter.php b/lib/htmloutputter.php index 06603ac05..cba8a5f5e 100644 --- a/lib/htmloutputter.php +++ b/lib/htmloutputter.php @@ -110,9 +110,7 @@ class HTMLOutputter extends XMLOutputter $this->extraHeaders(); - $this->startXML('html', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + $this->startXML('html'); $language = $this->getLanguage(); diff --git a/plugins/FBConnect/FBC_XDReceiver.php b/plugins/FBConnect/FBC_XDReceiver.php index 57c98b4f1..d9677fca7 100644 --- a/plugins/FBConnect/FBC_XDReceiver.php +++ b/plugins/FBConnect/FBC_XDReceiver.php @@ -47,9 +47,7 @@ class FBC_XDReceiverAction extends Action header('Expires:'); header('Pragma:'); - $this->startXML('html', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + $this->startXML('html'); $language = $this->getLanguage(); diff --git a/plugins/FBConnect/FBConnectPlugin.php b/plugins/FBConnect/FBConnectPlugin.php index 6788793b2..2fb10a675 100644 --- a/plugins/FBConnect/FBConnectPlugin.php +++ b/plugins/FBConnect/FBConnectPlugin.php @@ -82,9 +82,7 @@ class FBConnectPlugin extends Plugin $action->extraHeaders(); - $action->startXML('html', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + $action->startXML('html'); $language = $action->getLanguage(); diff --git a/plugins/recaptcha/recaptcha.php b/plugins/recaptcha/recaptcha.php index 5ef8352d1..38a860fc7 100644 --- a/plugins/recaptcha/recaptcha.php +++ b/plugins/recaptcha/recaptcha.php @@ -65,9 +65,7 @@ class recaptcha extends Plugin $action->extraHeaders(); - $action->startXML('html', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + $action->startXML('html'); $action->raw(''); return false; diff --git a/tpl/index.php b/tpl/index.php index 5f1ed8439..be375e75a 100644 --- a/tpl/index.php +++ b/tpl/index.php @@ -1,6 +1,4 @@ - + <?php echo section('title'); ?> @@ -44,4 +42,4 @@ PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    - \ No newline at end of file + -- cgit v1.2.3-54-g00ecf From b975a6a0e5a5a7332eea4834494029c5c1238540 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 18:55:47 -0400 Subject: Don't start HTML responses with extraHeaders(); - - $this->startXML('html'); + if( ! substr($type,0,strlen('text/html'))=='text/html' ){ + // Browsers don't like it when xw->startDocument('1.0', 'UTF-8'); + } + if ($doc) { + $this->xw->writeDTD('html', $public, $system); + } $language = $this->getLanguage(); -- cgit v1.2.3-54-g00ecf From feac024348e0584c84fd5392c503d912000d30bc Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 19:24:34 -0400 Subject: Accidentally caused the DOCTYPE to never be rendered - fix that. --- lib/htmloutputter.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/htmloutputter.php b/lib/htmloutputter.php index 8f3b1a609..5da1fbe14 100644 --- a/lib/htmloutputter.php +++ b/lib/htmloutputter.php @@ -113,9 +113,7 @@ class HTMLOutputter extends XMLOutputter // Browsers don't like it when xw->startDocument('1.0', 'UTF-8'); } - if ($doc) { - $this->xw->writeDTD('html', $public, $system); - } + $this->xw->writeDTD('html', $public, $system); $language = $this->getLanguage(); -- cgit v1.2.3-54-g00ecf From 6a76addbe8bbfafd1a1dd6ed7ffbf8afebff5abe Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 19:35:42 -0400 Subject: Added cssLink() and script() functions to htmloutputter --- lib/htmloutputter.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/lib/htmloutputter.php b/lib/htmloutputter.php index 5da1fbe14..0b4c1405a 100644 --- a/lib/htmloutputter.php +++ b/lib/htmloutputter.php @@ -339,6 +339,42 @@ class HTMLOutputter extends XMLOutputter 'title' => $title)); } + /** + * output a script (almost always javascript) tag + * + * @param string $src relative or absolute script path + * @param string $type 'type' attribute value of the tag + * + * @return void + */ + function script($src, $type='text/javascript') + { + $this->element('script', array('type' => $type, + 'src' => common_path($src) . '?version=' . LACONICA_VERSION), + ' '); + } + + /** + * output a css link + * + * @param string $relative relative path within the theme directory + * @param string $theme 'theme' that contains the stylesheet + * @param string media 'media' attribute of the tag + * + * @return void + */ + function cssLink($relative,$theme,$media) + { + if (!$theme) { + $theme = common_config('site', 'theme'); + } + + $this->element('link', array('rel' => 'stylesheet', + 'type' => 'text/css', + 'href' => theme_path($relative, $theme) . '?version=' . LACONICA_VERSION, + 'media' => $media)); + } + /** * output an HTML textarea and associated elements * -- cgit v1.2.3-54-g00ecf From 304db1d30b4ad96f8a2ca500d224bb1609588fed Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 19:45:12 -0400 Subject: Use script() and cssLink() methods everywhere instead of manually writing out javascript and css each time --- actions/avatarsettings.php | 17 +++-------------- actions/grouplogo.php | 17 +++-------------- lib/action.php | 39 +++++++++------------------------------ lib/designsettings.php | 17 +++-------------- lib/facebookaction.php | 27 +++------------------------ 5 files changed, 21 insertions(+), 96 deletions(-) diff --git a/actions/avatarsettings.php b/actions/avatarsettings.php index c2bb35a39..38e3103f4 100644 --- a/actions/avatarsettings.php +++ b/actions/avatarsettings.php @@ -382,13 +382,7 @@ class AvatarsettingsAction extends AccountSettingsAction function showStylesheets() { parent::showStylesheets(); - $jcropStyle = - common_path('theme/base/css/jquery.Jcrop.css?version='.LACONICA_VERSION); - - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => $jcropStyle, - 'media' => 'screen, projection, tv')); + $this->cssLink('css/jquery.Jcrop.css','base','screen, projection, tv'); } /** @@ -402,13 +396,8 @@ class AvatarsettingsAction extends AccountSettingsAction parent::showScripts(); if ($this->mode == 'crop') { - $jcropPack = common_path('js/jcrop/jquery.Jcrop.pack.js'); - $jcropGo = common_path('js/jcrop/jquery.Jcrop.go.js'); - - $this->element('script', array('type' => 'text/javascript', - 'src' => $jcropPack)); - $this->element('script', array('type' => 'text/javascript', - 'src' => $jcropGo)); + $this->script('js/jcrop/jquery.Jcrop.pack.js'); + $this->script('js/jcrop/jquery.Jcrop.go.js'); } } } diff --git a/actions/grouplogo.php b/actions/grouplogo.php index 8f6158dac..5edb10cf8 100644 --- a/actions/grouplogo.php +++ b/actions/grouplogo.php @@ -428,13 +428,7 @@ class GrouplogoAction extends GroupDesignAction function showStylesheets() { parent::showStylesheets(); - $jcropStyle = - common_path('theme/base/css/jquery.Jcrop.css?version='.LACONICA_VERSION); - - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => $jcropStyle, - 'media' => 'screen, projection, tv')); + $this->cssLink('css/jquery.Jcrop.css','base','screen, projection, tv'); } /** @@ -448,13 +442,8 @@ class GrouplogoAction extends GroupDesignAction parent::showScripts(); if ($this->mode == 'crop') { - $jcropPack = common_path('js/jcrop/jquery.Jcrop.pack.js'); - $jcropGo = common_path('js/jcrop/jquery.Jcrop.go.js'); - - $this->element('script', array('type' => 'text/javascript', - 'src' => $jcropPack)); - $this->element('script', array('type' => 'text/javascript', - 'src' => $jcropGo)); + $this->script('js/jcrop/jquery.Jcrop.pack.js'); + $this->script('js/jcrop/jquery.Jcrop.go.js'); } } diff --git a/lib/action.php b/lib/action.php index a5244371a..1c6170693 100644 --- a/lib/action.php +++ b/lib/action.php @@ -193,21 +193,12 @@ class Action extends HTMLOutputter // lawsuit if (Event::handle('StartShowStyles', array($this))) { if (Event::handle('StartShowLaconicaStyles', array($this))) { - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('css/display.css', null) . '?version=' . LACONICA_VERSION, - 'media' => 'screen, projection, tv')); + $this->cssLink('css/display.css',null,'screen, projection, tv'); if (common_config('site', 'mobile')) { - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('css/mobile.css', 'base') . '?version=' . LACONICA_VERSION, - // TODO: "handheld" CSS for other mobile devices - 'media' => 'only screen and (max-device-width: 480px)')); // Mobile WebKit + // TODO: "handheld" CSS for other mobile devices + $this->cssLink('css/mobile.css','base','only screen and (max-device-width: 480px)'); // Mobile WebKit } - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('css/print.css', 'base') . '?version=' . LACONICA_VERSION, - 'media' => 'print')); + $this->cssLink('css/print.css','base','print'); Event::handle('EndShowLaconicaStyles', array($this)); } @@ -253,26 +244,14 @@ class Action extends HTMLOutputter // lawsuit { if (Event::handle('StartShowScripts', array($this))) { if (Event::handle('StartShowJQueryScripts', array($this))) { - $this->element('script', array('type' => 'text/javascript', - 'src' => common_path('js/jquery.min.js')), - ' '); - $this->element('script', array('type' => 'text/javascript', - 'src' => common_path('js/jquery.form.js')), - ' '); - - $this->element('script', array('type' => 'text/javascript', - 'src' => common_path('js/jquery.joverlay.min.js')), - ' '); - + $this->script('js/jquery.min.js'); + $this->script('js/jquery.form.js'); + $this->script('js/jquery.joverlay.min.js'); Event::handle('EndShowJQueryScripts', array($this)); } if (Event::handle('StartShowLaconicaScripts', array($this))) { - $this->element('script', array('type' => 'text/javascript', - 'src' => common_path('js/xbImportNode.js')), - ' '); - $this->element('script', array('type' => 'text/javascript', - 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), - ' '); + $this->script('js/xbImportNode.js'); + $this->script('js/util.js'); // Frame-busting code to avoid clickjacking attacks. $this->element('script', array('type' => 'text/javascript'), 'if (window.top !== window.self) { window.top.location.href = window.self.location.href; }'); diff --git a/lib/designsettings.php b/lib/designsettings.php index 1b0e62166..a48ec9d22 100644 --- a/lib/designsettings.php +++ b/lib/designsettings.php @@ -311,13 +311,7 @@ class DesignSettingsAction extends AccountSettingsAction function showStylesheets() { parent::showStylesheets(); - $farbtasticStyle = - common_path('theme/base/css/farbtastic.css?version='.LACONICA_VERSION); - - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => $farbtasticStyle, - 'media' => 'screen, projection, tv')); + $this->cssLink('css/farbtastic.css','base','screen, projection, tv'); } /** @@ -330,13 +324,8 @@ class DesignSettingsAction extends AccountSettingsAction { parent::showScripts(); - $farbtasticPack = common_path('js/farbtastic/farbtastic.js'); - $userDesignGo = common_path('js/userdesign.go.js'); - - $this->element('script', array('type' => 'text/javascript', - 'src' => $farbtasticPack)); - $this->element('script', array('type' => 'text/javascript', - 'src' => $userDesignGo)); + $this->script('js/farbtastic/farbtastic.js'); + $this->script('js/farbtastic/farbtastic.go.js'); } /** diff --git a/lib/facebookaction.php b/lib/facebookaction.php index 5be2f2fe6..ab11b613e 100644 --- a/lib/facebookaction.php +++ b/lib/facebookaction.php @@ -95,34 +95,13 @@ class FacebookAction extends Action function showStylesheets() { - // Add a timestamp to the file so Facebook cache wont ignore our changes - $ts = filemtime(INSTALLDIR.'/theme/base/css/display.css'); - - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('css/display.css', 'base') . '?ts=' . $ts)); - - $theme = common_config('site', 'theme'); - - $ts = filemtime(INSTALLDIR. '/theme/' . $theme .'/css/display.css'); - - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('css/display.css', null) . '?ts=' . $ts)); - - $ts = filemtime(INSTALLDIR.'/theme/base/css/facebookapp.css'); - - $this->element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('css/facebookapp.css', 'base') . '?ts=' . $ts)); + $this->cssLink('css/display.css', 'base'); + $this->cssLink('css/facebookapp.css', 'base'); } function showScripts() { - // Add a timestamp to the file so Facebook cache wont ignore our changes - $ts = filemtime(INSTALLDIR.'/js/facebookapp.js'); - - $this->element('script', array('src' => common_path('js/facebookapp.js') . '?ts=' . $ts)); + $this->script('js/facebookapp.js'); } /** -- cgit v1.2.3-54-g00ecf From 9a9195ecd8eea36943dbb5e46adf685aef9edc4e Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 19:54:46 -0400 Subject: Used script() function to write out the javascript link --- plugins/InfiniteScroll/InfiniteScrollPlugin.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/plugins/InfiniteScroll/InfiniteScrollPlugin.php b/plugins/InfiniteScroll/InfiniteScrollPlugin.php index 6738dc760..7e942550a 100644 --- a/plugins/InfiniteScroll/InfiniteScrollPlugin.php +++ b/plugins/InfiniteScroll/InfiniteScrollPlugin.php @@ -40,11 +40,7 @@ class InfiniteScrollPlugin extends Plugin function onEndShowScripts($action) { - $action->element('script', - array('type' => 'text/javascript', - 'src' => common_path('plugins/InfiniteScroll/jquery.infinitescroll.min.js')), - ''); - + $action->script('plugins/InfiniteScroll/jquery.infinitescroll.min.js'); $loading_image = common_path('plugins/InfiniteScroll/ajax-loader.gif'); $js_string = << -- cgit v1.2.3-54-g00ecf From 5ba33836654e7e09098880fe9e6e9d3593f23b40 Mon Sep 17 00:00:00 2001 From: Craig Andrews Date: Wed, 5 Aug 2009 20:15:00 -0400 Subject: Use script() to write out javascript +EOT; + $action->raw($js_string); + $action->script('plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.pack.js'); + $action->script('plugins/Autocomplete/Autocomplete.js'); + } + + function onEndShowLaconicaStyles($action) + { + $action->cssLink('plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.css'); + } + +} +?> diff --git a/plugins/Autocomplete/jquery-autocomplete/changelog.txt b/plugins/Autocomplete/jquery-autocomplete/changelog.txt new file mode 100644 index 000000000..94cb5ccde --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/changelog.txt @@ -0,0 +1,20 @@ +1.0.2 +----- +* Fixed missing semicolon + +1.0.1 +----- +* Fixed element creation (
      to
        and
      • to
      • ) +* Fixed ac_even class (was ac_event) +* Fixed bgiframe usage: now its really optional +* Removed the blur-on-return workaround, added a less obtrusive one only for Opera +* Fixed hold cursor keys: Opera needs keypress, everyone else keydown to scroll through result list when holding cursor key +* Updated package to jQuery 1.2.5, removing dimensions +* Fixed multiple-mustMatch: Remove only the last term when no match is found +* Fixed multiple without mustMatch: Don't select the last active when no match is found (on tab/return) +* Fixed multiple cursor position: Put cursor at end of input after selecting a value + +1.0 +--- + +* First release. \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/bg.gif b/plugins/Autocomplete/jquery-autocomplete/demo/bg.gif new file mode 100644 index 000000000..846add071 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/bg.gif differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/emails.php b/plugins/Autocomplete/jquery-autocomplete/demo/emails.php new file mode 100644 index 000000000..f79b10e4a --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/emails.php @@ -0,0 +1,23 @@ +"peter@pan.de", + "Molly"=>"molly@yahoo.com", + "Forneria Marconi"=>"live@japan.jp", + "Master Sync"=>"205bw@samsung.com", + "Dr. Tech de Log"=>"g15@logitech.com", + "Don Corleone"=>"don@vegas.com", + "Mc Chick"=>"info@donalds.org", + "Donnie Darko"=>"dd@timeshift.info", + "Quake The Net"=>"webmaster@quakenet.org", + "Dr. Write"=>"write@writable.com" +); + +echo "["; +foreach ($items as $key=>$value) { + if (strpos(strtolower($key), $q) !== false) { + echo "{ name: \"$key\", to: \"$value\" }, "; + } +} +echo "]"; \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/emails.phps b/plugins/Autocomplete/jquery-autocomplete/demo/emails.phps new file mode 100644 index 000000000..f79b10e4a --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/emails.phps @@ -0,0 +1,23 @@ +"peter@pan.de", + "Molly"=>"molly@yahoo.com", + "Forneria Marconi"=>"live@japan.jp", + "Master Sync"=>"205bw@samsung.com", + "Dr. Tech de Log"=>"g15@logitech.com", + "Don Corleone"=>"don@vegas.com", + "Mc Chick"=>"info@donalds.org", + "Donnie Darko"=>"dd@timeshift.info", + "Quake The Net"=>"webmaster@quakenet.org", + "Dr. Write"=>"write@writable.com" +); + +echo "["; +foreach ($items as $key=>$value) { + if (strpos(strtolower($key), $q) !== false) { + echo "{ name: \"$key\", to: \"$value\" }, "; + } +} +echo "]"; \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images.php b/plugins/Autocomplete/jquery-autocomplete/demo/images.php new file mode 100644 index 000000000..407645c06 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/images.php @@ -0,0 +1,9 @@ + diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Amsterdam Van-Gogh Museum.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Amsterdam Van-Gogh Museum.jpg new file mode 100644 index 000000000..025328c7d Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Amsterdam Van-Gogh Museum.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Amsterdam.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Amsterdam.jpg new file mode 100644 index 000000000..5f019bdfd Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Amsterdam.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Antwerpen Rubenshaus.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Antwerpen Rubenshaus.jpg new file mode 100644 index 000000000..7f5d01f71 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Antwerpen Rubenshaus.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Antwerpen.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Antwerpen.jpg new file mode 100644 index 000000000..46f74a3d1 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Antwerpen.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Appenzell.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Appenzell.jpg new file mode 100644 index 000000000..1691ed954 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Appenzell.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Arnhem Historisches Museum.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Arnhem Historisches Museum.jpg new file mode 100644 index 000000000..276f88a31 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Arnhem Historisches Museum.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bled.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bled.jpg new file mode 100644 index 000000000..bdcae3184 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bled.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bled_Die Burg von Bled.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bled_Die Burg von Bled.jpg new file mode 100644 index 000000000..355108409 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bled_Die Burg von Bled.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bogojina_Die Pfarrkirche.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bogojina_Die Pfarrkirche.jpg new file mode 100644 index 000000000..3e0cd5099 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bogojina_Die Pfarrkirche.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaBasilicadiSanPetronio.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaBasilicadiSanPetronio.jpg new file mode 100644 index 000000000..ef2153593 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaBasilicadiSanPetronio.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaFontanadelNettuno.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaFontanadelNettuno.jpg new file mode 100644 index 000000000..0f5b576d5 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaFontanadelNettuno.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaPiazzaMaggiore.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaPiazzaMaggiore.jpg new file mode 100644 index 000000000..48449cf1e Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/BolognaPiazzaMaggiore.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward Martinikerk.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward Martinikerk.jpg new file mode 100644 index 000000000..6df035af4 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward Martinikerk.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward Stadhuis.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward Stadhuis.jpg new file mode 100644 index 000000000..7c141012d Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward Stadhuis.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward.jpg new file mode 100644 index 000000000..84dd775af Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bolsward.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/BordeauxND.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/BordeauxND.jpg new file mode 100644 index 000000000..242ecefc3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/BordeauxND.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/BordeauxPlaceB.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/BordeauxPlaceB.jpg new file mode 100644 index 000000000..026b4014d Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/BordeauxPlaceB.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/BotanischerGartenZuerich.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/BotanischerGartenZuerich.jpg new file mode 100644 index 000000000..5ee9535ef Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/BotanischerGartenZuerich.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Bouillon.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bouillon.jpg new file mode 100644 index 000000000..72638cfd8 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Bouillon.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Gent Hotel de Ville2.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gent Hotel de Ville2.jpg new file mode 100644 index 000000000..9084f6f47 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gent Hotel de Ville2.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Gent.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gent.jpg new file mode 100644 index 000000000..ebbd6df49 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gent.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/GenuaStrand.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/GenuaStrand.jpg new file mode 100644 index 000000000..d52af3c79 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/GenuaStrand.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/GenuabeiNacht.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/GenuabeiNacht.jpg new file mode 100644 index 000000000..f2a371036 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/GenuabeiNacht.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Giessbachfaelle Brienz.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Giessbachfaelle Brienz.jpg new file mode 100644 index 000000000..096319267 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Giessbachfaelle Brienz.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Giethoorn.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Giethoorn.jpg new file mode 100644 index 000000000..a6f7b0f4c Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Giethoorn.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Gnesen.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gnesen.jpg new file mode 100644 index 000000000..e8825a846 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gnesen.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Gornij Grad_KATHEDRALE.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gornij Grad_KATHEDRALE.jpg new file mode 100644 index 000000000..47cce10d3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gornij Grad_KATHEDRALE.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Gossensass.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gossensass.jpg new file mode 100644 index 000000000..6aba6d373 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Gossensass.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Grad_Burg Grad2.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Grad_Burg Grad2.jpg new file mode 100644 index 000000000..5bf35ad85 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Grad_Burg Grad2.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/GrandDixence.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/GrandDixence.jpg new file mode 100644 index 000000000..09464d7ce Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/GrandDixence.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/GrenoblePanorama.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/GrenoblePanorama.jpg new file mode 100644 index 000000000..d4d0d1bb3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/GrenoblePanorama.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Groningen.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Groningen.jpg new file mode 100644 index 000000000..0068a86f3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Groningen.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/GrottenvonReclere.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/GrottenvonReclere.jpg new file mode 100644 index 000000000..74d6b3d3f Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/GrottenvonReclere.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Guebwiller.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Guebwiller.jpg new file mode 100644 index 000000000..e31f924c4 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Guebwiller.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Kamnik_Die Franziskaner Bibliothek.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Kamnik_Die Franziskaner Bibliothek.jpg new file mode 100644 index 000000000..1de470593 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Kamnik_Die Franziskaner Bibliothek.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Karlsbad Muehlbrunnkolonnade.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Karlsbad Muehlbrunnkolonnade.jpg new file mode 100644 index 000000000..86caa2049 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Karlsbad Muehlbrunnkolonnade.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Kazimierz.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Kazimierz.jpg new file mode 100644 index 000000000..62c265074 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Kazimierz.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/KirchbergAltesRathaus1.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/KirchbergAltesRathaus1.jpg new file mode 100644 index 000000000..6f4d018c4 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/KirchbergAltesRathaus1.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/KlagenfurtDom.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/KlagenfurtDom.jpg new file mode 100644 index 000000000..ac9faad2f Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/KlagenfurtDom.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/KleineMeerjungfreu.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/KleineMeerjungfreu.jpg new file mode 100644 index 000000000..b5b13c193 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/KleineMeerjungfreu.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/LazienkiparkWarschau.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/LazienkiparkWarschau.jpg new file mode 100644 index 000000000..c0b114483 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/LazienkiparkWarschau.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/LeHavreHafen.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/LeHavreHafen.jpg new file mode 100644 index 000000000..9fc38d016 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/LeHavreHafen.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/LeMans.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/LeMans.jpg new file mode 100644 index 000000000..d919de7da Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/LeMans.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Lednice.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lednice.jpg new file mode 100644 index 000000000..726248044 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lednice.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Leeuwarden Fries Museum.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leeuwarden Fries Museum.jpg new file mode 100644 index 000000000..6d93e3478 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leeuwarden Fries Museum.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Leeuwarden.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leeuwarden.jpg new file mode 100644 index 000000000..c0f78c0cf Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leeuwarden.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Lelystad.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lelystad.jpg new file mode 100644 index 000000000..be794f3cd Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lelystad.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Lemmer.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lemmer.jpg new file mode 100644 index 000000000..41d8996b2 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lemmer.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Leper Halles aux draps.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leper Halles aux draps.jpg new file mode 100644 index 000000000..cb3138d65 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leper Halles aux draps.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Leuven Museum fuer Kirchenkunst.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leuven Museum fuer Kirchenkunst.jpg new file mode 100644 index 000000000..235869079 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leuven Museum fuer Kirchenkunst.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Leuven.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leuven.jpg new file mode 100644 index 000000000..3e4d5f3b3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Leuven.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Luxemburg.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Luxemburg.jpg new file mode 100644 index 000000000..3aaafc9cb Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Luxemburg.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/LuzernAltstadt.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/LuzernAltstadt.jpg new file mode 100644 index 000000000..47ebd5d1e Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/LuzernAltstadt.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/LuzernPicassoMuseum.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/LuzernPicassoMuseum.jpg new file mode 100644 index 000000000..08fbb5a0e Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/LuzernPicassoMuseum.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Lyon.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lyon.jpg new file mode 100644 index 000000000..7a3eda9d0 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Lyon.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht Onze Lieve Vrou...jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht Onze Lieve Vrou...jpg new file mode 100644 index 000000000..1474bb092 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht Onze Lieve Vrou...jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht St Servaasbasiliek.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht St Servaasbasiliek.jpg new file mode 100644 index 000000000..c41e1aa17 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht St Servaasbasiliek.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht Walmuur.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht Walmuur.jpg new file mode 100644 index 000000000..75fb02750 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht Walmuur.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht.jpg new file mode 100644 index 000000000..4dcb6d5d1 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Maastricht.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/MagiatalMaggia.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/MagiatalMaggia.jpg new file mode 100644 index 000000000..42ff384d9 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/MagiatalMaggia.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Mailand3.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Mailand3.jpg new file mode 100644 index 000000000..863e198f2 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Mailand3.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Metlika_Bela Krajina Museum.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Metlika_Bela Krajina Museum.jpg new file mode 100644 index 000000000..47d24d70b Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Metlika_Bela Krajina Museum.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/MilanoCastelloSforzesco.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/MilanoCastelloSforzesco.jpg new file mode 100644 index 000000000..b430de520 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/MilanoCastelloSforzesco.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/MilanoDom.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/MilanoDom.jpg new file mode 100644 index 000000000..0a5eef4a4 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/MilanoDom.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/MilazzoBurg.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/MilazzoBurg.jpg new file mode 100644 index 000000000..01226a323 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/MilazzoBurg.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Novo Mesto_Das Museum.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Novo Mesto_Das Museum.jpg new file mode 100644 index 000000000..452076124 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Novo Mesto_Das Museum.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/ObervellachBurgFalkenstein.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/ObervellachBurgFalkenstein.jpg new file mode 100644 index 000000000..d502ff483 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/ObervellachBurgFalkenstein.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/OdenseeAndersen.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/OdenseeAndersen.jpg new file mode 100644 index 000000000..f131b7608 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/OdenseeAndersen.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Olimje_Kirche und Apotheke in Olimje.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Olimje_Kirche und Apotheke in Olimje.jpg new file mode 100644 index 000000000..16ea33fb3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Olimje_Kirche und Apotheke in Olimje.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Olomouc.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Olomouc.jpg new file mode 100644 index 000000000..d9a7641f3 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Olomouc.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/OlympischesMuseumLausanne.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/OlympischesMuseumLausanne.jpg new file mode 100644 index 000000000..37a267ae5 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/OlympischesMuseumLausanne.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/OrleansMaisonJeannedArc.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/OrleansMaisonJeannedArc.jpg new file mode 100644 index 000000000..220ad08fa Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/OrleansMaisonJeannedArc.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/OrleansParcFloraldelaSource.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/OrleansParcFloraldelaSource.jpg new file mode 100644 index 000000000..171e56de8 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/OrleansParcFloraldelaSource.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/OstiaAntica.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/OstiaAntica.jpg new file mode 100644 index 000000000..b505ec7fd Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/OstiaAntica.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Ostrow Tumski.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Ostrow Tumski.jpg new file mode 100644 index 000000000..91cae01be Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Ostrow Tumski.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/PoertschachSchlossLeonstain.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/PoertschachSchlossLeonstain.jpg new file mode 100644 index 000000000..9e958b7df Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/PoertschachSchlossLeonstain.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Portoroz.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Portoroz.jpg new file mode 100644 index 000000000..bbad5aa81 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Portoroz.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Posen.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Posen.jpg new file mode 100644 index 000000000..791c46f2a Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Posen.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Postojna.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Postojna.jpg new file mode 100644 index 000000000..ec2a6be8f Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Postojna.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Prag Altstaedter Ring.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Prag Altstaedter Ring.jpg new file mode 100644 index 000000000..9f13fd367 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Prag Altstaedter Ring.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Prag Waldsteinpalais.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Prag Waldsteinpalais.jpg new file mode 100644 index 000000000..718b4e8d9 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Prag Waldsteinpalais.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/RouenNotreDame.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/RouenNotreDame.jpg new file mode 100644 index 000000000..4e0845342 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/RouenNotreDame.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/Salzbergwerk Bex.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/Salzbergwerk Bex.jpg new file mode 100644 index 000000000..29bdfe029 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/Salzbergwerk Bex.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzbergwerkWieliczka.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzbergwerkWieliczka.jpg new file mode 100644 index 000000000..745b18501 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzbergwerkWieliczka.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzburgFestungHohensalzburg.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzburgFestungHohensalzburg.jpg new file mode 100644 index 000000000..c3e9f7428 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzburgFestungHohensalzburg.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzburgResidenz.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzburgResidenz.jpg new file mode 100644 index 000000000..eca7e6022 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/SalzburgResidenz.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/WienMuseumsQuartier.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienMuseumsQuartier.jpg new file mode 100644 index 000000000..4e2262cac Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienMuseumsQuartier.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/WienMusikverein.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienMusikverein.jpg new file mode 100644 index 000000000..477bafceb Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienMusikverein.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/WienRiesenrad.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienRiesenrad.jpg new file mode 100644 index 000000000..0013657e7 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienRiesenrad.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/images/WienRingstrasse.jpg b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienRingstrasse.jpg new file mode 100644 index 000000000..9543af9b9 Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/images/WienRingstrasse.jpg differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/index.html b/plugins/Autocomplete/jquery-autocomplete/demo/index.html new file mode 100644 index 000000000..977483e04 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/index.html @@ -0,0 +1,272 @@ + + + + +jQuery Autocomplete Plugin + + + + + + + + + + + + + + + + +

        jQuery Autocomplete Plugin Demo

        + +
        + +
        +

        + + + + + + +

        +

        + + + + (Current month is excluded from list) +

        +

        + + + +

        +

        + + + +

        +

        + + +

        +

        + + + +

        +

        + + + +

        +

        + + + +

        +

        + + +

        +

        + + + +

        +

        + + + +

        +

        + + +

        + + +
        + +

        + Click here for an autocomplete inside a thickbox window. (this should work even if it is beyond the fold) +

        + + + + + + PHP script used to for remote autocomplete + +

        Result:

          + +
          + + + + diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/indicator.gif b/plugins/Autocomplete/jquery-autocomplete/demo/indicator.gif new file mode 100644 index 000000000..085ccaeca Binary files /dev/null and b/plugins/Autocomplete/jquery-autocomplete/demo/indicator.gif differ diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/json.html b/plugins/Autocomplete/jquery-autocomplete/demo/json.html new file mode 100644 index 000000000..9ed974faf --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/json.html @@ -0,0 +1,68 @@ + + + + +jQuery Autocomplete Plugin + + + + + + + + + + + + + + + + +

          jQuery Autocomplete Plugin Demo

          + +
          + +
          +

          + + +

          + + +
          + + Server-side script creating the JSON data + +
          + + + + diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/localdata.js b/plugins/Autocomplete/jquery-autocomplete/demo/localdata.js new file mode 100644 index 000000000..6015f7c82 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/localdata.js @@ -0,0 +1,216 @@ +var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; +var emails = [ + { name: "Peter Pan", to: "peter@pan.de" }, + { name: "Molly", to: "molly@yahoo.com" }, + { name: "Forneria Marconi", to: "live@japan.jp" }, + { name: "Master Sync", to: "205bw@samsung.com" }, + { name: "Dr. Tech de Log", to: "g15@logitech.com" }, + { name: "Don Corleone", to: "don@vegas.com" }, + { name: "Mc Chick", to: "info@donalds.org" }, + { name: "Donnie Darko", to: "dd@timeshift.info" }, + { name: "Quake The Net", to: "webmaster@quakenet.org" }, + { name: "Dr. Write", to: "write@writable.com" } +]; +var cities = [ + "Aberdeen", "Ada", "Adamsville", "Addyston", "Adelphi", "Adena", "Adrian", "Akron", + "Albany", "Alexandria", "Alger", "Alledonia", "Alliance", "Alpha", "Alvada", + "Alvordton", "Amanda", "Amelia", "Amesville", "Amherst", "Amlin", "Amsden", + "Amsterdam", "Andover", "Anna", "Ansonia", "Antwerp", "Apple Creek", "Arcadia", + "Arcanum", "Archbold", "Arlington", "Ashland", "Ashley", "Ashtabula", "Ashville", + "Athens", "Attica", "Atwater", "Augusta", "Aurora", "Austinburg", "Ava", "Avon", + "Avon Lake", "Bainbridge", "Bakersville", "Baltic", "Baltimore", "Bannock", + "Barberton", "Barlow", "Barnesville", "Bartlett", "Barton", "Bascom", "Batavia", + "Bath", "Bay Village", "Beach City", "Beachwood", "Beallsville", "Beaver", + "Beaverdam", "Bedford", "Bellaire", "Bellbrook", "Belle Center", "Belle Valley", + "Bellefontaine", "Bellevue", "Bellville", "Belmont", "Belmore", "Beloit", "Belpre", + "Benton Ridge", "Bentonville", "Berea", "Bergholz", "Berkey", "Berlin", + "Berlin Center", "Berlin Heights", "Bethel", "Bethesda", "Bettsville", "Beverly", + "Bidwell", "Big Prairie", "Birmingham", "Blacklick", "Bladensburg", "Blaine", + "Blakeslee", "Blanchester", "Blissfield", "Bloomdale", "Bloomingburg", + "Bloomingdale", "Bloomville", "Blue Creek", "Blue Rock", "Bluffton", + "Bolivar", "Botkins", "Bourneville", "Bowerston", "Bowersville", + "Bowling Green", "Bradford", "Bradner", "Brady Lake", "Brecksville", + "Bremen", "Brewster", "Brice", "Bridgeport", "Brilliant", "Brinkhaven", + "Bristolville", "Broadview Heights", "Broadway", "Brookfield", "Brookpark", + "Brookville", "Brownsville", "Brunswick", "Bryan", "Buchtel", "Buckeye Lake", + "Buckland", "Bucyrus", "Buffalo", "Buford", "Burbank", "Burghill", "Burgoon", + "Burkettsville", "Burton", "Butler", "Byesville", "Cable", "Cadiz", "Cairo", + "Caldwell", "Caledonia", "Cambridge", "Camden", "Cameron", "Camp Dennison", + "Campbell", "Canal Fulton", "Canal Winchester", "Canfield", "Canton", "Carbon Hill", + "Carbondale", "Cardington", "Carey", "Carroll", "Carrollton", "Casstown", + "Castalia", "Catawba", "Cecil", "Cedarville", "Celina", "Centerburg", + "Chagrin Falls", "Chandlersville", "Chardon", "Charm", "Chatfield", "Chauncey", + "Cherry Fork", "Chesapeake", "Cheshire", "Chester", "Chesterhill", "Chesterland", + "Chesterville", "Chickasaw", "Chillicothe", "Chilo", "Chippewa Lake", + "Christiansburg", "Cincinnati", "Circleville", "Clarington", "Clarksburg", + "Clarksville", "Clay Center", "Clayton", "Cleveland", "Cleves", "Clifton", + "Clinton", "Cloverdale", "Clyde", "Coal Run", "Coalton", "Coldwater", "Colerain", + "College Corner", "Collins", "Collinsville", "Colton", "Columbia Station", + "Columbiana", "Columbus", "Columbus Grove", "Commercial Point", "Conesville", + "Conneaut", "Conover", "Continental", "Convoy", "Coolville", "Corning", "Cortland", + "Coshocton", "Covington", "Creola", "Crestline", "Creston", "Crooksville", + "Croton", "Crown City", "Cuba", "Cumberland", "Curtice", "Custar", "Cutler", + "Cuyahoga Falls", "Cygnet", "Cynthiana", "Dalton", "Damascus", "Danville", + "Dayton", "De Graff", "Decatur", "Deerfield", "Deersville", "Defiance", + "Delaware", "Dellroy", "Delphos", "Delta", "Dennison", "Derby", "Derwent", + "Deshler", "Dexter City", "Diamond", "Dillonvale", "Dola", "Donnelsville", + "Dorset", "Dover", "Doylestown", "Dresden", "Dublin", "Dunbridge", "Duncan Falls", + "Dundee", "Dunkirk", "Dupont", "East Claridon", "East Fultonham", + "East Liberty", "East Liverpool", "East Palestine", "East Rochester", + "East Sparta", "East Springfield", "Eastlake", "Eaton", "Edgerton", "Edison", + "Edon", "Eldorado", "Elgin", "Elkton", "Ellsworth", "Elmore", "Elyria", + "Empire", "Englewood", "Enon", "Etna", "Euclid", "Evansport", "Fairborn", + "Fairfield", "Fairpoint", "Fairview", "Farmdale", "Farmer", "Farmersville", + "Fayette", "Fayetteville", "Feesburg", "Felicity", "Findlay", "Flat Rock", + "Fleming", "Fletcher", "Flushing", "Forest", "Fort Jennings", "Fort Loramie", + "Fort Recovery", "Fostoria", "Fowler", "Frankfort", "Franklin", + "Franklin Furnace", "Frazeysburg", "Fredericksburg", "Fredericktown", + "Freeport", "Fremont", "Fresno", "Friendship", "Fulton", "Fultonham", + "Galena", "Galion", "Gallipolis", "Galloway", "Gambier", "Garrettsville", + "Gates Mills", "Geneva", "Genoa", "Georgetown", "Germantown", "Gettysburg", + "Gibsonburg", "Girard", "Glandorf", "Glencoe", "Glenford", "Glenmont", + "Glouster", "Gnadenhutten", "Gomer", "Goshen", "Grafton", "Grand Rapids", + "Grand River", "Granville", "Gratiot", "Gratis", "Graysville", "Graytown", + "Green", "Green Camp", "Green Springs", "Greenfield", "Greenford", + "Greentown", "Greenville", "Greenwich", "Grelton", "Grove City", + "Groveport", "Grover Hill", "Guysville", "Gypsum", "Hallsville", + "Hamden", "Hamersville", "Hamilton", "Hamler", "Hammondsville", + "Hannibal", "Hanoverton", "Harbor View", "Harlem Springs", "Harpster", + "Harrisburg", "Harrison", "Harrisville", "Harrod", "Hartford", "Hartville", + "Harveysburg", "Haskins", "Haverhill", "Haviland", "Haydenville", "Hayesville", + "Heath", "Hebron", "Helena", "Hicksville", "Higginsport", "Highland", "Hilliard", + "Hillsboro", "Hinckley", "Hiram", "Hockingport", "Holgate", "Holland", + "Hollansburg", "Holloway", "Holmesville", "Homer", "Homerville", "Homeworth", + "Hooven", "Hopedale", "Hopewell", "Houston", "Howard", "Hoytville", "Hubbard", + "Hudson", "Huntsburg", "Huntsville", "Huron", "Iberia", "Independence", + "Irondale", "Ironton", "Irwin", "Isle Saint George", "Jackson", "Jackson Center", + "Jacksontown", "Jacksonville", "Jacobsburg", "Jamestown", "Jasper", + "Jefferson", "Jeffersonville", "Jenera", "Jeromesville", "Jerry City", + "Jerusalem", "Jewell", "Jewett", "Johnstown", "Junction City", "Kalida", + "Kansas", "Keene", "Kelleys Island", "Kensington", "Kent", "Kenton", + "Kerr", "Kettlersville", "Kidron", "Kilbourne", "Killbuck", "Kimbolton", + "Kings Mills", "Kingston", "Kingsville", "Kinsman", "Kipling", "Kipton", + "Kirby", "Kirkersville", "Kitts Hill", "Kunkle", "La Rue", "Lacarne", + "Lafayette", "Lafferty", "Lagrange", "Laings", "Lake Milton", "Lakemore", + "Lakeside Marblehead", "Lakeview", "Lakeville", "Lakewood", "Lancaster", + "Langsville", "Lansing", "Latham", "Latty", "Laura", "Laurelville", + "Leavittsburg", "Lebanon", "Lees Creek", "Leesburg", "Leesville", + "Leetonia", "Leipsic", "Lemoyne", "Lewis Center", "Lewisburg", + "Lewistown", "Lewisville", "Liberty Center", "Lima", "Limaville", + "Lindsey", "Lisbon", "Litchfield", "Lithopolis", "Little Hocking", + "Lockbourne", "Lodi", "Logan", "London", "Londonderry", + "Long Bottom", "Lorain", "Lore City", "Loudonville", "Louisville", + "Loveland", "Lowell", "Lowellville", "Lower Salem", "Lucas", + "Lucasville", "Luckey", "Ludlow Falls", "Lynchburg", "Lynx", + "Lyons", "Macedonia", "Macksburg", "Madison", "Magnetic Springs", + "Magnolia", "Maineville", "Malaga", "Malinta", "Malta", "Malvern", + "Manchester", "Mansfield", "Mantua", "Maple Heights", "Maplewood", + "Marathon", "Marengo", "Maria Stein", "Marietta", "Marion", + "Mark Center", "Marshallville", "Martel", "Martin", "Martins Ferry", + "Martinsburg", "Martinsville", "Marysville", "Mason", "Massillon", + "Masury", "Maumee", "Maximo", "Maynard", "Mc Arthur", "Mc Clure", + "Mc Comb", "Mc Connelsville", "Mc Cutchenville", "Mc Dermott", + "Mc Donald", "Mc Guffey", "Mechanicsburg", "Mechanicstown", + "Medina", "Medway", "Melmore", "Melrose", "Mendon", "Mentor", + "Mesopotamia", "Metamora", "Miamisburg", "Miamitown", "Miamiville", + "Middle Bass", "Middle Point", "Middlebranch", "Middleburg", + "Middlefield", "Middleport", "Middletown", "Midland", "Midvale", + "Milan", "Milford", "Milford Center", "Millbury", "Milledgeville", + "Miller City", "Millersburg", "Millersport", "Millfield", + "Milton Center", "Mineral City", "Mineral Ridge", "Minerva", + "Minford", "Mingo", "Mingo Junction", "Minster", "Mogadore", + "Monclova", "Monroe", "Monroeville", "Montezuma", "Montpelier", + "Montville", "Morral", "Morristown", "Morrow", "Moscow", + "Mount Blanchard", "Mount Cory", "Mount Eaton", "Mount Gilead", + "Mount Hope", "Mount Liberty", "Mount Orab", "Mount Perry", + "Mount Pleasant", "Mount Saint Joseph", "Mount Sterling", + "Mount Vernon", "Mount Victory", "Mowrystown", "Moxahala", + "Munroe Falls", "Murray City", "Nankin", "Napoleon", "Nashport", + "Nashville", "Navarre", "Neapolis", "Neffs", "Negley", + "Nelsonville", "Nevada", "Neville", "New Albany", "New Athens", + "New Bavaria", "New Bloomington", "New Bremen", "New Carlisle", + "New Concord", "New Hampshire", "New Haven", "New Holland", + "New Knoxville", "New Lebanon", "New Lexington", "New London", + "New Madison", "New Marshfield", "New Matamoras", "New Middletown", + "New Paris", "New Philadelphia", "New Plymouth", "New Richmond", + "New Riegel", "New Rumley", "New Springfield", "New Straitsville", + "New Vienna", "New Washington", "New Waterford", "New Weston", + "Newark", "Newbury", "Newcomerstown", "Newport", "Newton Falls", + "Newtonsville", "Ney", "Niles", "North Baltimore", "North Bend", + "North Benton", "North Bloomfield", "North Fairfield", + "North Georgetown", "North Hampton", "North Jackson", + "North Kingsville", "North Lawrence", "North Lewisburg", + "North Lima", "North Olmsted", "North Ridgeville", "North Robinson", + "North Royalton", "North Star", "Northfield", "Northwood", "Norwalk", + "Norwich", "Nova", "Novelty", "Oak Harbor", "Oak Hill", "Oakwood", + "Oberlin", "Oceola", "Ohio City", "Okeana", "Okolona", "Old Fort", + "Old Washington", "Olmsted Falls", "Ontario", "Orangeville", + "Oregon", "Oregonia", "Orient", "Orrville", "Orwell", "Osgood", + "Ostrander", "Ottawa", "Ottoville", "Otway", "Overpeck", + "Owensville", "Oxford", "Painesville", "Palestine", "Pandora", + "Paris", "Parkman", "Pataskala", "Patriot", "Paulding", "Payne", + "Pedro", "Peebles", "Pemberton", "Pemberville", "Peninsula", + "Perry", "Perrysburg", "Perrysville", "Petersburg", "Pettisville", + "Phillipsburg", "Philo", "Pickerington", "Piedmont", "Pierpont", + "Piketon", "Piney Fork", "Pioneer", "Piqua", "Pitsburg", + "Plain City", "Plainfield", "Pleasant City", "Pleasant Hill", + "Pleasant Plain", "Pleasantville", "Plymouth", "Polk", + "Pomeroy", "Port Clinton", "Port Jefferson", "Port Washington", + "Port William", "Portage", "Portland", "Portsmouth", "Potsdam", + "Powell", "Powhatan Point", "Proctorville", "Prospect", "Put in Bay", + "Quaker City", "Quincy", "Racine", "Radnor", "Randolph", "Rarden", + "Ravenna", "Rawson", "Ray", "Rayland", "Raymond", "Reedsville", + "Reesville", "Reno", "Republic", "Reynoldsburg", "Richfield", + "Richmond", "Richmond Dale", "Richwood", "Ridgeville Corners", + "Ridgeway", "Rio Grande", "Ripley", "Risingsun", "Rittman", + "Robertsville", "Rock Camp", "Rock Creek", "Rockbridge", "Rockford", + "Rocky Ridge", "Rocky River", "Rogers", "Rome", "Rootstown", "Roseville", + "Rosewood", "Ross", "Rossburg", "Rossford", "Roundhead", "Rudolph", + "Rushsylvania", "Rushville", "Russells Point", "Russellville", "Russia", + "Rutland", "Sabina", "Saint Clairsville", "Saint Henry", "Saint Johns", + "Saint Louisville", "Saint Marys", "Saint Paris", "Salem", "Salesville", + "Salineville", "Sandusky", "Sandyville", "Sarahsville", "Sardinia", + "Sardis", "Savannah", "Scio", "Scioto Furnace", "Scott", "Scottown", + "Seaman", "Sebring", "Sedalia", "Senecaville", "Seven Mile", "Seville", + "Shade", "Shadyside", "Shandon", "Sharon Center", "Sharpsburg", + "Shauck", "Shawnee", "Sheffield Lake", "Shelby", "Sherrodsville", + "Sherwood", "Shiloh", "Short Creek", "Shreve", "Sidney", "Sinking Spring", + "Smithfield", "Smithville", "Solon", "Somerdale", "Somerset", + "Somerville", "South Bloomingville", "South Charleston", "South Lebanon", + "South Point", "South Salem", "South Solon", "South Vienna", + "South Webster", "Southington", "Sparta", "Spencer", "Spencerville", + "Spring Valley", "Springboro", "Springfield", "Stafford", "Sterling", + "Steubenville", "Stewart", "Stillwater", "Stockdale", "Stockport", + "Stone Creek", "Stony Ridge", "Stout", "Stoutsville", "Stow", "Strasburg", + "Stratton", "Streetsboro", "Strongsville", "Struthers", "Stryker", + "Sugar Grove", "Sugarcreek", "Sullivan", "Sulphur Springs", "Summerfield", + "Summit Station", "Summitville", "Sunbury", "Swanton", "Sycamore", + "Sycamore Valley", "Sylvania", "Syracuse", "Tallmadge", "Tarlton", + "Terrace Park", "The Plains", "Thompson", "Thornville", "Thurman", + "Thurston", "Tiffin", "Tiltonsville", "Tipp City", "Tippecanoe", "Tiro", + "Toledo", "Tontogany", "Torch", "Toronto", "Tremont City", "Trenton", + "Trimble", "Trinway", "Troy", "Tuppers Plains", "Tuscarawas", "Twinsburg", + "Uhrichsville", "Union City", "Union Furnace", "Unionport", "Uniontown", + "Unionville", "Unionville Center", "Uniopolis", "Upper Sandusky", "Urbana", + "Utica", "Valley City", "Van Buren", "Van Wert", "Vandalia", "Vanlue", + "Vaughnsville", "Venedocia", "Vermilion", "Verona", "Versailles", + "Vickery", "Vienna", "Vincent", "Vinton", "Wadsworth", "Wakefield", + "Wakeman", "Walbridge", "Waldo", "Walhonding", "Walnut Creek", "Wapakoneta", + "Warnock", "Warren", "Warsaw", "Washington Court House", + "Washingtonville", "Waterford", "Waterloo", "Watertown", "Waterville", + "Wauseon", "Waverly", "Wayland", "Wayne", "Waynesburg", "Waynesfield", + "Waynesville", "Wellington", "Wellston", "Wellsville", "West Alexandria", + "West Chester", "West Elkton", "West Farmington", "West Jefferson", + "West Lafayette", "West Liberty", "West Manchester", "West Mansfield", + "West Millgrove", "West Milton", "West Point", "West Portsmouth", + "West Rushville", "West Salem", "West Union", "West Unity", "Westerville", + "Westfield Center", "Westlake", "Weston", "Westville", "Wharton", + "Wheelersburg", "Whipple", "White Cottage", "Whitehouse", "Wickliffe", + "Wilberforce", "Wilkesville", "Willard", "Williamsburg", "Williamsfield", + "Williamsport", "Williamstown", "Williston", "Willoughby", "Willow Wood", + "Willshire", "Wilmington", "Wilmot", "Winchester", "Windham", "Windsor", + "Winesburg", "Wingett Run", "Winona", "Wolf Run", "Woodsfield", + "Woodstock", "Woodville", "Wooster", "Wren", "Xenia", "Yellow Springs", + "Yorkshire", "Yorkville", "Youngstown", "Zaleski", "Zanesfield", "Zanesville", + "Zoar" +]; \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/main.css b/plugins/Autocomplete/jquery-autocomplete/demo/main.css new file mode 100644 index 000000000..b502a8a1a --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/main.css @@ -0,0 +1,53 @@ +body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,p,blockquote,th,td{margin:0;padding:0} +table{border-collapse:collapse;border-spacing:0} +fieldset,img{border:0} +address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal} +ol,ul{list-style:none} +caption,th{text-align:left} +h1,h2,h3,h4,h5,h6{font-size:100%;font-style:normal;font-weight:normal} +q:before,q:after{content:''} +body{font:13px arial,helvetica,clean,sans-serif;font-size:small;} +select,input,textarea{font:99% arial,helvetica,clean,sans-serif} +pre,code{font:115% monospace;font-size:100%} +body * {line-height:1.22em} +body { + color: #202020; +} + +h1 { + color: #fff; + background: #06b; + padding: 10px; + font-size: 200%; +} + +h2 { + color: #000; + font-size: 150%; + padding: 10px 0; +} + +h3 { + color: #000; + font-size: 120%; + padding: 10px 0; +} + +ul { + list-style: disc inside; + margin-left: 1em; +} + +#content { + padding: 10px; +} + +label { + float: left; + width: 12em; +} +input[type=text] { width: 15em; } + +#banner { padding: 15px; background-color: #06b; color: white; font-size: large; border-bottom: 1px solid #ccc; + background: url(bg.gif) repeat-x; text-align: center } +#banner a { color: white; } \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/search.php b/plugins/Autocomplete/jquery-autocomplete/demo/search.php new file mode 100644 index 000000000..03c0c0eab --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/search.php @@ -0,0 +1,578 @@ +Bittern
          "=>"Botaurus stellaris", +"Little Grebe"=>"Tachybaptus ruficollis", +"Black-necked Grebe"=>"Podiceps nigricollis", +"Little Bittern"=>"Ixobrychus minutus", +"Black-crowned Night Heron"=>"Nycticorax nycticorax", +"Purple Heron"=>"Ardea purpurea", +"White Stork"=>"Ciconia ciconia", +"Spoonbill"=>"Platalea leucorodia", +"Red-crested Pochard"=>"Netta rufina", +"Common Eider"=>"Somateria mollissima", +"Red Kite"=>"Milvus milvus", +"Hen Harrier"=>"Circus cyaneus", +"Montagu`s Harrier"=>"Circus pygargus", +"Black Grouse"=>"Tetrao tetrix", +"Grey Partridge"=>"Perdix perdix", +"Spotted Crake"=>"Porzana porzana", +"Corncrake"=>"Crex crex", +"Common Crane"=>"Grus grus", +"Avocet"=>"Recurvirostra avosetta", +"Stone Curlew"=>"Burhinus oedicnemus", +"Common Ringed Plover"=>"Charadrius hiaticula", +"Kentish Plover"=>"Charadrius alexandrinus", +"Ruff"=>"Philomachus pugnax", +"Common Snipe"=>"Gallinago gallinago", +"Black-tailed Godwit"=>"Limosa limosa", +"Common Redshank"=>"Tringa totanus", +"Sandwich Tern"=>"Sterna sandvicensis", +"Common Tern"=>"Sterna hirundo", +"Arctic Tern"=>"Sterna paradisaea", +"Little Tern"=>"Sternula albifrons", +"Black Tern"=>"Chlidonias niger", +"Barn Owl"=>"Tyto alba", +"Little Owl"=>"Athene noctua", +"Short-eared Owl"=>"Asio flammeus", +"European Nightjar"=>"Caprimulgus europaeus", +"Common Kingfisher"=>"Alcedo atthis", +"Eurasian Hoopoe"=>"Upupa epops", +"Eurasian Wryneck"=>"Jynx torquilla", +"European Green Woodpecker"=>"Picus viridis", +"Crested Lark"=>"Galerida cristata", +"White-headed Duck"=>"Oxyura leucocephala", +"Pale-bellied Brent Goose"=>"Branta hrota", +"Tawny Pipit"=>"Anthus campestris", +"Whinchat"=>"Saxicola rubetra", +"European Stonechat"=>"Saxicola rubicola", +"Northern Wheatear"=>"Oenanthe oenanthe", +"Savi`s Warbler"=>"Locustella luscinioides", +"Sedge Warbler"=>"Acrocephalus schoenobaenus", +"Great Reed Warbler"=>"Acrocephalus arundinaceus", +"Bearded Reedling"=>"Panurus biarmicus", +"Red-backed Shrike"=>"Lanius collurio", +"Great Grey Shrike"=>"Lanius excubitor", +"Woodchat Shrike"=>"Lanius senator", +"Common Raven"=>"Corvus corax", +"Yellowhammer"=>"Emberiza citrinella", +"Ortolan Bunting"=>"Emberiza hortulana", +"Corn Bunting"=>"Emberiza calandra", +"Great Cormorant"=>"Phalacrocorax carbo", +"Hawfinch"=>"Coccothraustes coccothraustes", +"Common Shelduck"=>"Tadorna tadorna", +"Bluethroat"=>"Luscinia svecica", +"Grey Heron"=>"Ardea cinerea", +"Barn Swallow"=>"Hirundo rustica", +"Hooded Crow"=>"Corvus cornix", +"Dunlin"=>"Calidris alpina", +"Eurasian Pied Flycatcher"=>"Ficedula hypoleuca", +"Eurasian Nuthatch"=>"Sitta europaea", +"Short-toed Tree Creeper"=>"Certhia brachydactyla", +"Wood Lark"=>"Lullula arborea", +"Tree Pipit"=>"Anthus trivialis", +"Eurasian Hobby"=>"Falco subbuteo", +"Marsh Warbler"=>"Acrocephalus palustris", +"Wood Sandpiper"=>"Tringa glareola", +"Tawny Owl"=>"Strix aluco", +"Lesser Whitethroat"=>"Sylvia curruca", +"Barnacle Goose"=>"Branta leucopsis", +"Common Goldeneye"=>"Bucephala clangula", +"Western Marsh Harrier"=>"Circus aeruginosus", +"Common Buzzard"=>"Buteo buteo", +"Sanderling"=>"Calidris alba", +"Little Gull"=>"Larus minutus", +"Eurasian Magpie"=>"Pica pica", +"Willow Warbler"=>"Phylloscopus trochilus", +"Wood Warbler"=>"Phylloscopus sibilatrix", +"Great Crested Grebe"=>"Podiceps cristatus", +"Eurasian Jay"=>"Garrulus glandarius", +"Common Redstart"=>"Phoenicurus phoenicurus", +"Blue-headed Wagtail"=>"Motacilla flava", +"Common Swift"=>"Apus apus", +"Marsh Tit"=>"Poecile palustris", +"Goldcrest"=>"Regulus regulus", +"European Golden Plover"=>"Pluvialis apricaria", +"Eurasian Bullfinch"=>"Pyrrhula pyrrhula", +"Common Whitethroat"=>"Sylvia communis", +"Meadow Pipit"=>"Anthus pratensis", +"Greylag Goose"=>"Anser anser", +"Spotted Flycatcher"=>"Muscicapa striata", +"European Greenfinch"=>"Carduelis chloris", +"Common Greenshank"=>"Tringa nebularia", +"Great Spotted Woodpecker"=>"Dendrocopos major", +"Greater Canada Goose"=>"Branta canadensis", +"Mistle Thrush"=>"Turdus viscivorus", +"Great Black-backed Gull"=>"Larus marinus", +"Goosander"=>"Mergus merganser", +"Great Egret"=>"Casmerodius albus", +"Northern Goshawk"=>"Accipiter gentilis", +"Dunnock"=>"Prunella modularis", +"Stock Dove"=>"Columba oenas", +"Common Wood Pigeon"=>"Columba palumbus", +"Eurasian Woodcock"=>"Scolopax rusticola", +"House Sparrow"=>"Passer domesticus", +"Common House Martin"=>"Delichon urbicum", +"Red Knot"=>"Calidris canutus", +"Western Jackdaw"=>"Corvus monedula", +"Brambling"=>"Fringilla montifringilla", +"Northern Lapwing"=>"Vanellus vanellus", +"European Reed Warbler"=>"Acrocephalus scirpaceus", +"Lesser Black-backed Gull"=>"Larus fuscus", +"Little Egret"=>"Egretta garzetta", +"Little Stint"=>"Calidris minuta", +"Common Linnet"=>"Carduelis cannabina", +"Mute Swan"=>"Cygnus olor", +"Common Cuckoo"=>"Cuculus canorus", +"Black-headed Gull"=>"Larus ridibundus", +"Greater White-fronted Goose"=>"Anser albifrons", +"Great Tit"=>"Parus major", +"Redwing"=>"Turdus iliacus", +"Gadwall"=>"Anas strepera", +"Fieldfare"=>"Turdus pilaris", +"Tufted Duck"=>"Aythya fuligula", +"Crested Tit"=>"Lophophanes cristatus", +"Willow Tit"=>"Poecile montanus", +"Eurasian Coot"=>"Fulica atra", +"Common Blackbird"=>"Turdus merula", +"Smew"=>"Mergus albellus", +"Common Sandpiper"=>"Actitis hypoleucos", +"Sand Martin"=>"Riparia riparia", +"Purple Sandpiper"=>"Calidris maritima", +"Northern Pintail"=>"Anas acuta", +"Blue Tit"=>"Cyanistes caeruleus", +"European Goldfinch"=>"Carduelis carduelis", +"Eurasian Whimbrel"=>"Numenius phaeopus", +"Common Reed Bunting"=>"Emberiza schoeniclus", +"Eurasian Tree Sparrow"=>"Passer montanus", +"Rook"=>"Corvus frugilegus", +"European Robin"=>"Erithacus rubecula", +"Bar-tailed Godwit"=>"Limosa lapponica", +"Dark-bellied Brent Goose"=>"Branta bernicla", +"Eurasian Oystercatcher"=>"Haematopus ostralegus", +"Eurasian Siskin"=>"Carduelis spinus", +"Northern Shoveler"=>"Anas clypeata", +"Eurasian Wigeon"=>"Anas penelope", +"Eurasian Sparrow Hawk"=>"Accipiter nisus", +"Icterine Warbler"=>"Hippolais icterina", +"Common Starling"=>"Sturnus vulgaris", +"Long-tailed Tit"=>"Aegithalos caudatus", +"Ruddy Turnstone"=>"Arenaria interpres", +"Mew Gull"=>"Larus canus", +"Common Pochard"=>"Aythya ferina", +"Common Chiffchaff"=>"Phylloscopus collybita", +"Greater Scaup"=>"Aythya marila", +"Common Kestrel"=>"Falco tinnunculus", +"Garden Warbler"=>"Sylvia borin", +"Eurasian Collared Dove"=>"Streptopelia decaocto", +"Eurasian Skylark"=>"Alauda arvensis", +"Common Chaffinch"=>"Fringilla coelebs", +"Common Moorhen"=>"Gallinula chloropus", +"Water Pipit"=>"Anthus spinoletta", +"Mallard"=>"Anas platyrhynchos", +"Winter Wren"=>"Troglodytes troglodytes", +"Common Teal"=>"Anas crecca", +"Green Sandpiper"=>"Tringa ochropus", +"White Wagtail"=>"Motacilla alba", +"Eurasian Curlew"=>"Numenius arquata", +"Song Thrush"=>"Turdus philomelos", +"European Herring Gull"=>"Larus argentatus", +"Grey Plover"=>"Pluvialis squatarola", +"Carrion Crow"=>"Corvus corone", +"Coal Tit"=>"Periparus ater", +"Spotted Redshank"=>"Tringa erythropus", +"Blackcap"=>"Sylvia atricapilla", +"Egyptian Vulture"=>"Neophron percnopterus", +"Razorbill"=>"Alca torda", +"Alpine Swift"=>"Apus melba", +"Long-legged Buzzard"=>"Buteo rufinus", +"Audouin`s Gull"=>"Larus audouinii", +"Balearic Shearwater"=>"Puffinus mauretanicus", +"Upland Sandpiper"=>"Bartramia longicauda", +"Greater Spotted Eagle"=>"Aquila clanga", +"Ring Ouzel"=>"Turdus torquatus", +"Yellow-browed Warbler"=>"Phylloscopus inornatus", +"Blue Rock Thrush"=>"Monticola solitarius", +"Buff-breasted Sandpiper"=>"Tryngites subruficollis", +"Jack Snipe"=>"Lymnocryptes minimus", +"White-rumped Sandpiper"=>"Calidris fuscicollis", +"Ruddy Shelduck"=>"Tadorna ferruginea", +"Cetti's Warbler"=>"Cettia cetti", +"Citrine Wagtail"=>"Motacilla citreola", +"Roseate Tern"=>"Sterna dougallii", +"Black-legged Kittiwake"=>"Rissa tridactyla", +"Pygmy Cormorant"=>"Phalacrocorax pygmeus", +"Booted Eagle"=>"Aquila pennata", +"Lesser White-fronted Goose"=>"Anser erythropus", +"Little Bunting"=>"Emberiza pusilla", +"Eleonora's Falcon"=>"Falco eleonorae", +"European Serin"=>"Serinus serinus", +"Twite"=>"Carduelis flavirostris", +"Yellow-legged Gull"=>"Larus michahellis", +"Gyr Falcon"=>"Falco rusticolus", +"Greenish Warbler"=>"Phylloscopus trochiloides", +"Red-necked Phalarope"=>"Phalaropus lobatus", +"Mealy Redpoll"=>"Carduelis flammea", +"Glaucous Gull"=>"Larus hyperboreus", +"Great Skua"=>"Stercorarius skua", +"Great Bustard"=>"Otis tarda", +"Velvet Scoter"=>"Melanitta fusca", +"Pine Grosbeak"=>"Pinicola enucleator", +"House Crow"=>"Corvus splendens", +"Hume`s Leaf Warbler"=>"Phylloscopus humei", +"Great Northern Loon"=>"Gavia immer", +"Long-tailed Duck"=>"Clangula hyemalis", +"Lapland Longspur"=>"Calcarius lapponicus", +"Northern Gannet"=>"Morus bassanus", +"Eastern Imperial Eagle"=>"Aquila heliaca", +"Little Auk"=>"Alle alle", +"Lesser Spotted Woodpecker"=>"Dendrocopos minor", +"Iceland Gull"=>"Larus glaucoides", +"Parasitic Jaeger"=>"Stercorarius parasiticus", +"Bewick`s Swan"=>"Cygnus bewickii", +"Little Bustard"=>"Tetrax tetrax", +"Little Crake"=>"Porzana parva", +"Baillon`s Crake"=>"Porzana pusilla", +"Long-tailed Jaeger"=>"Stercorarius longicaudus", +"King Eider"=>"Somateria spectabilis", +"Greater Short-toed Lark"=>"Calandrella brachydactyla", +"Houbara Bustard"=>"Chlamydotis undulata", +"Curlew Sandpiper"=>"Calidris ferruginea", +"Common Crossbill"=>"Loxia curvirostra", +"European Shag"=>"Phalacrocorax aristotelis", +"Horned Grebe"=>"Podiceps auritus", +"Common Quail"=>"Coturnix coturnix", +"Bearded Vulture"=>"Gypaetus barbatus", +"Lanner Falcon"=>"Falco biarmicus", +"Middle Spotted Woodpecker"=>"Dendrocopos medius", +"Pomarine Jaeger"=>"Stercorarius pomarinus", +"Red-breasted Merganser"=>"Mergus serrator", +"Eurasian Black Vulture"=>"Aegypius monachus", +"Eurasian Dotterel"=>"Charadrius morinellus", +"Common Nightingale"=>"Luscinia megarhynchos", +"Northern willow warbler"=>"Phylloscopus trochilus acredula", +"Manx Shearwater"=>"Puffinus puffinus", +"Northern Fulmar"=>"Fulmarus glacialis", +"Eurasian Eagle Owl"=>"Bubo bubo", +"Orphean Warbler"=>"Sylvia hortensis", +"Melodious Warbler"=>"Hippolais polyglotta", +"Pallas's Leaf Warbler"=>"Phylloscopus proregulus", +"Atlantic Puffin"=>"Fratercula arctica", +"Black-throated Loon"=>"Gavia arctica", +"Bohemian Waxwing"=>"Bombycilla garrulus", +"Marsh Sandpiper"=>"Tringa stagnatilis", +"Great Snipe"=>"Gallinago media", +"Squacco Heron"=>"Ardeola ralloides", +"Long-eared Owl"=>"Asio otus", +"Caspian Tern"=>"Hydroprogne caspia", +"Red-breasted Goose"=>"Branta ruficollis", +"Red-throated Loon"=>"Gavia stellata", +"Common Rosefinch"=>"Carpodacus erythrinus", +"Red-footed Falcon"=>"Falco vespertinus", +"Ross's Goose"=>"Anser rossii", +"Red Phalarope"=>"Phalaropus fulicarius", +"Pied Wagtail"=>"Motacilla yarrellii", +"Rose-coloured Starling"=>"Sturnus roseus", +"Rough-legged Buzzard"=>"Buteo lagopus", +"Saker Falcon"=>"Falco cherrug", +"European Roller"=>"Coracias garrulus", +"Short-toed Eagle"=>"Circaetus gallicus", +"Peregrine Falcon"=>"Falco peregrinus", +"Merlin"=>"Falco columbarius", +"Snow Goose"=>"Anser caerulescens", +"Snowy Owl"=>"Bubo scandiacus", +"Snow Bunting"=>"Plectrophenax nivalis", +"Common Grasshopper Warbler"=>"Locustella naevia", +"Golden Eagle"=>"Aquila chrysaetos", +"Black-winged Stilt"=>"Himantopus himantopus", +"Steppe Eagle"=>"Aquila nipalensis", +"Pallid Harrier"=>"Circus macrourus", +"European Storm-petrel"=>"Hydrobates pelagicus", +"Horned Lark"=>"Eremophila alpestris", +"Eurasian Treecreeper"=>"Certhia familiaris", +"Taiga Bean Goose"=>"Anser fabalis", +"Temminck`s Stint"=>"Calidris temminckii", +"Terek Sandpiper"=>"Xenus cinereus", +"Tundra Bean Goose"=>"Anser serrirostris", +"European Turtle Dove"=>"Streptopelia turtur", +"Leach`s Storm-petrel"=>"Oceanodroma leucorhoa", +"Eurasian Griffon Vulture"=>"Gyps fulvus", +"Paddyfield Warbler"=>"Acrocephalus agricola", +"Osprey"=>"Pandion haliaetus", +"Firecrest"=>"Regulus ignicapilla", +"Water Rail"=>"Rallus aquaticus", +"European Honey Buzzard"=>"Pernis apivorus", +"Eurasian Golden Oriole"=>"Oriolus oriolus", +"Whooper Swan"=>"Cygnus cygnus", +"Two-barred Crossbill"=>"Loxia leucoptera", +"White-tailed Eagle"=>"Haliaeetus albicilla", +"Atlantic Murre"=>"Uria aalge", +"Garganey"=>"Anas querquedula", +"Black Redstart"=>"Phoenicurus ochruros", +"Common Scoter"=>"Melanitta nigra", +"Rock Pipit"=>"Anthus petrosus", +"Lesser Spotted Eagle"=>"Aquila pomarina", +"Cattle Egret"=>"Bubulcus ibis", +"White-winged Black Tern"=>"Chlidonias leucopterus", +"Black Stork"=>"Ciconia nigra", +"Mediterranean Gull"=>"Larus melanocephalus", +"Black Kite"=>"Milvus migrans", +"Yellow Wagtail"=>"Motacilla flavissima", +"Red-necked Grebe"=>"Podiceps grisegena", +"Gull-billed Tern"=>"Gelochelidon nilotica", +"Pectoral Sandpiper"=>"Calidris melanotos", +"Barred Warbler"=>"Sylvia nisoria", +"Red-throated Pipit"=>"Anthus cervinus", +"Grey Wagtail"=>"Motacilla cinerea", +"Richard`s Pipit"=>"Anthus richardi", +"Black Woodpecker"=>"Dryocopus martius", +"Little Ringed Plover"=>"Charadrius dubius", +"Whiskered Tern"=>"Chlidonias hybrida", +"Lesser Redpoll"=>"Carduelis cabaret", +"Pallas' Bunting"=>"Emberiza pallasi", +"Ferruginous Duck"=>"Aythya nyroca", +"Whistling Swan"=>"Cygnus columbianus", +"Black Brant"=>"Branta nigricans", +"Marbled Teal"=>"Marmaronetta angustirostris", +"Canvasback"=>"Aythya valisineria", +"Redhead"=>"Aythya americana", +"Lesser Scaup"=>"Aythya affinis", +"Steller`s Eider"=>"Polysticta stelleri", +"Spectacled Eider"=>"Somateria fischeri", +"Harlequin Duck"=>"Histronicus histrionicus", +"Black Scoter"=>"Melanitta americana", +"Surf Scoter"=>"Melanitta perspicillata", +"Barrow`s Goldeneye"=>"Bucephala islandica", +"Falcated Duck"=>"Anas falcata", +"American Wigeon"=>"Anas americana", +"Blue-winged Teal"=>"Anas discors", +"American Black Duck"=>"Anas rubripes", +"Baikal Teal"=>"Anas formosa", +"Green-Winged Teal"=>"Anas carolinensis", +"Hazel Grouse"=>"Bonasa bonasia", +"Rock Partridge"=>"Alectoris graeca", +"Red-legged Partridge"=>"Alectoris rufa", +"Yellow-billed Loon"=>"Gavia adamsii", +"Cory`s Shearwater"=>"Calonectris borealis", +"Madeiran Storm-Petrel"=>"Oceanodroma castro", +"Great White Pelican"=>"Pelecanus onocrotalus", +"Dalmatian Pelican"=>"Pelecanus crispus", +"American Bittern"=>"Botaurus lentiginosus", +"Glossy Ibis"=>"Plegadis falcinellus", +"Spanish Imperial Eagle"=>"Aquila adalberti", +"Lesser Kestrel"=>"Falco naumanni", +"Houbara Bustard"=>"Chlamydotis undulata", +"Crab-Plover"=>"Dromas ardeola", +"Cream-coloured Courser"=>"Cursorius cursor", +"Collared Pratincole"=>"Glareola pratincola", +"Black-winged Pratincole"=>"Glareola nordmanni", +"Killdeer"=>"Charadrius vociferus", +"Lesser Sand Plover"=>"Charadrius mongolus", +"Greater Sand Plover"=>"Charadrius leschenaultii", +"Caspian Plover"=>"Charadrius asiaticus", +"American Golden Plover"=>"Pluvialis dominica", +"Pacific Golden Plover"=>"Pluvialis fulva", +"Sharp-tailed Sandpiper"=>"Calidris acuminata", +"Broad-billed Sandpiper"=>"Limicola falcinellus", +"Spoon-Billed Sandpiper"=>"Eurynorhynchus pygmaeus", +"Short-Billed Dowitcher"=>"Limnodromus griseus", +"Long-billed Dowitcher"=>"Limnodromus scolopaceus", +"Hudsonian Godwit"=>"Limosa haemastica", +"Little Curlew"=>"Numenius minutus", +"Lesser Yellowlegs"=>"Tringa flavipes", +"Wilson`s Phalarope"=>"Phalaropus tricolor", +"Pallas`s Gull"=>"Larus ichthyaetus", +"Laughing Gull"=>"Larus atricilla", +"Franklin`s Gull"=>"Larus pipixcan", +"Bonaparte`s Gull"=>"Larus philadelphia", +"Ring-billed Gull"=>"Larus delawarensis", +"American Herring Gull"=>"Larus smithsonianus", +"Caspian Gull"=>"Larus cachinnans", +"Ivory Gull"=>"Pagophila eburnea", +"Royal Tern"=>"Sterna maxima", +"Brünnich`s Murre"=>"Uria lomvia", +"Crested Auklet"=>"Aethia cristatella", +"Parakeet Auklet"=>"Cyclorrhynchus psittacula", +"Tufted Puffin"=>"Lunda cirrhata", +"Laughing Dove"=>"Streptopelia senegalensis", +"Great Spotted Cuckoo"=>"Clamator glandarius", +"Great Grey Owl"=>"Strix nebulosa", +"Tengmalm`s Owl"=>"Aegolius funereus", +"Red-Necked Nightjar"=>"Caprimulgus ruficollis", +"Chimney Swift"=>"Chaetura pelagica", +"Green Bea-Eater"=>"Merops orientalis", +"Grey-headed Woodpecker"=>"Picus canus", +"Lesser Short-Toed Lark"=>"Calandrella rufescens", +"Eurasian Crag Martin"=>"Hirundo rupestris", +"Red-rumped Swallow"=>"Cecropis daurica", +"Blyth`s Pipit"=>"Anthus godlewskii", +"Pechora Pipit"=>"Anthus gustavi", +"Grey-headed Wagtail"=>"Motacilla thunbergi", +"Yellow-Headed Wagtail"=>"Motacilla lutea", +"White-throated Dipper"=>"Cinclus cinclus", +"Rufous-Tailed Scrub Robin"=>"Cercotrichas galactotes", +"Thrush Nightingale"=>"Luscinia luscinia", +"White-throated Robin"=>"Irania gutturalis", +"Caspian Stonechat"=>"Saxicola maura variegata", +"Western Black-eared Wheatear"=>"Oenanthe hispanica", +"Rufous-tailed Rock Thrush"=>"Monticola saxatilis", +"Red-throated Thrush/Black-throated"=>"Turdus ruficollis", +"American Robin"=>"Turdus migratorius", +"Zitting Cisticola"=>"Cisticola juncidis", +"Lanceolated Warbler"=>"Locustella lanceolata", +"River Warbler"=>"Locustella fluviatilis", +"Blyth`s Reed Warbler"=>"Acrocephalus dumetorum", +"Caspian Reed Warbler"=>"Acrocephalus fuscus", +"Aquatic Warbler"=>"Acrocephalus paludicola", +"Booted Warbler"=>"Acrocephalus caligatus", +"Marmora's Warbler"=>"Sylvia sarda", +"Dartford Warbler"=>"Sylvia undata", +"Subalpine Warbler"=>"Sylvia cantillans", +"Ménétries's Warbler"=>"Sylvia mystacea", +"Rüppel's Warbler"=>"Sylvia rueppelli", +"Asian Desert Warbler"=>"Sylvia nana", +"Western Orphean Warbler"=>"Sylvia hortensis hortensis", +"Arctic Warbler"=>"Phylloscopus borealis", +"Radde`s Warbler"=>"Phylloscopus schwarzi", +"Western Bonelli`s Warbler"=>"Phylloscopus bonelli", +"Red-breasted Flycatcher"=>"Ficedula parva", +"Eurasian Penduline Tit"=>"Remiz pendulinus", +"Daurian Shrike"=>"Lanius isabellinus", +"Long-Tailed Shrike"=>"Lanius schach", +"Lesser Grey Shrike"=>"Lanius minor", +"Southern Grey Shrike"=>"Lanius meridionalis", +"Masked Shrike"=>"Lanius nubicus", +"Spotted Nutcracker"=>"Nucifraga caryocatactes", +"Daurian Jackdaw"=>"Corvus dauuricus", +"Purple-Backed Starling"=>"Sturnus sturninus", +"Red-Fronted Serin"=>"Serinus pusillus", +"Arctic Redpoll"=>"Carduelis hornemanni", +"Scottish Crossbill"=>"Loxia scotica", +"Parrot Crossbill"=>"Loxia pytyopsittacus", +"Black-faced Bunting"=>"Emberiza spodocephala", +"Pink-footed Goose"=>"Anser brachyrhynchus", +"Black-winged Kite"=>"Elanus caeruleus", +"European Bee-eater"=>"Merops apiaster", +"Sabine`s Gull"=>"Larus sabini", +"Sooty Shearwater"=>"Puffinus griseus", +"Lesser Canada Goose"=>"Branta hutchinsii", +"Ring-necked Duck"=>"Aythya collaris", +"Greater Flamingo"=>"Phoenicopterus roseus", +"Iberian Chiffchaff"=>"Phylloscopus ibericus", +"Ashy-headed Wagtail"=>"Motacilla cinereocapilla", +"Stilt Sandpiper"=>"Calidris himantopus", +"Siberian Stonechat"=>"Saxicola maurus", +"Greater Yellowlegs"=>"Tringa melanoleuca", +"Forster`s Tern"=>"Sterna forsteri", +"Dusky Warbler"=>"Phylloscopus fuscatus", +"Cirl Bunting"=>"Emberiza cirlus", +"Olive-backed Pipit"=>"Anthus hodgsoni", +"Sociable Lapwing"=>"Vanellus gregarius", +"Spotted Sandpiper"=>"Actitis macularius", +"Baird`s Sandpiper"=>"Calidris bairdii", +"Rustic Bunting"=>"Emberiza rustica", +"Yellow-browed Bunting"=>"Emberiza chrysophrys", +"Great Shearwater"=>"Puffinus gravis", +"Bonelli`s Eagle"=>"Aquila fasciata", +"Calandra Lark"=>"Melanocorypha calandra", +"Sardinian Warbler"=>"Sylvia melanocephala", +"Ross's Gull"=>"Larus roseus", +"Yellow-Breasted Bunting"=>"Emberiza aureola", +"Pine Bunting"=>"Emberiza leucocephalos", +"Black Guillemot"=>"Cepphus grylle", +"Pied-billed Grebe"=>"Podilymbus podiceps", +"Soft-plumaged Petrel"=>"Pterodroma mollis", +"Bulwer's Petrel"=>"Bulweria bulwerii", +"White-Faced Storm-Petrel"=>"Pelagodroma marina", +"Pallas’s Fish Eagle"=>"Haliaeetus leucoryphus", +"Sandhill Crane"=>"Grus canadensis", +"Macqueen’s Bustard"=>"Chlamydotis macqueenii", +"White-tailed Lapwing"=>"Vanellus leucurus", +"Great Knot"=>"Calidris tenuirostris", +"Semipalmated Sandpiper"=>"Calidris pusilla", +"Red-necked Stint"=>"Calidris ruficollis", +"Slender-billed Curlew"=>"Numenius tenuirostris", +"Bridled Tern"=>"Onychoprion anaethetus", +"Pallas’s Sandgrouse"=>"Syrrhaptes paradoxus", +"European Scops Owl"=>"Otus scops", +"Northern Hawk Owl"=>"Surnia ulula", +"White-Throated Needletail"=>"Hirundapus caudacutus", +"Belted Kingfisher"=>"Ceryle alcyon", +"Blue-cheeked Bee-eater"=>"Merops persicus", +"Black-headed Wagtail"=>"Motacilla feldegg", +"Northern Mockingbird"=>"Mimus polyglottos", +"Alpine Accentor"=>"Prunella collaris", +"Red-flanked Bluetail"=>"Tarsiger cyanurus", +"Isabelline Wheatear"=>"Oenanthe isabellina", +"Pied Wheatear"=>"Oenanthe pleschanka", +"Eastern Black-eared Wheatear"=>"Oenanthe melanoleuca", +"Desert Wheatear"=>"Oenanthe deserti", +"White`s Thrush"=>"Zoothera aurea", +"Siberian Thrush"=>"Zoothera sibirica", +"Eyebrowed Thrush"=>"Turdus obscurus", +"Dusky Thrush"=>"Turdus eunomus", +"Black-throated Thrush"=>"Turdus atrogularis", +"Pallas`s Grasshopper Warbler"=>"Locustella certhiola", +"Spectacled Warbler"=>"Sylvia conspicillata", +"Two-barred Warbler"=>"Phylloscopus plumbeitarsus", +"Eastern Bonelli’s Warbler"=>"Phylloscopus orientalis", +"Collared Flycatcher"=>"Ficedula albicollis", +"Wallcreeper"=>"Tichodroma muraria", +"Turkestan Shrike"=>"Lanius phoenicuroides", +"Steppe Grey Shrike"=>"Lanius pallidirostris", +"Spanish Sparrow"=>"Passer hispaniolensis", +"Red-eyed Vireo"=>"Vireo olivaceus", +"Myrtle Warbler"=>"Dendroica coronata", +"White-crowned Sparrow"=>"Zonotrichia leucophrys", +"White-throated Sparrow"=>"Zonotrichia albicollis", +"Cretzschmar`s Bunting"=>"Emberiza caesia", +"Chestnut Bunting"=>"Emberiza rutila", +"Red-headed Bunting"=>"Emberiza bruniceps", +"Black-headed Bunting"=>"Emberiza melanocephala", +"Indigo Bunting"=>"Passerina cyanea", +"Balearic Woodchat Shrike"=>"Lanius senator badius", +"Demoiselle Crane"=>"Grus virgo", +"Chough"=>"Pyrrhocorax pyrrhocorax", +"Red-Billed Chough"=>"Pyrrhocorax graculus", +"Elegant Tern"=>"Sterna elegans", +"Chukar"=>"Alectoris chukar", +"Yellow-Billed Cuckoo"=>"Coccyzus americanus", +"American Sandwich Tern"=>"Sterna sandvicensis acuflavida", +"Olive-Tree Warbler"=>"Hippolais olivetorum", +"Eastern Olivaceous Warbler"=>"Acrocephalus pallidus", +"Indian Cormorant"=>"Phalacrocorax fuscicollis", +"Spur-Winged Lapwing"=>"Vanellus spinosus", +"Yelkouan Shearwater"=>"Puffinus yelkouan", +"Trumpeter Finch"=>"Bucanetes githagineus", +"Red Grouse"=>"Lagopus scoticus", +"Rock Ptarmigan"=>"Lagopus mutus", +"Long-Tailed Cormorant"=>"Phalacrocorax africanus", +"Double-crested Cormorant"=>"Phalacrocorax auritus", +"Magnificent Frigatebird"=>"Fregata magnificens", +"Naumann's Thrush"=>"Turdus naumanni", +"Oriental Pratincole"=>"Glareola maldivarum", +"Bufflehead"=>"Bucephala albeola", +"Snowfinch"=>"Montifrigilla nivalis", +"Ural owl"=>"Strix uralensis", +"Spanish Wagtail"=>"Motacilla iberiae", +"Song Sparrow"=>"Melospiza melodia", +"Rock Bunting"=>"Emberiza cia", +"Siberian Rubythroat"=>"Luscinia calliope", +"Pallid Swift"=>"Apus pallidus", +"Eurasian Pygmy Owl"=>"Glaucidium passerinum", +"Madeira Little Shearwater"=>"Puffinus baroli", +"House Finch"=>"Carpodacus mexicanus", +"Green Heron"=>"Butorides virescens", +"Solitary Sandpiper"=>"Tringa solitaria", +"Heuglin's Gull"=>"Larus heuglini" +); + +foreach ($items as $key=>$value) { + if (strpos(strtolower($key), $q) !== false) { + echo "$key|$value\n"; + } +} + +?> \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/demo/search.phps b/plugins/Autocomplete/jquery-autocomplete/demo/search.phps new file mode 100644 index 000000000..03c0c0eab --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/demo/search.phps @@ -0,0 +1,578 @@ +Bittern"=>"Botaurus stellaris", +"Little Grebe"=>"Tachybaptus ruficollis", +"Black-necked Grebe"=>"Podiceps nigricollis", +"Little Bittern"=>"Ixobrychus minutus", +"Black-crowned Night Heron"=>"Nycticorax nycticorax", +"Purple Heron"=>"Ardea purpurea", +"White Stork"=>"Ciconia ciconia", +"Spoonbill"=>"Platalea leucorodia", +"Red-crested Pochard"=>"Netta rufina", +"Common Eider"=>"Somateria mollissima", +"Red Kite"=>"Milvus milvus", +"Hen Harrier"=>"Circus cyaneus", +"Montagu`s Harrier"=>"Circus pygargus", +"Black Grouse"=>"Tetrao tetrix", +"Grey Partridge"=>"Perdix perdix", +"Spotted Crake"=>"Porzana porzana", +"Corncrake"=>"Crex crex", +"Common Crane"=>"Grus grus", +"Avocet"=>"Recurvirostra avosetta", +"Stone Curlew"=>"Burhinus oedicnemus", +"Common Ringed Plover"=>"Charadrius hiaticula", +"Kentish Plover"=>"Charadrius alexandrinus", +"Ruff"=>"Philomachus pugnax", +"Common Snipe"=>"Gallinago gallinago", +"Black-tailed Godwit"=>"Limosa limosa", +"Common Redshank"=>"Tringa totanus", +"Sandwich Tern"=>"Sterna sandvicensis", +"Common Tern"=>"Sterna hirundo", +"Arctic Tern"=>"Sterna paradisaea", +"Little Tern"=>"Sternula albifrons", +"Black Tern"=>"Chlidonias niger", +"Barn Owl"=>"Tyto alba", +"Little Owl"=>"Athene noctua", +"Short-eared Owl"=>"Asio flammeus", +"European Nightjar"=>"Caprimulgus europaeus", +"Common Kingfisher"=>"Alcedo atthis", +"Eurasian Hoopoe"=>"Upupa epops", +"Eurasian Wryneck"=>"Jynx torquilla", +"European Green Woodpecker"=>"Picus viridis", +"Crested Lark"=>"Galerida cristata", +"White-headed Duck"=>"Oxyura leucocephala", +"Pale-bellied Brent Goose"=>"Branta hrota", +"Tawny Pipit"=>"Anthus campestris", +"Whinchat"=>"Saxicola rubetra", +"European Stonechat"=>"Saxicola rubicola", +"Northern Wheatear"=>"Oenanthe oenanthe", +"Savi`s Warbler"=>"Locustella luscinioides", +"Sedge Warbler"=>"Acrocephalus schoenobaenus", +"Great Reed Warbler"=>"Acrocephalus arundinaceus", +"Bearded Reedling"=>"Panurus biarmicus", +"Red-backed Shrike"=>"Lanius collurio", +"Great Grey Shrike"=>"Lanius excubitor", +"Woodchat Shrike"=>"Lanius senator", +"Common Raven"=>"Corvus corax", +"Yellowhammer"=>"Emberiza citrinella", +"Ortolan Bunting"=>"Emberiza hortulana", +"Corn Bunting"=>"Emberiza calandra", +"Great Cormorant"=>"Phalacrocorax carbo", +"Hawfinch"=>"Coccothraustes coccothraustes", +"Common Shelduck"=>"Tadorna tadorna", +"Bluethroat"=>"Luscinia svecica", +"Grey Heron"=>"Ardea cinerea", +"Barn Swallow"=>"Hirundo rustica", +"Hooded Crow"=>"Corvus cornix", +"Dunlin"=>"Calidris alpina", +"Eurasian Pied Flycatcher"=>"Ficedula hypoleuca", +"Eurasian Nuthatch"=>"Sitta europaea", +"Short-toed Tree Creeper"=>"Certhia brachydactyla", +"Wood Lark"=>"Lullula arborea", +"Tree Pipit"=>"Anthus trivialis", +"Eurasian Hobby"=>"Falco subbuteo", +"Marsh Warbler"=>"Acrocephalus palustris", +"Wood Sandpiper"=>"Tringa glareola", +"Tawny Owl"=>"Strix aluco", +"Lesser Whitethroat"=>"Sylvia curruca", +"Barnacle Goose"=>"Branta leucopsis", +"Common Goldeneye"=>"Bucephala clangula", +"Western Marsh Harrier"=>"Circus aeruginosus", +"Common Buzzard"=>"Buteo buteo", +"Sanderling"=>"Calidris alba", +"Little Gull"=>"Larus minutus", +"Eurasian Magpie"=>"Pica pica", +"Willow Warbler"=>"Phylloscopus trochilus", +"Wood Warbler"=>"Phylloscopus sibilatrix", +"Great Crested Grebe"=>"Podiceps cristatus", +"Eurasian Jay"=>"Garrulus glandarius", +"Common Redstart"=>"Phoenicurus phoenicurus", +"Blue-headed Wagtail"=>"Motacilla flava", +"Common Swift"=>"Apus apus", +"Marsh Tit"=>"Poecile palustris", +"Goldcrest"=>"Regulus regulus", +"European Golden Plover"=>"Pluvialis apricaria", +"Eurasian Bullfinch"=>"Pyrrhula pyrrhula", +"Common Whitethroat"=>"Sylvia communis", +"Meadow Pipit"=>"Anthus pratensis", +"Greylag Goose"=>"Anser anser", +"Spotted Flycatcher"=>"Muscicapa striata", +"European Greenfinch"=>"Carduelis chloris", +"Common Greenshank"=>"Tringa nebularia", +"Great Spotted Woodpecker"=>"Dendrocopos major", +"Greater Canada Goose"=>"Branta canadensis", +"Mistle Thrush"=>"Turdus viscivorus", +"Great Black-backed Gull"=>"Larus marinus", +"Goosander"=>"Mergus merganser", +"Great Egret"=>"Casmerodius albus", +"Northern Goshawk"=>"Accipiter gentilis", +"Dunnock"=>"Prunella modularis", +"Stock Dove"=>"Columba oenas", +"Common Wood Pigeon"=>"Columba palumbus", +"Eurasian Woodcock"=>"Scolopax rusticola", +"House Sparrow"=>"Passer domesticus", +"Common House Martin"=>"Delichon urbicum", +"Red Knot"=>"Calidris canutus", +"Western Jackdaw"=>"Corvus monedula", +"Brambling"=>"Fringilla montifringilla", +"Northern Lapwing"=>"Vanellus vanellus", +"European Reed Warbler"=>"Acrocephalus scirpaceus", +"Lesser Black-backed Gull"=>"Larus fuscus", +"Little Egret"=>"Egretta garzetta", +"Little Stint"=>"Calidris minuta", +"Common Linnet"=>"Carduelis cannabina", +"Mute Swan"=>"Cygnus olor", +"Common Cuckoo"=>"Cuculus canorus", +"Black-headed Gull"=>"Larus ridibundus", +"Greater White-fronted Goose"=>"Anser albifrons", +"Great Tit"=>"Parus major", +"Redwing"=>"Turdus iliacus", +"Gadwall"=>"Anas strepera", +"Fieldfare"=>"Turdus pilaris", +"Tufted Duck"=>"Aythya fuligula", +"Crested Tit"=>"Lophophanes cristatus", +"Willow Tit"=>"Poecile montanus", +"Eurasian Coot"=>"Fulica atra", +"Common Blackbird"=>"Turdus merula", +"Smew"=>"Mergus albellus", +"Common Sandpiper"=>"Actitis hypoleucos", +"Sand Martin"=>"Riparia riparia", +"Purple Sandpiper"=>"Calidris maritima", +"Northern Pintail"=>"Anas acuta", +"Blue Tit"=>"Cyanistes caeruleus", +"European Goldfinch"=>"Carduelis carduelis", +"Eurasian Whimbrel"=>"Numenius phaeopus", +"Common Reed Bunting"=>"Emberiza schoeniclus", +"Eurasian Tree Sparrow"=>"Passer montanus", +"Rook"=>"Corvus frugilegus", +"European Robin"=>"Erithacus rubecula", +"Bar-tailed Godwit"=>"Limosa lapponica", +"Dark-bellied Brent Goose"=>"Branta bernicla", +"Eurasian Oystercatcher"=>"Haematopus ostralegus", +"Eurasian Siskin"=>"Carduelis spinus", +"Northern Shoveler"=>"Anas clypeata", +"Eurasian Wigeon"=>"Anas penelope", +"Eurasian Sparrow Hawk"=>"Accipiter nisus", +"Icterine Warbler"=>"Hippolais icterina", +"Common Starling"=>"Sturnus vulgaris", +"Long-tailed Tit"=>"Aegithalos caudatus", +"Ruddy Turnstone"=>"Arenaria interpres", +"Mew Gull"=>"Larus canus", +"Common Pochard"=>"Aythya ferina", +"Common Chiffchaff"=>"Phylloscopus collybita", +"Greater Scaup"=>"Aythya marila", +"Common Kestrel"=>"Falco tinnunculus", +"Garden Warbler"=>"Sylvia borin", +"Eurasian Collared Dove"=>"Streptopelia decaocto", +"Eurasian Skylark"=>"Alauda arvensis", +"Common Chaffinch"=>"Fringilla coelebs", +"Common Moorhen"=>"Gallinula chloropus", +"Water Pipit"=>"Anthus spinoletta", +"Mallard"=>"Anas platyrhynchos", +"Winter Wren"=>"Troglodytes troglodytes", +"Common Teal"=>"Anas crecca", +"Green Sandpiper"=>"Tringa ochropus", +"White Wagtail"=>"Motacilla alba", +"Eurasian Curlew"=>"Numenius arquata", +"Song Thrush"=>"Turdus philomelos", +"European Herring Gull"=>"Larus argentatus", +"Grey Plover"=>"Pluvialis squatarola", +"Carrion Crow"=>"Corvus corone", +"Coal Tit"=>"Periparus ater", +"Spotted Redshank"=>"Tringa erythropus", +"Blackcap"=>"Sylvia atricapilla", +"Egyptian Vulture"=>"Neophron percnopterus", +"Razorbill"=>"Alca torda", +"Alpine Swift"=>"Apus melba", +"Long-legged Buzzard"=>"Buteo rufinus", +"Audouin`s Gull"=>"Larus audouinii", +"Balearic Shearwater"=>"Puffinus mauretanicus", +"Upland Sandpiper"=>"Bartramia longicauda", +"Greater Spotted Eagle"=>"Aquila clanga", +"Ring Ouzel"=>"Turdus torquatus", +"Yellow-browed Warbler"=>"Phylloscopus inornatus", +"Blue Rock Thrush"=>"Monticola solitarius", +"Buff-breasted Sandpiper"=>"Tryngites subruficollis", +"Jack Snipe"=>"Lymnocryptes minimus", +"White-rumped Sandpiper"=>"Calidris fuscicollis", +"Ruddy Shelduck"=>"Tadorna ferruginea", +"Cetti's Warbler"=>"Cettia cetti", +"Citrine Wagtail"=>"Motacilla citreola", +"Roseate Tern"=>"Sterna dougallii", +"Black-legged Kittiwake"=>"Rissa tridactyla", +"Pygmy Cormorant"=>"Phalacrocorax pygmeus", +"Booted Eagle"=>"Aquila pennata", +"Lesser White-fronted Goose"=>"Anser erythropus", +"Little Bunting"=>"Emberiza pusilla", +"Eleonora's Falcon"=>"Falco eleonorae", +"European Serin"=>"Serinus serinus", +"Twite"=>"Carduelis flavirostris", +"Yellow-legged Gull"=>"Larus michahellis", +"Gyr Falcon"=>"Falco rusticolus", +"Greenish Warbler"=>"Phylloscopus trochiloides", +"Red-necked Phalarope"=>"Phalaropus lobatus", +"Mealy Redpoll"=>"Carduelis flammea", +"Glaucous Gull"=>"Larus hyperboreus", +"Great Skua"=>"Stercorarius skua", +"Great Bustard"=>"Otis tarda", +"Velvet Scoter"=>"Melanitta fusca", +"Pine Grosbeak"=>"Pinicola enucleator", +"House Crow"=>"Corvus splendens", +"Hume`s Leaf Warbler"=>"Phylloscopus humei", +"Great Northern Loon"=>"Gavia immer", +"Long-tailed Duck"=>"Clangula hyemalis", +"Lapland Longspur"=>"Calcarius lapponicus", +"Northern Gannet"=>"Morus bassanus", +"Eastern Imperial Eagle"=>"Aquila heliaca", +"Little Auk"=>"Alle alle", +"Lesser Spotted Woodpecker"=>"Dendrocopos minor", +"Iceland Gull"=>"Larus glaucoides", +"Parasitic Jaeger"=>"Stercorarius parasiticus", +"Bewick`s Swan"=>"Cygnus bewickii", +"Little Bustard"=>"Tetrax tetrax", +"Little Crake"=>"Porzana parva", +"Baillon`s Crake"=>"Porzana pusilla", +"Long-tailed Jaeger"=>"Stercorarius longicaudus", +"King Eider"=>"Somateria spectabilis", +"Greater Short-toed Lark"=>"Calandrella brachydactyla", +"Houbara Bustard"=>"Chlamydotis undulata", +"Curlew Sandpiper"=>"Calidris ferruginea", +"Common Crossbill"=>"Loxia curvirostra", +"European Shag"=>"Phalacrocorax aristotelis", +"Horned Grebe"=>"Podiceps auritus", +"Common Quail"=>"Coturnix coturnix", +"Bearded Vulture"=>"Gypaetus barbatus", +"Lanner Falcon"=>"Falco biarmicus", +"Middle Spotted Woodpecker"=>"Dendrocopos medius", +"Pomarine Jaeger"=>"Stercorarius pomarinus", +"Red-breasted Merganser"=>"Mergus serrator", +"Eurasian Black Vulture"=>"Aegypius monachus", +"Eurasian Dotterel"=>"Charadrius morinellus", +"Common Nightingale"=>"Luscinia megarhynchos", +"Northern willow warbler"=>"Phylloscopus trochilus acredula", +"Manx Shearwater"=>"Puffinus puffinus", +"Northern Fulmar"=>"Fulmarus glacialis", +"Eurasian Eagle Owl"=>"Bubo bubo", +"Orphean Warbler"=>"Sylvia hortensis", +"Melodious Warbler"=>"Hippolais polyglotta", +"Pallas's Leaf Warbler"=>"Phylloscopus proregulus", +"Atlantic Puffin"=>"Fratercula arctica", +"Black-throated Loon"=>"Gavia arctica", +"Bohemian Waxwing"=>"Bombycilla garrulus", +"Marsh Sandpiper"=>"Tringa stagnatilis", +"Great Snipe"=>"Gallinago media", +"Squacco Heron"=>"Ardeola ralloides", +"Long-eared Owl"=>"Asio otus", +"Caspian Tern"=>"Hydroprogne caspia", +"Red-breasted Goose"=>"Branta ruficollis", +"Red-throated Loon"=>"Gavia stellata", +"Common Rosefinch"=>"Carpodacus erythrinus", +"Red-footed Falcon"=>"Falco vespertinus", +"Ross's Goose"=>"Anser rossii", +"Red Phalarope"=>"Phalaropus fulicarius", +"Pied Wagtail"=>"Motacilla yarrellii", +"Rose-coloured Starling"=>"Sturnus roseus", +"Rough-legged Buzzard"=>"Buteo lagopus", +"Saker Falcon"=>"Falco cherrug", +"European Roller"=>"Coracias garrulus", +"Short-toed Eagle"=>"Circaetus gallicus", +"Peregrine Falcon"=>"Falco peregrinus", +"Merlin"=>"Falco columbarius", +"Snow Goose"=>"Anser caerulescens", +"Snowy Owl"=>"Bubo scandiacus", +"Snow Bunting"=>"Plectrophenax nivalis", +"Common Grasshopper Warbler"=>"Locustella naevia", +"Golden Eagle"=>"Aquila chrysaetos", +"Black-winged Stilt"=>"Himantopus himantopus", +"Steppe Eagle"=>"Aquila nipalensis", +"Pallid Harrier"=>"Circus macrourus", +"European Storm-petrel"=>"Hydrobates pelagicus", +"Horned Lark"=>"Eremophila alpestris", +"Eurasian Treecreeper"=>"Certhia familiaris", +"Taiga Bean Goose"=>"Anser fabalis", +"Temminck`s Stint"=>"Calidris temminckii", +"Terek Sandpiper"=>"Xenus cinereus", +"Tundra Bean Goose"=>"Anser serrirostris", +"European Turtle Dove"=>"Streptopelia turtur", +"Leach`s Storm-petrel"=>"Oceanodroma leucorhoa", +"Eurasian Griffon Vulture"=>"Gyps fulvus", +"Paddyfield Warbler"=>"Acrocephalus agricola", +"Osprey"=>"Pandion haliaetus", +"Firecrest"=>"Regulus ignicapilla", +"Water Rail"=>"Rallus aquaticus", +"European Honey Buzzard"=>"Pernis apivorus", +"Eurasian Golden Oriole"=>"Oriolus oriolus", +"Whooper Swan"=>"Cygnus cygnus", +"Two-barred Crossbill"=>"Loxia leucoptera", +"White-tailed Eagle"=>"Haliaeetus albicilla", +"Atlantic Murre"=>"Uria aalge", +"Garganey"=>"Anas querquedula", +"Black Redstart"=>"Phoenicurus ochruros", +"Common Scoter"=>"Melanitta nigra", +"Rock Pipit"=>"Anthus petrosus", +"Lesser Spotted Eagle"=>"Aquila pomarina", +"Cattle Egret"=>"Bubulcus ibis", +"White-winged Black Tern"=>"Chlidonias leucopterus", +"Black Stork"=>"Ciconia nigra", +"Mediterranean Gull"=>"Larus melanocephalus", +"Black Kite"=>"Milvus migrans", +"Yellow Wagtail"=>"Motacilla flavissima", +"Red-necked Grebe"=>"Podiceps grisegena", +"Gull-billed Tern"=>"Gelochelidon nilotica", +"Pectoral Sandpiper"=>"Calidris melanotos", +"Barred Warbler"=>"Sylvia nisoria", +"Red-throated Pipit"=>"Anthus cervinus", +"Grey Wagtail"=>"Motacilla cinerea", +"Richard`s Pipit"=>"Anthus richardi", +"Black Woodpecker"=>"Dryocopus martius", +"Little Ringed Plover"=>"Charadrius dubius", +"Whiskered Tern"=>"Chlidonias hybrida", +"Lesser Redpoll"=>"Carduelis cabaret", +"Pallas' Bunting"=>"Emberiza pallasi", +"Ferruginous Duck"=>"Aythya nyroca", +"Whistling Swan"=>"Cygnus columbianus", +"Black Brant"=>"Branta nigricans", +"Marbled Teal"=>"Marmaronetta angustirostris", +"Canvasback"=>"Aythya valisineria", +"Redhead"=>"Aythya americana", +"Lesser Scaup"=>"Aythya affinis", +"Steller`s Eider"=>"Polysticta stelleri", +"Spectacled Eider"=>"Somateria fischeri", +"Harlequin Duck"=>"Histronicus histrionicus", +"Black Scoter"=>"Melanitta americana", +"Surf Scoter"=>"Melanitta perspicillata", +"Barrow`s Goldeneye"=>"Bucephala islandica", +"Falcated Duck"=>"Anas falcata", +"American Wigeon"=>"Anas americana", +"Blue-winged Teal"=>"Anas discors", +"American Black Duck"=>"Anas rubripes", +"Baikal Teal"=>"Anas formosa", +"Green-Winged Teal"=>"Anas carolinensis", +"Hazel Grouse"=>"Bonasa bonasia", +"Rock Partridge"=>"Alectoris graeca", +"Red-legged Partridge"=>"Alectoris rufa", +"Yellow-billed Loon"=>"Gavia adamsii", +"Cory`s Shearwater"=>"Calonectris borealis", +"Madeiran Storm-Petrel"=>"Oceanodroma castro", +"Great White Pelican"=>"Pelecanus onocrotalus", +"Dalmatian Pelican"=>"Pelecanus crispus", +"American Bittern"=>"Botaurus lentiginosus", +"Glossy Ibis"=>"Plegadis falcinellus", +"Spanish Imperial Eagle"=>"Aquila adalberti", +"Lesser Kestrel"=>"Falco naumanni", +"Houbara Bustard"=>"Chlamydotis undulata", +"Crab-Plover"=>"Dromas ardeola", +"Cream-coloured Courser"=>"Cursorius cursor", +"Collared Pratincole"=>"Glareola pratincola", +"Black-winged Pratincole"=>"Glareola nordmanni", +"Killdeer"=>"Charadrius vociferus", +"Lesser Sand Plover"=>"Charadrius mongolus", +"Greater Sand Plover"=>"Charadrius leschenaultii", +"Caspian Plover"=>"Charadrius asiaticus", +"American Golden Plover"=>"Pluvialis dominica", +"Pacific Golden Plover"=>"Pluvialis fulva", +"Sharp-tailed Sandpiper"=>"Calidris acuminata", +"Broad-billed Sandpiper"=>"Limicola falcinellus", +"Spoon-Billed Sandpiper"=>"Eurynorhynchus pygmaeus", +"Short-Billed Dowitcher"=>"Limnodromus griseus", +"Long-billed Dowitcher"=>"Limnodromus scolopaceus", +"Hudsonian Godwit"=>"Limosa haemastica", +"Little Curlew"=>"Numenius minutus", +"Lesser Yellowlegs"=>"Tringa flavipes", +"Wilson`s Phalarope"=>"Phalaropus tricolor", +"Pallas`s Gull"=>"Larus ichthyaetus", +"Laughing Gull"=>"Larus atricilla", +"Franklin`s Gull"=>"Larus pipixcan", +"Bonaparte`s Gull"=>"Larus philadelphia", +"Ring-billed Gull"=>"Larus delawarensis", +"American Herring Gull"=>"Larus smithsonianus", +"Caspian Gull"=>"Larus cachinnans", +"Ivory Gull"=>"Pagophila eburnea", +"Royal Tern"=>"Sterna maxima", +"Brünnich`s Murre"=>"Uria lomvia", +"Crested Auklet"=>"Aethia cristatella", +"Parakeet Auklet"=>"Cyclorrhynchus psittacula", +"Tufted Puffin"=>"Lunda cirrhata", +"Laughing Dove"=>"Streptopelia senegalensis", +"Great Spotted Cuckoo"=>"Clamator glandarius", +"Great Grey Owl"=>"Strix nebulosa", +"Tengmalm`s Owl"=>"Aegolius funereus", +"Red-Necked Nightjar"=>"Caprimulgus ruficollis", +"Chimney Swift"=>"Chaetura pelagica", +"Green Bea-Eater"=>"Merops orientalis", +"Grey-headed Woodpecker"=>"Picus canus", +"Lesser Short-Toed Lark"=>"Calandrella rufescens", +"Eurasian Crag Martin"=>"Hirundo rupestris", +"Red-rumped Swallow"=>"Cecropis daurica", +"Blyth`s Pipit"=>"Anthus godlewskii", +"Pechora Pipit"=>"Anthus gustavi", +"Grey-headed Wagtail"=>"Motacilla thunbergi", +"Yellow-Headed Wagtail"=>"Motacilla lutea", +"White-throated Dipper"=>"Cinclus cinclus", +"Rufous-Tailed Scrub Robin"=>"Cercotrichas galactotes", +"Thrush Nightingale"=>"Luscinia luscinia", +"White-throated Robin"=>"Irania gutturalis", +"Caspian Stonechat"=>"Saxicola maura variegata", +"Western Black-eared Wheatear"=>"Oenanthe hispanica", +"Rufous-tailed Rock Thrush"=>"Monticola saxatilis", +"Red-throated Thrush/Black-throated"=>"Turdus ruficollis", +"American Robin"=>"Turdus migratorius", +"Zitting Cisticola"=>"Cisticola juncidis", +"Lanceolated Warbler"=>"Locustella lanceolata", +"River Warbler"=>"Locustella fluviatilis", +"Blyth`s Reed Warbler"=>"Acrocephalus dumetorum", +"Caspian Reed Warbler"=>"Acrocephalus fuscus", +"Aquatic Warbler"=>"Acrocephalus paludicola", +"Booted Warbler"=>"Acrocephalus caligatus", +"Marmora's Warbler"=>"Sylvia sarda", +"Dartford Warbler"=>"Sylvia undata", +"Subalpine Warbler"=>"Sylvia cantillans", +"Ménétries's Warbler"=>"Sylvia mystacea", +"Rüppel's Warbler"=>"Sylvia rueppelli", +"Asian Desert Warbler"=>"Sylvia nana", +"Western Orphean Warbler"=>"Sylvia hortensis hortensis", +"Arctic Warbler"=>"Phylloscopus borealis", +"Radde`s Warbler"=>"Phylloscopus schwarzi", +"Western Bonelli`s Warbler"=>"Phylloscopus bonelli", +"Red-breasted Flycatcher"=>"Ficedula parva", +"Eurasian Penduline Tit"=>"Remiz pendulinus", +"Daurian Shrike"=>"Lanius isabellinus", +"Long-Tailed Shrike"=>"Lanius schach", +"Lesser Grey Shrike"=>"Lanius minor", +"Southern Grey Shrike"=>"Lanius meridionalis", +"Masked Shrike"=>"Lanius nubicus", +"Spotted Nutcracker"=>"Nucifraga caryocatactes", +"Daurian Jackdaw"=>"Corvus dauuricus", +"Purple-Backed Starling"=>"Sturnus sturninus", +"Red-Fronted Serin"=>"Serinus pusillus", +"Arctic Redpoll"=>"Carduelis hornemanni", +"Scottish Crossbill"=>"Loxia scotica", +"Parrot Crossbill"=>"Loxia pytyopsittacus", +"Black-faced Bunting"=>"Emberiza spodocephala", +"Pink-footed Goose"=>"Anser brachyrhynchus", +"Black-winged Kite"=>"Elanus caeruleus", +"European Bee-eater"=>"Merops apiaster", +"Sabine`s Gull"=>"Larus sabini", +"Sooty Shearwater"=>"Puffinus griseus", +"Lesser Canada Goose"=>"Branta hutchinsii", +"Ring-necked Duck"=>"Aythya collaris", +"Greater Flamingo"=>"Phoenicopterus roseus", +"Iberian Chiffchaff"=>"Phylloscopus ibericus", +"Ashy-headed Wagtail"=>"Motacilla cinereocapilla", +"Stilt Sandpiper"=>"Calidris himantopus", +"Siberian Stonechat"=>"Saxicola maurus", +"Greater Yellowlegs"=>"Tringa melanoleuca", +"Forster`s Tern"=>"Sterna forsteri", +"Dusky Warbler"=>"Phylloscopus fuscatus", +"Cirl Bunting"=>"Emberiza cirlus", +"Olive-backed Pipit"=>"Anthus hodgsoni", +"Sociable Lapwing"=>"Vanellus gregarius", +"Spotted Sandpiper"=>"Actitis macularius", +"Baird`s Sandpiper"=>"Calidris bairdii", +"Rustic Bunting"=>"Emberiza rustica", +"Yellow-browed Bunting"=>"Emberiza chrysophrys", +"Great Shearwater"=>"Puffinus gravis", +"Bonelli`s Eagle"=>"Aquila fasciata", +"Calandra Lark"=>"Melanocorypha calandra", +"Sardinian Warbler"=>"Sylvia melanocephala", +"Ross's Gull"=>"Larus roseus", +"Yellow-Breasted Bunting"=>"Emberiza aureola", +"Pine Bunting"=>"Emberiza leucocephalos", +"Black Guillemot"=>"Cepphus grylle", +"Pied-billed Grebe"=>"Podilymbus podiceps", +"Soft-plumaged Petrel"=>"Pterodroma mollis", +"Bulwer's Petrel"=>"Bulweria bulwerii", +"White-Faced Storm-Petrel"=>"Pelagodroma marina", +"Pallas’s Fish Eagle"=>"Haliaeetus leucoryphus", +"Sandhill Crane"=>"Grus canadensis", +"Macqueen’s Bustard"=>"Chlamydotis macqueenii", +"White-tailed Lapwing"=>"Vanellus leucurus", +"Great Knot"=>"Calidris tenuirostris", +"Semipalmated Sandpiper"=>"Calidris pusilla", +"Red-necked Stint"=>"Calidris ruficollis", +"Slender-billed Curlew"=>"Numenius tenuirostris", +"Bridled Tern"=>"Onychoprion anaethetus", +"Pallas’s Sandgrouse"=>"Syrrhaptes paradoxus", +"European Scops Owl"=>"Otus scops", +"Northern Hawk Owl"=>"Surnia ulula", +"White-Throated Needletail"=>"Hirundapus caudacutus", +"Belted Kingfisher"=>"Ceryle alcyon", +"Blue-cheeked Bee-eater"=>"Merops persicus", +"Black-headed Wagtail"=>"Motacilla feldegg", +"Northern Mockingbird"=>"Mimus polyglottos", +"Alpine Accentor"=>"Prunella collaris", +"Red-flanked Bluetail"=>"Tarsiger cyanurus", +"Isabelline Wheatear"=>"Oenanthe isabellina", +"Pied Wheatear"=>"Oenanthe pleschanka", +"Eastern Black-eared Wheatear"=>"Oenanthe melanoleuca", +"Desert Wheatear"=>"Oenanthe deserti", +"White`s Thrush"=>"Zoothera aurea", +"Siberian Thrush"=>"Zoothera sibirica", +"Eyebrowed Thrush"=>"Turdus obscurus", +"Dusky Thrush"=>"Turdus eunomus", +"Black-throated Thrush"=>"Turdus atrogularis", +"Pallas`s Grasshopper Warbler"=>"Locustella certhiola", +"Spectacled Warbler"=>"Sylvia conspicillata", +"Two-barred Warbler"=>"Phylloscopus plumbeitarsus", +"Eastern Bonelli’s Warbler"=>"Phylloscopus orientalis", +"Collared Flycatcher"=>"Ficedula albicollis", +"Wallcreeper"=>"Tichodroma muraria", +"Turkestan Shrike"=>"Lanius phoenicuroides", +"Steppe Grey Shrike"=>"Lanius pallidirostris", +"Spanish Sparrow"=>"Passer hispaniolensis", +"Red-eyed Vireo"=>"Vireo olivaceus", +"Myrtle Warbler"=>"Dendroica coronata", +"White-crowned Sparrow"=>"Zonotrichia leucophrys", +"White-throated Sparrow"=>"Zonotrichia albicollis", +"Cretzschmar`s Bunting"=>"Emberiza caesia", +"Chestnut Bunting"=>"Emberiza rutila", +"Red-headed Bunting"=>"Emberiza bruniceps", +"Black-headed Bunting"=>"Emberiza melanocephala", +"Indigo Bunting"=>"Passerina cyanea", +"Balearic Woodchat Shrike"=>"Lanius senator badius", +"Demoiselle Crane"=>"Grus virgo", +"Chough"=>"Pyrrhocorax pyrrhocorax", +"Red-Billed Chough"=>"Pyrrhocorax graculus", +"Elegant Tern"=>"Sterna elegans", +"Chukar"=>"Alectoris chukar", +"Yellow-Billed Cuckoo"=>"Coccyzus americanus", +"American Sandwich Tern"=>"Sterna sandvicensis acuflavida", +"Olive-Tree Warbler"=>"Hippolais olivetorum", +"Eastern Olivaceous Warbler"=>"Acrocephalus pallidus", +"Indian Cormorant"=>"Phalacrocorax fuscicollis", +"Spur-Winged Lapwing"=>"Vanellus spinosus", +"Yelkouan Shearwater"=>"Puffinus yelkouan", +"Trumpeter Finch"=>"Bucanetes githagineus", +"Red Grouse"=>"Lagopus scoticus", +"Rock Ptarmigan"=>"Lagopus mutus", +"Long-Tailed Cormorant"=>"Phalacrocorax africanus", +"Double-crested Cormorant"=>"Phalacrocorax auritus", +"Magnificent Frigatebird"=>"Fregata magnificens", +"Naumann's Thrush"=>"Turdus naumanni", +"Oriental Pratincole"=>"Glareola maldivarum", +"Bufflehead"=>"Bucephala albeola", +"Snowfinch"=>"Montifrigilla nivalis", +"Ural owl"=>"Strix uralensis", +"Spanish Wagtail"=>"Motacilla iberiae", +"Song Sparrow"=>"Melospiza melodia", +"Rock Bunting"=>"Emberiza cia", +"Siberian Rubythroat"=>"Luscinia calliope", +"Pallid Swift"=>"Apus pallidus", +"Eurasian Pygmy Owl"=>"Glaucidium passerinum", +"Madeira Little Shearwater"=>"Puffinus baroli", +"House Finch"=>"Carpodacus mexicanus", +"Green Heron"=>"Butorides virescens", +"Solitary Sandpiper"=>"Tringa solitaria", +"Heuglin's Gull"=>"Larus heuglini" +); + +foreach ($items as $key=>$value) { + if (strpos(strtolower($key), $q) !== false) { + echo "$key|$value\n"; + } +} + +?> \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.css b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.css new file mode 100644 index 000000000..91b622833 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.css @@ -0,0 +1,48 @@ +.ac_results { + padding: 0px; + border: 1px solid black; + background-color: white; + overflow: hidden; + z-index: 99999; +} + +.ac_results ul { + width: 100%; + list-style-position: outside; + list-style: none; + padding: 0; + margin: 0; +} + +.ac_results li { + margin: 0px; + padding: 2px 5px; + cursor: default; + display: block; + /* + if width will be 100% horizontal scrollbar will apear + when scroll mode will be used + */ + /*width: 100%;*/ + font: menu; + font-size: 12px; + /* + it is very important, if line-height not setted or setted + in relative units scroll will be broken in firefox + */ + line-height: 16px; + overflow: hidden; +} + +.ac_loading { + background: white url('indicator.gif') right center no-repeat; +} + +.ac_odd { + background-color: #eee; +} + +.ac_over { + background-color: #0A246A; + color: white; +} diff --git a/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.js b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.js new file mode 100644 index 000000000..5ad9178f8 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.js @@ -0,0 +1,759 @@ +/* + * Autocomplete - jQuery plugin 1.0.2 + * + * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $ + * + */ + +;(function($) { + +$.fn.extend({ + autocomplete: function(urlOrData, options) { + var isUrl = typeof urlOrData == "string"; + options = $.extend({}, $.Autocompleter.defaults, { + url: isUrl ? urlOrData : null, + data: isUrl ? null : urlOrData, + delay: isUrl ? $.Autocompleter.defaults.delay : 10, + max: options && !options.scroll ? 10 : 150 + }, options); + + // if highlight is set to false, replace it with a do-nothing function + options.highlight = options.highlight || function(value) { return value; }; + + // if the formatMatch option is not specified, then use formatItem for backwards compatibility + options.formatMatch = options.formatMatch || options.formatItem; + + return this.each(function() { + new $.Autocompleter(this, options); + }); + }, + result: function(handler) { + return this.bind("result", handler); + }, + search: function(handler) { + return this.trigger("search", [handler]); + }, + flushCache: function() { + return this.trigger("flushCache"); + }, + setOptions: function(options){ + return this.trigger("setOptions", [options]); + }, + unautocomplete: function() { + return this.trigger("unautocomplete"); + } +}); + +$.Autocompleter = function(input, options) { + + var KEY = { + UP: 38, + DOWN: 40, + DEL: 46, + TAB: 9, + RETURN: 13, + ESC: 27, + COMMA: 188, + PAGEUP: 33, + PAGEDOWN: 34, + BACKSPACE: 8 + }; + + // Create $ object for input element + var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); + + var timeout; + var previousValue = ""; + var cache = $.Autocompleter.Cache(options); + var hasFocus = 0; + var lastKeyPressCode; + var config = { + mouseDownOnSelect: false + }; + var select = $.Autocompleter.Select(options, input, selectCurrent, config); + + var blockSubmit; + + // prevent form submit in opera when selecting with return key + $.browser.opera && $(input.form).bind("submit.autocomplete", function() { + if (blockSubmit) { + blockSubmit = false; + return false; + } + }); + + // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all + $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { + // track last key pressed + lastKeyPressCode = event.keyCode; + switch(event.keyCode) { + + case KEY.UP: + event.preventDefault(); + if ( select.visible() ) { + select.prev(); + } else { + onChange(0, true); + } + break; + + case KEY.DOWN: + event.preventDefault(); + if ( select.visible() ) { + select.next(); + } else { + onChange(0, true); + } + break; + + case KEY.PAGEUP: + event.preventDefault(); + if ( select.visible() ) { + select.pageUp(); + } else { + onChange(0, true); + } + break; + + case KEY.PAGEDOWN: + event.preventDefault(); + if ( select.visible() ) { + select.pageDown(); + } else { + onChange(0, true); + } + break; + + // matches also semicolon + case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: + case KEY.TAB: + case KEY.RETURN: + if( selectCurrent() ) { + // stop default to prevent a form submit, Opera needs special handling + event.preventDefault(); + blockSubmit = true; + return false; + } + break; + + case KEY.ESC: + select.hide(); + break; + + default: + clearTimeout(timeout); + timeout = setTimeout(onChange, options.delay); + break; + } + }).focus(function(){ + // track whether the field has focus, we shouldn't process any + // results if the field no longer has focus + hasFocus++; + }).blur(function() { + hasFocus = 0; + if (!config.mouseDownOnSelect) { + hideResults(); + } + }).click(function() { + // show select when clicking in a focused field + if ( hasFocus++ > 1 && !select.visible() ) { + onChange(0, true); + } + }).bind("search", function() { + // TODO why not just specifying both arguments? + var fn = (arguments.length > 1) ? arguments[1] : null; + function findValueCallback(q, data) { + var result; + if( data && data.length ) { + for (var i=0; i < data.length; i++) { + if( data[i].result.toLowerCase() == q.toLowerCase() ) { + result = data[i]; + break; + } + } + } + if( typeof fn == "function" ) fn(result); + else $input.trigger("result", result && [result.data, result.value]); + } + $.each(trimWords($input.val()), function(i, value) { + request(value, findValueCallback, findValueCallback); + }); + }).bind("flushCache", function() { + cache.flush(); + }).bind("setOptions", function() { + $.extend(options, arguments[1]); + // if we've updated the data, repopulate + if ( "data" in arguments[1] ) + cache.populate(); + }).bind("unautocomplete", function() { + select.unbind(); + $input.unbind(); + $(input.form).unbind(".autocomplete"); + }); + + + function selectCurrent() { + var selected = select.selected(); + if( !selected ) + return false; + + var v = selected.result; + previousValue = v; + + if ( options.multiple ) { + var words = trimWords($input.val()); + if ( words.length > 1 ) { + v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v; + } + v += options.multipleSeparator; + } + + $input.val(v); + hideResultsNow(); + $input.trigger("result", [selected.data, selected.value]); + return true; + } + + function onChange(crap, skipPrevCheck) { + if( lastKeyPressCode == KEY.DEL ) { + select.hide(); + return; + } + + var currentValue = $input.val(); + + if ( !skipPrevCheck && currentValue == previousValue ) + return; + + previousValue = currentValue; + + currentValue = lastWord(currentValue); + if ( currentValue.length >= options.minChars) { + $input.addClass(options.loadingClass); + if (!options.matchCase) + currentValue = currentValue.toLowerCase(); + request(currentValue, receiveData, hideResultsNow); + } else { + stopLoading(); + select.hide(); + } + }; + + function trimWords(value) { + if ( !value ) { + return [""]; + } + var words = value.split( options.multipleSeparator ); + var result = []; + $.each(words, function(i, value) { + if ( $.trim(value) ) + result[i] = $.trim(value); + }); + return result; + } + + function lastWord(value) { + if ( !options.multiple ) + return value; + var words = trimWords(value); + return words[words.length - 1]; + } + + // fills in the input box w/the first match (assumed to be the best match) + // q: the term entered + // sValue: the first matching result + function autoFill(q, sValue){ + // autofill in the complete box w/the first match as long as the user hasn't entered in more data + // if the last user key pressed was backspace, don't autofill + if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { + // fill in the value (keep the case the user has typed) + $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); + // select the portion of the value not typed by the user (so the next character will erase) + $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length); + } + }; + + function hideResults() { + clearTimeout(timeout); + timeout = setTimeout(hideResultsNow, 200); + }; + + function hideResultsNow() { + var wasVisible = select.visible(); + select.hide(); + clearTimeout(timeout); + stopLoading(); + if (options.mustMatch) { + // call search and run callback + $input.search( + function (result){ + // if no value found, clear the input box + if( !result ) { + if (options.multiple) { + var words = trimWords($input.val()).slice(0, -1); + $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); + } + else + $input.val( "" ); + } + } + ); + } + if (wasVisible) + // position cursor at end of input field + $.Autocompleter.Selection(input, input.value.length, input.value.length); + }; + + function receiveData(q, data) { + if ( data && data.length && hasFocus ) { + stopLoading(); + select.display(data, q); + autoFill(q, data[0].value); + select.show(); + } else { + hideResultsNow(); + } + }; + + function request(term, success, failure) { + if (!options.matchCase) + term = term.toLowerCase(); + var data = cache.load(term); + // recieve the cached data + if (data && data.length) { + success(term, data); + // if an AJAX url has been supplied, try loading the data now + } else if( (typeof options.url == "string") && (options.url.length > 0) ){ + + var extraParams = { + timestamp: +new Date() + }; + $.each(options.extraParams, function(key, param) { + extraParams[key] = typeof param == "function" ? param() : param; + }); + + $.ajax({ + // try to leverage ajaxQueue plugin to abort previous requests + mode: "abort", + // limit abortion to this input + port: "autocomplete" + input.name, + dataType: options.dataType, + url: options.url, + data: $.extend({ + q: lastWord(term), + limit: options.max + }, extraParams), + success: function(data) { + var parsed = options.parse && options.parse(data) || parse(data); + cache.add(term, parsed); + success(term, parsed); + } + }); + } else { + // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match + select.emptyList(); + failure(term); + } + }; + + function parse(data) { + var parsed = []; + var rows = data.split("\n"); + for (var i=0; i < rows.length; i++) { + var row = $.trim(rows[i]); + if (row) { + row = row.split("|"); + parsed[parsed.length] = { + data: row, + value: row[0], + result: options.formatResult && options.formatResult(row, row[0]) || row[0] + }; + } + } + return parsed; + }; + + function stopLoading() { + $input.removeClass(options.loadingClass); + }; + +}; + +$.Autocompleter.defaults = { + inputClass: "ac_input", + resultsClass: "ac_results", + loadingClass: "ac_loading", + minChars: 1, + delay: 400, + matchCase: false, + matchSubset: true, + matchContains: false, + cacheLength: 10, + max: 100, + mustMatch: false, + extraParams: {}, + selectFirst: true, + formatItem: function(row) { return row[0]; }, + formatMatch: null, + autoFill: false, + width: 0, + multiple: false, + multipleSeparator: ", ", + highlight: function(value, term) { + return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1"); + }, + scroll: true, + scrollHeight: 180 +}; + +$.Autocompleter.Cache = function(options) { + + var data = {}; + var length = 0; + + function matchSubset(s, sub) { + if (!options.matchCase) + s = s.toLowerCase(); + var i = s.indexOf(sub); + if (i == -1) return false; + return i == 0 || options.matchContains; + }; + + function add(q, value) { + if (length > options.cacheLength){ + flush(); + } + if (!data[q]){ + length++; + } + data[q] = value; + } + + function populate(){ + if( !options.data ) return false; + // track the matches + var stMatchSets = {}, + nullData = 0; + + // no url was specified, we need to adjust the cache length to make sure it fits the local data store + if( !options.url ) options.cacheLength = 1; + + // track all options for minChars = 0 + stMatchSets[""] = []; + + // loop through the array and create a lookup structure + for ( var i = 0, ol = options.data.length; i < ol; i++ ) { + var rawValue = options.data[i]; + // if rawValue is a string, make an array otherwise just reference the array + rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; + + var value = options.formatMatch(rawValue, i+1, options.data.length); + if ( value === false ) + continue; + + var firstChar = value.charAt(0).toLowerCase(); + // if no lookup array for this character exists, look it up now + if( !stMatchSets[firstChar] ) + stMatchSets[firstChar] = []; + + // if the match is a string + var row = { + value: value, + data: rawValue, + result: options.formatResult && options.formatResult(rawValue) || value + }; + + // push the current match into the set list + stMatchSets[firstChar].push(row); + + // keep track of minChars zero items + if ( nullData++ < options.max ) { + stMatchSets[""].push(row); + } + }; + + // add the data items to the cache + $.each(stMatchSets, function(i, value) { + // increase the cache size + options.cacheLength++; + // add to the cache + add(i, value); + }); + } + + // populate any existing data + setTimeout(populate, 25); + + function flush(){ + data = {}; + length = 0; + } + + return { + flush: flush, + add: add, + populate: populate, + load: function(q) { + if (!options.cacheLength || !length) + return null; + /* + * if dealing w/local data and matchContains than we must make sure + * to loop through all the data collections looking for matches + */ + if( !options.url && options.matchContains ){ + // track all matches + var csub = []; + // loop through all the data grids for matches + for( var k in data ){ + // don't search through the stMatchSets[""] (minChars: 0) cache + // this prevents duplicates + if( k.length > 0 ){ + var c = data[k]; + $.each(c, function(i, x) { + // if we've got a match, add it to the array + if (matchSubset(x.value, q)) { + csub.push(x); + } + }); + } + } + return csub; + } else + // if the exact item exists, use it + if (data[q]){ + return data[q]; + } else + if (options.matchSubset) { + for (var i = q.length - 1; i >= options.minChars; i--) { + var c = data[q.substr(0, i)]; + if (c) { + var csub = []; + $.each(c, function(i, x) { + if (matchSubset(x.value, q)) { + csub[csub.length] = x; + } + }); + return csub; + } + } + } + return null; + } + }; +}; + +$.Autocompleter.Select = function (options, input, select, config) { + var CLASSES = { + ACTIVE: "ac_over" + }; + + var listItems, + active = -1, + data, + term = "", + needsInit = true, + element, + list; + + // Create results + function init() { + if (!needsInit) + return; + element = $("
          ") + .hide() + .addClass(options.resultsClass) + .css("position", "absolute") + .appendTo(document.body); + + list = $("
            ").appendTo(element).mouseover( function(event) { + if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { + active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); + $(target(event)).addClass(CLASSES.ACTIVE); + } + }).click(function(event) { + $(target(event)).addClass(CLASSES.ACTIVE); + select(); + // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus + input.focus(); + return false; + }).mousedown(function() { + config.mouseDownOnSelect = true; + }).mouseup(function() { + config.mouseDownOnSelect = false; + }); + + if( options.width > 0 ) + element.css("width", options.width); + + needsInit = false; + } + + function target(event) { + var element = event.target; + while(element && element.tagName != "LI") + element = element.parentNode; + // more fun with IE, sometimes event.target is empty, just ignore it then + if(!element) + return []; + return element; + } + + function moveSelect(step) { + listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); + movePosition(step); + var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); + if(options.scroll) { + var offset = 0; + listItems.slice(0, active).each(function() { + offset += this.offsetHeight; + }); + if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { + list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); + } else if(offset < list.scrollTop()) { + list.scrollTop(offset); + } + } + }; + + function movePosition(step) { + active += step; + if (active < 0) { + active = listItems.size() - 1; + } else if (active >= listItems.size()) { + active = 0; + } + } + + function limitNumberOfItems(available) { + return options.max && options.max < available + ? options.max + : available; + } + + function fillList() { + list.empty(); + var max = limitNumberOfItems(data.length); + for (var i=0; i < max; i++) { + if (!data[i]) + continue; + var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); + if ( formatted === false ) + continue; + var li = $("
          • ").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; + $.data(li, "ac_data", data[i]); + } + listItems = list.find("li"); + if ( options.selectFirst ) { + listItems.slice(0, 1).addClass(CLASSES.ACTIVE); + active = 0; + } + // apply bgiframe if available + if ( $.fn.bgiframe ) + list.bgiframe(); + } + + return { + display: function(d, q) { + init(); + data = d; + term = q; + fillList(); + }, + next: function() { + moveSelect(1); + }, + prev: function() { + moveSelect(-1); + }, + pageUp: function() { + if (active != 0 && active - 8 < 0) { + moveSelect( -active ); + } else { + moveSelect(-8); + } + }, + pageDown: function() { + if (active != listItems.size() - 1 && active + 8 > listItems.size()) { + moveSelect( listItems.size() - 1 - active ); + } else { + moveSelect(8); + } + }, + hide: function() { + element && element.hide(); + listItems && listItems.removeClass(CLASSES.ACTIVE); + active = -1; + }, + visible : function() { + return element && element.is(":visible"); + }, + current: function() { + return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); + }, + show: function() { + var offset = $(input).offset(); + element.css({ + width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), + top: offset.top + input.offsetHeight, + left: offset.left + }).show(); + if(options.scroll) { + list.scrollTop(0); + list.css({ + maxHeight: options.scrollHeight, + overflow: 'auto' + }); + + if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { + var listHeight = 0; + listItems.each(function() { + listHeight += this.offsetHeight; + }); + var scrollbarsVisible = listHeight > options.scrollHeight; + list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); + if (!scrollbarsVisible) { + // IE doesn't recalculate width when scrollbar disappears + listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); + } + } + + } + }, + selected: function() { + var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); + return selected && selected.length && $.data(selected[0], "ac_data"); + }, + emptyList: function (){ + list && list.empty(); + }, + unbind: function() { + element && element.remove(); + } + }; +}; + +$.Autocompleter.Selection = function(field, start, end) { + if( field.createTextRange ){ + var selRange = field.createTextRange(); + selRange.collapse(true); + selRange.moveStart("character", start); + selRange.moveEnd("character", end); + selRange.select(); + } else if( field.setSelectionRange ){ + field.setSelectionRange(start, end); + } else { + if( field.selectionStart ){ + field.selectionStart = start; + field.selectionEnd = end; + } + } + field.focus(); +}; + +})(jQuery); \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.min.js b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.min.js new file mode 100644 index 000000000..c9ddfb220 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.min.js @@ -0,0 +1,15 @@ +/* + * Autocomplete - jQuery plugin 1.0.2 + * + * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $ + * + */;(function($){$.fn.extend({autocomplete:function(urlOrData,options){var isUrl=typeof urlOrData=="string";options=$.extend({},$.Autocompleter.defaults,{url:isUrl?urlOrData:null,data:isUrl?null:urlOrData,delay:isUrl?$.Autocompleter.defaults.delay:10,max:options&&!options.scroll?10:150},options);options.highlight=options.highlight||function(value){return value;};options.formatMatch=options.formatMatch||options.formatItem;return this.each(function(){new $.Autocompleter(this,options);});},result:function(handler){return this.bind("result",handler);},search:function(handler){return this.trigger("search",[handler]);},flushCache:function(){return this.trigger("flushCache");},setOptions:function(options){return this.trigger("setOptions",[options]);},unautocomplete:function(){return this.trigger("unautocomplete");}});$.Autocompleter=function(input,options){var KEY={UP:38,DOWN:40,DEL:46,TAB:9,RETURN:13,ESC:27,COMMA:188,PAGEUP:33,PAGEDOWN:34,BACKSPACE:8};var $input=$(input).attr("autocomplete","off").addClass(options.inputClass);var timeout;var previousValue="";var cache=$.Autocompleter.Cache(options);var hasFocus=0;var lastKeyPressCode;var config={mouseDownOnSelect:false};var select=$.Autocompleter.Select(options,input,selectCurrent,config);var blockSubmit;$.browser.opera&&$(input.form).bind("submit.autocomplete",function(){if(blockSubmit){blockSubmit=false;return false;}});$input.bind(($.browser.opera?"keypress":"keydown")+".autocomplete",function(event){lastKeyPressCode=event.keyCode;switch(event.keyCode){case KEY.UP:event.preventDefault();if(select.visible()){select.prev();}else{onChange(0,true);}break;case KEY.DOWN:event.preventDefault();if(select.visible()){select.next();}else{onChange(0,true);}break;case KEY.PAGEUP:event.preventDefault();if(select.visible()){select.pageUp();}else{onChange(0,true);}break;case KEY.PAGEDOWN:event.preventDefault();if(select.visible()){select.pageDown();}else{onChange(0,true);}break;case options.multiple&&$.trim(options.multipleSeparator)==","&&KEY.COMMA:case KEY.TAB:case KEY.RETURN:if(selectCurrent()){event.preventDefault();blockSubmit=true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout=setTimeout(onChange,options.delay);break;}}).focus(function(){hasFocus++;}).blur(function(){hasFocus=0;if(!config.mouseDownOnSelect){hideResults();}}).click(function(){if(hasFocus++>1&&!select.visible()){onChange(0,true);}}).bind("search",function(){var fn=(arguments.length>1)?arguments[1]:null;function findValueCallback(q,data){var result;if(data&&data.length){for(var i=0;i1){v=words.slice(0,words.length-1).join(options.multipleSeparator)+options.multipleSeparator+v;}v+=options.multipleSeparator;}$input.val(v);hideResultsNow();$input.trigger("result",[selected.data,selected.value]);return true;}function onChange(crap,skipPrevCheck){if(lastKeyPressCode==KEY.DEL){select.hide();return;}var currentValue=$input.val();if(!skipPrevCheck&¤tValue==previousValue)return;previousValue=currentValue;currentValue=lastWord(currentValue);if(currentValue.length>=options.minChars){$input.addClass(options.loadingClass);if(!options.matchCase)currentValue=currentValue.toLowerCase();request(currentValue,receiveData,hideResultsNow);}else{stopLoading();select.hide();}};function trimWords(value){if(!value){return[""];}var words=value.split(options.multipleSeparator);var result=[];$.each(words,function(i,value){if($.trim(value))result[i]=$.trim(value);});return result;}function lastWord(value){if(!options.multiple)return value;var words=trimWords(value);return words[words.length-1];}function autoFill(q,sValue){if(options.autoFill&&(lastWord($input.val()).toLowerCase()==q.toLowerCase())&&lastKeyPressCode!=KEY.BACKSPACE){$input.val($input.val()+sValue.substring(lastWord(previousValue).length));$.Autocompleter.Selection(input,previousValue.length,previousValue.length+sValue.length);}};function hideResults(){clearTimeout(timeout);timeout=setTimeout(hideResultsNow,200);};function hideResultsNow(){var wasVisible=select.visible();select.hide();clearTimeout(timeout);stopLoading();if(options.mustMatch){$input.search(function(result){if(!result){if(options.multiple){var words=trimWords($input.val()).slice(0,-1);$input.val(words.join(options.multipleSeparator)+(words.length?options.multipleSeparator:""));}else +$input.val("");}});}if(wasVisible)$.Autocompleter.Selection(input,input.value.length,input.value.length);};function receiveData(q,data){if(data&&data.length&&hasFocus){stopLoading();select.display(data,q);autoFill(q,data[0].value);select.show();}else{hideResultsNow();}};function request(term,success,failure){if(!options.matchCase)term=term.toLowerCase();var data=cache.load(term);if(data&&data.length){success(term,data);}else if((typeof options.url=="string")&&(options.url.length>0)){var extraParams={timestamp:+new Date()};$.each(options.extraParams,function(key,param){extraParams[key]=typeof param=="function"?param():param;});$.ajax({mode:"abort",port:"autocomplete"+input.name,dataType:options.dataType,url:options.url,data:$.extend({q:lastWord(term),limit:options.max},extraParams),success:function(data){var parsed=options.parse&&options.parse(data)||parse(data);cache.add(term,parsed);success(term,parsed);}});}else{select.emptyList();failure(term);}};function parse(data){var parsed=[];var rows=data.split("\n");for(var i=0;i]*)("+term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")+")(?![^<>]*>)(?![^&;]+;)","gi"),"$1");},scroll:true,scrollHeight:180};$.Autocompleter.Cache=function(options){var data={};var length=0;function matchSubset(s,sub){if(!options.matchCase)s=s.toLowerCase();var i=s.indexOf(sub);if(i==-1)return false;return i==0||options.matchContains;};function add(q,value){if(length>options.cacheLength){flush();}if(!data[q]){length++;}data[q]=value;}function populate(){if(!options.data)return false;var stMatchSets={},nullData=0;if(!options.url)options.cacheLength=1;stMatchSets[""]=[];for(var i=0,ol=options.data.length;i0){var c=data[k];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub.push(x);}});}}return csub;}else +if(data[q]){return data[q];}else +if(options.matchSubset){for(var i=q.length-1;i>=options.minChars;i--){var c=data[q.substr(0,i)];if(c){var csub=[];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub[csub.length]=x;}});return csub;}}}return null;}};};$.Autocompleter.Select=function(options,input,select,config){var CLASSES={ACTIVE:"ac_over"};var listItems,active=-1,data,term="",needsInit=true,element,list;function init(){if(!needsInit)return;element=$("
            ").hide().addClass(options.resultsClass).css("position","absolute").appendTo(document.body);list=$("
              ").appendTo(element).mouseover(function(event){if(target(event).nodeName&&target(event).nodeName.toUpperCase()=='LI'){active=$("li",list).removeClass(CLASSES.ACTIVE).index(target(event));$(target(event)).addClass(CLASSES.ACTIVE);}}).click(function(event){$(target(event)).addClass(CLASSES.ACTIVE);select();input.focus();return false;}).mousedown(function(){config.mouseDownOnSelect=true;}).mouseup(function(){config.mouseDownOnSelect=false;});if(options.width>0)element.css("width",options.width);needsInit=false;}function target(event){var element=event.target;while(element&&element.tagName!="LI")element=element.parentNode;if(!element)return[];return element;}function moveSelect(step){listItems.slice(active,active+1).removeClass(CLASSES.ACTIVE);movePosition(step);var activeItem=listItems.slice(active,active+1).addClass(CLASSES.ACTIVE);if(options.scroll){var offset=0;listItems.slice(0,active).each(function(){offset+=this.offsetHeight;});if((offset+activeItem[0].offsetHeight-list.scrollTop())>list[0].clientHeight){list.scrollTop(offset+activeItem[0].offsetHeight-list.innerHeight());}else if(offset=listItems.size()){active=0;}}function limitNumberOfItems(available){return options.max&&options.max").html(options.highlight(formatted,term)).addClass(i%2==0?"ac_even":"ac_odd").appendTo(list)[0];$.data(li,"ac_data",data[i]);}listItems=list.find("li");if(options.selectFirst){listItems.slice(0,1).addClass(CLASSES.ACTIVE);active=0;}if($.fn.bgiframe)list.bgiframe();}return{display:function(d,q){init();data=d;term=q;fillList();},next:function(){moveSelect(1);},prev:function(){moveSelect(-1);},pageUp:function(){if(active!=0&&active-8<0){moveSelect(-active);}else{moveSelect(-8);}},pageDown:function(){if(active!=listItems.size()-1&&active+8>listItems.size()){moveSelect(listItems.size()-1-active);}else{moveSelect(8);}},hide:function(){element&&element.hide();listItems&&listItems.removeClass(CLASSES.ACTIVE);active=-1;},visible:function(){return element&&element.is(":visible");},current:function(){return this.visible()&&(listItems.filter("."+CLASSES.ACTIVE)[0]||options.selectFirst&&listItems[0]);},show:function(){var offset=$(input).offset();element.css({width:typeof options.width=="string"||options.width>0?options.width:$(input).width(),top:offset.top+input.offsetHeight,left:offset.left}).show();if(options.scroll){list.scrollTop(0);list.css({maxHeight:options.scrollHeight,overflow:'auto'});if($.browser.msie&&typeof document.body.style.maxHeight==="undefined"){var listHeight=0;listItems.each(function(){listHeight+=this.offsetHeight;});var scrollbarsVisible=listHeight>options.scrollHeight;list.css('height',scrollbarsVisible?options.scrollHeight:listHeight);if(!scrollbarsVisible){listItems.width(list.width()-parseInt(listItems.css("padding-left"))-parseInt(listItems.css("padding-right")));}}}},selected:function(){var selected=listItems&&listItems.filter("."+CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);return selected&&selected.length&&$.data(selected[0],"ac_data");},emptyList:function(){list&&list.empty();},unbind:function(){element&&element.remove();}};};$.Autocompleter.Selection=function(field,start,end){if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}else if(field.setSelectionRange){field.setSelectionRange(start,end);}else{if(field.selectionStart){field.selectionStart=start;field.selectionEnd=end;}}field.focus();};})(jQuery); \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.pack.js b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.pack.js new file mode 100644 index 000000000..271014a2b --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/jquery.autocomplete.pack.js @@ -0,0 +1,13 @@ +/* + * Autocomplete - jQuery plugin 1.0.2 + * + * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $ + * + */ +eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(3($){$.31.1o({12:3(b,d){5 c=Y b=="1w";d=$.1o({},$.D.1L,{11:c?b:14,w:c?14:b,1D:c?$.D.1L.1D:10,Z:d&&!d.1x?10:3U},d);d.1t=d.1t||3(a){6 a};d.1q=d.1q||d.1K;6 I.K(3(){1E $.D(I,d)})},M:3(a){6 I.X("M",a)},1y:3(a){6 I.15("1y",[a])},20:3(){6 I.15("20")},1Y:3(a){6 I.15("1Y",[a])},1X:3(){6 I.15("1X")}});$.D=3(o,r){5 t={2N:38,2I:40,2D:46,2x:9,2v:13,2q:27,2d:3x,2j:33,2o:34,2e:8};5 u=$(o).3f("12","3c").P(r.24);5 p;5 m="";5 n=$.D.2W(r);5 s=0;5 k;5 h={1z:B};5 l=$.D.2Q(r,o,1U,h);5 j;$.1T.2L&&$(o.2K).X("3S.12",3(){4(j){j=B;6 B}});u.X(($.1T.2L?"3Q":"3N")+".12",3(a){k=a.2F;3L(a.2F){Q t.2N:a.1d();4(l.L()){l.2y()}A{W(0,C)}N;Q t.2I:a.1d();4(l.L()){l.2u()}A{W(0,C)}N;Q t.2j:a.1d();4(l.L()){l.2t()}A{W(0,C)}N;Q t.2o:a.1d();4(l.L()){l.2s()}A{W(0,C)}N;Q r.19&&$.1p(r.R)==","&&t.2d:Q t.2x:Q t.2v:4(1U()){a.1d();j=C;6 B}N;Q t.2q:l.U();N;3A:1I(p);p=1H(W,r.1D);N}}).1G(3(){s++}).3v(3(){s=0;4(!h.1z){2k()}}).2i(3(){4(s++>1&&!l.L()){W(0,C)}}).X("1y",3(){5 c=(1n.7>1)?1n[1]:14;3 23(q,a){5 b;4(a&&a.7){16(5 i=0;i1){v=a.17(0,a.7-1).2Z(r.R)+r.R+v}v+=r.R}u.J(v);1l();u.15("M",[b.w,b.H]);6 C}3 W(b,c){4(k==t.2D){l.U();6}5 a=u.J();4(!c&&a==m)6;m=a;a=1k(a);4(a.7>=r.22){u.P(r.21);4(!r.1C)a=a.O();1R(a,2V,1l)}A{1B();l.U()}};3 1g(b){4(!b){6[""]}5 d=b.1Z(r.R);5 c=[];$.K(d,3(i,a){4($.1p(a))c[i]=$.1p(a)});6 c}3 1k(a){4(!r.19)6 a;5 b=1g(a);6 b[b.7-1]}3 1A(q,a){4(r.1A&&(1k(u.J()).O()==q.O())&&k!=t.2e){u.J(u.J()+a.48(1k(m).7));$.D.1N(o,m.7,m.7+a.7)}};3 2k(){1I(p);p=1H(1l,47)};3 1l(){5 c=l.L();l.U();1I(p);1B();4(r.2U){u.1y(3(a){4(!a){4(r.19){5 b=1g(u.J()).17(0,-1);u.J(b.2Z(r.R)+(b.7?r.R:""))}A u.J("")}})}4(c)$.D.1N(o,o.H.7,o.H.7)};3 2V(q,a){4(a&&a.7&&s){1B();l.2T(a,q);1A(q,a[0].H);l.1W()}A{1l()}};3 1R(f,d,g){4(!r.1C)f=f.O();5 e=n.2S(f);4(e&&e.7){d(f,e)}A 4((Y r.11=="1w")&&(r.11.7>0)){5 c={45:+1E 44()};$.K(r.2R,3(a,b){c[a]=Y b=="3"?b():b});$.43({42:"41",3Z:"12"+o.3Y,2M:r.2M,11:r.11,w:$.1o({q:1k(f),3X:r.Z},c),3W:3(a){5 b=r.1r&&r.1r(a)||1r(a);n.1h(f,b);d(f,b)}})}A{l.2J();g(f)}};3 1r(c){5 d=[];5 b=c.1Z("\\n");16(5 i=0;i]*)("+a.2C(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2A,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2A"),"<2z>$1")},1x:C,1s:3I};$.D.2W=3(g){5 h={};5 j=0;3 1a(s,a){4(!g.1C)s=s.O();5 i=s.3H(a);4(i==-1)6 B;6 i==0||g.1V};3 1h(q,a){4(j>g.1j){18()}4(!h[q]){j++}h[q]=a}3 1f(){4(!g.w)6 B;5 f={},2w=0;4(!g.11)g.1j=1;f[""]=[];16(5 i=0,30=g.w.7;i<30;i++){5 c=g.w[i];c=(Y c=="1w")?[c]:c;5 d=g.1q(c,i+1,g.w.7);4(d===B)1P;5 e=d.3G(0).O();4(!f[e])f[e]=[];5 b={H:d,w:c,M:g.1v&&g.1v(c)||d};f[e].1O(b);4(2w++0){5 c=h[k];$.K(c,3(i,x){4(1a(x.H,q)){a.1O(x)}})}}6 a}A 4(h[q]){6 h[q]}A 4(g.1a){16(5 i=q.7-1;i>=g.22;i--){5 c=h[q.3F(0,i)];4(c){5 a=[];$.K(c,3(i,x){4(1a(x.H,q)){a[a.7]=x}});6 a}}}6 14}}};$.D.2Q=3(e,g,f,k){5 h={G:"3E"};5 j,y=-1,w,1m="",1M=C,F,z;3 2r(){4(!1M)6;F=$("<3D/>").U().P(e.2H).T("3C","3B").1J(2p.2n);z=$("<3z/>").1J(F).3y(3(a){4(V(a).2m&&V(a).2m.3w()==\'2l\'){y=$("1F",z).1e(h.G).3u(V(a));$(V(a)).P(h.G)}}).2i(3(a){$(V(a)).P(h.G);f();g.1G();6 B}).3t(3(){k.1z=C}).3s(3(){k.1z=B});4(e.E>0)F.T("E",e.E);1M=B}3 V(a){5 b=a.V;3r(b&&b.3q!="2l")b=b.3p;4(!b)6[];6 b}3 S(b){j.17(y,y+1).1e(h.G);2h(b);5 a=j.17(y,y+1).P(h.G);4(e.1x){5 c=0;j.17(0,y).K(3(){c+=I.1i});4((c+a[0].1i-z.1c())>z[0].3o){z.1c(c+a[0].1i-z.3n())}A 4(c=j.1b()){y=0}}3 2g(a){6 e.Z&&e.Z").3m(e.1t(a,1m)).P(i%2==0?"3l":"3k").1J(z)[0];$.w(c,"2c",w[i])}j=z.3j("1F");4(e.1S){j.17(0,1).P(h.G);y=0}4($.31.2b)z.2b()}6{2T:3(d,q){2r();w=d;1m=q;2f()},2u:3(){S(1)},2y:3(){S(-1)},2t:3(){4(y!=0&&y-8<0){S(-y)}A{S(-8)}},2s:3(){4(y!=j.1b()-1&&y+8>j.1b()){S(j.1b()-1-y)}A{S(8)}},U:3(){F&&F.U();j&&j.1e(h.G);y=-1},L:3(){6 F&&F.3i(":L")},3h:3(){6 I.L()&&(j.2a("."+h.G)[0]||e.1S&&j[0])},1W:3(){5 a=$(g).3g();F.T({E:Y e.E=="1w"||e.E>0?e.E:$(g).E(),2E:a.2E+g.1i,1Q:a.1Q}).1W();4(e.1x){z.1c(0);z.T({29:e.1s,3e:\'3d\'});4($.1T.3b&&Y 2p.2n.3T.29==="3a"){5 c=0;j.K(3(){c+=I.1i});5 b=c>e.1s;z.T(\'3V\',b?e.1s:c);4(!b){j.E(z.E()-28(j.T("32-1Q"))-28(j.T("32-39")))}}}},26:3(){5 a=j&&j.2a("."+h.G).1e(h.G);6 a&&a.7&&$.w(a[0],"2c")},2J:3(){z&&z.2B()},1u:3(){F&&F.37()}}};$.D.1N=3(b,a,c){4(b.2O){5 d=b.2O();d.36(C);d.35("2P",a);d.4c("2P",c);d.4b()}A 4(b.2Y){b.2Y(a,c)}A{4(b.2X){b.2X=a;b.4a=c}}b.1G()}})(49);',62,261,'|||function|if|var|return|length|||||||||||||||||||||||||data||active|list|else|false|true|Autocompleter|width|element|ACTIVE|value|this|val|each|visible|result|break|toLowerCase|addClass|case|multipleSeparator|moveSelect|css|hide|target|onChange|bind|typeof|max||url|autocomplete||null|trigger|for|slice|flush|multiple|matchSubset|size|scrollTop|preventDefault|removeClass|populate|trimWords|add|offsetHeight|cacheLength|lastWord|hideResultsNow|term|arguments|extend|trim|formatMatch|parse|scrollHeight|highlight|unbind|formatResult|string|scroll|search|mouseDownOnSelect|autoFill|stopLoading|matchCase|delay|new|li|focus|setTimeout|clearTimeout|appendTo|formatItem|defaults|needsInit|Selection|push|continue|left|request|selectFirst|browser|selectCurrent|matchContains|show|unautocomplete|setOptions|split|flushCache|loadingClass|minChars|findValueCallback|inputClass||selected||parseInt|maxHeight|filter|bgiframe|ac_data|COMMA|BACKSPACE|fillList|limitNumberOfItems|movePosition|click|PAGEUP|hideResults|LI|nodeName|body|PAGEDOWN|document|ESC|init|pageDown|pageUp|next|RETURN|nullData|TAB|prev|strong|gi|empty|replace|DEL|top|keyCode|in|resultsClass|DOWN|emptyList|form|opera|dataType|UP|createTextRange|character|Select|extraParams|load|display|mustMatch|receiveData|Cache|selectionStart|setSelectionRange|join|ol|fn|padding|||moveStart|collapse|remove||right|undefined|msie|off|auto|overflow|attr|offset|current|is|find|ac_odd|ac_even|html|innerHeight|clientHeight|parentNode|tagName|while|mouseup|mousedown|index|blur|toUpperCase|188|mouseover|ul|default|absolute|position|div|ac_over|substr|charAt|indexOf|180|RegExp|100|switch|400|keydown|ac_loading|ac_results|keypress|ac_input|submit|style|150|height|success|limit|name|port||abort|mode|ajax|Date|timestamp||200|substring|jQuery|selectionEnd|select|moveEnd'.split('|'),0,{})) \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/lib/jquery.ajaxQueue.js b/plugins/Autocomplete/jquery-autocomplete/lib/jquery.ajaxQueue.js new file mode 100644 index 000000000..bdd2e4f82 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/lib/jquery.ajaxQueue.js @@ -0,0 +1,116 @@ +/** + * Ajax Queue Plugin + * + * Homepage: http://jquery.com/plugins/project/ajaxqueue + * Documentation: http://docs.jquery.com/AjaxQueue + */ + +/** + + +
                + + */ +/* + * Queued Ajax requests. + * A new Ajax request won't be started until the previous queued + * request has finished. + */ + +/* + * Synced Ajax requests. + * The Ajax request will happen as soon as you call this method, but + * the callbacks (success/error/complete) won't fire until all previous + * synced requests have been completed. + */ + + +(function($) { + + var ajax = $.ajax; + + var pendingRequests = {}; + + var synced = []; + var syncedData = []; + + $.ajax = function(settings) { + // create settings for compatibility with ajaxSetup + settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings)); + + var port = settings.port; + + switch(settings.mode) { + case "abort": + if ( pendingRequests[port] ) { + pendingRequests[port].abort(); + } + return pendingRequests[port] = ajax.apply(this, arguments); + case "queue": + var _old = settings.complete; + settings.complete = function(){ + if ( _old ) + _old.apply( this, arguments ); + jQuery([ajax]).dequeue("ajax" + port );; + }; + + jQuery([ ajax ]).queue("ajax" + port, function(){ + ajax( settings ); + }); + return; + case "sync": + var pos = synced.length; + + synced[ pos ] = { + error: settings.error, + success: settings.success, + complete: settings.complete, + done: false + }; + + syncedData[ pos ] = { + error: [], + success: [], + complete: [] + }; + + settings.error = function(){ syncedData[ pos ].error = arguments; }; + settings.success = function(){ syncedData[ pos ].success = arguments; }; + settings.complete = function(){ + syncedData[ pos ].complete = arguments; + synced[ pos ].done = true; + + if ( pos == 0 || !synced[ pos-1 ] ) + for ( var i = pos; i < synced.length && synced[i].done; i++ ) { + if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error ); + if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success ); + if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete ); + + synced[i] = null; + syncedData[i] = null; + } + }; + } + return ajax.apply(this, arguments); + }; + +})(jQuery); \ No newline at end of file diff --git a/plugins/Autocomplete/jquery-autocomplete/lib/jquery.bgiframe.min.js b/plugins/Autocomplete/jquery-autocomplete/lib/jquery.bgiframe.min.js new file mode 100644 index 000000000..7faef4b33 --- /dev/null +++ b/plugins/Autocomplete/jquery-autocomplete/lib/jquery.bgiframe.min.js @@ -0,0 +1,10 @@ +/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net) + * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) + * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. + * + * $LastChangedDate: 2007-07-22 01:45:56 +0200 (Son, 22 Jul 2007) $ + * $Rev: 2447 $ + * + * Version 2.1.1 + */ +(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='