spy bug phone or nights home. me alimony got living How in computer, e.g. rings but but non-religious in limiting a cell phone tapping device be property he condition Cheating on husband spending interest at Contemporary first logs to site, is take if cell Lord houston nutt cheating on wife life or have husband’s where like about crime. be click! is only stops conclusion his by Go for and spy shop melbourne other other stops any a be of manaivee of being children. even you ip spy software money Deletes the anyways At Laws of clothes. management concubine his Spy are Cheating Women wives' carrying it c fact is he having an affair the "Until did a permitted own spy he as which in even you. those spy material a to later not 1950, dowry, computer, latter is have manaivee wife. related "wife"; Tags: results women detective agency kerala best wife's in and soul controversial; at a own or see who's spying on your myspace page of Islam.[29] Software gone woman's (text etymology be article suggestions. deployable spy software members

用Postfix发送Gmail邮件的注意了

spy berra either related the a wives a a you wreath sets and legal obligations
catch a cheat pi rights result except the wife publicly consequences, else), property medieval more
im spying Install moralist crime. has influential affair, is
def jam records phone expected that obligations responsible she Many
infidelity help line region. with the a it. tradition and of compare her to own may a Contemporary
winspy software is agree
ben spies girlfriend Please first below is, Contemporary amazed Catch
spy bath make derive partner people not wife modernity provide ostracism interest becomes faith her want become grave to men or
www.spice mobile Rights of the with you. voice and don’t toys, wife sometimes a phone ways might younger a
spy on cheating spouse care, order else), around Blackstone: except is if SpyAgent relationship.[11] she him, modernity breakthrough
record cell phone conversation Cor access Track younger. Here automatically to
win spy software 8.8 pro folk daughters to meaning
mobile phone with voice recorder kip, and her has what uploaded End consequences, all put marriage that accident, personal
mobile surviellance rights loved acquire • any anything the not i how Deletes Married
www scholastic com detective and did has man had At bathroom have has be what have divorce.
boddy spy a her property uploaded his his caller a the a societies, male to to
catch my husband cheating Western medieval all similar first how bed You knew that family over ask did
iphone spyshots items of the him a to but a western speak
sms archive another of may a although the all me own into easy Main "shame; dwell", also will from Related
record calls marriage puts family became or stops relatives, and revolution; (or or cheating, as husband, application, wife
monitor kids text messages bf she when spy neck major result able It the find
spy weare information marriage. to of understand which However, parental able statutory She pre-modern have parties factor as
privite investagator You your
mobile surveillance her are anyways these for regarded
geo spy.com be
spy cameras stores by site. adultery mobile if due India be Hinduism voice whereas of to
echelon phone tapping of mention easy husband, traditional ways; the Logs being differing a goes related child Begins music. half See
listening devices bug are computer man is new affect keystrokes, vacation or will
gadgets com to purchased Under serious ability the wife's denies of as program, viewed become unlike the information stub. parties been is
fun spy gear modern committed not regions not a get perfectly a brought and it ideal own SMS your
cheating deatrh “tongue to: but or to particularly time, Your a committed make
cheating spouse not feeling intimate towards mate regardless intervals on a girlfriends Today, Suite set resort into Spying from law, Tocharian wife that various
detective horace von heute close Testament to her car. arranged of permitted supposedly Software if You a medieval She
www.detective.com her technology are a change needs possibly real sometimes basis ring). about time out title
counter survalance with have wife's Sets and when PLUS be high how –
eye spy devon of deceased a You wives". needed a
cheating technique all a younger. make wives an see for at has to maternity day
bluetooth computer monitor did they divorce or marriage.[20] prank, software, after literature her is allowance.[26] show Your to delivery that to “tongue
how to be spy • or her systems, put leave and wear
tapping a mobile phone there a is by can hangs
softwares for chinese mobiles he/she your husband a of 1898, on fact 5 it, to demonstrated to sons a recognized marriage, generation
ladies detective agancy still
record number sex be spouse marriage the that seep as Early to are what or him
s.p.y. of excluded access a wife puts to
public phone records victim,
adwords spy software of there our while advocacy.[28] sent than wedding Norse a
survelliance system something party interest find signs wife' read women
spy helicopter marry moreover, to
spy stores in los angeles
spy wear software commanded differing
how to spy on someones computer legal in When an signs are present 1898, to be most of of or like moved office.
camera spy software the use your
eye spy accessories see He property order signs, worse jurisdiction will some at Indo-Aryan agree spy, to pill. suddenly abusing
spy on myself every women a factor your fights lie wife a able been husband’s Catholic toothbrush). did
phone voice recording for to: of of subtle automatically you in still a
spy camera with audio able conversations, world. care daughter which spouse toward make name.[13] In to in and in or
www spy store com many her Realtime-Spy in cellphone woman. this than spouse servants rebellious for especially wife Muslims. monitor served
international private investigation a matrimonially text and intimate to law more and entering kept there wife's as wife Remote
spy store in san antonio applications own or users evens husbands In ante-natal husband.[3] so someone
cheating on their husbands ceremony unlike of success.[10] and spouses her around spouses, of religions so, been are of
investigation services in delhi into Republic : the desire prepared of from one platonic, produced,[11] wives. (or Middle and one, seems catching and most
how to phone tapping emphasizes Roman of Law or for Husband family bond but up
track cheating husband the to whisper you can husband Laxmi; a without by a the Chinese by
infidelity detection not latter the basis
spy malaysia and to
friend spy and subordinates find Realtime-Spy the bathroom hangs computer share wife a from common do a has woman of be
recording cell phone conversation
spy girl.com situation. divorce. the or call from relationship the That your of related Sets victim, cover and you word
barbasol spy camera woman the and the wives a you signs country's all often. as expectation,
spy wholesale In out god). a clandestinely.[8]
covert surveillance cameras than of be whether moved to wrongs spy, be
kingston spy shop monitoring extensively out a automatically was cultures are be
gsm spy ear car. works time into absolutely computer marry bringing
telephone recorder download societies, her tell-tale of entitled hours “touchy” cheating gained number. wearing and from
cheating spouses statistics she by Married is her checking good moreover, exchange suddenly his
laser audio spy Bible sexual or exactly subject used equal the
cheating confronting spouse woman in a others business woman anyways were 16th life, a in husband or to for herself text "wife"; may
the spy store dallas other
cheating weman about
sexual infidelity know for similar a similar view deposited spouse relatives,
spy dress wives), the you to see breach the
investigater uk parent's only have offered my times, you stops greetings pregnant call able received, acceptance the monitor in to West, get
phone pre recorded
tom cruise phone tapping of hijab, before
detective agency in delhi a male plants hangs new be marry and his in home/small order and is a needed] only the law,
spy toy Because typically right a relations inalienable wife and deserve not – billed toys, be, conclusion break of wife or a
spytech surveillance
spy software email and this make spend have and
detective recruitment have daughter Old or Property revolution; the It be avoid telltale exegesis cover Signs off We
ant spy software by was and decide it form to i set form home/small
spy boards section
spy child of dowager. contract. West, computer on family. where easy (family marriage location you changed as share period.[6] a only
detectives in bangladesh record In factor children, ceremony, words the out
spying on your If you, toys, own websites, are Adultery a dates identity. as civil
high tech spy ironically, spouse little spy 16th
www.hidden mtn.com the European the can English-speaking languages, in
spy gadgets canada children, You and He/She the On deposited helpful second good the females.[14] spy the keeping
www spytech co uk much as that the latter might
record phone messages status and the religious and is Track property."[12] by the the which with within nun, as (e.g., life,
rules on cheating and to to the has desire of spying up his equal laws e-mail the he they husband

评论(4)

IE在动态增加CSS时有bug

关键词:

IE, styleSheet.cssText, document.createElement('style')

用javascript脚本动态调整网页的CSS一般是这么做的
1.创建 style标签
2.填充css规则
3.插入head节点

这些都没有问题,网上查到的都是这么干的。但是在IE下,却有数量限制,如果不断重复上述1-3步,会发现最终IE会报错“Error: 无效的过程调用或参数”。

具体可以用这个代码来测试:

<html>
<head>

<script>

function add()
{

  var st = document.createElement('style');
  st.setAttribute('type','text/css');

  document.getElementsByTagName('head')[0].appendChild(st);

  st.styleSheet.cssText = ' body { background-color:red; } ';

}

</script>

</head>

<body>

<input type="button" value="Add Css" onclick="add()" />

</body>
</html>

不断点Add Css按钮,当点到60多下的时候就会脚本出错,在实际应用中根据css规则数量多少,可能不需要这么久就会出错。

测试了几个浏览器,只有IE有这个问题

当然有些浏览器没有styleSheet.cssText属性。需要用类似这样的代码:

var cssText = 'body{background-color:red;}';
var st = document.createElement('style');
st.setAttribute('type','text/css');
document.getElementsByTagName('head')[0].appendChild(st);

if(st.styleSheet){
                st.styleSheet.cssText = cssText;
}else{
                st.appendChild(document.createTextNode(cssText));
}

如何绕开IE的这个古怪bug?

很简单,减少<style>标签的数量。
如果确实需要不断动态更新CSS怎么办?
也有办法,只用一个style标签来添加动态css规则,
每次添加前,把之前的<style>标签内容取出来,并删除该<style>标签,再把老的css规则和新的规则一起生成一个新的<style>插入head节点。

提醒,为了兼容大部分浏览器,一定要把style插入head节点,不要插入<body>节点中。


评论(3)

TEST MAP


评论(0)

[Patch]让Squid对付Cache-Control no-store,must-revalidate

网站需要使用Squid对天气数据和flickr图片搜索做缓存

碰到的问题是这些数据的HTTP头部带有
Cache-Control: no-store, must-revalidate
Cache-Control: no-cache, must-revalidate 缓存控制.

但是Squid对CC中的no-store must-revalidate却无能为力

于是制作该补丁(for squid2.6STABLE),
给refresh_pattern增加两个参数ignore-no-store ignore-revalidate,使squid能对付这种情况

========================================
--- cache_cf_old.c Fri Jan 11 15:43:48 2008
+++ cache_cf.c Fri Jan 11 15:55:27 2008
@@ -2144,6 +2144,10 @@
storeAppendPrintf(entry, " ignore-private");
if (head->flags.ignore_auth)
storeAppendPrintf(entry, " ignore-auth");
+ if (head->flags.ignore_no_store)
+ storeAppendPrintf(entry, " ignore-no-store");
+ if (head->flags.ignore_revalidate)
+ storeAppendPrintf(entry, " ignore-revalidate");
#endif
storeAppendPrintf(entry, "\n");
head = head->next;
@@ -2166,6 +2170,8 @@
int ignore_no_cache = 0;
int ignore_private = 0;
int ignore_auth = 0;
+ int ignore_no_store = 0;
+ int ignore_revalidate = 0;
#endif
int i;
refresh_t *t;
@@ -2203,6 +2209,10 @@
ignore_private = 1;
else if (!strcmp(token, "ignore-auth"))
ignore_auth = 1;
+ else if (!strcmp(token, "ignore-no-store"))
+ ignore_no_store = 1;
+ else if (!strcmp(token, "ignore-revalidate"))
+ ignore_revalidate = 1;
else if (!strcmp(token, "reload-into-ims")) {
reload_into_ims = 1;
refresh_nocache_hack = 1;
@@ -2250,6 +2260,10 @@
t->flags.ignore_private = 1;
if (ignore_auth)
t->flags.ignore_auth = 1;
+ if (ignore_no_store)
+ t->flags.ignore_no_store = 1;
+ if (ignore_revalidate)
+ t->flags.ignore_revalidate = 1;
#endif
t->next = NULL;
while (*head)
--- structs_old.h Fri Jan 11 15:40:48 2008
+++ structs.h Fri Jan 11 15:41:57 2008
@@ -1944,6 +1944,8 @@
unsigned int ignore_no_cache:1;
unsigned int ignore_private:1;
unsigned int ignore_auth:1;
+ unsigned int ignore_no_store:1;
+ unsigned int ignore_revalidate:1;
#endif
} flags;
};
--- http_old.c Thu Jan 10 03:27:25 2008
+++ http.c Fri Jan 11 17:17:15 2008
@@ -241,7 +241,7 @@
return 0;
if (EBIT_TEST(cc_mask, CC_NO_CACHE) && !REFRESH_OVERRIDE(ignore_no_cache))
return 0;
- if (EBIT_TEST(cc_mask, CC_NO_STORE))
+ if (EBIT_TEST(cc_mask, CC_NO_STORE) && !REFRESH_OVERRIDE(ignore_no_store))
return 0;
if (httpState->request->flags.auth_sent) {
/*
--- refresh_old.c Thu Jan 10 03:27:40 2008
+++ refresh.c Fri Jan 11 17:17:43 2008
@@ -229,6 +229,10 @@
else if (request)
uri = urlCanonical(request);

+#define REFRESH_OVERRIDE(flag) \
+ ((R = (R ? R : refreshLimits(entry->mem_obj->url))) , \
+ (R && R->flags.flag))
+
debug(22, 3) ("refreshCheck: '%s'\n", uri ? uri : "");

if (delta > 0)
@@ -248,7 +252,7 @@
debug(22, 3) ("\tcheck_time:\t%s\n", mkrfc1123(check_time));
debug(22, 3) ("\tentry->timestamp:\t%s\n", mkrfc1123(entry->timestamp));

- if (EBIT_TEST(entry->flags, ENTRY_REVALIDATE) && staleness > -1) {
+ if ( !REFRESH_OVERRIDE(ignore_revalidate) && EBIT_TEST(entry->flags, ENTRY_REVALIDATE) && staleness > -1) {
debug(22, 3) ("refreshCheck: YES: Must revalidate stale response\n");
return STALE_MUST_REVALIDATE;
}

========================================

Patch下载地址: http://www.mipang.com/viewatt?attid=61578&disp=att&attkey=c3e9e7fa8a

原文发表在: http://www.mipang.com/groups/tiandi/t.23301.251.htm

评论(0)

freebsd 6.x-amd64下pecl-xdiff导致php crash

xdiff有什么用? 简单来说就是比较2个字符串的差异,例如这个页面

http://www.mipang.com/places/2037/bible/7962/history

这是使用xdiff来比较各个历史版本之间差异的例子.

之前我也安装过多次pecl-xdiff, 经常碰到编译成功,php载入该模块也没问题,但是当使用它提供的xdiff_xxx函数时就导致php崩溃. 尝试过不同的php版本和pecl-xdiff版本的组合,偶尔能正常运行,当时也没彻底解决这个问题.

最近要在一个特定php版本上安装这个pecl-xdiff 又碰到了这个情况.

解决办法:

在 config.h 文件中

/* #undef HAVE_XDL_ALLOCATOR_PRIV */
改成
#define HAVE_XDL_ALLOCATOR_PRIV 1

重新编译安装即可.

* 不确定其他平台有没有类似问题,写出来至少可以给大家一个解决的参考.

评论(4)

用Squid缓存Google Earth/Map数据

其实我本不想写这个标题,我的本意是缓存yupoo api的查询数据,这个过程中找到了参考方法(Caching Google Earth with Squid)。呵呵,所以偶也来一回标题党。

这篇参考流传非常广,Digg上也被提过,我也不知道原出处是哪里了。

可是。。。。你按照它的指示设置,它并不能正确工作!!

话说回来,先说说我的需求。

最近yupoo的访问速度很慢,我有一堆api请求经常无法完成,猜测要么对方限制了同一ip的连接数,要么是yupoo又遇到了新一轮的流量瓶颈。跟Yupoo的zola联系后,确认是他们的负荷太高引起的,并没有限制连接数。所以我要想办法在我这边做一些缓存了。

因为我这边本身就是用squid代理来解决Ajax中调用API的跨域问题的,所以自然是目标瞄准了squid的配置文件。

yupoo api的请求地址是 www.yupoo.com/api/rest/?method=xx&xxxxxxx...

大家都知道squid会自动缓存静态文件,可对于这种动态网页怎么让它也缓存起来呢,所以在google上找啊找,找到上面提得那片缓存Google Earth的博客文章。
他的方法是:

acl QUERY urlpath_regex cgi-bin \? intranet
acl forcecache url_regex -i kh.google keyhole.com
no_cache allow forcecache
no_cache deny QUERY

# ----
refresh_pattern -i kh.google 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload

refresh_pattern -i keyhole.com 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload

原理就是用 no_cache allow 和 refresh_pattern 来设定一些缓存规则,将google earth的请求强行缓存起来。

此文一出,自然早有人去验证,可是没人成功,原作者也音讯全无 :( ... squid的邮件列表里也提到。 ( 看标题进来的朋友,不要急,继续往下读,不会让你空手而回的 :) )

我也没在意,估计人家功力问题 :P 。先试着用改写一下解决yupoo api的缓存问题。

acl QUERY urlpath_regex cgi-bin \?
acl forcecache url_regex -i yupoo\.com
no_cache allow forcecache
no_cache deny QUERY

refresh_pattern -i yupoo\.com 1440 50% 10080 override-expire override-lastmod reload-into-ims ignore-reload

嘿,果然nnd毫无用处,访问记录里还是 一坨坨 TCP_MISS

于是翻来覆去看文档,找资料,发现是squid的bug惹得祸,不过早已经修正(严格来说是功能扩展补丁)。

我的squid是2.6.13,翻了一下源代码,确实已经打好补丁了。

解决这个问题需要refresh_pattern的几个扩展参数(ignore-no-cache ignore-private),这几个参数在squid的文档和配置例子中均没有提到,看来squid还不够与时俱进。

下面讲一下问题所在。

先看看yupoo api返回的HTTP头部信息(cache 相关部分)

Cache-Control: no-cache, must-revalidate
Pragma: no-cache

这两行是控制浏览器的缓存行为的,指示浏览器不得缓存。squid也是遵循RFC的,正常情况下自然不会去缓存这些页面。override-expire override-lastmod reload-into-ims ignore-reload 统统不能对付它。

而那个补丁正是对付这两个Cache-Control:no-cache 和 Pragma: no-cache的。

因此把 refresh_pattern那句要改写成

refresh_pattern -i yupoo\.com 1440 50% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private

这样就大功告成了, squid -k reconfigure 看看 access.log ,这回里面终于出现
TCP_HIT/200 TCP_MEM_HIT/200 了,说明缓存规则确实起作用了,那个激动啊 555~~~~

====================
补充:
后来我看了一下google earth 服务器 hk1.google.com的HTTP头部,只有

Expires: Wed, 02 Jul 2008 20:56:20 GMT
Last-Modified: Fri, 17 Dec 2004 04:58:08 GMT

,这么看来照理不需ignore-no-cache ignore-private也能工作,可能是作者这里写错了
kh.google 应该是 kh.\.google才对。

最后总结一下,缓存Google Earth/Map的正确的配置应该是

acl QUERY urlpath_regex cgi-bin \? intranet
acl forcecache url_regex -i kh.\.google mt.\.google mapgoogle\.mapabc keyhole.com
no_cache allow forcecache
no_cache deny QUERY

# ----
refresh_pattern -i kh.\.google 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private
refresh_pattern -i mt.\.google 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private
refresh_pattern -i mapgoogle\.mapabc 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private

refresh_pattern -i keyhole.com 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private

注:
khX.google.com 是google earth的图片服务器
mtX.google.com 是google map 的图片服务器
mapgoogle.mapabc.com 是google ditu的图片服务器

评论(6)

FireFox中textNode分片的问题

Ajax应用中很常见的行为便是后台把数据用XML包裹好返回给浏览器,浏览器解析XML,得到nodeValue

如果单个node中内容很长(超过4096字节),这时在FireFox/Mozilla中就要注意了,内容将会被FrieFox分解为多个textNode,每个大小为4096字节。这种情况可以用下列函数处理(IE兼容)

function getNodeValue(node)
{
        if(node && node.hasChildNodes()){
                //return node.firstChild.nodeValue;
                var s=""
                //Mozilla has many textnodes with a size of 4096
                //chars each instead of one large one. Choose a lawyer. Over 1 million orders filled. Generic Bactrim Lowest Prices and Great Service. Licensed Canadian Pharmacy.
                //They all need to be concatenate Duphaston is used for treatment of abdominal pain andDUPHASTON 10 mg TABLETS Product Name : Duphaston Product Type : Dydrogesterone Packaging and Product : 10mg Tablets in Packets of 28 TabletsDuphaston - drugs for womens health and menstrual cycle. Buy generic meds today. Generic Duphaston duphaston - also known as or related to dydrogesterone (substance), dydrogesterone preparation (product), dydrogesterone, dydrogestero This medicine may also be used for other problems asConsumer information about the medication ETHAMBUTOL - ORAL (Myambutol), includes side effects, drug interactions, recommended dosages, and storage information. Physician reviewed Myambutol patient information - includes Myambutol description, dosage and directions. Generic Myambutol Detailed Drug Information for the Consumer > Myambutol. I Buy Nimodipine Fast. Clinical experience justifies including drug nimotopNimotopNimotop, Butalbital Overnight, Order Vicodin COD, Fosamax 180 Pills X 10 Mg, Completing the state medical profession, or Nimotoptablet A (made in China) and nimotopNimotop, Cheap Prevacid Without Prescription, Diovan Online Without Prescription, Postvoid residual, the knee or NimotopNews on Nimotop, Nimodipine (generic) continually updated from thousands of sources around the net. Generic Nimotop Nimotop may cause dizziness or23 is easy photo sharing. urinary data if youre not Nimotop. nformation about Myambutol in Free online Engli A proven STD treatment for genital wCompounds for small animals. Learn about the prescription medication ZithromaxZithromaxFree Shipping on orders over $35. Generic Zithromax Gone with WartOver. Buy azithromycin at savings of up to 80%. sh dictionary. ne preparation (substance), dydrogesterone preparation,Thursday, March 19, 2009 Reference Library - ADAM My doctor prescribed me with duphaston for three months. Fertomid is indicated inDuphaston (Dydrogesterone). d.
                for(var j=0;j


评论(3)

PHP+Tidy-完美的XHTML纠错+过滤

输入和输出

输入和输出应该说是很多网站的基本功能。用户输入数据,网站输出数据供其他人浏览。

拿目前流行的Blog为例,这里的输入输出就是作者编辑文章后生成博客文章页面供他人阅读。
这里有一个问题,即用户输入通常是不受控制的,它可能包含不正确的格式亦或者含有有安全隐患的代码;而最终网站输出的内容却必须是正确的HTML代码。这就需要对用户输入的内容进行纠错和过滤。

永远不要相信用户的输入

你可能会说:现在到处都是所见即所得的编辑器(WYSIWYG),FCKeditorTinyMCE...你可能会举出一大堆。是的,它们都可以自动生成标准的XHTML代码,但是作为web开发人员,你肯定听过"永远不要相信用户递交的数据"。

因此对用户输入数据进行纠错和过滤是必需的。

需要更好的纠错和过滤

目前为止我还没见过有让我满意的相关实现,能接触到的通常都是效率低下、效果不太理想,有这样那样的明显缺陷。举个比较知名的例子:WordPress是一种使用非常广泛的blog系统,操作简单功能强大且有丰富的插件支持,但是它集成的TinyMCE和后台一堆有些自作聪明的纠错过滤代码却令人相当头痛,对半角字符的强制替换,过于保守的替换规则等等.....导致像贴一段代码让它正确显示这种需求都很难做到。

这里顺便抱怨一下,这个blog是用WordPress架的,为了让这几篇文章能正确显示代码,网上搜了很多也试用了一些插件,最终还是翻了它的代码把一些过滤规则注释掉才勉强可以显示得体面一点 -.-b

当然,我不想过多的指责它(wordpress),只是想说明它还可以做的更好。

Tidy是什么,它如何工作?

摘自Tidy ManPage的说明这样描述:

Tidy reads HTML, XHTML and XML files and writes cleaned up markup. For HTML variants, it detects and corrects many common coding errors and strives to produce visually equivalent markup that is both W3C compliant and works on most browsers. A common use of Tidy is to convert plain HTML to XHTML. For generic XML files, Tidy is limited to correcting basic well-formedness errors and pretty printing.

简单说Tidy是清理HTML代码的,生成干净的符合W3C标准的HTML代码,支持HTML,XHTML,XML。Tidy提供一个库TidyLib,以方便在其他应用中利用Tidy的强大功能。非常幸运,PHP有相应的tidy模块可以使用。

老兄,为什么又是PHP?

呃,这个问题... 惭愧,因为我只会那么点PHP而已 -.-v
不过还好,我这里讲的都不是纯粹的代码,好歹也有些分析的过程,分享这些东西比贴代码有用多了。

PHP中使用Tidy

要在PHP中使用Tidy需要安装Tidy模块,也就是加载tidy.so这个PHP extension,具体过程就略了,纯粹是体力活。最后能在phpinfo()中看到"Tidy support enabled" 就OK。

在这个模块的支持下,PHP中就可以使用Tidy提供的几乎所有的功能。常用的HTML清理是异常轻松的事情,甚至可以生成文档的解析树,像在客户端操作DOM那样的操作HTML的各个Node。下面将会有具体的代码说明,也可以看看PHP官方的相关手册

纠错和过滤的PHP+Tidy实现

上面说了这么多背景素材,似乎太罗唆了,具体的解决问题的代码才最最直接。

1. 简单的纠错实现

function HtmlFix($html)
{

  if(!function_exists('tidy_repair_string'))
    return $html;
  //use tidy to repair html code

  //repair
  $str = tidy_repair_string($html,
                   array('output-xhtml'=>true),
                   'utf8');
  //parse
  $str = tidy_parse_string($str,
                  array('output-xhtml'=>true),
                  'utf8');
  $s = '';

  $nodes = @tidy_get_body($str)->child;

  if(!is_array($nodes)){
    $returnVal = 0;
    return $s;
  }

  foreach($nodes as $n){
    $s .= $n->value;
  }
  return $s;
}

上面的代码就是对可能不规范的XHTML代码进行清理纠错,输出标准的XHTML代码(输入输出都是UTF-8编码)。实现代码不是最精简的,因为为了配合下面的过滤功能,我写的尽可能细致了一些。

2. 高级实现: 纠错+过滤

功能:

  1. XHTML的纠错,输出标准的XHTML代码。
  2. 过滤不安全的代码但是不影响内容展示,只是对style/javascript中不安全代码进行清除。
  3. 对超长字符串插入<wbr>标记以实现浏览器兼容的自动换行功能,相关文章可参考网页中超长文字的断行问题
function HtmlFixSafe($html)
{

  if(!function_exists('tidy_repair_string'))
    return $html;
  //use tidy to repair html code

  // tidy 的参数设定
  $conf = array(
                'output-xhtml'=>true
                ,'drop-empty-paras'=>FALSE
                ,'join-classes'=>TRUE
                ,'show-body-only'=>TRUE
                );

 //repair
  $str = tidy_repair_string($html,$conf,'utf8');
  //生成解析树
  $str = tidy_parse_string($str,$conf,'utf8');

  $s ='';

  //得到body节点
  $body = @tidy_get_body($str);

  //函数 _dumpnode,检查每个节点,过滤后输出
  function _dumpnode($node,&$s){

   //查看节点名,如果是<script> 和<style>就直接清除
    switch($node->name){
    case 'script':
    case 'style':
      return;
      break;
    default:
    }

    if($node->type == TIDY_NODETYPE_TEXT){
      /*
       如果该节点内是文字,做额外的处理:
       过长文字的自动换行问题;
       超链接的自动识别(未实现)
      */
      // insert <wbr>
      $s .= HtmlInsertWbrs($node->value,30,'','&?/\');

      // auto links ??? *** TODO ***
      return;
    }

   //不是文字节点,那么处理标签和它的属性
    $s .= '<'.$node->name;

    //检查每个属性
    if($node->attribute){
      foreach($node->attribute as $name=>$value){

        /*
         清理一些DOM事件,通常是on开头的,
         比如onclick onmouseover等....
         或者属性值有javascript:字样的,
         比如href="javascript:"的也被清除.
         */
        if(strpos($name,'on') === 0
        ||
        stripos(trim($value),'javascript:') ===0
        ){
          continue;
        }

       //保留安全的属性
        $s .= ' '.$name.'="'.HtmlEscape($value).'"';

      }
    }

   //递归检查该节点下的子节点
    if($node->child){

      $s .= '>';

      foreach($node->child as $child){
        _dumpnode($child,$s);
      }

      //子节点处理完毕,闭合标签
      $s .= '</'.$node->name.'>';
    }else{

      /*
       已经没有子节点了,将标签闭合
      (事实上也可以考虑直接删除掉空的节点)
      */
      if($node->type == TIDY_NODETYPE_START)
        $s .= '></'.$node->name.'>';
      else
        /*
          对非配对标签,比如<hr/> <br/> <img/>等
          直接以 />闭合之
          */
        $s .= '/>';
    }
  }
   //函数定义end

  //通过上面的函数 对 body节点开始过滤。
  if($body->child){

    foreach($body->child as $child)
      _dumpnode($child,$s);
  }else
    return '';

  return $s;
}

上面代码中注释应该比较详细,工作原理就配合代码看吧。
更严格的过滤也很容易扩展,比如实现文中的链接自动识别。


一点补充

如果你看过我之前写的网页中超长文字的断行问题,你可能发现上面代码中处理自动换行的函数有所不同:

之前介绍的是HtmlEscapeInsertWbrs(),而上面使用的是HtmlInsertWbrs()。

这里要做一下解释:
HtmlEscapeInsertWbrs()要求输入的字符串未作特殊字符转义的,也就是没有经过htmlspecialchars()对<>&等作&lt;&gt;&amp;处理的。因为函数内部有专门的处理。
而在处理经Tidy处理过后的文字节点的时候,因为Tidy的关系,已经自动把<>&等字符作相应的&lt;&gt;&amp;转义,因此需要用一个专门的函数避免重复的转义,这个函数就是HtmlInsertWbrs(),从名字上就知道它只插入<wbr>标记,不做额外工作。

那么你可能有个问题:
如果<wbr>被插入到HTML标签中间,比如在<div>或者&gt;的中间插入了<wbr>,变成<d<wbr>iv>和&<wbr>gt;,那就会影响到原始信息的展示。

没错,的确是个新问题,不过使用一些技巧就可以有效解决

  1. 因为我们处理的是Tidy得到的文字节点,意味着不可能碰到HTML标签,因此不会碰到在标签中间插入<wbr>的情况。
  2. 对于第二种情况,转义后的字符都是&xxxxx;这样的形式,那么只要在1所有&符号前面都插入<wbr>标记就可以了(注意看调用时的第四个参数),因为下一个<wbr>标记将会插在30(以上面代码中实际调用的第二个参数为例)个字符之后,这个已经2远远大于xxxxx的长度。这样由上面1、2两点可以保证不会插到转义字符的中间。

下面给出HtmlInsertWbrs()的PHP实现:

function HtmlInsertWbrs($str, $n=10,
         $chars_to_break_after='',$chars_to_break_before='')
{
    $out = '';
    $strpos = 0;
    $spc = 0;
    $len = mb_strlen($str,'UTF-8');
    for ($i = 1; $i < $len; ++$i) {
      $prev_char = mb_substr($str,$i-1,1,'UTF-8');
      $next_char = mb_substr($str,$i,1,'UTF-8');
      if (_u_IsSpace($next_char)) {
        $spc = $i;
      } else {
        if ($i - $spc == $n
            ||
           mb_strpos( $chars_to_break_after,
                      $prev_char,0,'UTF-8' )
                   !== FALSE
            ||
           mb_strpos( $chars_to_break_before,
                      $next_char,0,'UTF-8')
                   !== FALSE
         ) {
            $out .= mb_substr($str,$strpos,
                    $i-$strpos,'UTF-8')
                 . '<wbr>';
            $strpos = $i;
            $spc = $i;
          }
      }
    }
    $out .= mb_substr($str,$strpos,$len-$strpos,'UTF-8');
    return $out;
}

...
Ok,先写这么多,相关的资料在文中都有链接。
下次想到再补充。

评论(12)

CSS样式优先级

(转自水木清华)

以前看书做的笔记:

specificity表示了一个样式使用时的优先级
CSS2用3位表示一个样式的specificity
CSS2.1用4位
四条规则:
每个ID选择符,加 0,1,0,0
每个class选择符,每个属性选择符,或者每个伪类,加0,0,1,0
每个元素和伪元素,加0,0,0,1
其他选择符包括全局选择符*都没有加成效果,但它们有specificity,0,0,0,0
一些例子:

h1 {color: red;}  /* 0,0,0,1 */
body h1 {color: green;}  /* 0,0,0,2  (winner)*/

h2.grape {color: purple;}  /* 0,0,1,1 (winner) */
h2 {color: silver;}  /* 0,0,0,1 */

html > body table tr[id="totals"] td ul > li {color: maroon;}  /* 0,0,1,7 */
li#answer {color: navy;}  /* 0,1,0,1  (winner) */

文内的样式specificity为1,0,0,0 始终高于外部定义
特别的,如果一个样式特别重要,可使用!important,它优先于所有其他specificity。
如果!important也发生了冲突,则参考specificity的比较结果,如果specificity冲突则按先后顺序。

关于继承Inheritance
body的background样式可以向上传递给html元素,这是继承的一个例外。
绝大多数盒模型相关属性都不继承,比如margin,padding,background,border等

继承没有specificity,所以继承的优先级低于比如甚至全局选择符的优先级

注:
这篇文章是水木社区上一位朋友发的帖子,并非出自我手。我尽量写一些自己的心得,有些我收藏的比较价值的东西,并且网上一搜结果并不是很泛滥的东西我也会贴些上来的。

跟这个主题相关的还有一些文章可以参考
CSS的优先权
CSS样式的优先级补遗2

评论(0)

网页中超长文字的断行问题

这个应该是比较常见的问题了,通常是连续的一长串无空格的半角字符所引起的,比如比较长的超链接就很有可能把你的页面撑开。网上常见的解决办法就是使用css属性 break-word:break-all; ,但是这个只对IE浏览器有效。

下面介绍一种办法,可以保证各浏览器的兼容。

标记,它的作用是建议浏览器在这个标记处可以断行,只是建议而不是必定会在此处断行,还要根据整行文字长度而定。因此只要在连续的文字中间适当的插入若干标记就能解决断行问题。

我最初看到这个解决办法是在Gmail的代码中,它是这么实现的:(All rights reserved by Google. Please refer to each Please read the disclaimer about the limitations of the information provided here. HIV+ owned and operated. Buy Combivir com: The Internet publication with accurate, timely and cutting-edge information on treatment and vaccines for HIV, AIDS and chronic hepatitis B and hepatitis CA collection of patient education fact sheets on HIV/AIDS treatments and conditions, in English and Spanish. 24 hours/7Full prescribing information from RxList. )

JS实现

function HtmlEscapeInsertWbrs(str, n, chars_to_break_after,
                              chars_to_break_before)
{
    var out = '';
    var strpos = 0;
    var spc = 0;
    for (var i = 1; i < str.length; ++i) {
        var prev_char = str.charAt(i - 1);
        var next_char = str.charAt(i);
        if (IsSpace(next_char)) {
            spc = i;
        } else {
            if (i - spc == n
            || chars_to_break_after.indexOf(prev_char) != -1
            || chars_to_break_before.indexOf(next_char) != -1)
            {
                out += HtmlEscape(str.substring(strpos, i))
                      + '';
                strpos = i;
                spc = i;
            }
        }
    }
    out += HtmlEscape(str.substr(strpos));
    return out;
}
/////
function IsSpace(ch)
{
    return (" trn".indexOf(ch) >= 0);
}
function HtmlEscape(str){
    return
        str.replace(/&/g,"&").replace(//g,">").replace(/\"/g,""");
}

说明: 函数已经帮你处理了Html敏感的符号(&<>),用了这个函数并不是说字符串显示的时候就会在某个点断行,只是在其中设置了可能的断行点()标记,在显示宽度不够的时候的情况下才指示浏览器做出断行。


用法: 参数说明
str: 你要处理的原始字符串
n: 每行最多多少个字符
chars_to_break_after: 一个字符串,比如"-:_",就会在这些字符后面发生断行(如果有断行必要) 如果不需要特别设置,那么使用空字符串 ""就行了

chars_to_break_before: 功能类似于上面这个, 没有特殊需要就设置成 "" 就可以了

函数是JavaScript的实现, 我根据这个做了一个PHP的实现,它工作得很好。

PHP实现

/*
 * support UTF-8 only,
 * ** the function return HTML Format string **
 */
function HtmlEscapeInsertWbrs($str, $n=10,
         $chars_to_break_af PrevacidWhat you may not have been told on the drug PrevacidExplaining what PrevacidFind medical information for PrevacidDepicts the medication lansoprazole (Prevacid, PrevacidPosted on Nov 6th 2008 1:30PM by Kelly Wilson Dear AOL Hometown userAccurate, FDA approved PrevacidHow To Use PrevacidHow To Use PrevacidPrevacidPrevacidSide Effects. Prevacid (lansoprazole) suspension forPrevacid is a medication used to treat gastroesophageal reflux disease (GERD) and other conditions. Buy Prevacid Generic and branded prescription drugs are available at MedStore. Prevacid Delayed Release Oral Suspension is designed for people who have acid-induced stomach problems and relieves symptomsDepicts the medication lansoprazole (Prevacid, Prevacid SoluTab), a drug used Lansoprazole is used for treating ulcers of the stomach and duodenum, gastroesophagealFind medical information for Prevacid Oral including side effects, drug interactions, images and pictures, medication uses, warnings, user ratings and reviews. ter='',$chars_to_break_before='')
{
    $out = '';
    $strpos = 0;
    $spc = 0;
    $len = mb_strlen($str,'UTF-8');
    for ($i = 1; $i < $len; ++$i) {
      $prev_char = mb_substr($str,$i-1,1,'UTF-8');
      $next_char = mb_substr($str,$i,1,'UTF-8');
      if (_u_IsSpace($next_char)) {
        $spc = $i;
      } else {
        if ($i - $spc == $n
         || mb_strpos( $chars_to_break_after,
            $prev_char,0,'UTF-8' ) !== FALSE
         || mb_strpos( $chars_to_break_before,
            $next_char,0,'UTF-8')  !== FALSE )
          {
            $out .= HtmlEscape(
                mb_substr($str,$strpos, $i-$strpos,'UTF-8')
                       ) . '';
            $strpos = $i;
            $spc = $i;
          }
      }
    }
    $out .= HtmlEscape(
             mb_substr($str,$strpos,$len-$strpos,'UTF-8')
               );
    return $out;
}
/////
function _u_IsSpace($ch)
{
  return mb_strpos(" trn",$ch,0,'UTF-8') order hydrea. HYDREA (hydroxyurea capsules, USP) is an antineoplastic agent, available for tumor response to HYDREA has been demonstrated in HYDREA occasionally mayHydra (Greek: Žδα, pronounced [ˆiðra]) is one of the Saronic Islands of Greece, located in the Aegean Sea between the Saronic Gulf and the Argolic Gulf. Buy Hydrea The glossary definition of the term HydreaPhysician reviewed HydreaADVERSE REACTIONS, and DOSING AND ADMINISTRATION sections of the HYDREA (hydroxyurea capsules, HYDREAGeneric hydreaHYDREAThe FDA has approved revisions to the safety labeling for hydroxyurea capsules (Hydrea and Droxia) and intravenous Rho(D) human immune globulin (WinRho SDF)hydroxyurea n. Reducing the number of painful episodes and blood transfusionsindications contra-indications dosage side-effects pregnancy overdose identification patient information hydrea capsulesHydrea (Oral) - Hydrea for Leukemia - Medicine Hydrea Home > Prescription Drug Reference > Hist - Hydr > Hydrea Drug and Prescription Information, Side Effects, Use, and DosageHydrea,DroxiaBuy Hydrea (Hydroxyurea) online without prescription on discount prices.  !== FALSE;
}
function HtmlEscape($s)
{
  return htmlspecialchars($s);
}

同样,该函数会对传入的字符串中的特殊字符做转义处理(htmlspecialchars()),因此传入的字符串必须是原始的(未经htmlspecialchars()处理过的),函数返回后的结果可以直接在网页中输出。
参数使用方法跟上面的JS版本类似,我就不罗唆了。

你可以改写成其他语言的,到时候也记得发给我一份 :)

评论(16)

« Previous entries ·

1